Merge completions slice 3 (#94): schema-driven expected-here

This commit is contained in:
Mihaela Mihaljevic 2026-06-08 13:27:37 +02:00
commit 1e89790e87
4 changed files with 236 additions and 0 deletions

View File

@ -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<Int> = []
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<Int>) -> Set<Int> {
var seen = seed
var stack = Array(seed)

View File

@ -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)
}
}
}

View File

@ -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
}
}
}
}

View File

@ -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 = """
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="order">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="qty" type="xs:integer"/>
<xs:element name="note" type="xs:string" minOccurs="0"/>
</xs:sequence>
<xs:attribute name="id" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>
"""
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("<order id='1'></order>")?.elements == ["name"])
#expect(try completions("<order><name>n</name></order>")?.elements == ["qty"])
#expect(try completions("<order><name>n</name><qty>1</qty></order>")?.elements == ["note"])
}
@Test("complete reflects whether a required child is still expected")
func test_complete() throws {
#expect(try completions("<order><name>n</name></order>")?.complete == false)
#expect(try completions("<order><name>n</name><qty>1</qty></order>")?.complete == true)
}
@Test("Attribute completions carry required and present status")
func test_attributes() throws {
let attrs = try #require(try completions("<order></order>")?.attributes)
#expect(attrs == [.init(name: "id", required: true, present: false)])
let present = try #require(try completions("<order id='1'></order>")?.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 = """
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType><xs:sequence>
<xs:element name="item">
<xs:complexType><xs:sequence>
<xs:element name="a" type="xs:string"/>
</xs:sequence></xs:complexType>
</xs:element>
</xs:sequence></xs:complexType>
</xs:element>
</xs:schema>
"""
let schema = try PureXML.Schema.Document(nestedXsd)
let (tree, _) = PureXML.readTree("<root><item></item></root>")
let here = schema.completions(at: [.element("root"), .element("item")], in: tree)
#expect(here?.elements == ["a"])
#expect(here?.complete == false)
}
}