From b3e126c4301973a5c4dfb3c446908b976b8615a1 Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Mon, 8 Jun 2026 13:27:37 +0200 Subject: [PATCH] feat(editor): schema-driven completions and what-is-missing Slice 3 of #94. From the compiled schema, compute exactly what is allowed at an element, for autocomplete and "what's missing". - ContentNFA.follow(after:) returns the precise follow-set: the element-name labels the content automaton can accept next after the children already present, plus whether the content may legally end there. - Schema.Completions reports the allowed next elements, the complete flag (false means a required child is still expected), a wildcard flag, and each declared attribute with its required and present status. - CompletionEngine resolves an element's declared type along a coding path (the global declaration, then each parent's content model) and computes the completions; Schema.Document.completions(at:in:) is the entry over a ranged tree. Tests pin the follow-set as the children accumulate (name then qty then the optional note, complete flipping true), the attribute required/present status, and resolution for a nested element by its coding path. --- Sources/Schema/ContentMatcher.swift | 24 ++++++ Sources/Schema/SchemaDocument.swift | 14 ++++ Sources/Schema/XSDCompletions.swift | 126 ++++++++++++++++++++++++++++ Tests/XSDCompletionTests2.swift | 72 ++++++++++++++++ 4 files changed, 236 insertions(+) create mode 100644 Sources/Schema/XSDCompletions.swift create mode 100644 Tests/XSDCompletionTests2.swift diff --git a/Sources/Schema/ContentMatcher.swift b/Sources/Schema/ContentMatcher.swift index fe8a869..eaa2e1f 100644 --- a/Sources/Schema/ContentMatcher.swift +++ b/Sources/Schema/ContentMatcher.swift @@ -43,6 +43,30 @@ extension PureXML.Schema { return current.contains(accept) } + /// After consuming `names`, the labels the automaton can accept next and + /// whether the content may legally end here. The follow-set: the exact set + /// of element names allowed at this point, for completions and for telling + /// whether something is still required. Returns an empty, not-complete + /// result when the prefix is already invalid. + func follow(after names: [PureXML.Model.QualifiedName]) -> (allowed: [TermLabel], complete: Bool) { + var current = closure([start]) + for name in names { + var next: Set = [] + for state in current { + if let label = states[state].label, let target = states[state].target, label.matches(name) { + next.insert(target) + } + } + if next.isEmpty { return ([], false) } + current = closure(next) + } + var labels: [TermLabel] = [] + for state in current where states[state].target != nil { + if let label = states[state].label { labels.append(label) } + } + return (labels, current.contains(accept)) + } + private func closure(_ seed: Set) -> Set { var seen = seed var stack = Array(seed) diff --git a/Sources/Schema/SchemaDocument.swift b/Sources/Schema/SchemaDocument.swift index dfc3e85..ad0dd50 100644 --- a/Sources/Schema/SchemaDocument.swift +++ b/Sources/Schema/SchemaDocument.swift @@ -58,5 +58,19 @@ public extension PureXML.Schema { ) return PureXML.Validation.XSD.validator().errors(for: .element(root), in: context) } + + /// What the schema allows at the element a coding `path` addresses in + /// `tree`: the next child elements (the content-model follow-set), whether + /// the content may end there, and the declared attributes with their + /// required/present status. For editor completions and "what's missing". + /// Returns nil when the path does not address a declared element. + public func completions(at path: [PureXML.Validation.PathKey], in tree: PureXML.Model.TreeNode) -> Completions? { + guard let node = tree.node(at: path), case let .element(element) = node.node, + let type = CompletionEngine.elementType(at: path, elements: elements, types: types) + else { + return nil + } + return CompletionEngine.completions(for: element, type: type, types: types) + } } } diff --git a/Sources/Schema/XSDCompletions.swift b/Sources/Schema/XSDCompletions.swift new file mode 100644 index 0000000..b72f7f1 --- /dev/null +++ b/Sources/Schema/XSDCompletions.swift @@ -0,0 +1,126 @@ +public extension PureXML.Schema { + /// What a schema allows at an element: the next child elements, whether the + /// content may end here, and the declared attributes. For editor completions + /// and "what's missing". + struct Completions: Sendable, Equatable { + /// Element names allowed as the next child at the current position, in + /// content-model order. A content model with a wildcard (`xs:any`) leaves + /// this empty and sets `allowsAnyElement`. + public var elements: [String] + /// Whether the content may legally end here. When false, a required child + /// is still expected. + public var complete: Bool + /// Whether a wildcard permits arbitrary further elements here. + public var allowsAnyElement: Bool + /// The declared attributes, each with whether it is required and already + /// present on the element. + public var attributes: [AttributeCompletion] + + public init(elements: [String], complete: Bool, allowsAnyElement: Bool, attributes: [AttributeCompletion]) { + self.elements = elements + self.complete = complete + self.allowsAnyElement = allowsAnyElement + self.attributes = attributes + } + } + + /// One declared attribute in a ``Completions``. + struct AttributeCompletion: Sendable, Equatable { + public var name: String + public var required: Bool + public var present: Bool + + public init(name: String, required: Bool, present: Bool) { + self.name = name + self.required = required + self.present = present + } + } + + /// Computes ``Completions`` from the compiled schema: the follow-set of a + /// content model and the resolution of an element's declared type along a + /// coding path. + enum CompletionEngine { + /// The completions for `element` given its declared `type`, resolving + /// references through `types`. + static func completions(for element: PureXML.Model.Element, type: ElementType, types: [String: ElementType]) -> Completions { + guard case let .complex(complex) = resolve(type, types: types) else { + return Completions(elements: [], complete: true, allowsAnyElement: false, attributes: []) + } + let present = Set(element.attributes.map(\.name.localName)) + let attributes = complex.attributes.map { + AttributeCompletion(name: $0.name.localName, required: $0.required, present: present.contains($0.name.localName)) + } + let childNames = element.children.compactMap { child -> PureXML.Model.QualifiedName? in + if case let .element(inner) = child { return inner.name } + return nil + } + switch complex.content { + case let .elementOnly(particle), let .mixed(particle): + let (labels, complete) = ContentNFABuilder.build(particle).follow(after: childNames) + let names = labels.compactMap { if case let .name(name) = $0 { name.description } else { nil } } + let anyElement = labels.contains { if case .any = $0 { true } else { false } } + return Completions(elements: names, complete: complete, allowsAnyElement: anyElement, attributes: attributes) + case .empty, .simpleContent: + return Completions(elements: [], complete: true, allowsAnyElement: false, attributes: attributes) + } + } + + /// Resolves the declared type of the element a coding path addresses, by + /// walking the global declaration then each parent's content model. + static func elementType( + at path: [PureXML.Validation.PathKey], + elements: [String: ElementType], + types: [String: ElementType], + ) -> ElementType? { + guard let first = path.first, var current = elements[first.stringValue] else { return nil } + for step in path.dropFirst() { + guard case let .complex(complex) = resolve(current, types: types), + let childType = childTypes(of: complex)[step.stringValue] + else { + return nil + } + current = childType + } + return current + } + + /// Resolves an `ElementType` to its underlying simple or complex type, + /// following named references. + static func resolve(_ type: ElementType, types: [String: ElementType]) -> ElementType { + var current = type + var guardCount = 0 + while case let .typeReference(name) = current, let next = types[name], guardCount < types.count + 1 { + current = next + guardCount += 1 + } + return current + } + + /// The child element declarations of a complex type's content model, keyed + /// by the qualified-name description used in coding paths. + private static func childTypes(of complex: ComplexType) -> [String: ElementType] { + switch complex.content { + case let .elementOnly(particle), let .mixed(particle): + var result: [String: ElementType] = [:] + collect(particle.term, into: &result) + return result + case .empty, .simpleContent: + return [:] + } + } + + private static func collect(_ term: Term, into result: inout [String: ElementType]) { + switch term { + case let .element(name, type): + if let type { result[name.description] = type } + case let .group(group): + for member in group.particles { + collect(member.term, into: &result) + } + case .wildcard: + break + } + } + } +} diff --git a/Tests/XSDCompletionTests2.swift b/Tests/XSDCompletionTests2.swift new file mode 100644 index 0000000..1cc39bd --- /dev/null +++ b/Tests/XSDCompletionTests2.swift @@ -0,0 +1,72 @@ +@testable import PureXML +import Testing + +/// Schema-driven completions: the exact follow-set of allowed next elements, +/// whether content may end, and attribute required/present status. The basis for +/// editor autocomplete and "what's missing". +@Suite("XSD completions") +struct XSDCompletionTests2 { + private let xsd = """ + + + + + + + + + + + + + """ + + private func completions(_ xml: String) throws -> PureXML.Schema.Completions? { + let schema = try PureXML.Schema.Document(xsd) + let (tree, _) = PureXML.readTree(xml) + return schema.completions(at: [.element("order")], in: tree) + } + + @Test("The follow-set is the exact next allowed element") + func test_followSet() throws { + #expect(try completions("")?.elements == ["name"]) + #expect(try completions("n")?.elements == ["qty"]) + #expect(try completions("n1")?.elements == ["note"]) + } + + @Test("complete reflects whether a required child is still expected") + func test_complete() throws { + #expect(try completions("n")?.complete == false) + #expect(try completions("n1")?.complete == true) + } + + @Test("Attribute completions carry required and present status") + func test_attributes() throws { + let attrs = try #require(try completions("")?.attributes) + #expect(attrs == [.init(name: "id", required: true, present: false)]) + let present = try #require(try completions("")?.attributes) + #expect(present == [.init(name: "id", required: true, present: true)]) + } + + @Test("Completions resolve for a nested element by its coding path") + func test_nested() throws { + let nestedXsd = """ + + + + + + + + + + + + """ + let schema = try PureXML.Schema.Document(nestedXsd) + let (tree, _) = PureXML.readTree("") + let here = schema.completions(at: [.element("root"), .element("item")], in: tree) + #expect(here?.elements == ["a"]) + #expect(here?.complete == false) + } +}