4 Commits

Author SHA1 Message Date
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 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 235 additions and 14 deletions
+128
View File
@@ -1523,3 +1523,131 @@ 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) {
s := re.src
var names []string
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, fmt.Errorf("regex /%s/: unsupported \\k", s)
}
n, j, err := name(i+3, '>')
if err != nil || !slices.Contains(names, n) {
return nil, fmt.Errorf("regex /%s/: unsupported back reference", s)
}
i = j
case c == '\\' && i+1 < len(s) && s[i+1] == 'g':
return nil, 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, 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, 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, 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, fmt.Errorf("regex /%s/: unsupported group option", s)
}
}
if j == len(s) {
return nil, 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 == '(':
ext = append(ext, ext[len(ext)-1])
i++
case c == ')':
if len(ext) == 1 {
return nil, fmt.Errorf("regex /%s/: unmatched close parenthesis", s)
}
ext = ext[:len(ext)-1]
i++
default:
i++
}
}
if len(ext) != 1 {
return nil, fmt.Errorf("regex /%s/: end pattern with unmatched parenthesis", s)
}
return names, nil
}
var rubyIdent = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
+23
View File
@@ -337,3 +337,26 @@ 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)
}
}
}
+50
View File
@@ -369,3 +369,53 @@ 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")
}
})
}
}
+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 = "15"
var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`)
+5 -3
View File
@@ -1075,9 +1075,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)
+28 -10
View File
@@ -10,6 +10,7 @@ import (
"slices"
"strconv"
"strings"
"unicode/utf8"
)
type regex struct{ src, flags string }
@@ -702,6 +703,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 +739,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 +1252,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
}
@@ -1940,8 +1962,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 +2093,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 := ""