PureXML/Sources/Schema/XSDDerivationTables.swift
Mihaela Mihaljevic 1fe670581f feat(schema): key the instance derivation/substitution backbone by namespaced identity; re-land blockDefault; invalid-instances-accepted 89 to 81 (#186, #147)
The instance-validity derivation and substitution tables were keyed by bare
local name, so two same-local-name types or elements in different namespaces
collided. In multi-document validation this let one schema's block/derivation
facts shadow another's, and it blocked honouring blockDefault (whose re-land
widened that collision into an over-rejection).

Key the instance subsystem by namespaced identity {ns}local instead. The shared
DerivationTables keeps its bare-keyed fields for the schema-validity machinery
(Particle-Valid-Restriction and the consistency rules, which resolve QNames to
bare names and walk the same backbone) and gains parallel ns* fields built in
the same pass, resolving each container's components through its target
namespace and prefix bindings. Only the instance consumers
(blockedSubstitutionError, notDerivedSubstitutionError, abstractTypeError, the
substitution-group closure, and referenceParticle) read the ns* tables, via a
derivationKey(fromReference:) that reduces a type:{ns}local reference, a bare
name, or an element ref to a {ns}local backbone key. A key miss stays permissive
(no constraint, substitution allowed), so the re-keying cannot over-reject.

With the namespaced backbone in place, blockDefault is re-landed FP-free: a
schema's blockDefault supplies the {disallowed substitutions} of every element
and complex type without an explicit block (own block overrides; block="" clears;
intersected with the methods each component admits), so blockDefault="extension"
bars an extension substitution and "#all" bars all, without one namespace's
defaults shadowing another's.

The pure re-keying preserves single-document behaviour exactly (the corpus is
overwhelmingly single-namespace, where {ns}local and bare coincide): all four
XSTS buckets held at vsr=0 / isa=69 / vir=0 / ivi=89 after re-keying alone.
blockDefault then drove invalid-instances-accepted 89 to 81, no false positive
(valid-instances-rejected and valid-schemas-rejected held at 0), no other bucket
moved. An adversarial review exercised same- and cross-namespace substitutions,
no-targetNamespace keys, simple-type restriction, transitive substitution groups,
and blockDefault override/over-block cases, and the prior multi-document
cross-namespace blockDefault over-rejection is now accepted while a same-namespace
blocked substitution is still rejected (precise, not merely permissive).
2026-06-18 12:41:18 +02:00

122 lines
6.8 KiB
Swift

private typealias XSDDerivNode = PureXML.Schema.XSDNode
extension PureXML.Schema.XSDParser {
/// Gathers the derivation-control facts (``DerivationTables``) from a schema's
/// definition containers, building both the bare-keyed tables (for the
/// schema-consistency machinery) and the namespaced (`{ns}local`) tables (for
/// the instance-validity subsystem) in one pass, resolving each container's
/// components through its target namespace and prefix bindings.
static func derivationTables(_ containers: [XSDTree], mainTargetNamespace: String?) -> DerivationTables {
var tables = DerivationTables()
let namespaceMap = resolveContainerNamespaces(containers, mainTargetNamespace: mainTargetNamespace)
for index in containers.indices {
let container = containers[index]
let containerNamespace = namespaceMap[index] ?? mainTargetNamespace
for type in descendants(container, named: "complexType") {
gatherType(type, in: containerNamespace, into: &tables)
}
for type in descendants(container, named: "simpleType") {
gatherSimpleType(type, in: containerNamespace, into: &tables)
}
for element in descendants(container, named: "element") {
gatherElement(element, in: containerNamespace, into: &tables)
}
}
return tables
}
/// The namespaced derivation-table key (`{ns}local`) for a component named
/// `local` in `namespace`, matching ``ComplexValidator/key(_:)``.
static func derivationKey(_ local: String, in namespace: String?) -> String {
PureXML.Schema.ComplexValidator.key(PureXML.Model.QualifiedName(localName: local, namespaceURI: namespace))
}
/// The namespaced key a base/type QName resolves to, given `node`'s in-scope
/// prefix bindings. A prefixed QName uses its prefix's binding; an unprefixed
/// QName the default-namespace binding when declared, else the component's own
/// target namespace.
private static func resolvedKey(of qualified: String, on node: XSDTree, default containerNamespace: String?) -> String {
let bindings = namespaceBindingsInScope(of: node, defaultBindings: [:])
let resolved = XSDDerivNode.prefix(qualified) != nil
? XSDDerivNode.referenceNamespace(qualified, bindings)
: (bindings[""] ?? containerNamespace)
return derivationKey(XSDDerivNode.stripPrefix(qualified), in: resolved)
}
/// Records a named `simpleType`'s restriction derivation and `final` controls.
/// A `simpleType` derives from its `restriction`'s `base`; a `list`/`union`
/// constructs a new type (deriving from `anySimpleType`), so it is left
/// unrecorded, which keeps two independent list/union types correctly
/// non-derivable from one another.
private static func gatherSimpleType(_ type: XSDTree, in namespace: String?, into tables: inout DerivationTables) {
guard let name = XSDDerivNode.attribute(type, "name") else { return }
let finalSet = methodSet(XSDDerivNode.attribute(type, "final"))
if !finalSet.isEmpty { tables.typeFinal[name] = finalSet }
guard let restriction = XSDDerivNode.firstChild(type, named: "restriction"),
let base = XSDDerivNode.attribute(restriction, "base") else { return }
tables.typeDerivation[name] = PureXML.Schema.TypeDerivation(base: XSDDerivNode.stripPrefix(base), method: .restriction)
tables.nsTypeDerivation[derivationKey(name, in: namespace)] = PureXML.Schema.TypeDerivation(
base: resolvedKey(of: base, on: type, default: namespace),
method: .restriction,
)
}
private static func gatherType(_ type: XSDTree, in namespace: String?, into tables: inout DerivationTables) {
guard let name = XSDDerivNode.attribute(type, "name") else { return }
let key = derivationKey(name, in: namespace)
if XSDDerivNode.attribute(type, "abstract") == "true" {
tables.abstractTypes.insert(name)
tables.nsAbstractTypes.insert(key)
}
let block = blockMethods(of: type, admitting: [.extension, .restriction])
if !block.isEmpty {
tables.typeBlock[name] = block
tables.nsTypeBlock[key] = block
}
let finalSet = finalMethods(of: type)
if !finalSet.isEmpty { tables.typeFinal[name] = finalSet }
if let derivation = derivationInfo(type) { tables.typeDerivation[name] = derivation }
if let derivation = namespacedDerivationInfo(type, in: namespace) { tables.nsTypeDerivation[key] = derivation }
}
private static func gatherElement(_ element: XSDTree, in namespace: String?, into tables: inout DerivationTables) {
guard let name = XSDDerivNode.attribute(element, "name") else { return }
let key = derivationKey(name, in: namespace)
if XSDDerivNode.attribute(element, "abstract") == "true" { tables.abstractElements.insert(name) }
let block = blockMethods(of: element, admitting: [.extension, .restriction, .substitution])
if !block.isEmpty {
tables.elementBlock[name] = block
tables.nsElementBlock[key] = block
}
let isGlobal = element.parent.map {
$0.name?.namespaceURI == xsdNamespace && XSDDerivNode.localName($0) == "schema"
} ?? false
if isGlobal {
let finalSet = finalMethods(of: element)
if !finalSet.isEmpty { tables.elementFinal[name] = finalSet }
}
if let type = XSDDerivNode.attribute(element, "type") {
tables.elementTypeNames[name] = XSDDerivNode.stripPrefix(type)
tables.nsElementTypeNames[key] = resolvedKey(of: type, on: element, default: namespace)
}
}
/// The namespaced (`{ns}local`-based) derivation backbone of a complex type:
/// the same `complexContent`/`simpleContent` extension/restriction base as
/// ``derivationInfo(_:)``, but with the base resolved to a namespaced key.
private static func namespacedDerivationInfo(_ type: XSDTree, in namespace: String?) -> PureXML.Schema.TypeDerivation? {
let container = XSDDerivNode.firstChild(type, named: "complexContent")
?? XSDDerivNode.firstChild(type, named: "simpleContent")
guard let container else { return nil }
if let ext = XSDDerivNode.firstChild(container, named: "extension"), let base = XSDDerivNode.attribute(ext, "base") {
return PureXML.Schema.TypeDerivation(base: resolvedKey(of: base, on: type, default: namespace), method: .extension)
}
if let res = XSDDerivNode.firstChild(container, named: "restriction"), let base = XSDDerivNode.attribute(res, "base") {
return PureXML.Schema.TypeDerivation(base: resolvedKey(of: base, on: type, default: namespace), method: .restriction)
}
return nil
}
}