diff --git a/internal/gentypes/eval.go b/internal/gentypes/eval.go index bf2d87a..eaaac75 100644 --- a/internal/gentypes/eval.go +++ b/internal/gentypes/eval.go @@ -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 @@ -1528,8 +1777,13 @@ func (p *parser) loadFeature(name string) error { // (?#...) 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 - 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) @@ -1543,15 +1797,15 @@ func onigNames(re regex) ([]string, error) { 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) + 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, fmt.Errorf("regex /%s/: unsupported back reference", s) + 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, fmt.Errorf("regex /%s/: unsupported subexpression call", s) + 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 @@ -1579,7 +1833,7 @@ func onigNames(re regex) ([]string, error) { } } if depth != 0 { - return nil, fmt.Errorf("regex /%s/: premature end of char-class", s) + 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' { @@ -1592,7 +1846,7 @@ func onigNames(re regex) ([]string, error) { } } if i++; i > len(s) { - return nil, fmt.Errorf("regex /%s/: end pattern in group", 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:], "(?') @@ -1601,7 +1855,7 @@ func onigNames(re regex) ([]string, error) { } n, j, err := name(i+3, end) if err != nil { - return nil, err + return nil, 0, err } if !slices.Contains(names, n) { names = append(names, n) @@ -1619,11 +1873,11 @@ func onigNames(re regex) ([]string, error) { x = on case 'i', 'm': default: - return nil, fmt.Errorf("regex /%s/: unsupported group option", s) + return nil, 0, fmt.Errorf("regex /%s/: unsupported group option", s) } } if j == len(s) { - return nil, fmt.Errorf("regex /%s/: end pattern in group", s) + return nil, 0, fmt.Errorf("regex /%s/: end pattern in group", s) } if s[j] == ')' { ext[len(ext)-1] = x @@ -1632,11 +1886,14 @@ func onigNames(re regex) ([]string, error) { } 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, fmt.Errorf("regex /%s/: unmatched close parenthesis", s) + return nil, 0, fmt.Errorf("regex /%s/: unmatched close parenthesis", s) } ext = ext[:len(ext)-1] i++ @@ -1645,9 +1902,9 @@ func onigNames(re regex) ([]string, error) { } } if len(ext) != 1 { - return nil, fmt.Errorf("regex /%s/: end pattern with unmatched parenthesis", s) + return nil, 0, fmt.Errorf("regex /%s/: end pattern with unmatched parenthesis", s) } - return names, nil + return names, plain, nil } var rubyIdent = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) diff --git a/internal/gentypes/eval_test.go b/internal/gentypes/eval_test.go index ea2c65d..517c71b 100644 --- a/internal/gentypes/eval_test.go +++ b/internal/gentypes/eval_test.go @@ -300,19 +300,19 @@ func TestOnigCheck(t *testing.T) { {`a\`, false, false}, {`(?<=(a))`, true, false}, {`(?<=^a)`, true, false}, - {`(?a)`, true, false}, - {`\x41`, true, false}, + {`(?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) } } @@ -360,3 +360,34 @@ func TestOnigNames(t *testing.T) { } } } + +// 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}, + {`(?a)\1`, "", false, false}, {`(?x)(y)\1`, "", false, false}, {`(?a)\k`, "", true, true}, {`\k(?x)`, "", false, false}, + {`(?a)(?b)`, "", true, true}, {`(?'q'x)`, "", true, true}, {`(?<1a>x)`, "", false, false}, {`(?a)(?<=\k)`, "", 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}, + {`(?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) + } + } +} diff --git a/internal/gentypes/fidelity_test.go b/internal/gentypes/fidelity_test.go index e718937..b5880af 100644 --- a/internal/gentypes/fidelity_test.go +++ b/internal/gentypes/fidelity_test.go @@ -419,3 +419,27 @@ func TestFidelityGenclassNames(t *testing.T) { }) } } + +// 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 /(?a)\\k\\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 /(?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) + } + }) + } +} diff --git a/internal/gentypes/generate.go b/internal/gentypes/generate.go index 6eab518..0bc0fd3 100644 --- a/internal/gentypes/generate.go +++ b/internal/gentypes/generate.go @@ -18,7 +18,7 @@ import ( const OutDir = ".resource_types" // Version changes whenever generated output can change, so deploys rebuild typed environments. -const Version = "15" +const Version = "16" var moduleName = regexp.MustCompile(`^[a-z][a-z0-9_]*$`) diff --git a/internal/gentypes/load.go b/internal/gentypes/load.go index 8291eee..09a940f 100644 --- a/internal/gentypes/load.go +++ b/internal/gentypes/load.go @@ -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 } diff --git a/internal/gentypes/parse.go b/internal/gentypes/parse.go index 657e6e4..1029c8a 100644 --- a/internal/gentypes/parse.go +++ b/internal/gentypes/parse.go @@ -148,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 } @@ -1785,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