Class: Lutaml::Xml::Schema::XsdSchema
- Inherits:
-
Object
- Object
- Lutaml::Xml::Schema::XsdSchema
- Extended by:
- Model::Schema::SharedMethods
- Includes:
- Model::Schema::SharedMethods
- Defined in:
- lib/lutaml/xml/schema/xsd_schema.rb
Overview
XSD Schema generation for XML models
Generates W3C XML Schema (XSD) from LutaML model classes. Supports namespace declarations, type definitions, and nested models.
Defined Under Namespace
Classes: Context
Constant Summary collapse
- UNSUPPORTED_XSD_REGEX_FLAGS =
Regexp::IGNORECASE | Regexp::MULTILINE | Regexp::EXTENDED
Class Method Summary collapse
- .attr_is_xml_attribute?(xml_mapping, attr_name) ⇒ Boolean
- .build_element_attributes(name, xsd_type, attr, xml_mapping, attr_name) ⇒ Object
-
.classify_xsd_type(type_name, klass, register) ⇒ Symbol
Classify an XSD type name into one of three categories.
-
.collection_placeholder?(attr, mapping) ⇒ Boolean
Whether a nested model is emitted only as a placeholder: a collection of a type_name-less model renders as
<element name="item" type="xs:string"/>, so the model's own content is never inlined or referenced. -
.declare_referenced_namespaces!(schema_attrs, referenced, target_uri, skip_validation) ⇒ Object
Declare xmlns:
for every namespace this schema references. - .effective_facets(attr, attr_type) ⇒ Object
- .emit_bound(xml, element, value, type) ⇒ Object
- .emit_facet(xml, element, value) ⇒ Object
-
.emit_import(xml, ns_class) ⇒ Object
Emit a single xs:import for a namespace class, with schemaLocation when the class declares one.
- .emit_restriction(xml, base, facets, type) ⇒ Object
- .emit_restriction_facets(xml, facets, type) ⇒ Object
- .emit_value_element(xml, attrs, xsd_type, attr_type, attr) ⇒ Object
-
.emit_xsd_attribute(xml, attr, rule, xsd_type, attr_type) ⇒ Object
Emit an
xs:attribute, inlining anxs:restrictionwhen the attribute is a constrained value type (itstype=moves into the restriction base) and/or an annotation when the mapping carries documentation. -
.foreign_namespace?(mapping, target_uri) ⇒ Boolean
Whether a nested model's mapping belongs to a namespace other than the schema's target namespace.
-
.foreign_prefix_error(ns_class, schema_attrs, target_uri) ⇒ Object
Why a foreign namespace's prefix cannot be used in this schema's QNames, or nil when it can.
- .generate(klass, options = {}) ⇒ Object
- .generate_annotation(xml, xml_mapping) ⇒ Object
- .generate_attributes(xml, klass, register, xml_mapping) ⇒ Object
- .generate_complex_type(xml, klass, type_name, register, xml_mapping = nil, ctx:) ⇒ Object
- .generate_complex_type_content(xml, klass, register, xml_mapping, ctx:) ⇒ Object
- .generate_elements(xml, klass, register, xml_mapping, ctx:) ⇒ Object
-
.generate_imports(xml, namespace_class) ⇒ Object
Emit xs:import for each namespace the root's XmlNamespace class explicitly declares.
- .generate_includes(xml, namespace_class) ⇒ Object
- .generate_nested_type_definitions(xml, klass, register, ctx:, seen: nil) ⇒ Object
-
.generate_referenced_imports(xml, referenced, target_uri, imported_uris) ⇒ Object
xs:import for every referenced foreign namespace, deduped by URI against the explicit imports already emitted.
- .generate_schema(xml, klass, xml_mapping, register, options) ⇒ Object
- .get_attribute_xsd_type(attr, attr_type, register, _mapping_rule = nil) ⇒ Object
-
.get_namespace_info(klass) ⇒ Object
Namespace information for a Type::Value class (the only kind the namespace walk queries — nested models are handled structurally by referenced_namespaces).
- .get_target_xsd_type(attr, register) ⇒ Object
- .get_xsd_type(type) ⇒ Object
- .has_explicit_xml_mapping?(klass, xml_mapping) ⇒ Boolean
-
.imported_foreign_type?(mapping, target_uri) ⇒ Boolean
Whether a nested model is referenced across a schema-document boundary: it lives in a foreign namespace AND exposes a named type, so it is referenced by a prefixed QName and resolved through an xs:import.
- .leading_backslash_run(source) ⇒ Object
- .lexical_value(type, value) ⇒ Object
- .missing_schema_location_error(ns_class) ⇒ Object
-
.nested_ref_prefix(nested_mapping, ctx) ⇒ Object
The prefix a named-type reference should carry.
- .pattern_value(regexp) ⇒ Object
-
.prefix_collision_error(prefix, uri, schema_attrs) ⇒ Object
The collision message when
prefixis already bound to a different namespace thanuriinschema_attrs, or nil when there is no conflict. -
.qn(local) ⇒ Object
Qualify an XSD structure element name with the bound prefix, so the prefix used on emitted elements always matches the declared xmlns.
-
.qualify_type_ref(type_name, prefix) ⇒ Object
Qualify a named-type reference with the given prefix so it resolves to the namespace the type is defined in.
- .raise_inexpressible_pattern!(regexp, detail) ⇒ Object
-
.referenced_namespaces(klass, register, target_uri, seen = Set.new) ⇒ Hash
Namespaces referenced by THIS schema document, collected by walking the model tree from the root class (structural, no instance needed).
- .reject_invalid_xsd_pattern!(regexp, source) ⇒ Object
- .reject_unsupported_regex_flags!(regexp) ⇒ Object
- .strip_leading_anchor(source) ⇒ Object
- .strip_ruby_anchors(source) ⇒ Object
- .strip_trailing_anchor(source) ⇒ Object
-
.synthesize_target_prefix(referenced) ⇒ Object
A synthetic prefix for a target namespace that declares none, avoiding every prefix claimed by a referenced namespace.
-
.target_namespace_attrs(xml_mapping) ⇒ Object
targetNamespace, form defaults, and the target xmlns declaration, derived from the root mapping's namespace configuration.
-
.target_ns_prefix(xml_mapping) ⇒ Object
The prefix of the schema's target namespace, or nil when the schema has no target namespace (named types then live in no-namespace and their references stay unprefixed).
- .trailing_backslash_run(source, pos) ⇒ Object
-
.type_resolvable?(type_name, klass, register) ⇒ Boolean
Check if a custom XSD type can be resolved in the model hierarchy.
-
.usable_prefix?(prefix) ⇒ Boolean
Whether a prefix can appear in emitted QNames: present and not the reserved XSD vocabulary prefix.
-
.validate_xsd_types!(klass, register, seen = Set.new) ⇒ Object
Validate all XSD types referenced by the model.
-
.xs(xml, local, attrs = nil, &block) ⇒ Object
Emit an XSD structure element (<xs:local ...>) through the builder.
- .xsd_escape(text) ⇒ Object
-
.xsd_ns ⇒ Object
The XSD vocabulary namespace, routed through the project's namespace object so the declared prefix and every emitted prefix stay in sync.
Methods included from Model::Schema::SharedMethods
Class Method Details
.attr_is_xml_attribute?(xml_mapping, attr_name) ⇒ Boolean
798 799 800 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 798 def self.attr_is_xml_attribute?(xml_mapping, attr_name) xml_mapping.attributes.any? { |rule| rule.to == attr_name } end |
.build_element_attributes(name, xsd_type, attr, xml_mapping, attr_name) ⇒ Object
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 802 def self.build_element_attributes(name, xsd_type, attr, xml_mapping, attr_name) attrs = { name: name.to_s, type: xsd_type } # Handle collection cardinality if attr.collection? range = attr.resolved_collection if range attrs[:minOccurs] = range.min.to_s attrs[:maxOccurs] = range.end.infinite? ? "unbounded" : range.max.to_s else attrs[:minOccurs] = "0" attrs[:maxOccurs] = "unbounded" end end # Add form attribute from mapping rule if present if xml_mapping rule = xml_mapping.find_element(attr_name) attrs[:form] = rule.form.to_s if rule&.form attrs[:annotation] = rule.documentation if rule&.documentation end attrs end |
.classify_xsd_type(type_name, klass, register) ⇒ Symbol
Classify an XSD type name into one of three categories
114 115 116 117 118 119 120 121 122 123 124 125 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 114 def self.classify_xsd_type(type_name, klass, register) return :builtin if BuiltinTypes.builtin?(type_name) # Custom type - check if resolvable if type_name && !type_name.start_with?("xs:") return :custom if type_resolvable?(type_name, klass, register) return :unresolvable end :unknown end |
.collection_placeholder?(attr, mapping) ⇒ Boolean
Whether a nested model is emitted only as a placeholder: a collection
of a type_name-less model renders as <element name="item" type="xs:string"/>, so the model's own content is never inlined or
referenced. This document therefore neither declares its namespaces
nor defines its nested types — the walkers must not descend into it.
490 491 492 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 490 def self.collection_placeholder?(attr, mapping) attr.collection? && mapping&.type_name_value.nil? end |
.declare_referenced_namespaces!(schema_attrs, referenced, target_uri, skip_validation) ⇒ Object
Declare xmlns:
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 310 def self.declare_referenced_namespaces!(schema_attrs, referenced, target_uri, skip_validation) referenced[:foreign_models].each do |ns_class| # An unusable or colliding prefix makes emitted QNames resolve to # the wrong namespace — never recoverable, even under # skip_validation. error = foreign_prefix_error(ns_class, schema_attrs, target_uri) raise Lutaml::Model::Error, error if error # A missing schema_location leaves the import unresolvable but the # output structurally correct — recoverable under skip_validation. unless ns_class.schema_location error = missing_schema_location_error(ns_class) raise Lutaml::Model::Error, error unless skip_validation warn "[Lutaml::Model] WARN: #{error} " \ "(skip_validation: emitting best-effort output)" end schema_attrs[:"xmlns:#{ns_class.prefix_default}"] = ns_class.uri end referenced[:type_values].each do |ns_class| prefix = ns_class.prefix_default next unless usable_prefix?(prefix) # A prefix bound to two different namespaces emits QNames that # resolve to the wrong one — the same unrecoverable collision the # foreign path raises on, so raise here too rather than silently # keeping the first binding. error = prefix_collision_error(prefix, ns_class.uri, schema_attrs) raise Lutaml::Model::Error, error if error schema_attrs[:"xmlns:#{prefix}"] = ns_class.uri end end |
.effective_facets(attr, attr_type) ⇒ Object
639 640 641 642 643 644 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 639 def self.effective_facets(attr, attr_type) return {} unless attr_type.is_a?(Class) && attr_type < Lutaml::Model::Type::Value attr.effective_restriction_facets(attr_type) end |
.emit_bound(xml, element, value, type) ⇒ Object
691 692 693 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 691 def self.emit_bound(xml, element, value, type) emit_facet(xml, element, lexical_value(type, value)) unless value.nil? end |
.emit_facet(xml, element, value) ⇒ Object
695 696 697 698 699 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 695 def self.emit_facet(xml, element, value) return if value.nil? xml.public_send(qn(element), value: value.to_s) end |
.emit_import(xml, ns_class) ⇒ Object
Emit a single xs:import for a namespace class, with schemaLocation when the class declares one.
406 407 408 409 410 411 412 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 406 def self.emit_import(xml, ns_class) import_attrs = { namespace: ns_class.uri } if ns_class.schema_location import_attrs[:schemaLocation] = ns_class.schema_location end xs(xml, "import", import_attrs) end |
.emit_restriction(xml, base, facets, type) ⇒ Object
657 658 659 660 661 662 663 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 657 def self.emit_restriction(xml, base, facets, type) xs(xml, "simpleType") do xs(xml, "restriction", base: base) do emit_restriction_facets(xml, facets, type) end end end |
.emit_restriction_facets(xml, facets, type) ⇒ Object
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 665 def self.emit_restriction_facets(xml, facets, type) emit_bound(xml, :minExclusive, facets[:min_exclusive], type) emit_bound(xml, :minInclusive, facets[:min_inclusive], type) emit_bound(xml, :maxExclusive, facets[:max_exclusive], type) emit_bound(xml, :maxInclusive, facets[:max_inclusive], type) emit_facet(xml, :totalDigits, facets[:total_digits]) emit_facet(xml, :fractionDigits, facets[:fraction_digits]) emit_facet(xml, :length, facets[:length]) emit_facet(xml, :minLength, facets[:min_length]) emit_facet(xml, :maxLength, facets[:max_length]) Array(facets[:enumeration]).each do |value| emit_facet(xml, :enumeration, lexical_value(type, value)) end emit_facet(xml, :whiteSpace, facets[:white_space]) patterns = Array(facets[:pattern]) if patterns.size > 1 raise Lutaml::Model::Error, "Cannot export #{patterns.size} conjunctive patterns on " \ "#{type} to a single xs:restriction: sibling xs:pattern " \ "facets are alternatives (OR), and XSD cannot express " \ "conjunction (AND) without nested restriction derivation, " \ "which is not yet supported." end patterns.each { |re| emit_facet(xml, :pattern, pattern_value(re)) } end |
.emit_value_element(xml, attrs, xsd_type, attr_type, attr) ⇒ Object
646 647 648 649 650 651 652 653 654 655 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 646 def self.emit_value_element(xml, attrs, xsd_type, attr_type, attr) facets = effective_facets(attr, attr_type) if facets.any? xs(xml, "element", attrs.except(:type)) do emit_restriction(xml, xsd_type, facets, attr_type) end else xs(xml, "element", attrs.merge(type: xsd_type)) end end |
.emit_xsd_attribute(xml, attr, rule, xsd_type, attr_type) ⇒ Object
Emit an xs:attribute, inlining an xs:restriction when the attribute
is a constrained value type (its type= moves into the restriction
base) and/or an annotation when the mapping carries documentation.
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 618 def self.emit_xsd_attribute(xml, attr, rule, xsd_type, attr_type) facets = effective_facets(attr, attr_type) restricted = facets.any? attr_attrs = { name: rule.name } attr_attrs[:type] = xsd_type unless restricted attr_attrs[:use] = "required" if attr.[:required] attr_attrs[:form] = rule.form.to_s if rule.form return xs(xml, "attribute", attr_attrs) unless restricted || rule.documentation xs(xml, "attribute", attr_attrs) do if rule.documentation xs(xml, "annotation") do xs(xml, "documentation", rule.documentation) end end emit_restriction(xml, xsd_type, facets, attr_type) if restricted end end |
.foreign_namespace?(mapping, target_uri) ⇒ Boolean
Whether a nested model's mapping belongs to a namespace other than the schema's target namespace. A model with no namespace belongs to the target schema (not foreign).
466 467 468 469 470 471 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 466 def self.foreign_namespace?(mapping, target_uri) ns_class = mapping&.namespace_class return false unless ns_class ns_class.uri != target_uri end |
.foreign_prefix_error(ns_class, schema_attrs, target_uri) ⇒ Object
Why a foreign namespace's prefix cannot be used in this schema's QNames, or nil when it can.
348 349 350 351 352 353 354 355 356 357 358 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 348 def self.foreign_prefix_error(ns_class, schema_attrs, target_uri) prefix = ns_class.prefix_default unless usable_prefix?(prefix) schema_desc = target_uri ? "the '#{target_uri}'" : "this no-namespace" return "XSD generation: foreign namespace '#{ns_class.uri}' " \ "needs a usable prefix_default (not nil/empty/'xs') to " \ "be referenced from #{schema_desc} schema." end prefix_collision_error(prefix, ns_class.uri, schema_attrs) end |
.generate(klass, options = {}) ⇒ Object
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 88 def self.generate(klass, = {}) register = extract_register_from(klass) xml_mapping = klass.mappings_for(:xml) # Validate XSD types unless explicitly skipped validate_xsd_types!(klass, register) unless [:skip_validation] # Use Builder with adapter from options or config adapter_type = [:adapter] || Lutaml::Model::Config.xml_adapter_type || :nokogiri schema_builder = Builder.new( adapter_type: adapter_type, options: { encoding: "UTF-8" }, ) do |xml| generate_schema(xml, klass, xml_mapping, register, ) end schema_builder.to_xml() end |
.generate_annotation(xml, xml_mapping) ⇒ Object
422 423 424 425 426 427 428 429 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 422 def self.generate_annotation(xml, xml_mapping) xs(xml, "annotation") do doc_text = xml_mapping.documentation_text doc_text ||= xml_mapping.namespace_class&.documentation if xml_mapping.namespace_class xs(xml, "documentation", doc_text) if doc_text end end |
.generate_attributes(xml, klass, register, xml_mapping) ⇒ Object
602 603 604 605 606 607 608 609 610 611 612 613 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 602 def self.generate_attributes(xml, klass, register, xml_mapping) return unless xml_mapping xml_mapping.attributes.each do |rule| attr = klass.attributes[rule.to] next unless attr attr_type = attr.type(register) xsd_type = get_attribute_xsd_type(attr, attr_type, register, rule) emit_xsd_attribute(xml, attr, rule, xsd_type, attr_type) end end |
.generate_complex_type(xml, klass, type_name, register, xml_mapping = nil, ctx:) ⇒ Object
508 509 510 511 512 513 514 515 516 517 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 508 def self.generate_complex_type(xml, klass, type_name, register, xml_mapping = nil, ctx:) xs(xml, "complexType", { name: type_name }) do if klass.attributes.any? xs(xml, "sequence") do generate_elements(xml, klass, register, xml_mapping, ctx: ctx) end end generate_attributes(xml, klass, register, xml_mapping) end end |
.generate_complex_type_content(xml, klass, register, xml_mapping, ctx:) ⇒ Object
494 495 496 497 498 499 500 501 502 503 504 505 506 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 494 def self.generate_complex_type_content(xml, klass, register, xml_mapping, ctx:) xs(xml, "complexType") do if klass.attributes.any? xs(xml, "sequence") do generate_elements(xml, klass, register, xml_mapping, ctx: ctx) end end if xml_mapping generate_attributes(xml, klass, register, xml_mapping) end end end |
.generate_elements(xml, klass, register, xml_mapping, ctx:) ⇒ Object
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 519 def self.generate_elements(xml, klass, register, xml_mapping, ctx:) klass.attributes.each do |name, attr| next if xml_mapping && attr_is_xml_attribute?(xml_mapping, name) # Find the mapping rule for this attribute mapping_rule = xml_mapping&.find_element(name) attr_type = attr.type(register) if attr_type <= Lutaml::Model::Serialize # Nested model - check if it has a type_name for reference nested_mapping = attr_type.mappings_for(:xml) nested_type_name = nested_mapping&.type_name_value if attr.collection? # Collection of models element_attrs = { name: name.to_s } element_attrs[:minOccurs] = "0" element_attrs[:maxOccurs] = "unbounded" if nested_type_name # Reference named type by its owning namespace's prefix element_attrs[:type] = qualify_type_ref( nested_type_name, nested_ref_prefix(nested_mapping, ctx), ) xs(xml, "element", element_attrs) else # Inline anonymous complexType xs(xml, "element", element_attrs) do xs(xml, "complexType") do xs(xml, "sequence") do xs(xml, "element", { name: "item", type: get_xsd_type(attr_type) }) end end end end elsif nested_type_name # Single nested model - reference by its owning namespace prefix xs(xml, "element", { name: name.to_s, type: qualify_type_ref( nested_type_name, nested_ref_prefix(nested_mapping, ctx), ) }) else # Inline anonymous complexType xs(xml, "element", { name: name.to_s }) do generate_complex_type_content(xml, attr_type, register, nil, ctx: ctx) end end else # Value type xsd_type = get_attribute_xsd_type(attr, attr_type, register, mapping_rule) if attr.collection? # Collection of simple types element_attrs = { name: name.to_s } element_attrs[:minOccurs] = "0" element_attrs[:maxOccurs] = "unbounded" xs(xml, "element", element_attrs) do xs(xml, "complexType") do xs(xml, "sequence") do emit_value_element(xml, { name: "item" }, xsd_type, attr_type, attr) end end end else # Simple element element_attrs = build_element_attributes(name, xsd_type, attr, xml_mapping, name) emit_value_element(xml, element_attrs, xsd_type, attr_type, attr) end end end end |
.generate_imports(xml, namespace_class) ⇒ Object
Emit xs:import for each namespace the root's XmlNamespace class explicitly declares. Returns the Set of imported URIs so the tree import loop can dedupe against them.
391 392 393 394 395 396 397 398 399 400 401 402 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 391 def self.generate_imports(xml, namespace_class) imported = Set.new return imported unless namespace_class.imports&.any? namespace_class.imports.each do |imported_ns| next unless imported.add?(imported_ns.uri) emit_import(xml, imported_ns) end imported end |
.generate_includes(xml, namespace_class) ⇒ Object
414 415 416 417 418 419 420 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 414 def self.generate_includes(xml, namespace_class) return unless namespace_class.includes&.any? namespace_class.includes.each do |schema_location| xs(xml, "include", { schemaLocation: schema_location }) end end |
.generate_nested_type_definitions(xml, klass, register, ctx:, seen: nil) ⇒ Object
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 431 def self.generate_nested_type_definitions(xml, klass, register, ctx:, seen: nil) # Cycle guard, seeded with the root class (already defined by # generate_schema) so it is never redefined via a back-reference. seen ||= Set[klass] klass.attributes.each_value do |attr| attr_type = attr.type(register) next unless attr_type <= Lutaml::Model::Serialize nested_mapping = attr_type.mappings_for(:xml) # Skip models this document does not emit — checked before the cycle # guard so an unemitted reference never consumes the model's slot and # masks an emitted reference elsewhere. A collection of a type_name- # less model is a placeholder; an imported foreign type is defined in # its own schema document. A foreign model without a type_name is # inlined here, so we still descend to define the types it references. next if collection_placeholder?(attr, nested_mapping) next if imported_foreign_type?(nested_mapping, ctx.target_uri) next unless seen.add?(attr_type) nested_type_name = nested_mapping&.type_name_value if nested_type_name generate_complex_type(xml, attr_type, nested_type_name, register, nested_mapping, ctx: ctx) end generate_nested_type_definitions(xml, attr_type, register, ctx: ctx, seen: seen) end end |
.generate_referenced_imports(xml, referenced, target_uri, imported_uris) ⇒ Object
xs:import for every referenced foreign namespace, deduped by URI against the explicit imports already emitted.
379 380 381 382 383 384 385 386 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 379 def self.generate_referenced_imports(xml, referenced, target_uri, imported_uris) (referenced[:foreign_models] + referenced[:type_values]).each do |ns_class| next if ns_class.uri == target_uri next unless imported_uris.add?(ns_class.uri) emit_import(xml, ns_class) end end |
.generate_schema(xml, klass, xml_mapping, register, options) ⇒ Object
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 188 def self.generate_schema(xml, klass, xml_mapping, register, ) skip_validation = [:skip_validation] # Bind the XSD vocabulary namespace to the "xs" prefix (via the # namespace object, not a hardcoded string) so the xs:-prefixed type # references and the prefixed structure elements are both declared. schema_attrs = { xsd_ns.attr_name.to_sym => xsd_ns.uri } schema_attrs.merge!(target_namespace_attrs(xml_mapping)) target_uri = schema_attrs[:targetNamespace] referenced = referenced_namespaces(klass, register, target_uri) # Named-type references into the target namespace need a usable # prefix; synthesise a non-colliding one when the namespace class # declares none. target_prefix = target_ns_prefix(xml_mapping) if target_uri && target_prefix.nil? target_prefix = synthesize_target_prefix(referenced) schema_attrs[:"xmlns:#{target_prefix}"] = target_uri end declare_referenced_namespaces!(schema_attrs, referenced, target_uri, skip_validation) ctx = Context.new(target_prefix, target_uri) xs(xml, "schema", schema_attrs) do # Explicit imports declared on the root's XmlNamespace class. imported_uris = Set.new if xml_mapping.namespace_class imported_uris = generate_imports(xml, xml_mapping.namespace_class) generate_includes(xml, xml_mapping.namespace_class) end generate_referenced_imports(xml, referenced, target_uri, imported_uris) if xml_mapping.documentation_text || xml_mapping.namespace_class&.documentation generate_annotation(xml, xml_mapping) end element_name = if has_explicit_xml_mapping?(klass, xml_mapping) xml_mapping.element_name || xml_mapping.root_element end type_name = xml_mapping.type_name_value # Generate XSD based on three patterns: # Pattern 1: element only -> inline anonymous complexType # Pattern 2: type_name only -> named complexType (no element) # Pattern 3: both element and type_name -> element + named complexType if element_name && type_name xs(xml, "element", { name: element_name, type: qualify_type_ref(type_name, target_prefix) }) generate_complex_type(xml, klass, type_name, register, xml_mapping, ctx: ctx) elsif type_name && !element_name generate_complex_type(xml, klass, type_name, register, xml_mapping, ctx: ctx) else # Use class name as fallback element name if not specified elem_name = element_name || klass.name xs(xml, "element", { name: elem_name }) do generate_complex_type_content(xml, klass, register, xml_mapping, ctx: ctx) end end generate_nested_type_definitions(xml, klass, register, ctx: ctx) end end |
.get_attribute_xsd_type(attr, attr_type, register, _mapping_rule = nil) ⇒ Object
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 836 def self.get_attribute_xsd_type(attr, attr_type, register, _mapping_rule = nil) if attr.union? raise Lutaml::Model::UnionSchemaUnsupportedError.new(attr.name, "XSD") end # 1. Check for deprecated attribute-level xsd_type override return attr.[:xsd_type] if attr.[:xsd_type] # 2. Check if type has xsd_type method (Type-level) if attr_type.is_a?(Class) && attr_type < Lutaml::Model::Type::Value # Special handling for Reference type if attr_type == Lutaml::Model::Type::Reference target_xsd_type = get_target_xsd_type(attr, register) return attr_type.xsd_type(target_xsd_type) end return attr_type.xsd_type end # 3. Fall back to default mapping get_xsd_type(attr_type) end |
.get_namespace_info(klass) ⇒ Object
Namespace information for a Type::Value class (the only kind the namespace walk queries — nested models are handled structurally by referenced_namespaces). Returns {} for anything else.
910 911 912 913 914 915 916 917 918 919 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 910 def self.get_namespace_info(klass) return {} unless klass.is_a?(::Class) if defined?(Lutaml::Model::Type::Value) && klass <= Lutaml::Model::Type::Value return get_type_namespace_info(klass) end {} end |
.get_target_xsd_type(attr, register) ⇒ Object
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 942 def self.get_target_xsd_type(attr, register) return nil unless attr.[:ref_model_class] return nil unless attr.[:ref_key_attribute] begin model_class = Object.const_get(attr.[:ref_model_class]) target_attr = model_class.attributes[attr.[:ref_key_attribute]] return nil unless target_attr target_type = target_attr.type(register) get_attribute_xsd_type(target_attr, target_type, register) rescue NameError nil end end |
.get_xsd_type(type) ⇒ Object
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 958 def self.get_xsd_type(type) { Lutaml::Model::Type::String => "xs:string", Lutaml::Model::Type::Integer => "xs:integer", Lutaml::Model::Type::Boolean => "xs:boolean", Lutaml::Model::Type::Float => "xs:float", Lutaml::Model::Type::Decimal => "xs:decimal", Lutaml::Model::Type::Date => "xs:date", Lutaml::Model::Type::Time => "xs:time", Lutaml::Model::Type::DateTime => "xs:dateTime", Lutaml::Model::Type::TimeWithoutDate => "xs:time", Lutaml::Model::Type::Duration => "xs:duration", Lutaml::Model::Type::Uri => "xs:anyURI", Lutaml::Model::Type::QName => "xs:QName", Lutaml::Model::Type::Base64Binary => "xs:base64Binary", Lutaml::Model::Type::HexBinary => "xs:hexBinary", Lutaml::Model::Type::Hash => "xs:anyType", Lutaml::Model::Type::Symbol => "xs:string", }[type] || "xs:string" end |
.has_explicit_xml_mapping?(klass, xml_mapping) ⇒ Boolean
829 830 831 832 833 834 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 829 def self.has_explicit_xml_mapping?(klass, xml_mapping) return true unless xml_mapping.root_element base_name = Lutaml::Model::Utils.base_class_name(klass) xml_mapping.root_element != base_name end |
.imported_foreign_type?(mapping, target_uri) ⇒ Boolean
Whether a nested model is referenced across a schema-document boundary: it lives in a foreign namespace AND exposes a named type, so it is referenced by a prefixed QName and resolved through an xs:import. A foreign model WITHOUT a type_name has no named type to reference, so generate_elements inlines it into this document — it is not a boundary, and both the namespace walk and the type-definition walk must descend into it rather than treat it as imported.
480 481 482 483 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 480 def self.imported_foreign_type?(mapping, target_uri) foreign_namespace?(mapping, target_uri) && !mapping.type_name_value.nil? end |
.leading_backslash_run(source) ⇒ Object
745 746 747 748 749 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 745 def self.leading_backslash_run(source) run = 0 run += 1 while source[run] == "\\" run end |
.lexical_value(type, value) ⇒ Object
794 795 796 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 794 def self.lexical_value(type, value) type.serialize(type.cast(value)) end |
.missing_schema_location_error(ns_class) ⇒ Object
372 373 374 375 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 372 def self.missing_schema_location_error(ns_class) "XSD generation: foreign namespace '#{ns_class.uri}' needs a " \ "schema_location so its imported types can be resolved." end |
.nested_ref_prefix(nested_mapping, ctx) ⇒ Object
The prefix a named-type reference should carry. A foreign model's type lives in its own namespace, so the ref uses that namespace's prefix; a model in the target namespace (same URI or none) is defined in this schema, so the ref uses the target prefix.
79 80 81 82 83 84 85 86 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 79 def self.nested_ref_prefix(nested_mapping, ctx) ns_class = nested_mapping&.namespace_class return ctx.target_prefix unless ns_class return ctx.target_prefix if ns_class.uri == ctx.target_uri prefix = ns_class.prefix_default usable_prefix?(prefix) ? prefix : ctx.target_prefix end |
.pattern_value(regexp) ⇒ Object
701 702 703 704 705 706 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 701 def self.pattern_value(regexp) reject_unsupported_regex_flags!(regexp) source = strip_ruby_anchors(regexp.source) reject_invalid_xsd_pattern!(regexp, source) source end |
.prefix_collision_error(prefix, uri, schema_attrs) ⇒ Object
The collision message when prefix is already bound to a different
namespace than uri in schema_attrs, or nil when there is no
conflict.
363 364 365 366 367 368 369 370 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 363 def self.prefix_collision_error(prefix, uri, schema_attrs) existing = schema_attrs[:"xmlns:#{prefix}"] return unless existing && existing != uri "XSD generation: namespace prefix '#{prefix}' is bound " \ "to two different namespaces (#{existing} and #{uri}). " \ "Give them distinct prefixes." end |
.qn(local) ⇒ Object
Qualify an XSD structure element name with the bound prefix, so the prefix used on emitted elements always matches the declared xmlns.
25 26 27 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 25 def self.qn(local) "#{xsd_ns.prefix}:#{local}" end |
.qualify_type_ref(type_name, prefix) ⇒ Object
Qualify a named-type reference with the given prefix so it resolves to the namespace the type is defined in. Built-in refs (which already carry a prefix, e.g. "xs:string") and no-namespace schemas (prefix nil) are returned unchanged.
68 69 70 71 72 73 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 68 def self.qualify_type_ref(type_name, prefix) return type_name if prefix.nil? || type_name.nil? return type_name if type_name.include?(":") "#{prefix}:#{type_name}" end |
.raise_inexpressible_pattern!(regexp, detail) ⇒ Object
761 762 763 764 765 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 761 def self.raise_inexpressible_pattern!(regexp, detail) raise Lutaml::Model::Error, "Cannot export pattern #{regexp.inspect} to xs:pattern: " \ "it is not expressible in XSD's regexp subset (#{detail})." end |
.referenced_namespaces(klass, register, target_uri, seen = Set.new) ⇒ Hash
Namespaces referenced by THIS schema document, collected by walking the model tree from the root class (structural, no instance needed). The walk stops at foreign-model boundaries: a foreign model's type is imported — defined in its own schema document — so namespaces used only inside it are that document's concern, not this one's.
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 872 def self.referenced_namespaces(klass, register, target_uri, seen = Set.new) result = { foreign_models: [], type_values: [] } return result unless klass.is_a?(::Class) && seen.add?(klass) klass.attributes.each_value do |attr| type_class = attr.type(register) next unless type_class if type_class <= Lutaml::Model::Serialize mapping = type_class.mappings_for(:xml) if imported_foreign_type?(mapping, target_uri) result[:foreign_models] << mapping.namespace_class elsif collection_placeholder?(attr, mapping) # Placeholder collection: its content is never emitted, so it # contributes no namespaces to this document. next else nested = referenced_namespaces(type_class, register, target_uri, seen) result[:foreign_models].concat(nested[:foreign_models]) result[:type_values].concat(nested[:type_values]) end else ns = get_namespace_info(type_class)[:class] if ns.is_a?(::Class) && ns < Lutaml::Xml::Namespace result[:type_values] << ns end end end result[:foreign_models].uniq! result[:type_values].uniq! result end |
.reject_invalid_xsd_pattern!(regexp, source) ⇒ Object
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 767 def self.reject_invalid_xsd_pattern!(regexp, source) return unless defined?(::Nokogiri::XML::Schema) probe = <<~XSD <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:simpleType name="p"> <xs:restriction base="xs:string"> <xs:pattern value="#{xsd_escape(source)}"/> </xs:restriction> </xs:simpleType> </xs:schema> XSD schema = ::Nokogiri::XML::Schema(probe) return if schema.errors.empty? raise_inexpressible_pattern!(regexp, schema.errors.first.) rescue ::Nokogiri::XML::SyntaxError => e raise_inexpressible_pattern!(regexp, e.) end |
.reject_unsupported_regex_flags!(regexp) ⇒ Object
708 709 710 711 712 713 714 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 708 def self.reject_unsupported_regex_flags!(regexp) return if regexp..nobits?(UNSUPPORTED_XSD_REGEX_FLAGS) raise Lutaml::Model::Error, "Cannot export pattern #{regexp.inspect} to xs:pattern: " \ "the i/m/x flags are not expressible in XSD's regexp subset." end |
.strip_leading_anchor(source) ⇒ Object
721 722 723 724 725 726 727 728 729 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 721 def self.strip_leading_anchor(source) return source[1..] if source.start_with?("^") run = leading_backslash_run(source) return source unless run.odd? && source[run] == "A" # Keep the escaped-pair backslashes; drop the anchor's `\A`. source[0, run - 1] + source[(run + 1)..] end |
.strip_ruby_anchors(source) ⇒ Object
716 717 718 719 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 716 def self.strip_ruby_anchors(source) source = strip_leading_anchor(source) strip_trailing_anchor(source) end |
.strip_trailing_anchor(source) ⇒ Object
731 732 733 734 735 736 737 738 739 740 741 742 743 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 731 def self.strip_trailing_anchor(source) last = source[-1] before = source.length - 1 if ["z", "Z"].include?(last) && trailing_backslash_run(source, before).odd? return source[0...-2] end if last == "$" && trailing_backslash_run(source, before).even? return source[0...-1] end source end |
.synthesize_target_prefix(referenced) ⇒ Object
A synthetic prefix for a target namespace that declares none, avoiding every prefix claimed by a referenced namespace.
293 294 295 296 297 298 299 300 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 293 def self.synthesize_target_prefix(referenced) taken = (referenced[:foreign_models] + referenced[:type_values]) .filter_map(&:prefix_default) candidate = "tns" suffix = 0 candidate = "tns#{suffix += 1}" while taken.include?(candidate) candidate end |
.target_namespace_attrs(xml_mapping) ⇒ Object
targetNamespace, form defaults, and the target xmlns declaration, derived from the root mapping's namespace configuration.
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 264 def self.target_namespace_attrs(xml_mapping) attrs = {} if xml_mapping.namespace_class ns = xml_mapping.namespace_class attrs[:targetNamespace] = ns.uri attrs[:elementFormDefault] = ns.element_form_default.to_s attrs[:attributeFormDefault] = ns.attribute_form_default.to_s attrs[:version] = ns.version if ns.version prefix = xml_mapping.namespace_prefix || ns.prefix_default attrs[:"xmlns:#{prefix}"] = ns.uri if usable_prefix?(prefix) elsif xml_mapping.namespace_uri # Legacy: namespace URI without XmlNamespace class attrs[:targetNamespace] = xml_mapping.namespace_uri attrs[:elementFormDefault] = "unqualified" attrs[:attributeFormDefault] = "unqualified" if usable_prefix?(xml_mapping.namespace_prefix) attrs[:"xmlns:#{xml_mapping.namespace_prefix}"] = xml_mapping.namespace_uri end end attrs end |
.target_ns_prefix(xml_mapping) ⇒ Object
The prefix of the schema's target namespace, or nil when the schema has no target namespace (named types then live in no-namespace and their references stay unprefixed). Never returns the reserved "xs".
52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 52 def self.target_ns_prefix(xml_mapping) prefix = if xml_mapping&.namespace_class xml_mapping.namespace_prefix || xml_mapping.namespace_class.prefix_default elsif xml_mapping&.namespace_uri xml_mapping.namespace_prefix end prefix if usable_prefix?(prefix) end |
.trailing_backslash_run(source, pos) ⇒ Object
751 752 753 754 755 756 757 758 759 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 751 def self.trailing_backslash_run(source, pos) run = 0 i = pos - 1 while i >= 0 && source[i] == "\\" run += 1 i -= 1 end run end |
.type_resolvable?(type_name, klass, register) ⇒ Boolean
Check if a custom XSD type can be resolved in the model hierarchy
133 134 135 136 137 138 139 140 141 142 143 144 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 133 def self.type_resolvable?(type_name, klass, register) # Search in nested model attributes klass.attributes.each_value do |attr| attr_type = attr.type(register) next unless attr_type <= Lutaml::Model::Serialize nested_mapping = attr_type.mappings_for(:xml) return true if nested_mapping&.type_name_value == type_name end false end |
.usable_prefix?(prefix) ⇒ Boolean
Whether a prefix can appear in emitted QNames: present and not the reserved XSD vocabulary prefix.
40 41 42 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 40 def self.usable_prefix?(prefix) !prefix.nil? && !prefix.empty? && prefix != xsd_ns.prefix end |
.validate_xsd_types!(klass, register, seen = Set.new) ⇒ Object
Validate all XSD types referenced by the model
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 151 def self.validate_xsd_types!(klass, register, seen = Set.new) # Cycle guard: recursive models (A -> B -> A) would otherwise recurse # forever. A class already being validated needs no re-validation. return unless seen.add?(klass) errors = [] klass.attributes.each do |name, attr| attr_type = attr.type(register) # Validate Type::Value xsd_type if attr_type.is_a?(Class) && attr_type < Lutaml::Model::Type::Value type_name = attr_type.xsd_type classification = classify_xsd_type(type_name, klass, register) if classification == :unresolvable errors << "Attribute '#{name}' uses unresolvable xsd_type '#{type_name}'. " \ "Custom types must be defined as LutaML Type::Value or Model classes." end end # Recursively validate nested models if attr_type <= Lutaml::Model::Serialize begin validate_xsd_types!(attr_type, register, seen) rescue Lutaml::Model::UnresolvableTypeError => e errors << "In nested model #{attr_type.name}: #{e.}" end end end if errors.any? raise Lutaml::Model::UnresolvableTypeError, errors.join("\n") end end |
.xs(xml, local, attrs = nil, &block) ⇒ Object
Emit an XSD structure element (<xs:local ...>) through the builder.
30 31 32 33 34 35 36 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 30 def self.xs(xml, local, attrs = nil, &block) if attrs xml.public_send(qn(local), attrs, &block) else xml.public_send(qn(local), &block) end end |
.xsd_escape(text) ⇒ Object
790 791 792 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 790 def self.xsd_escape(text) text.gsub("&", "&").gsub("<", "<").gsub('"', """) end |
.xsd_ns ⇒ Object
The XSD vocabulary namespace, routed through the project's namespace object so the declared prefix and every emitted prefix stay in sync. W3c::XsNamespace binds "xs" (matching the built-in xs:-prefixed type references) and opts out of the W3C-reserved-prefix warning.
19 20 21 |
# File 'lib/lutaml/xml/schema/xsd_schema.rb', line 19 def self.xsd_ns @xsd_ns ||= Lutaml::Xml::W3c::XsNamespace.new end |