6 Commits

Author SHA1 Message Date
unkin-agent f59de880e3 Merge remote-tracking branch 'origin/benvin/gentypes-guard-attrnames' into benvin/gentypes-guard-regex
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-10 00:16:23 +11:00
unkin-agent 24000df1e0 Merge remote-tracking branch 'origin/benvin/gentypes-guard-titlepatterns' into benvin/gentypes-guard-attrnames
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-10 00:16:21 +11:00
unkin-agent b7d625894f Merge remote-tracking branch 'origin/benvin/gentypes-shellvar' into benvin/gentypes-guard-titlepatterns
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
2026-11-10 00:15:54 +11:00
unkin-agent 9b3a1ce2be Validate every regex literal as Ruby's parser does
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
Ruby compiles each non-interpolated regex literal while parsing a file, so an
invalid one fails the file even in a method that never runs. Check every
literal in each loaded file, string interpolations included, with an Onigmo
validator that now covers named groups, back references, POSIX brackets,
\u, \x and \p escapes, atomic and option-only groups, literal braces and
extended mode; anything it cannot prove skips.
2026-11-10 00:03:22 +11:00
unkin-agent 27eea3d175 Downcase and validate genclass names as openvox does
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
Type, attribute and provider names are downcased, and a name whose generated
constant const_set rejects skips: types and properties need a leading letter,
Parameter and Provider constants accept any [a-z0-9_] tail.
2026-11-09 23:39:07 +11:00
unkin-agent 419e2f88ce Name resource_api title pattern groups as Regexp#names does
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/lint Pipeline was successful
Scan the pattern the way Onigmo does: escapes, character classes, (?#...)
comments and extended-mode comments hold no groups, names are unique in
first-appearance order, and names or references w10k cannot model skip.
2026-11-09 23:28:18 +11:00
6 changed files with 689 additions and 147 deletions
+510 -125
View File
@@ -928,27 +928,89 @@ func (p *parser) regexInterp(t token) (rval, error) {
if err != nil {
return rval{}, err
}
if err := onigCheck(src, strings.Contains(t.flags, "i")); err != nil {
if err := onigCheck(src, t.flags); err != nil {
return rval{}, err
}
return rval{k: vRegex, re: regex{src, t.flags}}, nil
}
// onig checks a regex source against a subset of Onigmo's Ruby syntax that Ruby 3.3 compiles without error: literals,
// punctuation and class escapes, anchors, simple character classes, groups, lookarounds, alternation and
// quantifiers. A look-behind holds alternatives of fixed-length atoms only, with case folding off.
type onig struct {
s string
i int
depth int
// checkRegexes validates every regex literal Ruby compiles while parsing the file toks came from, as a SyntaxError for
// any invalid one fails the whole file; an interpolated literal compiles only when it runs.
func checkRegexes(toks []token, depth int) error {
if depth > maxDepth {
return errLimit
}
for _, t := range toks {
if t.kind == tRegex && !regexInterpolated(t.text) {
if err := onigCheck(t.text, t.flags); err != nil {
return fmt.Errorf("line %d: %w", t.line, err)
}
}
for _, pt := range t.parts {
if !pt.code {
continue
}
sub, err := lex(pt.text)
if err == nil {
err = checkRegexes(sub, depth+1)
}
if err != nil {
return fmt.Errorf("line %d: %w", t.line, err)
}
}
}
return nil
}
func onigCheck(src string, icase bool) error {
o := &onig{s: src}
err := o.alt(icase, false)
if err == nil && o.i < len(o.s) {
err = fmt.Errorf("unmatched close parenthesis")
// regexInterpolated reports an unescaped #{, #@ or #$ in a regex literal's source.
func regexInterpolated(s string) bool {
for i := 0; i+1 < len(s); i++ {
switch {
case s[i] == '\\':
i++
case s[i] == '#' && strings.IndexByte("{@$", s[i+1]) >= 0:
return true
}
}
return false
}
// onig checks a regex source against a subset of Onigmo's Ruby syntax that Ruby 3.3 compiles without error: literals,
// escapes, anchors, character classes with POSIX brackets, plain, named, atomic and option groups, lookarounds,
// back references, alternation, quantifiers and extended mode. A look-behind holds alternatives of fixed-length atoms
// only, with case folding off.
type onig struct {
s string
i int
depth int
ext bool
groups int
named bool
names map[string]bool
}
// onigCheck validates src compiled with flags, as Ruby does for a regex literal or Regexp.new.
func onigCheck(src, flags string) error {
err := func() error {
if strings.Trim(flags, "imxon") != "" || strings.Contains(flags, "n") && (strings.Contains(src, `\u`) || strings.ContainsFunc(src, func(r rune) bool { return r >= utf8.RuneSelf })) {
return fmt.Errorf("unsupported flags %q", flags)
}
names, groups, err := onigGroups(regex{src, flags})
if err != nil {
return err
}
o := &onig{s: src, ext: strings.Contains(flags, "x"), groups: groups, named: len(names) > 0, names: map[string]bool{}}
if o.named {
o.groups = 0
}
if err := o.alt(strings.Contains(flags, "i"), false); err != nil {
return err
}
if o.i < len(o.s) {
return fmt.Errorf("unmatched close parenthesis")
}
return nil
}()
if err != nil {
return fmt.Errorf("regex %q: %w", src, err)
}
@@ -962,6 +1024,22 @@ func (o *onig) peek(off int) byte {
return 0
}
// skipSpace skips extended-mode whitespace and # comments.
func (o *onig) skipSpace() {
for o.ext && o.i < len(o.s) {
switch o.s[o.i] {
case ' ', '\t', '\n', '\r', '\f', '\v':
o.i++
case '#':
for o.i < len(o.s) && o.s[o.i] != '\n' {
o.i++
}
default:
return
}
}
}
func (o *onig) alt(icase, behind bool) error {
for {
n, err := o.seq(icase, behind)
@@ -981,12 +1059,20 @@ func (o *onig) alt(icase, behind bool) error {
// seq parses one alternative and returns its length in characters.
func (o *onig) seq(icase, behind bool) (int, error) {
n := 0
for o.i < len(o.s) && o.s[o.i] != '|' && o.s[o.i] != ')' {
for o.skipSpace(); o.i < len(o.s) && o.s[o.i] != '|' && o.s[o.i] != ')'; o.skipSpace() {
w, repeatable, err := o.atom(icase, behind)
if err != nil {
return 0, err
}
if c := o.peek(0); c == '*' || c == '+' || c == '?' || c == '{' {
o.skipSpace()
brace, err := false, error(nil)
if o.peek(0) == '{' {
brace, err = o.interval()
}
if err != nil {
return 0, err
}
if c := o.peek(0); c == '*' || c == '+' || c == '?' || brace {
if !repeatable {
return 0, fmt.Errorf("invalid target of repeat operator")
}
@@ -1004,6 +1090,22 @@ func (o *onig) seq(icase, behind bool) (int, error) {
return n, nil
}
// interval reports whether a { at the cursor starts {n}, {n,}, {,m} or {n,m}; any other { is a literal, which
// extended mode makes undecided when spaces or comments follow it.
func (o *onig) interval() (bool, error) {
end := strings.IndexByte(o.s[o.i:], '}')
if end < 0 {
return false, nil
}
body := o.s[o.i+1 : o.i+end]
if o.ext && strings.ContainsAny(body, " \t\n\r\f\v#") {
return false, fmt.Errorf("unsupported { in extended mode")
}
lo, hi, comma := strings.Cut(body, ",")
digits := func(s string) bool { return s != "" && strings.Trim(s, "0123456789") == "" }
return digits(lo) && (!comma || hi == "" || digits(hi)) || lo == "" && comma && digits(hi), nil
}
// quantifier consumes one quantifier with an optional lazy or possessive suffix, returning its exact count or -1.
func (o *onig) quantifier() (int, error) {
exact := -1
@@ -1014,27 +1116,35 @@ func (o *onig) quantifier() (int, error) {
}
} else {
end := strings.IndexByte(o.s[o.i:], '}')
if end < 0 {
return 0, fmt.Errorf("unsupported literal {")
}
lo, hi, comma := strings.Cut(o.s[o.i+1:o.i+end], ",")
num := func(s string) (int, bool) {
num := func(s string) (int, error) {
if s == "" {
return 0, nil
}
n, err := strconv.Atoi(s)
return n, err == nil && s == strconv.Itoa(n) && n <= 100000
if err != nil || n > 100000 {
return 0, fmt.Errorf("too big number for repeat range")
}
return n, nil
}
l, err := num(lo)
if err != nil {
return 0, err
}
h, err := num(hi)
if err != nil {
return 0, err
}
l, lok := num(lo)
h, hok := num(hi)
switch {
case !comma && lok:
case !comma:
exact = l
case comma && lok && hi == "", comma && lo == "" && hok:
case comma && lok && hok && l <= h:
default:
return 0, fmt.Errorf("unsupported interval {%s}", o.s[o.i+1:o.i+end])
case hi != "" && l > h:
return 0, fmt.Errorf("upper is smaller than lower in repeat range")
}
o.i += end + 1
if o.peek(0) == '?' {
o.i++
exact = -1
}
}
if c := o.peek(0); c == '*' || c == '+' || c == '?' || c == '{' {
@@ -1047,57 +1157,12 @@ func (o *onig) quantifier() (int, error) {
func (o *onig) atom(icase, behind bool) (int, bool, error) {
switch c := o.s[o.i]; c {
case '(':
if behind {
return 0, false, fmt.Errorf("group in look-behind")
}
if o.depth++; o.depth > 64 {
return 0, false, fmt.Errorf("groups nested too deep")
}
defer func() { o.depth-- }()
o.i++
repeatable, lookbehind := true, false
if o.peek(0) == '?' {
switch {
case o.peek(1) == ':':
o.i += 2
case o.peek(1) == '=' || o.peek(1) == '!':
o.i += 2
repeatable = false
case o.peek(1) == '<' && (o.peek(2) == '=' || o.peek(2) == '!'):
if icase {
return 0, false, fmt.Errorf("look-behind with case folding")
}
o.i += 3
repeatable, lookbehind = false, true
default:
o.i++
on := true
for ; o.peek(0) != ':'; o.i++ {
switch f := o.peek(0); {
case f == '-' && on:
on = false
case f == 'i':
icase = on
case f == 'm' || f == 'x' && !on:
default:
return 0, false, fmt.Errorf("unsupported group option")
}
}
o.i++
}
}
if err := o.alt(icase, lookbehind); err != nil {
return 0, false, err
}
if o.peek(0) != ')' {
return 0, false, fmt.Errorf("end pattern with unmatched parenthesis")
}
o.i++
return 0, repeatable, nil
return o.group(icase, behind)
case '[':
return 1, true, o.class()
_, err := o.class()
return 1, true, err
case '\\':
w, err := o.escape(false)
w, err := o.escape(false, behind)
if w == 0 && behind {
return 0, false, fmt.Errorf("anchor in look-behind")
}
@@ -1111,7 +1176,13 @@ func (o *onig) atom(icase, behind bool) (int, bool, error) {
}
o.i++
return 0, false, nil
case '*', '+', '?', '{', ']':
case '{':
if ok, err := o.interval(); ok || err != nil {
return 0, false, fmt.Errorf("target of repeat operator is not specified")
}
o.i++
return 1, true, nil
case '*', '+', '?', ']':
return 0, false, fmt.Errorf("unsupported %q here", c)
}
r, n := utf8.DecodeRuneInString(o.s[o.i:])
@@ -1122,74 +1193,252 @@ func (o *onig) atom(icase, behind bool) (int, bool, error) {
return 1, true, nil
}
// group consumes a parenthesised group: plain, named, atomic, non-capturing with options, or a lookaround.
func (o *onig) group(icase, behind bool) (int, bool, error) {
if behind {
return 0, false, fmt.Errorf("group in look-behind")
}
if o.depth++; o.depth > 64 {
return 0, false, fmt.Errorf("groups nested too deep")
}
saved := o.ext
defer func() { o.depth--; o.ext = saved }()
o.i++
repeatable, lookbehind, name := true, false, ""
if o.peek(0) == '?' {
switch {
case o.peek(1) == ':' || o.peek(1) == '>':
o.i += 2
case o.peek(1) == '=' || o.peek(1) == '!':
o.i += 2
repeatable = false
case o.peek(1) == '<' && (o.peek(2) == '=' || o.peek(2) == '!'):
if icase {
return 0, false, fmt.Errorf("look-behind with case folding")
}
o.i += 3
repeatable, lookbehind = false, true
case o.peek(1) == '<' || o.peek(1) == '\'':
end := map[byte]byte{'<': '>', '\'': '\''}[o.peek(1)]
j := strings.IndexByte(o.s[o.i+2:], end)
if j < 0 || !rubyIdent.MatchString(o.s[o.i+2:o.i+2+j]) {
return 0, false, fmt.Errorf("invalid group name")
}
name = o.s[o.i+2 : o.i+2+j]
o.i += 3 + j
default:
o.i++
on, x := true, o.ext
if o.peek(0) == ')' {
return 0, false, fmt.Errorf("undefined group option")
}
for ; o.peek(0) != ':' && o.peek(0) != ')'; o.i++ {
switch f := o.peek(0); {
case f == '-' && on:
on = false
case f == 'i':
icase = on
case f == 'x':
x = on
case f == 'm':
default:
return 0, false, fmt.Errorf("unsupported group option")
}
}
o.ext = x
if o.s[o.i] == ')' {
o.i++
return 0, true, o.alt(icase, false)
}
o.i++
}
}
if err := o.alt(icase, lookbehind); err != nil {
return 0, false, err
}
if o.peek(0) != ')' {
return 0, false, fmt.Errorf("end pattern with unmatched parenthesis")
}
o.i++
if name != "" {
o.names[name] = true
}
return 0, repeatable, nil
}
// escape consumes a backslash escape, returning 1 for a character or class and 0 for an anchor, which a character
// class does not allow.
func (o *onig) escape(inClass bool) (int, error) {
func (o *onig) escape(inClass, behind bool) (int, error) {
c := o.peek(1)
o.i += 2
switch {
case strings.IndexByte("dDwWsShHntrfvea", c) >= 0:
return 1, nil
case !inClass && strings.IndexByte("AzZbB", c) >= 0:
case !inClass && strings.IndexByte("AzZbBG", c) >= 0:
return 0, nil
case c > 0x20 && c < 0x7f && !unicode.IsLetter(rune(c)) && !unicode.IsDigit(rune(c)):
case c == 'u':
cps, err := o.unicode()
if inClass && len(cps) != 1 {
return 0, fmt.Errorf("unsupported \\u list in char-class")
}
return len(cps), err
case c == '0':
for j := 0; j < 2 && o.peek(0) >= '0' && o.peek(0) <= '7'; j++ {
o.i++
}
return 1, nil
case c == 'x':
j := 0
for ; j < 2 && strings.IndexByte("0123456789abcdefABCDEF", o.peek(0)) >= 0; j++ {
o.i++
}
if v, _ := strconv.ParseUint(o.s[o.i-j:o.i], 16, 8); j == 0 || v >= 0x80 {
return 0, fmt.Errorf("invalid hex escape")
}
return 1, nil
case c == 'p' || c == 'P':
end := strings.IndexByte(o.s[o.i:], '}')
if o.peek(0) != '{' || end < 0 || !properties[strings.ToLower(strings.TrimPrefix(o.s[o.i+1:o.i+end], "^"))] {
return 0, fmt.Errorf("unsupported character property")
}
o.i += end + 1
return 1, nil
case !inClass && (c == 'R' || c == 'X'):
if behind {
return 0, fmt.Errorf("variable-length escape in look-behind")
}
return 1, nil
case !inClass && c >= '1' && c <= '9' && (o.peek(0) < '0' || o.peek(0) > '9'):
switch {
case behind:
return 0, fmt.Errorf("back reference in look-behind")
case o.named:
return 0, fmt.Errorf("numbered backref/call is not allowed")
case int(c-'0') > o.groups:
return 0, fmt.Errorf("invalid backref number")
}
return 1, nil
case !inClass && c == 'k' && o.peek(0) == '<':
j := strings.IndexByte(o.s[o.i:], '>')
if behind || j < 0 || !o.names[o.s[o.i+1:o.i+j]] {
return 0, fmt.Errorf("unsupported back reference")
}
o.i += j + 1
return 1, nil
case c >= 0x20 && c < 0x7f && !unicode.IsLetter(rune(c)) && !unicode.IsDigit(rune(c)):
return 1, nil
}
return 0, fmt.Errorf("unsupported escape")
}
// class consumes a bracket expression of characters, ranges in order and class escapes.
func (o *onig) class() error {
// unicode consumes the rest of \uHHHH or \u{H...}, returning the code points, none of them a surrogate.
func (o *onig) unicode() ([]int, error) {
var hexes []string
if o.peek(0) == '{' {
end := strings.IndexByte(o.s[o.i:], '}')
if end < 0 {
return nil, fmt.Errorf("invalid Unicode list")
}
hexes = strings.FieldsFunc(o.s[o.i+1:o.i+end], func(r rune) bool { return r == ' ' })
o.i += end + 1
} else if o.i+4 <= len(o.s) {
hexes = []string{o.s[o.i : o.i+4]}
o.i += 4
}
if len(hexes) == 0 {
return nil, fmt.Errorf("invalid Unicode escape")
}
var cps []int
for _, h := range hexes {
v, err := strconv.ParseUint(h, 16, 32)
if err != nil || len(h) > 6 || v > 0x10FFFF || v >= 0xD800 && v <= 0xDFFF {
return nil, fmt.Errorf("invalid Unicode escape")
}
cps = append(cps, int(v))
}
return cps, nil
}
// properties are the \p{...} names w10k accepts, lower-cased: general categories and POSIX-like classes.
var properties = set("l lu ll lt lm lo m mn mc me n nd nl no p pc pd ps pe pi pf po s sm sc sk so z zs zl zp c cc cf cs co cn alnum alpha blank cntrl digit graph lower print punct space upper xdigit word ascii any assigned")
// posixBrackets are the POSIX bracket names Onigmo accepts.
var posixBrackets = set("alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigit")
// classChar consumes one member of a character class, returning its code point, or -1 for a class or bracket.
func (o *onig) classChar() (int, error) {
c := o.peek(0)
switch {
case c == '[' && o.peek(1) == ':':
end := strings.Index(o.s[o.i:], ":]")
name := ""
if end > 2 {
name = strings.TrimPrefix(o.s[o.i+2:o.i+end], "^")
}
if !posixBrackets[name] {
return 0, fmt.Errorf("unsupported POSIX bracket")
}
o.i += end + 2
return -1, nil
case c == '\\':
e, start := o.peek(1), o.i
if _, err := o.escape(true, false); err != nil {
return 0, err
}
switch {
case strings.IndexByte("dDwWsShHntrfveapP", e) >= 0:
return -1, nil
case e == 'u':
o.i = start + 2
cps, err := o.unicode()
return cps[0], err
case e == '0':
v, _ := strconv.ParseUint(o.s[start+1:o.i], 8, 32)
return int(v), nil
case e == 'x':
v, _ := strconv.ParseUint(o.s[start+2:o.i], 16, 8)
return int(v), nil
}
return int(e), nil
case c == ']', c == '[', c == '&' && o.peek(1) == '&', c >= 0x80, o.i >= len(o.s):
return 0, fmt.Errorf("unsupported character class")
}
o.i++
return int(c), nil
}
// class consumes a bracket expression of characters, ranges in order, class escapes and POSIX brackets.
func (o *onig) class() (bool, error) {
o.i++
if o.peek(0) == '^' {
o.i++
}
n, prev := 0, -1
for {
c := o.peek(0)
for n := 0; ; n++ {
switch {
case o.i >= len(o.s):
return fmt.Errorf("premature end of char-class")
case c == ']' && n > 0:
o.i++
return nil
case c == ']', c == '[', c == '&' && o.peek(1) == '&', c >= 0x80:
return fmt.Errorf("unsupported character class")
case c == '\\':
e := o.peek(1)
if _, err := o.escape(true); err != nil {
return err
}
prev = -1
if strings.IndexByte("dDwWsShHntrfvea", e) < 0 {
prev = int(e)
}
case c == '-' && n > 0 && o.peek(1) != ']':
o.i++
hi := int(o.peek(0))
if o.peek(0) == '\\' {
if e := o.peek(1); strings.IndexByte("dDwWsShHntrfvea", e) >= 0 {
return fmt.Errorf("unsupported range end")
}
hi = int(o.peek(1))
if _, err := o.escape(true); err != nil {
return err
}
} else {
if hi == '[' || hi == ']' || hi >= 0x80 || o.i >= len(o.s) {
return fmt.Errorf("unsupported range end")
}
o.i++
}
if prev < 0 || hi < prev {
return fmt.Errorf("bad range in char-class")
}
prev = -1
default:
prev = int(c)
return false, fmt.Errorf("premature end of char-class")
case o.peek(0) == ']' && n > 0:
o.i++
return true, nil
}
lo, err := o.classChar()
if err != nil {
return false, err
}
if o.peek(0) != '-' || o.peek(1) == ']' {
continue
}
o.i++
hi, err := o.classChar()
if err != nil {
return false, err
}
if lo < 0 || hi < 0 {
return false, fmt.Errorf("unsupported range end")
}
if hi < lo {
return false, fmt.Errorf("bad range in char-class")
}
n++
}
}
@@ -1204,7 +1453,7 @@ func (p *parser) regexpNew() (rval, error) {
case args[0].k == vRegex:
return args[0], nil
case args[0].k == vStr:
if err := onigCheck(args[0].s, false); err != nil {
if err := onigCheck(args[0].s, ""); err != nil {
return rval{}, err
}
return rval{k: vRegex, re: regex{src: args[0].s}}, nil
@@ -1523,3 +1772,139 @@ func (p *parser) loadFeature(name string) error {
}
return p.load(srcs[0])
}
// onigNames ports Onigmo's Regexp#names: named groups in first-appearance order, skipping escapes, character classes,
// (?#...) comments and, in extended mode, # comments. A name outside [A-Za-z_][A-Za-z0-9_]* or a reference w10k
// cannot resolve is an error.
func onigNames(re regex) ([]string, error) {
names, _, err := onigGroups(re)
return names, err
}
// onigGroups is onigNames that also counts the plain capturing groups.
func onigGroups(re regex) (names []string, plain int, err error) {
s := re.src
ext := []bool{strings.Contains(re.flags, "x")}
name := func(i int, end byte) (string, int, error) {
j := strings.IndexByte(s[i:], end)
if j < 0 || !rubyIdent.MatchString(s[i:i+j]) {
return "", 0, fmt.Errorf("regex /%s/: unsupported group name", s)
}
return s[i : i+j], i + j + 1, nil
}
for i := 0; i < len(s); {
c := s[i]
switch {
case c == '\\' && i+1 < len(s) && s[i+1] == 'k':
if i+2 >= len(s) || s[i+2] != '<' {
return nil, 0, fmt.Errorf("regex /%s/: unsupported \\k", s)
}
n, j, err := name(i+3, '>')
if err != nil || !slices.Contains(names, n) {
return nil, 0, fmt.Errorf("regex /%s/: unsupported back reference", s)
}
i = j
case c == '\\' && i+1 < len(s) && s[i+1] == 'g':
return nil, 0, fmt.Errorf("regex /%s/: unsupported subexpression call", s)
case c == '\\':
_, n := utf8.DecodeRuneInString(s[min(i+1, len(s)):])
i += 1 + n
case c == '[':
depth := 0
for i < len(s) {
switch s[i] {
case '\\':
i++
case '[':
depth++
if i++; i < len(s) && s[i] == '^' {
i++
}
if i < len(s) && s[i] == ']' {
i++
}
continue
case ']':
depth--
}
i++
if depth == 0 {
break
}
}
if depth != 0 {
return nil, 0, fmt.Errorf("regex /%s/: premature end of char-class", s)
}
case ext[len(ext)-1] && c == '#':
for i < len(s) && s[i] != '\n' {
i++
}
case c == '(' && strings.HasPrefix(s[i:], "(?#"):
for i += 3; i < len(s) && s[i] != ')'; i++ {
if s[i] == '\\' {
i++
}
}
if i++; i > len(s) {
return nil, 0, fmt.Errorf("regex /%s/: end pattern in group", s)
}
case c == '(' && (strings.HasPrefix(s[i:], "(?<") && !strings.HasPrefix(s[i:], "(?<=") && !strings.HasPrefix(s[i:], "(?<!") || strings.HasPrefix(s[i:], "(?'")):
end := byte('>')
if s[i+2] == '\'' {
end = '\''
}
n, j, err := name(i+3, end)
if err != nil {
return nil, 0, err
}
if !slices.Contains(names, n) {
names = append(names, n)
}
ext = append(ext, ext[len(ext)-1])
i = j
case c == '(' && strings.HasPrefix(s[i:], "(?") && i+2 < len(s) && strings.IndexByte("imx-", s[i+2]) >= 0:
on, x := true, ext[len(ext)-1]
j := i + 2
for ; j < len(s) && s[j] != ':' && s[j] != ')'; j++ {
switch s[j] {
case '-':
on = false
case 'x':
x = on
case 'i', 'm':
default:
return nil, 0, fmt.Errorf("regex /%s/: unsupported group option", s)
}
}
if j == len(s) {
return nil, 0, fmt.Errorf("regex /%s/: end pattern in group", s)
}
if s[j] == ')' {
ext[len(ext)-1] = x
} else {
ext = append(ext, x)
}
i = j + 1
case c == '(':
if !strings.HasPrefix(s[i:], "(?") {
plain++
}
ext = append(ext, ext[len(ext)-1])
i++
case c == ')':
if len(ext) == 1 {
return nil, 0, fmt.Errorf("regex /%s/: unmatched close parenthesis", s)
}
ext = ext[:len(ext)-1]
i++
default:
i++
}
}
if len(ext) != 1 {
return nil, 0, fmt.Errorf("regex /%s/: end pattern with unmatched parenthesis", s)
}
return names, plain, nil
}
var rubyIdent = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
+60 -6
View File
@@ -300,19 +300,19 @@ func TestOnigCheck(t *testing.T) {
{`a\`, false, false},
{`(?<=(a))`, true, false},
{`(?<=^a)`, true, false},
{`(?<n>a)`, true, false},
{`\x41`, true, false},
{`(?<n>a)`, true, true},
{`\x41`, true, true},
{`(?i:(?<=ss))`, true, false},
{`a{1,2}+`, true, false},
{`[[:alpha:]]`, true, false},
{`(?x:a b)`, true, false},
{`a{`, true, false},
{`[[:alpha:]]`, true, true},
{`(?x:a b)`, true, true},
{`a{`, true, true},
{`a]`, true, false},
{`(?#c)`, true, false},
{`[a-\d]`, false, false},
{`[\d-z]`, false, false},
} {
if err := onigCheck(c.src, false); (err == nil) != c.want || err == nil && !c.ruby {
if err := onigCheck(c.src, ""); (err == nil) != c.want || err == nil && !c.ruby {
t.Errorf("%s: got %v, want accepted=%v (ruby compiles it: %v)", c.src, err, c.want, c.ruby)
}
}
@@ -337,3 +337,57 @@ func TestFileJoin(t *testing.T) {
t.Errorf("fileJoin of %d rooted parts allocates %v times", len(parts), n)
}
}
// Each case is Ruby 3.3's Regexp#names, or an error where Ruby raises or w10k does not model the name.
func TestOnigNames(t *testing.T) {
for _, c := range []struct{ src, flags, want string }{
{`(?<a>x)\(?<b>y\)[(?<c>)](?<a>z)`, "", "a"}, {`(?#c(?<a>x)(?<b>y)`, "", "b"}, {`(?#c\)(?<a>x)`, "", ""},
{"(?x) # (?<n>c)\n(?<m>d)", "", "m"}, {"(?x:a # (?<n>c)\n)(?<m>d) # (?<o>e)", "", "m o"}, {"(?x:a)# (?<n>c)\n", "", "n"},
{"(?x)[#](?<n>c)", "", "n"}, {`(?x)\#(?<n>c)`, "", "n"}, {`[]](?<a>x)`, "", "a"}, {`[^]](?<a>x)`, "", "a"},
{`[a[b](?<c>x)]](?<a>x)`, "", "a"}, {`[[:alpha:]](?<a>x)`, "", "a"}, {`[a&&[^b]](?<a>x)`, "", "a"}, {`[\]](?<a>x)`, "", "a"},
{`(?<=a)(?<!b)(?<c>d)`, "", "c"}, {`(?'q'x)(?<r>y)`, "", "q r"}, {`(?i)(?<a>x)`, "", "a"}, {`(?-x:#(?<a>x))`, "", "a"},
{`(?<a>x)\k<a>`, "", "a"}, {`(?<a_1>x)(?<_b>y)`, "", "a_1 _b"}, {`(?<a>x)(?<b>(?<c>y))`, "", "a b c"}, {`(?~ab)(?<a>x)`, "", "a"},
{`(?>a)(?<a>x)`, "", "a"}, {`\\(?<a>x)`, "", "a"}, {`\Q(?<a>x)`, "", "a"}, {"(?x)(?<a>x)#)\n(?<b>y)", "", "a b"},
{"(?x)a(?-x)#(?<b>y)", "", "b"}, {"(?x:(?-x)#(?<a>x))#(?<b>y)", "", "a b"}, {`(?<b>x)(?<a>y)(?<b>z)`, "", "b a"},
{"(?<a>x) # (?<b>y)\n (?<c>z)", "x", "a c"}, {`(x)`, "", ""},
{`\k<a>(?<a>x)`, "", "error"}, {`\g<a>(?<a>x)`, "", "error"}, {`(?<1a>x)`, "", "error"}, {`(?<a-b>x)`, "", "error"},
{`(?<>x)`, "", "error"}, {`(?<a>x`, "", "error"}, {`(?<a>x)\k<b>(?<b>y)`, "", "error"}, {`(?<a>x)\k<1>`, "", "error"},
{`(?<a>x)\k<a+0>`, "", "error"}, {`(?<é>x)`, "", "error"}, {`a)`, "", "error"}, {`[a`, "", "error"}, {`(?#a`, "", "error"},
} {
got, err := onigNames(regex{c.src, c.flags})
if g := strings.Join(got, " "); err != nil && c.want != "error" || err == nil && g != c.want {
t.Errorf("onigNames(%q) = %q %v, want %q", c.src, g, err, c.want)
}
}
}
// Each case is Ruby 3.3's verdict compiling src with flags; onigCheck accepts only sources Ruby compiles.
func TestOnigCheckSyntax(t *testing.T) {
for _, c := range []struct {
src, flags string
ruby, want bool
}{
{`\1(a)`, "", true, true}, {`(a)\1`, "", true, true}, {`(a)\2`, "", false, false}, {`\8`, "", false, false},
{`(?<n>a)\1`, "", false, false}, {`(?<a>x)(y)\1`, "", false, false}, {`(?<n>a)\k<n>`, "", true, true}, {`\k<a>(?<a>x)`, "", false, false},
{`(?<n>a)(?<n>b)`, "", true, true}, {`(?'q'x)`, "", true, true}, {`(?<1a>x)`, "", false, false}, {`(?<n>a)(?<=\k<n>)`, "", false, false},
{`\0`, "", true, true}, {`\012`, "", true, true}, {`\0123`, "", true, true},
{`{`, "", true, true}, {`a{`, "", true, true}, {`a{,}`, "", true, true}, {`a{1`, "", true, true}, {`{a}`, "", true, true}, {`a{ 2}`, "", true, true},
{`{2}`, "", false, false}, {`({2})`, "", false, false}, {`a|{2}`, "", false, false}, {`a{100001}`, "", false, false}, {`a{2,1}`, "", false, false},
{`(?<!n{2}?)a`, "", false, false}, {`(?<=a{2})`, "", true, true},
{`[[:alpha:]]`, "", true, true}, {`[[:^alpha:]]`, "", true, true}, {`[[:alpha:][:digit:]]`, "", true, true}, {`[[:foo:]]`, "", false, false},
{`[[:ALPHA:]]`, "", false, false}, {`[a-[:digit:]]`, "", false, false}, {`[[:digit:]-z]`, "", false, false},
{`\u007B`, "", true, true}, {`\u{7B 7C}`, "", true, true}, {`\u{ 7B}`, "", true, true}, {`[\u007B-\u00BF]`, "", true, true},
{`[\u00BF-\u007B]`, "", false, false}, {`\uD800`, "", false, false}, {`\u{110000}`, "", false, false}, {`\u7B`, "", false, false}, {`\u{}`, "", false, false},
{`(?>a)+`, "", true, true}, {`\Ga`, "", true, true},
{"a b # c\n d", "x", true, true}, {"[ ]#x\n", "x", true, true}, {`a\ b`, "x", true, true}, {"(?x:a # c\n)b", "", true, true},
{"a{2,1}", "x", false, false}, {"a #(\n)", "x", false, false}, {"{#(?>k\n2}u", "x", false, false}, {"a { 2 }", "x", true, false},
{`\p{L}`, "", true, true}, {`\P{^Alpha}`, "", true, true}, {`[\p{L}]`, "", true, true}, {`\p{Foo}`, "", false, false}, {`[\p{L}-z]`, "", false, false},
{`\x41`, "", true, true}, {`\xff`, "", false, false}, {`\x`, "", false, false}, {`[a-\x41]`, "", false, false}, {`\R\X`, "", true, true}, {`(?<=\R)`, "", false, false},
{`(?)a`, "", false, false}, {`(?i)a|b`, "", true, true}, {`a(?i)b|c)`, "", false, false}, {`(?i`, "", false, false},
{`ab`, "n", true, true}, {`é`, "n", true, false}, {`a`, "u", true, false},
} {
if err := onigCheck(c.src, c.flags); (err == nil) != c.want || err == nil && !c.ruby {
t.Errorf("%q /%s: got %v, want accepted=%v (ruby compiles it: %v)", c.src, c.flags, err, c.want, c.ruby)
}
}
}
+74
View File
@@ -369,3 +369,77 @@ func TestFidelityBlockCalls(t *testing.T) {
})
}
}
func rsapiPatterns(patterns string) map[string]string {
return map[string]string{"m/lib/puppet/type/t.rb": rsapi(" title_patterns: [\n"+patterns+" ],\n", " owner: { type: 'String', desc: 'o', behaviour: :namevar },\n")}
}
// Regexp#names counts only real named groups, so openvox 9.3.0 writes want; names w10k cannot model skip.
func TestFidelityTitlePatternNames(t *testing.T) {
env := fidelityEnv(t, rsapiPatterns(" { pattern: %r{^(?<name>[^-]*)\\(?<x>y\\)[(?<z>)]-(?<owner>.*)$}, desc: 'a' },\n"+
" { pattern: %r{^(?<name>.*) # (?<q>c)\n $}x, desc: 'b' },\n"))
want := " /^(?<name>[^-]*)\\(?<x>y\\)[(?<z>)]-(?<owner>.*)$/ => ['name', 'owner'],\n /(?x-mi:^(?<name>.*) # (?<q>c)\n $)/ => ['name']\n"
if b := readFile(t, filepath.Join(env, OutDir, "t.pp")); !strings.Contains(b, want) {
t.Fatalf("t.pp lacks %q:\n%s", want, b)
}
for _, re := range []string{`%r{^(?<name-x>.*)$}`, `%r{^\k<name>(?<name>.*)$}`, `%r{^(?<1name>.*)$}`} {
if exists(filepath.Join(fidelityEnv(t, rsapiPatterns(" { pattern: "+re+", desc: 'a' },\n")), OutDir, "t.pp")) {
t.Errorf("%s: t.pp written", re)
}
}
}
// genclass downcases type, attribute and provider names and const_set raises on a name its constant cannot take, so
// openvox 9.3.0 writes want for T and fails on each skip case but the non-ASCII name, which w10k does not model.
func TestFidelityGenclassNames(t *testing.T) {
env := fidelityEnv(t, map[string]string{
"m/lib/puppet/type/t.rb": "Puppet::Type.newtype(:T) do\n newparam(:Name_X) { isnamevar }\n newparam(:_p)\n newparam(:\"9p\")\n newparam(:\"\")\n newproperty(:Prop)\nend\n",
"m/lib/puppet/provider/t/a.rb": "Puppet::Type.type(:t).provide(:Foo) do\nend\n",
"m/lib/puppet/provider/t/b.rb": "Puppet::Type.type(:t).provide(:_x) do\nend\n",
"m/lib/puppet/provider/t/c.rb": "Puppet::Type.type(:t).provide(:\"9y\") do\nend\n",
"m/lib/puppet/type/u.rb": "Puppet::Type.newtype(:u) do\n newparam(:NAME)\nend\n",
})
want := " Puppet::Resource::Param(Any, 'prop')\n ],\n [\n Puppet::Resource::Param(Any, 'name_x', true),\n\n Puppet::Resource::Param(Any, '_p'),\n\n" +
" Puppet::Resource::Param(Any, '9p'),\n\n Puppet::Resource::Param(Any, ''),\n"
if b := readFile(t, filepath.Join(env, OutDir, "t.pp")); !strings.Contains(b, want) || !strings.Contains(b, " # 9y\n # : \n # \n # _x\n # : \n # \n # foo\n # :\n") {
t.Fatalf("t.pp differs from puppet's:\n%s", b)
}
if b := readFile(t, filepath.Join(env, OutDir, "u.pp")); !strings.Contains(b, "Param(Any, 'name')\n ],\n {\n /(?m-ix:(.*))/ => ['name']\n") {
t.Fatalf("u.pp differs from puppet's:\n%s", b)
}
for name, body := range map[string]string{
"params differing in case": " newparam(:a)\n newparam(:A)\n", "properties differing in case": " newproperty(:b)\n newproperty(:B)\n",
"property with leading underscore": " newproperty(:_b)\n", "property with leading digit": " newproperty(:\"9b\")\n",
"param with hyphen": " newparam(:\"a-b\")\n", "non-ASCII param": " newparam(:\"é\")\n",
} {
t.Run(name, func(t *testing.T) {
if exists(filepath.Join(fidelityEnv(t, map[string]string{"m/lib/puppet/type/t.rb": typeWith("t", body)}), OutDir, "t.pp")) {
t.Fatal("t.pp written")
}
})
}
}
// Ruby compiles every regex literal while parsing a file, so one Onigmo rejects fails the file even in a method that
// never runs; an interpolated literal compiles only when it runs. openvox 9.3.0 writes t.pp exactly when want is set.
func TestFidelityRegexLiterals(t *testing.T) {
for name, c := range map[string]struct {
files map[string]string
want bool
}{
"provider method": {provider("Puppet::Type.type(:t).provide(:x) do\n def m\n /a{2,1}/\n end\nend\n"), false},
"type class method": {map[string]string{"m/lib/puppet/type/t.rb": typeWith("t", " def self.m\n %r{(?<=a+)}\n end\n")}, false},
"string interpolation in a library": {map[string]string{"m/lib/puppet/type/t.rb": "require 'puppet_x/m/h'\n" + classic,
"m/lib/puppet_x/m/h.rb": "module PuppetX\n module M\n def self.h\n \"#{/[z-a]/}\"\n end\n end\nend\n"}, false},
"interpolated in a method": {provider("Puppet::Type.type(:t).provide(:x) do\n def m\n /#{y}(/\n end\nend\n"), true},
"Onigmo constructs": {provider("Puppet::Type.type(:t).provide(:x) do\n def m\n /(?<n>a)\\k<n>\\G[[:alpha:]]\\u{7B}{ # c\n/x\n end\nend\n"), true},
"back reference and octal": {provider("Puppet::Type.type(:t).provide(:x) do\n def m\n /^(['\"])(.*)\\1\\0(?>b)$/\n end\nend\n"), true},
"named group and backref 1": {provider("Puppet::Type.type(:t).provide(:x) do\n def m\n /(?<n>a)\\1/\n end\nend\n"), false},
} {
t.Run(name, func(t *testing.T) {
if got := exists(filepath.Join(fidelityEnv(t, c.files), OutDir, "t.pp")); got != c.want {
t.Fatalf("t.pp written = %v, want %v", got, c.want)
}
})
}
}
+1 -1
View File
@@ -18,7 +18,7 @@ import (
const OutDir = ".resource_types"
// Version changes whenever generated output can change, so deploys rebuild typed environments.
const Version = "13"
const Version = "16"
var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
+12 -4
View File
@@ -206,8 +206,11 @@ func (p *parser) load(f libFile) error {
}
p.w.loaded[key] = true
toks, err := lex(f.src)
if err == nil {
err = checkRegexes(toks, 0)
}
if err != nil {
return err
return fmt.Errorf("lib/%s: %w", f.rel, err)
}
q := &parser{toks: toks, consts: map[string]rval{}, used: map[int]bool{}, w: p.w, defined: p.w.defined, mod: f.mod, dir: path.Dir(f.rel), file: path.Base(f.rel), depth: p.depth, src: f.src}
if err := q.body("", q.fileStmt(nil)); err != nil {
@@ -1043,6 +1046,9 @@ type provDecl struct {
func providerFile(f libFile, typ string, rsapi bool, w *world) (pr *provDecl, err error) {
defer guard(&err)
toks, err := lex(f.src)
if err == nil {
err = checkRegexes(toks, 0)
}
if err != nil {
return nil, err
}
@@ -1075,9 +1081,11 @@ func providerFile(f libFile, typ string, rsapi bool, w *world) (pr *provDecl, er
if len(args) == 0 || len(args) > 2 || args[0].k != vSym && args[0].k != vStr || len(args) == 2 && args[1].k != vHash {
return true, fmt.Errorf("unsupported provide arguments")
}
name = args[0].s
if !rubyName.MatchString(name) {
return true, fmt.Errorf("unsupported provider name %q", name)
if name, err = genName(args[0].s, true); err == nil && name == "" {
err = fmt.Errorf("unsupported empty provider name")
}
if err != nil {
return true, err
}
kind := byte(kProv)
c = newClass(kind, true)
+32 -11
View File
@@ -10,6 +10,7 @@ import (
"slices"
"strconv"
"strings"
"unicode/utf8"
)
type regex struct{ src, flags string }
@@ -147,6 +148,9 @@ var watched = map[string]bool{
func parseFile(f libFile, w *world) (types []*rtype, err error) {
defer guard(&err)
toks, err := lex(f.src)
if err == nil {
err = checkRegexes(toks, 0)
}
if err != nil {
return nil, err
}
@@ -702,6 +706,21 @@ func (p *parser) methodCall(name string, inPuppet bool) bool {
return true
}
var constTail = regexp.MustCompile(`^[a-z0-9_]*$`)
// genName is the name genclass gives the class it defines for name: downcased, failing where const_set raises on the
// constant name2const builds from it, which with a prefix such as Parameter only needs a valid tail.
func genName(name string, prefixed bool) (string, error) {
n := strings.ToLower(name)
switch {
case strings.ContainsFunc(name, func(r rune) bool { return r >= utf8.RuneSelf }):
return "", fmt.Errorf("unsupported non-ASCII name %q", name)
case prefixed && constTail.MatchString(n), rubyName.MatchString(n):
return n, nil
}
return "", fmt.Errorf("wrong constant name for %q", name)
}
func symName(v rval) (string, error) {
switch v.k {
case vSym, vStr:
@@ -723,13 +742,16 @@ func (p *parser) newtype() error {
return fmt.Errorf("newtype with options is not supported")
}
name, err := symName(args[0])
if err == nil {
name, err = genName(name, false)
}
if err != nil {
return err
}
t := &rtype{name: name, methods: map[string]bool{}}
p.types = append(p.types, t)
if p.w != nil && name != "" {
c := "Puppet::Type::" + strings.ToUpper(name[:1]) + strings.ToLower(name[1:])
if p.w != nil {
c := "Puppet::Type::" + capitalize(name)
if p.w.user[c] {
return fmt.Errorf("newtype replaces class %s", c)
}
@@ -1233,6 +1255,9 @@ func (p *parser) newattr(t *rtype, property bool) error {
return fmt.Errorf("attribute without a name")
}
name, err := symName(args[0])
if err == nil {
name, err = genName(name, !property)
}
if err != nil {
return err
}
@@ -1763,7 +1788,7 @@ func (p *parser) primary() (rval, error) {
return rval{k: vSym, s: t.text}, nil
case tRegex:
p.take()
if strings.Contains(t.text, "#{") {
if regexInterpolated(t.text) {
return p.regexInterp(t)
}
return rval{k: vRegex, re: regex{t.text, t.flags}}, nil
@@ -1940,8 +1965,6 @@ var (
rubyName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
)
var namedGroup = regexp.MustCompile(`\(\?(?:<([A-Za-z_]\w*)>|'([A-Za-z_]\w*)')`)
const numericRe = `\A[[:blank:]]*([-+]?)[[:blank:]]*((0[xX][0-9A-Fa-f]+)|(0?\d+)((?:\.\d+)?(?:[eE]-?\d+)?))[[:blank:]]*\z`
func str(v rval, ok bool) (string, bool) {
@@ -2073,13 +2096,11 @@ func resourceAPIType(def rval) (*rtype, error) {
if e.k != vHash || !ok || re.k != vRegex {
return nil, fmt.Errorf("title_patterns entries need a literal regex pattern")
}
pt := pattern{re: re.re}
for _, m := range namedGroup.FindAllStringSubmatch(re.re.src, -1) {
if n := m[1] + m[2]; !slices.Contains(pt.names, n) {
pt.names = append(pt.names, n)
}
names, err := onigNames(re.re)
if err != nil {
return nil, fmt.Errorf("title_patterns: %w", err)
}
t.patterns = append(t.patterns, pt)
t.patterns = append(t.patterns, pattern{re: re.re, names: names})
}
} else {
first := ""