Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ All notable changes to GoTTP will be documented in this file.
### Changed (breaking: matching)
- **Indented template lines match the exact indent**: a template line's leading whitespace was turned into `[ \t]+`, so a line indented by two spaces also matched data indented by one space, four spaces or a tab. Python TTP rebuilds the indent verbatim, and gottp now does the same: two spaces match exactly two spaces, and a tab matches only a tab. Unindented lines are unchanged, and so is whitespace inside a line, which still matches any run of spaces and tabs. Templates that relied on the loose match need their indent to match the data. Templates saved with `SaveCompiledTemplate` keep the regex they were compiled with until they are compiled again. (#30)

### Changed (stricter YANG validation)
These fixes make `ParseWithValidation` report problems it used to pass, so output that was `Valid=true` can now be `Valid=false`. Parsed data is unchanged; only `ValidationResults` differ.
- **Integer leaves reject fractional numbers**: `12.5` no longer validates as a `uint8` (RFC 7950 9.2). A whole `float64` such as `12.0` (what a JSON round trip makes of an int) is still accepted. (#50)
- **`pattern` is enforced**: a string leaf must match all its patterns as a whole value, with XSD regex semantics (RFC 7950 9.4.5), and `modifier invert-match` is honoured. Patterns RE2 can't express (`\i`, `\c`, `\p{IsBlock}`, class subtraction) give a warning, once per group, instead of passing silently. (#55)
- **Enumeration and identityref membership is checked**: an enum leaf takes only its declared names, and an identityref only an identity derived from its base, in the RFC 7951 `module:identity` form (the module may be left out for an identity in the leaf's own module). A `union` with an enum member no longer accepts any string. (#56)
- **A `yang=` path at the wrong level is an error**: when none of a group's fields is defined under its path (for example the container instead of the list each match maps to), the result is `Valid=false` with one error that suggests the right path, instead of `Valid=true` with only warnings. (#57)
- **Leaves under `choice`/`case` are validated**: they were reported as "not defined" warnings and never type-checked. (#59)

## [v0.1.13] - 2026-09-03

### Fixed
Expand Down
Binary file modified editor/gottp.wasm
Binary file not shown.
Binary file modified editor/js/gottp.wasm
Binary file not shown.
3 changes: 2 additions & 1 deletion internal/yang/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ type ValidationError struct {
Field string
Line int
Column int

once bool // a warning reported once per Validate call, not per item
}

// Error implements the error interface
Expand All @@ -36,4 +38,3 @@ func (r *ValidationResult) HasErrors() bool {
func (r *ValidationResult) HasWarnings() bool {
return len(r.Warnings) > 0
}

22 changes: 19 additions & 3 deletions internal/yang/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ type ModuleSet struct {
mu sync.RWMutex
modules map[string]*yang.Module
schemas map[string]*yang.Entry
mset *yang.Modules // Shared Modules instance for dependency resolution
addedModules map[string]bool // Track which modules we've added (for error messages)
prefixToModule map[string]string // Map prefix to module name (e.g., "cms" -> "example-cable-modem-state")
mset *yang.Modules // Shared Modules instance for dependency resolution
addedModules map[string]bool // Track which modules we've added (for error messages)
prefixToModule map[string]string // Map prefix to module name (e.g., "cms" -> "example-cable-modem-state")
patternUses map[string]patternUse // pattern string -> whether it is used with invert-match
}

// NewModuleSet creates a new empty ModuleSet
Expand Down Expand Up @@ -99,6 +100,10 @@ func (ms *ModuleSet) ProcessAllModules() error {
return fmt.Errorf("failed to process YANG modules: %s", strings.Join(errorMsgs, "; "))
}

ms.patternUses = make(map[string]patternUse)
collectPatternModifiers(ms.mset.Modules, ms.patternUses)
collectPatternModifiers(ms.mset.SubModules, ms.patternUses)

// Update stored modules and schemas after processing
for name, module := range ms.mset.Modules {
ms.modules[name] = module
Expand All @@ -117,6 +122,16 @@ func (ms *ModuleSet) ProcessAllModules() error {
return nil
}

// patternModifier reports whether pattern p carries "modifier invert-match"
// in the loaded modules, and whether it is ambiguous because it is used both
// with and without it.
func (ms *ModuleSet) patternModifier(p string) (invert, ambiguous bool) {
ms.mu.RLock()
defer ms.mu.RUnlock()
use := ms.patternUses[p]
return use == patternInverted, use == patternPlain|patternInverted
}

// GetModule retrieves a module by name
func (ms *ModuleSet) GetModule(name string) (*yang.Module, bool) {
ms.mu.RLock()
Expand Down Expand Up @@ -161,6 +176,7 @@ func (ms *ModuleSet) Clear() {
ms.addedModules = make(map[string]bool)
ms.prefixToModule = make(map[string]string)
ms.mset = yang.NewModules() // Reset the shared Modules instance
ms.patternUses = nil
}

// FindSchemaByPath finds a schema entry by YANG path
Expand Down
293 changes: 293 additions & 0 deletions internal/yang/pattern.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,293 @@
package yang

import (
"fmt"
"regexp"
"strings"
"sync"

"github.com/openconfig/goyang/pkg/yang"
)

// YANG pattern statements (RFC 7950 9.4.5) are XML Schema regular
// expressions (XSD 1.0 Part 2, Appendix F). They differ from Go's RE2:
//
// - a pattern matches the whole value; there are no anchors, so ^ and $
// are ordinary characters;
// - "." excludes only \n and \r;
// - \d, \s and \w are Unicode-aware (\w is everything except punctuation,
// separators and "other" characters, so it excludes '_');
// - XSD has \i, \c, Unicode block escapes (\p{IsBasicLatin}) and character
// class subtraction ([a-z-[aeiou]]), which RE2 can't express.
//
// xsdToRE2 translates the subset RE2 can express and returns an error
// naming the construct otherwise.

// Replacements for XSD multi-character escapes. "in" is the text to use
// inside a positive character class; complement is set when the escape is
// the complement of a set, which RE2 can't put inside another class.
var xsdClassEscapes = map[byte]struct {
out string // replacement outside a character class
in string // set members, for use inside a class
complement bool // in is the set to exclude, not include
}{
'd': {`\p{Nd}`, `\p{Nd}`, false},
'D': {`\P{Nd}`, `\P{Nd}`, false},
's': {`[ \t\n\r]`, ` \t\n\r`, false},
'S': {`[^ \t\n\r]`, ` \t\n\r`, true},
'w': {`[^\p{P}\p{Z}\p{C}]`, `\p{P}\p{Z}\p{C}`, true},
'W': {`[\p{P}\p{Z}\p{C}]`, `\p{P}\p{Z}\p{C}`, false},
}

// XSD single-character escapes (\n, \r, \t and the metacharacters).
const xsdSingleEscapes = `nrt\|.-^?*+{}()[]`

// xsdToRE2 translates an XSD regular expression to an anchored Go regexp.
func xsdToRE2(p string) (string, error) {
var b strings.Builder
b.WriteString(`\A(?:`)
for i := 0; i < len(p); i++ {
c := p[i]
switch c {
case '\\':
if i+1 >= len(p) {
return "", fmt.Errorf("trailing backslash")
}
esc, n, err := translateEscape(p[i+1:], false)
if err != nil {
return "", err
}
b.WriteString(esc.out)
i += n
case '[':
cls, n, err := translateClass(p[i:])
if err != nil {
return "", err
}
b.WriteString(cls)
i += n - 1
case '.':
b.WriteString(`[^\n\r]`)
case '^', '$':
b.WriteByte('\\')
b.WriteByte(c)
case '(':
if i+1 < len(p) && p[i+1] == '?' {
return "", fmt.Errorf("'(?' is not XSD regex syntax")
}
b.WriteByte(c)
default:
b.WriteByte(c)
}
}
b.WriteString(`)\z`)
return b.String(), nil
}

type translatedEscape struct {
out string
in string
complement bool
}

// translateEscape translates the escape that follows a backslash. s starts
// after the backslash; n is the number of bytes of s consumed.
func translateEscape(s string, inClass bool) (translatedEscape, int, error) {
c := s[0]
if e, ok := xsdClassEscapes[c]; ok {
return translatedEscape{e.out, e.in, e.complement}, 1, nil
}
if strings.IndexByte(xsdSingleEscapes, c) >= 0 {
esc := `\` + string(c)
return translatedEscape{esc, esc, false}, 1, nil
}
switch c {
case 'p', 'P':
end := strings.IndexByte(s, '}')
if len(s) < 2 || s[1] != '{' || end < 0 {
return translatedEscape{}, 0, fmt.Errorf("malformed \\%c escape", c)
}
name := s[2:end]
if strings.HasPrefix(name, "Is") {
return translatedEscape{}, 0, fmt.Errorf("block escape \\%c{%s} (a Unicode block) is not supported by RE2", c, name)
}
esc := s[:end+1]
return translatedEscape{`\` + esc, `\` + esc, false}, end + 1, nil
case 'i', 'I', 'c', 'C':
return translatedEscape{}, 0, fmt.Errorf("XML name escape \\%c is not supported by RE2", c)
}
return translatedEscape{}, 0, fmt.Errorf("unknown escape \\%c", c)
}

// translateClass translates the character class at the start of s and
// returns the number of bytes consumed.
func translateClass(s string) (string, int, error) {
i := 1
negated := false
if i < len(s) && s[i] == '^' {
negated = true
i++
}
var members strings.Builder
var complements []string
for first := true; ; first = false {
if i >= len(s) {
return "", 0, fmt.Errorf("unterminated character class")
}
c := s[i]
switch {
case c == ']' && !first:
i++
return buildClass(negated, members.String(), complements, s[:i])
case c == '-' && i+1 < len(s) && s[i+1] == '[':
return "", 0, fmt.Errorf("character class subtraction is not supported by RE2")
case c == '\\':
if i+1 >= len(s) {
return "", 0, fmt.Errorf("trailing backslash")
}
esc, n, err := translateEscape(s[i+1:], true)
if err != nil {
return "", 0, err
}
if esc.complement {
complements = append(complements, esc.in)
} else {
members.WriteString(esc.in)
}
i += 1 + n
case c == '[' || c == '^':
// Literal in XSD; escaped so RE2 doesn't read [:alpha:].
members.WriteByte('\\')
members.WriteByte(c)
i++
default:
members.WriteByte(c)
i++
}
}
}

func buildClass(negated bool, members string, complements []string, src string) (string, int, error) {
if len(complements) == 0 {
if negated {
return "[^" + members + "]", len(src), nil
}
return "[" + members + "]", len(src), nil
}
if negated {
// [^a\w] is (not a) and (not \w): an intersection RE2 can't write.
return "", 0, fmt.Errorf("negated character class %s with \\S or \\w is not supported by RE2", src)
}
alts := make([]string, 0, len(complements)+1)
if members != "" {
alts = append(alts, "["+members+"]")
}
for _, c := range complements {
alts = append(alts, "[^"+c+"]")
}
return "(?:" + strings.Join(alts, "|") + ")", len(src), nil
}

// compiledPattern is a translated, compiled YANG pattern, or the reason it
// can't be checked.
type compiledPattern struct {
re *regexp.Regexp
err error
}

var patternCache sync.Map // XSD pattern -> *compiledPattern

func compilePattern(p string) *compiledPattern {
if cp, ok := patternCache.Load(p); ok {
return cp.(*compiledPattern)
}
cp := &compiledPattern{}
if expr, err := xsdToRE2(p); err != nil {
cp.err = err
} else if cp.re, err = regexp.Compile(expr); err != nil {
cp.err = fmt.Errorf("RE2 rejects the translation: %v", err)
}
actual, _ := patternCache.LoadOrStore(p, cp)
return actual.(*compiledPattern)
}

// patternFailure is a pattern a value failed, for an error message.
type patternFailure struct {
pattern string
invert bool
}

// checkPatterns checks s against every pattern of yangType (RFC 7950
// 9.4.5: all must hold). It returns the first pattern that fails. Patterns
// that can't be checked are skipped; uncheckablePatterns reports them.
func (v *Validator) checkPatterns(s string, yangType *yang.YangType) (patternFailure, bool) {
for _, p := range yangType.Pattern {
cp := compilePattern(p)
if cp.err != nil {
continue
}
invert, ambiguous := v.moduleSet.patternModifier(p)
if ambiguous {
continue
}
if cp.re.MatchString(s) == invert {
return patternFailure{p, invert}, false
}
}
return patternFailure{}, true
}

// uncheckablePatterns describes the patterns of yangType (and of its union
// members) that can't be checked.
func (v *Validator) uncheckablePatterns(yangType *yang.YangType) []string {
if yangType == nil {
return nil
}
var out []string
for _, p := range yangType.Pattern {
if cp := compilePattern(p); cp.err != nil {
out = append(out, fmt.Sprintf("pattern '%s' cannot be checked: %v", p, cp.err))
} else if _, ambiguous := v.moduleSet.patternModifier(p); ambiguous {
out = append(out, fmt.Sprintf("pattern '%s' cannot be checked: the loaded modules use it both with and without 'modifier invert-match'", p))
}
}
for _, member := range yangType.Type {
out = append(out, v.uncheckablePatterns(member)...)
}
return out
}

// collectPatternModifiers records which pattern strings carry
// "modifier invert-match". goyang flattens a type's patterns to strings and
// drops the modifier, so it is recovered from the parsed statements.
func collectPatternModifiers(mods map[string]*yang.Module, into map[string]patternUse) {
var walk func(s *yang.Statement)
walk = func(s *yang.Statement) {
if s == nil {
return
}
if s.Keyword == "pattern" {
use := patternPlain
for _, sub := range s.SubStatements() {
if sub.Keyword == "modifier" && sub.Argument == "invert-match" {
use = patternInverted
}
}
into[s.Argument] |= use
}
for _, sub := range s.SubStatements() {
walk(sub)
}
}
for _, m := range mods {
walk(m.Source)
}
}

// patternUse records how a pattern string is used across the loaded modules.
type patternUse uint8

const (
patternPlain patternUse = 1 << iota // used without invert-match
patternInverted // used with invert-match
)
Loading
Loading