PureXML/Sources/XPath/CoreFunctions.swift
Mihaela Mihaljevic d83e5a88ce feat(xpath): expression engine and the four-type model
Compile and evaluate full XPath 1.0 expressions, not just location paths.
Add the four-type Value (node-set, boolean, number, string) with the spec's
coercion rules and canonical number formatting, a recursive-descent parser
for the operator grammar (or/and, equality, relational, additive,
multiplicative, unary minus, union) whose grammatical position disambiguates
* and the operator keywords, function calls, variable references, and filter
expressions. Predicates are now arbitrary expressions (a numeric predicate
is a position test). Comparison follows the node-set quantification rules.
Query gains value/number/string/boolean accessors and a $variable binding
map; the core functions last, position, count, not, true, false, boolean,
number, and string ship with it.

Closes #42
2026-06-08 05:33:13 +02:00

31 lines
1.5 KiB
Swift

extension PureXML.XPath {
/// The core XPath functions tied to the four-type model and predicates:
/// `last`, `position`, `count`, `not`, `true`, `false`, `boolean`, `number`,
/// and `string`. The broader library (string, node, and number functions)
/// extends this table.
enum CoreFunctions {
static let table = FunctionTable([
"last": { _, context in .number(Double(context.size)) },
"position": { _, context in .number(Double(context.position)) },
"count": { arguments, _ in
guard let nodes = arguments.first?.nodes else {
throw PureXML.XPath.QueryError.invalidArguments("count() requires a node-set")
}
return .number(Double(nodes.count))
},
"not": { arguments, _ in .boolean(!(arguments.first?.boolean ?? false)) },
"true": { _, _ in .boolean(true) },
"false": { _, _ in .boolean(false) },
"boolean": { arguments, _ in .boolean(arguments.first?.boolean ?? false) },
"number": { arguments, context in
if let first = arguments.first { return .number(first.number) }
return .number(PureXML.XPath.Value.parseNumber(context.node.stringValue))
},
"string": { arguments, context in
if let first = arguments.first { return .string(first.string) }
return .string(context.node.stringValue)
},
])
}
}