schematron

package
v0.0.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: AGPL-3.0 Imports: 13 Imported by: 0

Documentation

Overview

Package schematron provides a minimal ISO Schematron loader and evaluator scoped to the subset of constructs the EN 16931 and XRechnung rule sets use. It is not a general-purpose Schematron implementation: abstract patterns, phases-with-roles, diagnostics, and let-substitution beyond a single namespace's worth of bindings are intentionally out of scope.

XPath subset

Rules are compiled and evaluated against github.com/antchfx/xpath, an XPath 1.0 engine that also implements a handful of XPath 2.0 builtins. A lightweight rewriter in xpath_rewrite.go bridges the remaining gap for the constructs the bundled rule sets rely on.

Supported (compiled and evaluated):

  • XPath 1.0 in full: path expressions, predicates, axes, arithmetic, comparison, boolean and node-set operators.
  • XPath 2.0 builtins provided by antchfx/xpath: matches, replace, string-join, lower-case, reverse, ends-with.
  • XPath 2.0 builtins emulated by the rewriter: upper-case (exact whenever the result is compared with ASCII text), xs:decimal / xs:integer / xs:double / xs:string / xs:date / xs:dateTime (cast → number or string), exists (→ boolean), abs (algebraic identity), count(distinct-values(X)) = 1 (uniqueness idiom), a top-level "every|some $V in PATH satisfies EXPR" (PATH is evaluated in the rule context and EXPR once per item in Go, with $V an element's path where it starts a step outside a predicate and its string value elsewhere), the same over a literal sequence anywhere (→ disjunction / conjunction), "EXPR = (a, b, c)" and "EXPR != (a, b, c)" (→ disjunction / conjunction of per-item comparisons), bare sequence "(X, Y, Z)" in boolean context (→ disjunction of boolean coercions), path-step cast like ".[pred]/xs:decimal(child)" (cast elided so implicit coercion at the surrounding operator does the work), round(...) (wrapped in number() to dodge an antchfx/xpath bug that emits int instead of float64).

Unsupported (rule is skipped; the evaluator surfaces the gap via SkippedRule):

  • tokenize(): regex-based string splitting with no XPath 1.0 equivalent.
  • distinct-values() outside the "count = 1" idiom.
  • "for $x in EXPR return BODY" expressions.
  • "if (COND) then A else B" conditional expressions.
  • string-to-codepoints() and other Unicode helpers.
  • User-defined xsl:function helpers (e.g. u:decimalOrZero).
  • xs:duration, xs:gYear, xs:* casts with no numeric equivalent.

Callers that need full XPath 2.0 coverage of skipped rules should pipe the embedded CII XML through an external XSLT 2.0 processor and treat those results as authoritative for the unsupported constructs.

Concurrency

A Schema is immutable once Load returns. Concurrent readers are safe. Mutating a Schema after Load is undefined.

Index

Constants

View Source
const SchematronNamespace = "http://purl.oclc.org/dsdl/schematron"

SchematronNamespace is the canonical ISO Schematron namespace URI.

Variables

View Source
var (
	// ErrSchemaParse signals that a Schematron document is not
	// well-formed XML or violates the structural shape the loader
	// expects (missing sch:schema root, etc.).
	ErrSchemaParse = errors.New("schematron: schema parse failed")

	// ErrUnresolvedRef signals that a phase references a pattern
	// that does not appear in the loaded schema, or a similar dangling
	// link surfaced during the post-load check.
	ErrUnresolvedRef = errors.New("schematron: unresolved reference")

	// ErrUnsupportedConstruct signals that the loader encountered a
	// Schematron construct outside the documented subset (abstract
	// patterns, diagnostics with phases, etc.). Returned eagerly so
	// future spec evolutions surface as a load failure rather than as
	// silent evaluation gaps.
	ErrUnsupportedConstruct = errors.New("schematron: unsupported construct")

	// ErrIncludeLoop signals that sch:include references form a
	// cycle. Loader rejects this rather than trying to break it.
	ErrIncludeLoop = errors.New("schematron: include cycle")
)

Sentinel errors returned by the loader. Wrap with fmt.Errorf and %w when annotating with the offending file so callers can keep using errors.Is.

Functions

func Validate

func Validate(ctx context.Context, schema *Schema, payload []byte, opts ...EvalOption) ([]Violation, []SkippedRule, error)

Validate parses payload, walks schema's active patterns, and returns one Violation per assertion that fired on a context match. Rule selection follows the Schematron convention: within a pattern, the first rule whose context matches a node wins for that node; later rules in the same pattern skip that node.

The skipped return lists every assertion or report whose XPath could not compile or evaluate. The evaluator silently drops these so a single unsupported construct does not abort the pass; the list lets callers audit the coverage gap.

payload must be well-formed XML. A parse error surfaces as the third return value distinct from violations so callers can tell "ran-but-failed-rules" apart from "could-not-run".

Types

type Assertion

type Assertion struct {
	ID      string
	Test    string
	Flag    string
	Role    string
	Message string
	Negate  bool
}

Assertion captures one sch:assert or sch:report. The Negate flag flips the boolean interpretation so the evaluator can dispatch uniformly: an assertion fires when its evaluated value differs from the not-firing convention. Concretely:

  • sch:assert fires when test() == false (Negate=false).
  • sch:report fires when test() == true (Negate=true).

type EvalOption

type EvalOption func(*evalOpts)

EvalOption configures Validate. Closures must be safe to call from any goroutine.

func WithPhase

func WithPhase(id string) EvalOption

WithPhase restricts evaluation to the patterns activated by the named phase. When the option is absent, Validate runs every pattern in source order.

func WithRuleOverrides

func WithRuleOverrides(overrides map[string]RuleOverride) EvalOption

WithRuleOverrides registers per-assertion Go evaluators that take precedence over the bundled XPath engine. The map key is the assertion's id attribute (e.g. "BR-DE-19"); the value is the Go function that decides whether the rule passes for a given context node. Unknown ids in the map are ignored.

Use this to handle rules whose XPath the engine cannot compile or evaluate. The companion package cii_schematron ships cii_schematron.BuiltinRuleOverrides with overrides for known holes in the EN 16931 / XRechnung rule sets.

type Let

type Let struct {
	Name  string
	Value string
}

Let is a sch:let binding: a name plus an XPath expression. The expression is kept as text; Validate substitutes it into the expressions that reference it before compilation.

type NamespaceDecl

type NamespaceDecl struct {
	Prefix string
	URI    string
}

NamespaceDecl binds a prefix to a namespace URI for XPath evaluation. Source order is preserved; downstream code that duplicates a prefix sees the last binding win.

type Pattern

type Pattern struct {
	ID    string
	Title string
	// Rules walks the pattern's sch:rule children in source order.
	Rules []*Rule
	// Lets carries pattern-scoped sch:let declarations. They
	// evaluate against the document root before any rule in the
	// pattern runs and the resulting literals substitute into the
	// rule contexts and assertion tests.
	Lets []Let
}

Pattern groups related rules. Patterns can be nested inside phases for staged validation; abstract patterns (with attribute abstract="true") are out of scope per the documented subset.

type Phase

type Phase struct {
	ID string
	// Active lists pattern ids the phase enables, in source order.
	Active []string
	// Lets carries phase-scoped sch:let bindings. Evaluation merges
	// these with the schema-level Lets when the phase is selected.
	Lets []Let
}

Phase names a set of active patterns. EN 16931 ships a single phase that activates every pattern; XRechnung ships multiple so callers can validate only the German-specific subset.

type Rule

type Rule struct {
	// Context is the raw XPath expression off the sch:rule
	// context attribute, kept as text; [Validate] compiles it via
	// antchfx/xpath.
	Context string
	// Asserts and Reports are kept separate so evaluation can apply
	// the inverted semantics without re-checking element kind.
	Asserts []*Assertion
	Reports []*Assertion
	// Lets carries rule-scoped sch:let bindings. Evaluation
	// resolves these on each context match before running the
	// assertions and reports.
	Lets []Let
}

Rule binds a context XPath to a list of assertions. Every assert fires when its test evaluates to false on a context match; every report fires when its test evaluates to true.

type RuleOverride

type RuleOverride func(ctx context.Context, node *xmlquery.Node) (bool, error)

RuleOverride is a Go implementation of one Schematron assertion or report test. It receives the matched context node and returns the boolean that the rule's XPath test expression would have produced:

  • For sch:assert: true means the rule passes (no violation).
  • For sch:report: true means the rule fires (one violation).

Overrides exist so callers can handle rules whose XPath uses XPath 2.0 constructs the bundled engine does not implement (for/return, if/then/else, string-to-codepoints). The evaluator consults the override map before attempting XPath compilation; a registered override always takes precedence. When an override returns an error, the rule lands in the skipped slice with the error's message as the reason, matching the shape of an XPath skip.

Implementations must be safe to call from any goroutine; Validate may invoke the same override concurrently against different context nodes when patterns share a rule id.

type Schema

type Schema struct {
	// Title is the value of the optional sch:title element. Empty
	// when the schema omits it.
	Title string
	// QueryBinding records the queryBinding attribute on sch:schema.
	// EN 16931 and XRechnung use "xslt2".
	// TODO: enforce "xslt2" at load; nothing checks the value yet.
	QueryBinding string
	// Namespaces collects every sch:ns child in source order.
	// Evaluation uses these to resolve XPath prefixes.
	Namespaces []NamespaceDecl
	// Patterns indexes top-level sch:pattern declarations by their
	// id. Pattern order is preserved in PatternOrder so callers that
	// run "all patterns" semantics walk them in the same order the
	// schema author wrote them.
	Patterns     map[string]*Pattern
	PatternOrder []string
	// Phases indexes sch:phase declarations by their id. Empty when
	// the schema declares no phases (the validator then runs every
	// pattern).
	Phases map[string]*Phase
	// Lets carries top-level sch:let bindings that apply to every
	// rule in the schema. Rule-scoped lets live on the [Rule] itself.
	Lets []Let
}

Schema is the loaded representation of one sch:schema document plus every schema reachable through sch:include during the load. Values must be treated as immutable after Load returns.

func Load

func Load(ctx context.Context, fsys fs.FS, rootPath string) (*Schema, error)

Load reads the Schematron document at rootPath from fsys, resolves every sch:include, and returns a fully-linked Schema. References from phase/active to missing patterns surface as ErrUnresolvedRef after the load.

fsys must be a forward-slash filesystem (the io/fs convention); embed.FS, os.DirFS, and testing/fstest.MapFS all qualify. Path resolution for includes is relative to the importing schema's location.

The loader checks ctx.Err() at each include boundary so callers that load large schema sets can bound provisioning time.

type SkippedRule

type SkippedRule struct {
	RuleID  string
	Context string
	Reason  string
}

SkippedRule captures one assertion or report that could not be evaluated. The evaluator silently skips such rules so an unsupported XPath construct in one rule does not abort the whole pass; this surface lets callers audit coverage instead of guessing from missing violations.

type Violation

type Violation struct {
	RuleID  string
	Flag    string
	Role    string
	Path    string
	Message string
	// Negate reflects the source kind: false for sch:assert, true
	// for sch:report. Useful when callers want to render the two
	// shapes with different prefixes.
	Negate bool
}

Violation is one Schematron assertion firing on a context node. RuleID and Flag/Role come from the source schema; Path locates the context node in the document for diagnostics.

func (Violation) Error

func (v Violation) Error() string

Error implements the error interface so callers can return Violations alongside other errors.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址