From 68ef063c3a8399e16989407376546f430e9aae9e Mon Sep 17 00:00:00 2001 From: Morvex885 <278529280+Morvex885@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:37:47 +0300 Subject: [PATCH 1/9] Preserve Mistgate node order in Mihomo template groups Expand automatic local members in the rendered template so Mihomo keeps the panel order. Leave external providers and cross-source filter priority to the core. Refs #92. --- docs/en/guide/subscriptions.md | 6 +- docs/ru/guide/subscriptions.md | 6 +- docs/zh/guide/subscriptions.md | 6 +- go.mod | 1 + go.sum | 2 + internal/panel/subs/mihomo_node_order_test.go | 96 +++-- internal/panel/subs/mihomo_order_core_test.go | 333 ++++++++++++++++++ .../subs/mihomo_template_internal_test.go | 2 +- internal/panel/subs/mihomo_template_test.go | 4 + .../subs/testdata/mihomo_template_pc.out.yaml | 10 +- .../testdata/mihomo_template_router.out.yaml | 9 +- internal/panel/subsettings/mihomo.go | 28 +- .../subsettings/mihomo_ordered_groups.go | 195 ++++++++++ .../subsettings/mihomo_ordered_groups_test.go | 142 ++++++++ 14 files changed, 779 insertions(+), 61 deletions(-) create mode 100644 internal/panel/subs/mihomo_order_core_test.go create mode 100644 internal/panel/subsettings/mihomo_ordered_groups.go create mode 100644 internal/panel/subsettings/mihomo_ordered_groups_test.go diff --git a/docs/en/guide/subscriptions.md b/docs/en/guide/subscriptions.md index c6e1e0919..86f47e9dd 100644 --- a/docs/en/guide/subscriptions.md +++ b/docs/en/guide/subscriptions.md @@ -334,11 +334,13 @@ The panel names the person's servers by the [server name template](#names-texts) Do not write a server's name in a group: the servers differ from person to person, and a name a person does not have makes Mihomo refuse the whole file. The save refuses it too. Ask Mihomo for the servers instead: -- `include-all-proxies: true` takes the person's servers and the proxies of your template; +- `include-all-proxies: true` adds the person's servers in panel order after the group's explicit members, then template proxies in declaration order; - `filter` and `exclude-filter` (regular expressions) narrow them by name, for example `filter: "Germany"`; -- `include-all: true` also takes the groups of your `proxy-providers`; +- `include-all: true` also adds providers from `proxy-providers`; with an explicit `use` list, providers follow the local proxies in the listed order; - the group `Auto` is the person's servers by speed. +When `filter` contains multiple backtick-separated expressions, their priority takes precedence over source order: in a mixed group Mihomo collects matches for the first expression across all sources before moving to the next. + A template for the group `ROUTER`, written with made-up names: ```yaml diff --git a/docs/ru/guide/subscriptions.md b/docs/ru/guide/subscriptions.md index 788b90524..752e74884 100644 --- a/docs/ru/guide/subscriptions.md +++ b/docs/ru/guide/subscriptions.md @@ -334,11 +334,13 @@ tproxy-port: 1181 Не пишите в группе имя сервера: у людей разные серверы, а имя, которого у человека нет, заставит Mihomo отвергнуть весь файл. Сохранение такое тоже отклонит. Серверы запрашивайте средствами Mihomo: -- `include-all-proxies: true` берёт серверы человека и прокси вашего шаблона; +- `include-all-proxies: true` добавляет после явных участников группы серверы человека в порядке панели, затем прокси шаблона в порядке объявления; - `filter` и `exclude-filter` (регулярные выражения) отбирают их по имени, например `filter: "Germany"`; -- `include-all: true` берёт ещё и группы из ваших `proxy-providers`; +- `include-all: true` также подключает провайдеров из `proxy-providers`; со списком `use` провайдеры идут в указанном порядке после локальных прокси; - группа `Auto` — серверы человека по скорости. +Если в `filter` несколько выражений через обратную кавычку, их приоритет важнее порядка источников: в смешанной группе Mihomo сначала собирает совпадения с первым выражением по всем источникам, затем со следующим. + Шаблон для группы `ROUTER` на выдуманных именах: ```yaml diff --git a/docs/zh/guide/subscriptions.md b/docs/zh/guide/subscriptions.md index a40cf62b3..acfcc32bb 100644 --- a/docs/zh/guide/subscriptions.md +++ b/docs/zh/guide/subscriptions.md @@ -332,11 +332,13 @@ tproxy-port: 1181 不要在分组里写服务器名称:每个人的服务器不同,用户没有的名称会让 Mihomo 拒绝整个文件,保存时也会被拒绝。请让 Mihomo 自己取服务器: -- `include-all-proxies: true` 取用户的服务器和你模板里的代理; +- `include-all-proxies: true` 先保留分组中明确列出的成员,再按面板顺序加入用户的服务器,最后按声明顺序加入模板中的代理; - `filter` 和 `exclude-filter`(正则表达式)按名称筛选,例如 `filter: "Germany"`; -- `include-all: true` 还会取你的 `proxy-providers` 里的分组; +- `include-all: true` 还会加入 `proxy-providers` 中的提供者;使用显式的 `use` 列表时,提供者在本地代理之后按列表顺序加入; - `Auto` 分组是按速度选择的用户服务器。 +如果 `filter` 包含多个用反引号分隔的表达式,表达式的优先级高于来源顺序:在混合分组中,Mihomo 先收集所有来源中匹配第一个表达式的代理,再处理下一个表达式。 + 下面是用虚构名称写的 `ROUTER` 分组模板: ```yaml diff --git a/go.mod b/go.mod index cc7255f51..b6b024ba6 100644 --- a/go.mod +++ b/go.mod @@ -26,6 +26,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/s3 v1.114.0 github.com/coder/websocket v1.8.15 github.com/descope/virtualwebauthn v1.0.5 + github.com/dlclark/regexp2 v1.12.0 github.com/go-webauthn/webauthn v0.18.2 github.com/google/jsonschema-go v0.4.3 github.com/mdlayher/genetlink v1.4.0 diff --git a/go.sum b/go.sum index a7f859729..0e7503620 100644 --- a/go.sum +++ b/go.sum @@ -140,6 +140,8 @@ github.com/descope/virtualwebauthn v1.0.5 h1:fMXji5UMepJC51Ge6d4v5IAjiJQRKmXE9hl github.com/descope/virtualwebauthn v1.0.5/go.mod h1:lLCfN+DpCM3iisM4bCILZlFEWkC1Zo7ZgsxC45CUapI= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8= +github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= github.com/docker/cli v29.8.0+incompatible h1:ih0c2jq/nN7QfES8zIfwSzIhRScjs4ehER+kZ60aeSk= diff --git a/internal/panel/subs/mihomo_node_order_test.go b/internal/panel/subs/mihomo_node_order_test.go index d20a50521..4dbedc7cf 100644 --- a/internal/panel/subs/mihomo_node_order_test.go +++ b/internal/panel/subs/mihomo_node_order_test.go @@ -73,6 +73,13 @@ func TestMihomoNodeOrderWithWarmViewsAndTemplatePreview(t *testing.T) { t.Fatalf("Mihomo proxies = %v, want %v", got, want) } } + proxyNames := func(proxies []endpoint) []string { + names := make([]string, 0, len(proxies)) + for _, p := range proxies { + names = append(names, p.name) + } + return names + } geoAnswer := answerOf(t, r.body(t, token)) geo := endpoints(geoAnswer) // C's direct proxy precedes the two protocols and their paths on D in the original geographic order. @@ -93,6 +100,12 @@ func TestMihomoNodeOrderWithWarmViewsAndTemplatePreview(t *testing.T) { !strings.HasPrefix(geo[0].name, "p") || !strings.HasPrefix(geo[1].name, "p") { t.Fatalf("expected relay port and disambiguated direct names: %v", geo) } + geoNames := proxyNames(geo) + selectMembers := append(append([]string{"Auto"}, geoNames...), "DIRECT") + if len(geoAnswer.Groups) != 2 || !slices.Equal(geoAnswer.Groups[0].Proxies, selectMembers) || + geoAnswer.Groups[1].Name != "Auto" || !slices.Equal(geoAnswer.Groups[1].Proxies, geoNames) { + t.Fatalf("built-in groups = %+v, want select %v and Auto %v", geoAnswer.Groups, selectMembers, geoNames) + } // Compare ordered labels, not credentials. Read again after cache expiry, so an unchanged stale view cannot hide a bug. otherOrders := func() [4][]string { @@ -161,20 +174,34 @@ func TestMihomoNodeOrderWithWarmViewsAndTemplatePreview(t *testing.T) { } const draft = `proxies: - {name: authored-z, type: socks5, server: z.example.com, port: 1080} + - {name: authored-y, type: socks5, server: y.example.com, port: 1080} - {name: authored-a, type: socks5, server: a.example.com, port: 1080} proxy-groups: - name: Work type: select include-all-proxies: true - proxies: [authored-z, DIRECT, authored-a] + proxies: [authored-z, DIRECT] rules: - MATCH,Work ` - templateEndpoints := func(generated []endpoint) []endpoint { - return append(slices.Clone(generated), endpoint{"authored-z", "socks5", "z.example.com", 1080}, endpoint{"authored-a", "socks5", "a.example.com", 1080}) + authored := []endpoint{ + {"authored-z", "socks5", "z.example.com", 1080}, + {"authored-y", "socks5", "y.example.com", 1080}, + {"authored-a", "socks5", "a.example.com", 1080}, } - previewAnswer := func() tplAnswer { + assertTemplate := func(a tplAnswer, generated []endpoint) { + t.Helper() + assertEndpoints(a, slices.Concat(generated, authored)) + names := proxyNames(generated) + workMembers := append(append([]string{"authored-z", "DIRECT"}, names...), "authored-y", "authored-a") + if len(a.Groups) != 2 || + a.Groups[0].Name != "Work" || !slices.Equal(a.Groups[0].Proxies, workMembers) || + a.Groups[1].Name != "Auto" || !slices.Equal(a.Groups[1].Proxies, names) { + t.Fatalf("template groups = %+v, want Work %v and Auto %v", a.Groups, workMembers, names) + } + } + previewAnswer := func(user string) tplAnswer { t.Helper() resp, err := r.preview(t, preview, user, draft, r.group2) if err != nil { @@ -182,62 +209,55 @@ rules: } return answerOf(t, resp.Yaml) } + // Save the old include-all-proxies form once; neither order change should require editing it. + r.save(t, nameByProfile, &adminv1.MihomoTemplate{Name: "work", Yaml: draft, GroupIds: []string{r.group2}}) + assertTemplate(answerOf(t, r.body(t, token)), geo) + assertTemplate(previewAnswer(user), geo) order := []string{"nod_b", d, "nod_a", "nod_c"} if err := r.st.SetNodeOrder(r.ctx, nil, order); err != nil { t.Fatal(err) } // Only D and C are usable; the relay through C still travels with D. manual := append(slices.Clone(geo[1:]), geo[0]) - assertEndpoints(previewAnswer(), templateEndpoints(manual)) + assertTemplate(previewAnswer(user), manual) clock = clock.Add(ttl - time.Nanosecond) - assertEndpoints(answerOf(t, r.body(t, token)), geo) + assertTemplate(answerOf(t, r.body(t, token)), geo) clock = clock.Add(time.Nanosecond) - actual := answerOf(t, r.body(t, token)) - assertEndpoints(actual, manual) - names := make([]string, 0, len(manual)) - for _, p := range manual { - names = append(names, p.name) - } - selectMembers := append(append([]string{"Auto"}, names...), "DIRECT") - if len(actual.Groups) != 2 || !slices.Equal(actual.Groups[0].Proxies, selectMembers) || - actual.Groups[1].Name != "Auto" || !slices.Equal(actual.Groups[1].Proxies, names) { - t.Fatalf("built-in groups = %+v, want select %v and Auto %v", actual.Groups, selectMembers, names) - } + assertTemplate(answerOf(t, r.body(t, token)), manual) assertManualOtherFormats() - r.save(t, nameByProfile, &adminv1.MihomoTemplate{Name: "work", Yaml: draft, GroupIds: []string{r.group2}}) - for _, a := range []tplAnswer{answerOf(t, r.body(t, token)), previewAnswer()} { - assertEndpoints(a, templateEndpoints(manual)) - if len(a.Groups) != 2 || !slices.Equal(a.Groups[0].Proxies, []string{"authored-z", "DIRECT", "authored-a"}) || - a.Groups[1].Name != "Auto" || !slices.Equal(a.Groups[1].Proxies, names) { - t.Fatalf("template groups = %+v", a.Groups) - } - } - // Unlisted nodes follow the saved IDs in geographic order (F before E, opposite their IDs). - r.save(t, nameByProfile) addNode("nod_f", "node-f", "AU") addNode("nod_e", "node-e", "FR") - _, newToken := r.newUser("bob", func(c *adminv1.CreateUserRequest) { + bob, bobToken := r.newUser("bob", func(c *adminv1.CreateUserRequest) { c.Nodes = &adminv1.NodeSelection{NodeIds: []string{d, "nod_c", "nod_e", "nod_f"}} }) - withAdditions := endpoints(answerOf(t, r.body(t, newToken))) - if len(withAdditions) != len(manual)+2 || !slices.Equal(withAdditions[:len(manual)], manual) || - withAdditions[len(manual)].server != "node-f.example.com" || withAdditions[len(manual)+1].server != "node-e.example.com" { - t.Fatalf("manual order with unlisted nodes = %v", withAdditions) + bobManual := answerOf(t, r.body(t, bobToken)) + bobEndpoints := endpoints(bobManual) + if len(bobEndpoints) != len(manual)+2+len(authored) { + t.Fatalf("Bob's proxies = %v, want two more nodes than Alice", bobEndpoints) + } + f, e := bobEndpoints[len(manual)], bobEndpoints[len(manual)+1] + if f.server != "node-f.example.com" || e.server != "node-e.example.com" || + f.kind != "hysteria2" || e.kind != "hysteria2" { + t.Fatalf("Bob's extra proxies = %v, %v; want Hysteria2 on F then E", f, e) } - f, e := withAdditions[len(manual)], withAdditions[len(manual)+1] + withAdditions := append(slices.Clone(manual), f, e) + assertTemplate(bobManual, withAdditions) + assertTemplate(previewAnswer(bob), withAdditions) + bobGeo := append([]endpoint{f, geo[0], e}, geo[1:]...) if err := r.st.SetNodeOrder(r.ctx, order, nil); err != nil { t.Fatal(err) } // Preview builds a fresh view, even while repeated HTTP requests still use the previous order. - assertEndpoints(previewAnswer(), templateEndpoints(geo)) + assertTemplate(previewAnswer(user), geo) + assertTemplate(previewAnswer(bob), bobGeo) clock = clock.Add(ttl - time.Nanosecond) - assertEndpoints(answerOf(t, r.body(t, token)), manual) - assertEndpoints(answerOf(t, r.body(t, newToken)), withAdditions) + assertTemplate(answerOf(t, r.body(t, token)), manual) + assertTemplate(answerOf(t, r.body(t, bobToken)), withAdditions) clock = clock.Add(time.Nanosecond) - assertEndpoints(answerOf(t, r.body(t, token)), geo) - assertEndpoints(answerOf(t, r.body(t, newToken)), append([]endpoint{f, geo[0], e}, geo[1:]...)) + assertTemplate(answerOf(t, r.body(t, token)), geo) + assertTemplate(answerOf(t, r.body(t, bobToken)), bobGeo) for i, got := range otherOrders() { if !slices.Equal(got, original[i]) { t.Errorf("format %d order after reset = %v, want %v", i, got, original[i]) diff --git a/internal/panel/subs/mihomo_order_core_test.go b/internal/panel/subs/mihomo_order_core_test.go new file mode 100644 index 000000000..28f7964ba --- /dev/null +++ b/internal/panel/subs/mihomo_order_core_test.go @@ -0,0 +1,333 @@ +package subs + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strings" + "sync" + "testing" + "time" +) + +// Observe the effective order in the core, not merely the order of the rendered YAML. +// Mihomo v1.19.34 reapplies multi-part filter priorities across providers after assembling a group. +func TestMihomoCoreOrderedGroups(t *testing.T) { + bin := os.Getenv("MIHOMO_BIN") + if bin == "" { + t.Skip("set MIHOMO_BIN to the Mihomo v1.19.34 executable") + } + + health := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodHead || r.URL.Path != "/health" { + http.NotFound(w, r) + return + } + w.Header().Set("Connection", "close") + w.WriteHeader(http.StatusNoContent) + })) + t.Cleanup(health.Close) + healthURL := health.URL + "/health" + target := health.Listener.Addr().(*net.TCPAddr) + httpPort := orderedMihomoHTTPProxy(t, target.String()) + socksPort := orderedMihomoSOCKSProxy(t, target.Port) + proxy := func(name, kind string, port int) string { + return fmt.Sprintf("- {name: %q, type: %s, server: 127.0.0.1, port: %d}\n", name, kind, port) + } + p := mihomoProfile{title: "Order fixture"} + for _, node := range []string{"DE-2", "LV", "DE-1", "KZ", "RU"} { + // Both the country order and the order of transports deliberately differ from name sorting. + p.names = append(p.names, node+" socks5", node+" http") + p.lines = append(p.lines, proxy("fragment", "socks5", socksPort), proxy("fragment", "http", httpPort)) + } + + dir := t.TempDir() + for _, provider := range []struct{ file, name string }{ + {"pasha.yaml", "Pasha"}, {"oversecure.yaml", "Oversecure"}, + } { + var file strings.Builder + file.WriteString("proxies:\n") + for _, country := range []string{"DE", "KZ", "RU"} { + file.WriteString(proxy(provider.name+" "+country, "http", httpPort)) + } + if err := os.WriteFile(filepath.Join(dir, provider.file), []byte(file.String()), 0o600); err != nil { + t.Fatal(err) + } + } + + tpl := fmt.Sprintf(`external-controller: '127.0.0.1:0' +log-level: info +geo-auto-update: false +unified-delay: false +proxy-providers: + pasha-main: + type: file + path: pasha.yaml + health-check: {enable: true, url: %[1]q, expected-status: '204'} + oversecure: + type: file + path: oversecure.yaml + health-check: {enable: true, url: %[1]q, expected-status: '204'} +proxy-groups: + - name: Auto + type: fallback + include-all-proxies: true + use: [oversecure, pasha-main] + url: %[1]q + expected-status: '204' + - name: AI Auto + type: fallback + include-all-proxies: true + use: [pasha-main, oversecure] + filter: %[2]q + exclude-filter: '(^| )RU( |$)' + url: %[1]q + expected-status: '204' + - name: Provider only + type: select + use: [pasha-main, oversecure] +rules: ['MATCH,Auto'] +`, healthURL, "KZ`.*") + out, used := templated(t, tpl, p) + if !used { + t.Fatal("the built-in profile was sent") + } + + got := orderedMihomoCoreProxies(t, bin, dir, out, healthURL, p.names) + for _, want := range []struct { + group, kind string + all []string + }{ + {"Auto", "Fallback", []string{ + "DE-2 socks5", "DE-2 http", "LV socks5", "LV http", "DE-1 socks5", "DE-1 http", "KZ socks5", "KZ http", "RU socks5", "RU http", + "Oversecure DE", "Oversecure KZ", "Oversecure RU", "Pasha DE", "Pasha KZ", "Pasha RU", + }}, + {"AI Auto", "Fallback", []string{ + "KZ socks5", "KZ http", "Pasha KZ", "Oversecure KZ", + "DE-2 socks5", "DE-2 http", "LV socks5", "LV http", "DE-1 socks5", "DE-1 http", "Pasha DE", "Oversecure DE", + }}, + {"Provider only", "Selector", []string{"Pasha DE", "Pasha KZ", "Pasha RU", "Oversecure DE", "Oversecure KZ", "Oversecure RU"}}, + } { + g := got[want.group] + if g.Type != want.kind || !slices.Equal(g.All, want.all) || g.Now != want.all[0] { + t.Errorf("%s: type=%q all=%q now=%q; want type=%q all=%q now=%q", want.group, g.Type, g.All, g.Now, want.kind, want.all, want.all[0]) + } + } +} + +type orderedMihomoProxy struct { + Type string `json:"type"` + All []string `json:"all"` + Now string `json:"now"` + Extra map[string]struct { + Alive bool `json:"alive"` + History []struct { + Delay uint16 `json:"delay"` + } `json:"history"` + } `json:"extra"` +} + +func orderedMihomoCoreProxies(t *testing.T, bin, dir, config, healthURL string, locals []string) map[string]orderedMihomoProxy { + t.Helper() + cfg := filepath.Join(dir, "config.yaml") + if err := os.WriteFile(cfg, []byte(config), 0o600); err != nil { + t.Fatal(err) + } + logFile, err := os.Create(filepath.Join(dir, "mihomo.log")) + if err != nil { + t.Fatal(err) + } + defer logFile.Close() + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + t.Cleanup(cancel) + cmd := exec.CommandContext(ctx, bin, "-d", dir, "-f", cfg) + // Don't inherit controller overrides, shell hooks or proxy environment variables. + cmd.Env = []string{"NO_COLOR=1"} + cmd.Stdout, cmd.Stderr = logFile, logFile + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + done := make(chan struct{}) + var exitErr error + go func() { + exitErr = cmd.Wait() + close(done) + }() + t.Cleanup(func() { + cancel() + <-done + if t.Failed() { + log, _ := os.ReadFile(logFile.Name()) + t.Logf("Mihomo output:\n%s", log) + } + }) + + // Let the core bind port zero itself; reserving and releasing a Go listener would race other tests. + bound := regexp.MustCompile(`RESTful API listening at: (127\.0\.0\.1:[0-9]+)`) + client := &http.Client{Transport: &http.Transport{}, Timeout: time.Second} + defer client.CloseIdleConnections() + tick := time.NewTicker(25 * time.Millisecond) + defer tick.Stop() + var status, endpoint string + for { + if endpoint == "" { + status = "waiting for the loopback controller" + log, err := os.ReadFile(logFile.Name()) + if err != nil { + t.Fatal(err) + } + if m := bound.FindSubmatch(log); m != nil { + endpoint = "http://" + string(m[1]) + "/proxies" + } + } + if endpoint != "" { + if got, err := orderedMihomoSnapshot(ctx, client, endpoint, healthURL, locals); err == nil { + return got + } else { + status = err.Error() + } + } + select { + case <-done: + t.Fatalf("Mihomo exited (%v): %s", exitErr, status) + case <-ctx.Done(): + t.Fatalf("Mihomo did not become ready: %s", status) + case <-tick.C: + } + } +} + +func orderedMihomoSnapshot(ctx context.Context, client *http.Client, endpoint, healthURL string, locals []string) (map[string]orderedMihomoProxy, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("GET /proxies: %s", resp.Status) + } + var snapshot struct { + Proxies map[string]orderedMihomoProxy `json:"proxies"` + } + if err := json.NewDecoder(resp.Body).Decode(&snapshot); err != nil { + return nil, err + } + // The controller can respond before provider loading or before the first health pass. + all := snapshot.Proxies["Provider only"].All + if !slices.Contains(all, "Pasha DE") || !slices.Contains(all, "Oversecure DE") { + return nil, fmt.Errorf("file providers not loaded: %q", all) + } + for _, name := range locals { + h := snapshot.Proxies[name].Extra[healthURL] + // Before the first actual check, Mihomo considers proxies alive by default. + if n := len(h.History); !h.Alive || n == 0 || h.History[n-1].Delay == 0 { + return nil, fmt.Errorf("%q has no successful health check at %s", name, healthURL) + } + } + return snapshot.Proxies, nil +} + +func orderedMihomoHTTPProxy(t *testing.T, target string) int { + t.Helper() + s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodConnect || r.Host != target { + http.Error(w, "only the local health endpoint is allowed", http.StatusForbidden) + return + } + conn, rw, err := http.NewResponseController(w).Hijack() + if err != nil { + return + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(2 * time.Second)) + orderedMihomoTunnel(conn, rw, target, func() error { + if _, err := rw.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil { + return err + } + return rw.Flush() + }) + })) + t.Cleanup(s.Close) + return s.Listener.Addr().(*net.TCPAddr).Port +} + +func orderedMihomoSOCKSProxy(t *testing.T, targetPort int) int { + t.Helper() + ln, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + target := fmt.Sprintf("127.0.0.1:%d", targetPort) + want := [10]byte{5, 1, 0, 1, 127, 0, 0, 1, byte(targetPort >> 8), byte(targetPort)} + var workers sync.WaitGroup + done := make(chan struct{}) + go func() { + defer close(done) + for { + conn, err := ln.Accept() + if err != nil { + return + } + workers.Go(func() { + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(2 * time.Second)) + // Accept only no-auth negotiation and an IPv4 CONNECT to the health fixture. + var hello [3]byte + if _, err := io.ReadFull(conn, hello[:]); err != nil || hello != [3]byte{5, 1, 0} { + return + } + if _, err := conn.Write([]byte{5, 0}); err != nil { + return + } + var request [10]byte + if _, err := io.ReadFull(conn, request[:]); err != nil || request != want { + return + } + orderedMihomoTunnel(conn, conn, target, func() error { + _, err := conn.Write([]byte{5, 0, 0, 1, 127, 0, 0, 1, 0, 0}) + return err + }) + }) + } + }() + t.Cleanup(func() { + _ = ln.Close() + <-done + workers.Wait() + }) + return ln.Addr().(*net.TCPAddr).Port +} + +func orderedMihomoTunnel(client net.Conn, in io.Reader, target string, ready func() error) { + upstream, err := net.DialTimeout("tcp4", target, time.Second) + if err != nil { + return + } + defer upstream.Close() + _ = upstream.SetDeadline(time.Now().Add(2 * time.Second)) + if err := ready(); err != nil { + return + } + done := make(chan struct{}) + go func() { + _, _ = io.Copy(upstream, in) + _ = upstream.(*net.TCPConn).CloseWrite() + close(done) + }() + _, _ = io.Copy(client, upstream) + _ = client.Close() + <-done +} diff --git a/internal/panel/subs/mihomo_template_internal_test.go b/internal/panel/subs/mihomo_template_internal_test.go index adc6736a6..47e1623dd 100644 --- a/internal/panel/subs/mihomo_template_internal_test.go +++ b/internal/panel/subs/mihomo_template_internal_test.go @@ -312,7 +312,7 @@ func TestMihomoTemplateDNS(t *testing.T) { func TestMihomoTemplateKeepsTheText(t *testing.T) { out, _ := templated(t, templateText(t, "mihomo_template_router.yaml"), twoServers(t)) for _, want := range []string{ - "# Router: transparent proxy for the LAN.", "x-check: &check", "<<: *check", "bind-address: \"*\"", "proxies: [Auto, DIRECT] # the panel's Auto group", + "# Router: transparent proxy for the LAN.", "x-check: &check", "<<: *check", "bind-address: \"*\"", "# the panel's Auto group", "filter: \"(?i)de|nl\"", "- GEOIP,LAN,DIRECT,no-resolve", } { if !strings.Contains(out, want) { diff --git a/internal/panel/subs/mihomo_template_test.go b/internal/panel/subs/mihomo_template_test.go index 0c32b0c3e..0d127d648 100644 --- a/internal/panel/subs/mihomo_template_test.go +++ b/internal/panel/subs/mihomo_template_test.go @@ -357,6 +357,10 @@ rules: } else if _, present := doc["proxy-providers"]; present || strings.Contains(output, "comment.example") { t.Errorf("other group got the PC block:\n%s", output) } + wantMembers = append(wantMembers, "p") + if tc.name == "ROUTER" { + wantMembers = append(wantMembers, "awg31") + } dns, _ := doc["dns"].(map[string]any) if doc["find-process-mode"] != tc.process || !reflect.DeepEqual(doc["tun"], wantTun) || !reflect.DeepEqual(dns["fake-ip-filter"], wantFilter) || !reflect.DeepEqual(doc["rules"], wantRules) { diff --git a/internal/panel/subs/testdata/mihomo_template_pc.out.yaml b/internal/panel/subs/testdata/mihomo_template_pc.out.yaml index 2c7ed7b5e..8847b8d6b 100644 --- a/internal/panel/subs/testdata/mihomo_template_pc.out.yaml +++ b/internal/panel/subs/testdata/mihomo_template_pc.out.yaml @@ -67,15 +67,21 @@ proxies: proxy-groups: - name: Servers type: select - include-all-proxies: true + include-all-proxies: false + proxies: + - "\U0001F1E9\U0001F1EA de1 · hy2" + - "\U0001F1F3\U0001F1F1 nl1 · awg" + - "office-socks" - name: Work type: select use: [office] proxies: [office-socks, DIRECT] - name: Nobody type: url-test - include-all-proxies: true + include-all-proxies: false filter: "no-such-server" + proxies: + - "COMPATIBLE" - name: "Auto" type: url-test proxies: diff --git a/internal/panel/subs/testdata/mihomo_template_router.out.yaml b/internal/panel/subs/testdata/mihomo_template_router.out.yaml index 1ab3ea310..13974a467 100644 --- a/internal/panel/subs/testdata/mihomo_template_router.out.yaml +++ b/internal/panel/subs/testdata/mihomo_template_router.out.yaml @@ -13,13 +13,16 @@ x-check: &check proxy-groups: - name: Proxy type: select - include-all-proxies: true - proxies: [Auto, DIRECT] # the panel's Auto group + include-all-proxies: false + proxies: [Auto, DIRECT, "\U0001F1E9\U0001F1EA de1 · hy2", "\U0001F1F3\U0001F1F1 nl1 · awg"] # the panel's Auto group - name: Fast <<: *check type: url-test - include-all-proxies: true + include-all-proxies: false filter: "(?i)de|nl" + proxies: + - "\U0001F1E9\U0001F1EA de1 · hy2" + - "\U0001F1F3\U0001F1F1 nl1 · awg" - name: "Auto" type: url-test proxies: diff --git a/internal/panel/subsettings/mihomo.go b/internal/panel/subsettings/mihomo.go index 4d9943fa1..c7599a858 100644 --- a/internal/panel/subsettings/mihomo.go +++ b/internal/panel/subsettings/mihomo.go @@ -22,9 +22,9 @@ import ( // the save is the trust boundary. Names of servers are hostile input: they enter the document as yaml.Node values with a quoted // style, never as text. // -// The panel touches three keys of the root: `proxies` (the person's servers go first), `proxy-groups` (an `Auto` group is added at -// the end while the switch of automatic selection is on and the template has no name `Auto`) and `dns` (added only when the template -// has none). The rest is encoded back as it was read, comments and anchors included. +// The panel touches three keys of the root: `proxies` (the person's servers go first), `proxy-groups` (automatic local members +// follow the person's server order, and an `Auto` group may be added) and `dns` (added only when the template has none). +// The rest is encoded back as it was read, comments and anchors included. // Limits enforced by Validate. const ( @@ -245,12 +245,15 @@ type tplNamed struct { } type tplGroup struct { - Name string `yaml:"name"` - Type string `yaml:"type"` - Proxies []string `yaml:"proxies"` - Use []string `yaml:"use"` - IncludeAllProxies bool `yaml:"include-all-proxies"` - IncludeAll bool `yaml:"include-all"` + Name string `yaml:"name"` + Type string `yaml:"type"` + Proxies []string `yaml:"proxies"` + Use []string `yaml:"use"` + Filter string `yaml:"filter"` + IncludeAllProxies bool `yaml:"include-all-proxies"` + IncludeAllProviders bool `yaml:"include-all-providers"` + IncludeAll bool `yaml:"include-all"` + EmptyFallback string `yaml:"empty-fallback"` } // tplInfo is a template read for the keys the panel works on. @@ -467,8 +470,8 @@ type MihomoOptions struct { var ErrNoServers = errors.New("mihomo template: no servers") // ApplyMihomoTemplate puts the servers of a person into a template: they go first in `proxies` (a name the template or the core has -// gets " ·" added, the template's names are never changed), then `Auto` and `dns` as described at the top of this file. The template -// is read anew each call (the stored document is shared: its nodes are not modified). The result is the document to send. +// gets " ·" added, the template's names are never changed), then expands automatic local group members and adds `Auto` and `dns` +// as described at the top of this file. The template is read anew each call. The result is the document to send. // // ponytail: a read, a decode of the names and an encode on every request (about 6 ms of wasm CPU for a 14 KB template, 27 ms for // 64 KiB). If that ever costs too much: remember the nodes per template text and copy them deeply. @@ -496,6 +499,9 @@ func ApplyMihomoTemplate(text string, servers []MihomoServer, opt MihomoOptions) names = append(names, name) nodes = append(nodes, s.Node) } + if err := expandOrderedMihomoGroups(t, names); err != nil { + return nil, err + } // The key is added at the end of the root when the template lacks it (or has it null). list := func(key string) *yaml.Node { diff --git a/internal/panel/subsettings/mihomo_ordered_groups.go b/internal/panel/subsettings/mihomo_ordered_groups.go new file mode 100644 index 000000000..ec5dcd9f8 --- /dev/null +++ b/internal/panel/subsettings/mihomo_ordered_groups.go @@ -0,0 +1,195 @@ +package subsettings + +import ( + "errors" + "fmt" + "strings" + "time" + + "github.com/dlclark/regexp2" + "gopkg.in/yaml.v3" +) + +const mihomoFilterBudget = 250 * time.Millisecond + +var errMihomoFilterBudget = errors.New("filter exceeded the matching time limit") + +// A filter cache belongs to one render. Regexp.MatchTimeout is mutable, so +// these expressions cannot be shared across renders. +type mihomoGroupFilters struct { + compiled map[string]*regexp2.Regexp + deadline time.Time +} + +func (f *mihomoGroupFilters) match(pattern, name string) (bool, error) { + remaining := time.Until(f.deadline) + if remaining <= 0 { + return false, errMihomoFilterBudget + } + re := f.compiled[pattern] + re.MatchTimeout = remaining + matched, err := re.MatchString(name) + if err != nil || time.Until(f.deadline) <= 0 { + return false, errMihomoFilterBudget + } + return matched, nil +} + +func (f *mihomoGroupFilters) orderedMembers(g tplGroup, names []string, static []tplNamed) ([]string, error) { + members := make([]string, 0, len(g.Proxies)+len(names)+len(static)) + members = append(members, g.Proxies...) + seen := make(map[string]bool, cap(members)) + for _, name := range members { + seen[name] = true + } + if g.Filter != "" && f.compiled == nil { + f.compiled = make(map[string]*regexp2.Regexp) + f.deadline = time.Now().Add(mihomoFilterBudget) + } + // For an empty filter the single empty expression means no matching is needed. + // In a nonempty filter, an empty component is a real regexp, just as in Mihomo. + for pattern := range strings.SplitSeq(g.Filter, "`") { + if g.Filter != "" && f.compiled[pattern] == nil { + if time.Until(f.deadline) <= 0 { + return nil, errMihomoFilterBudget + } + re, err := regexp2.Compile(pattern, regexp2.None) + if err != nil { + return nil, errors.New("invalid filter regular expression") + } + f.compiled[pattern] = re + } + add := func(name string) error { + if seen[name] { + return nil + } + if g.Filter != "" { + matched, err := f.match(pattern, name) + if err != nil || !matched { + return err + } + } + seen[name] = true + members = append(members, name) + return nil + } + for _, name := range names { + if err := add(name); err != nil { + return nil, err + } + } + for _, p := range static { + if err := add(p.Name); err != nil { + return nil, err + } + } + if g.Filter != "" && time.Until(f.deadline) <= 0 { + return nil, errMihomoFilterBudget + } + } + return members, nil +} + +func expandOrderedMihomoGroups(t *tplInfo, names []string) error { + groups, _ := rootValue(t.root, "proxy-groups") + var filters mihomoGroupFilters + providerCount := -1 + for i, g := range t.groups { + if !g.IncludeAll && !g.IncludeAllProxies { + continue + } + members, err := filters.orderedMembers(g, names, t.proxies) + if err != nil { + return fmt.Errorf("proxy-groups[%d]: %w", i, err) + } + if len(members) == 0 { + count := len(g.Use) + if g.IncludeAll || g.IncludeAllProviders { + if providerCount < 0 { + var providers map[string]yaml.Node + if v, _ := rootValue(t.root, "proxy-providers"); v != nil { + if err := v.Decode(&providers); err != nil { + return mihomoYAMLDiagnostic{err: err, prefix: "proxy-providers: "} + } + } + providerCount = len(providers) + } + count = providerCount + } + if count == 0 { + fallback := g.EmptyFallback + if fallback == "" { + fallback = "COMPATIBLE" + } + members = append(members, fallback) + } + } + + group := groups.Content[i] + if group.Kind == yaml.AliasNode || group.Anchor != "" || + groupValueHasAnchor(group, "proxies") || + g.IncludeAllProxies && groupValueHasAnchor(group, "include-all-proxies") || + g.IncludeAll && (groupValueHasAnchor(group, "include-all") || groupValueHasAnchor(group, "include-all-providers")) { + // Keep original anchor definitions inline and before their readers. A + // local merge overlay changes this group without changing what any alias sees. + group = mapOf(&yaml.Node{Kind: yaml.ScalarNode, Tag: "!!merge", Value: "<<"}, group) + groups.Content[i] = group + } + seq := quotedSeqOf(members) + if old, _ := rootValue(group, "proxies"); old != nil && old.Kind == yaml.SequenceNode { + // Keep the authored scalars and their comments. The decoded list + // can be shorter than the YAML sequence (e.g. a null item). + seq.Style = old.Style + seq.Content = append(old.Content, seq.Content[len(g.Proxies):]...) + } + setGroupValue(group, "proxies", seq) + if g.IncludeAllProxies { + setGroupBool(group, "include-all-proxies", false) + } + if g.IncludeAll { + setGroupBool(group, "include-all", false) + if !g.IncludeAllProviders { + setGroupBool(group, "include-all-providers", true) + } + } + } + return nil +} + +func groupValueHasAnchor(group *yaml.Node, key string) bool { + v, _ := rootValue(group, key) + return v != nil && hasYAMLAnchor(v) +} + +func hasYAMLAnchor(node *yaml.Node) bool { + if node.Anchor != "" { + return true + } + for _, child := range node.Content { + if hasYAMLAnchor(child) { + return true + } + } + return false +} + +func copyYAMLComments(dst, src *yaml.Node) { + dst.HeadComment, dst.LineComment, dst.FootComment = src.HeadComment, src.LineComment, src.FootComment +} + +func setGroupValue(group *yaml.Node, key string, value *yaml.Node) { + if old, i := rootValue(group, key); old != nil { + copyYAMLComments(value, old) + group.Content[i] = value + } else { + group.Content = append(group.Content, strNode(key), value) + } +} + +func setGroupBool(group *yaml.Node, key string, enabled bool) { + value := "false" + if enabled { + value = "true" + } + setGroupValue(group, key, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!bool", Value: value}) +} diff --git a/internal/panel/subsettings/mihomo_ordered_groups_test.go b/internal/panel/subsettings/mihomo_ordered_groups_test.go new file mode 100644 index 000000000..b3f339099 --- /dev/null +++ b/internal/panel/subsettings/mihomo_ordered_groups_test.go @@ -0,0 +1,142 @@ +package subsettings + +import ( + "errors" + "slices" + "strings" + "testing" + "time" + + "github.com/dlclark/regexp2" + "gopkg.in/yaml.v3" +) + +func TestMihomoOrderedGroups(t *testing.T) { + const head = `proxies: + - {name: Static, type: direct} + - {name: Another, type: direct} +proxy-providers: + Example: {type: file, path: example.yaml} +proxy-groups: + - name: Pick + type: fallback +` + for _, tc := range []struct { + name, fields string + want []string + providers bool + use []string + }{ + {"explicit and unique final names", " proxies: [Static, DIRECT]\n include-all-proxies: true\n", []string{"Static", "DIRECT", "Zulu", "Static ·", "Alpha", "Zulu ·", "Another"}, false, nil}, + {"ordered overlapping expressions with lookahead", " proxies: [DIRECT]\n include-all-proxies: true\n filter: '^Z(?=ulu ·$)`^[AZ]`.*'\n", []string{"DIRECT", "Zulu ·", "Zulu", "Alpha", "Another", "Static ·", "Static"}, false, nil}, + {"empty with reject", " include-all-proxies: true\n filter: '^Nothing$'\n empty-fallback: REJECT\n", []string{"REJECT"}, false, nil}, + {"empty by default", " include-all-proxies: true\n filter: '^Nothing$'\n", []string{"COMPATIBLE"}, false, nil}, + {"empty locals with explicit provider", " include-all-proxies: true\n filter: '^Nothing$'\n use: [Example]\n", nil, false, []string{"Example"}}, + {"include all implies providers", " include-all: true\n include-all-providers: false\n filter: '^Nothing$'\n", nil, true, nil}, + {"include all providers without locals", " include-all-proxies: true\n include-all-providers: true\n filter: '^Nothing$'\n", nil, true, nil}, + {"provider only", " use: [Example]\n", nil, false, []string{"Example"}}, + } { + t.Run(tc.name, func(t *testing.T) { + out, _ := apply(t, head+tc.fields, MihomoOptions{}, "Zulu", "Static", "Alpha", "Zulu") + info, err := loadTemplate(out) + if err != nil { + t.Fatal(err) + } + g := info.groups[0] + if !slices.Equal(g.Proxies, tc.want) || g.IncludeAll || g.IncludeAllProxies || g.IncludeAllProviders != tc.providers || !slices.Equal(g.Use, tc.use) { + t.Fatalf("group = %+v; want members %q, include-all-providers %t, use %q", g, tc.want, tc.providers, tc.use) + } + }) + } + t.Run("include all providers ignores use when provider map is empty", func(t *testing.T) { + out, _ := apply(t, `proxy-groups: + - name: Pick + type: select + include-all: true + use: [Ignored] + filter: '^Nothing$' +`, MihomoOptions{}, "Zulu") + info, err := loadTemplate(out) + if err != nil { + t.Fatal(err) + } + if got := info.groups[0].Proxies; !slices.Equal(got, []string{"COMPATIBLE"}) { + t.Fatalf("members = %q", got) + } + }) + t.Run("aliases and inherited flags stay local", func(t *testing.T) { + const text = `x-default: &default + type: select + include-all-proxies: true + proxies: &shared [DIRECT] # shared list +x-group: &aliased + <<: *default + name: Aliased +proxy-groups: + - *aliased + - &original + <<: *default + name: Changed + include-all: &flag true + proxies: &list + - &member REJECT # anchored member + - name: Outside + type: select + proxies: *list + - name: Inherited + <<: *default + include-all-proxies: false +x-copy: *original +x-flag: *flag +x-member: *member +` + out, _ := apply(t, text, MihomoOptions{}, "Zulu", "Alpha") + if err := CheckMihomoTemplate(out, false); err != nil { + t.Fatalf("changed output does not pass validation: %v\n%s", err, out) + } + var d struct { + Groups []tplGroup `yaml:"proxy-groups"` + Alias tplGroup `yaml:"x-group"` + Copy tplGroup `yaml:"x-copy"` + Flag bool `yaml:"x-flag"` + Member string `yaml:"x-member"` + } + if err := yaml.Unmarshal([]byte(out), &d); err != nil { + t.Fatal(err) + } + want := [][]string{{"DIRECT", "Zulu", "Alpha"}, {"REJECT", "Zulu", "Alpha"}, {"REJECT"}, {"DIRECT"}} + for i, g := range d.Groups { + if g.IncludeAll || g.IncludeAllProxies || !slices.Equal(g.Proxies, want[i]) { + t.Fatalf("group %s = %+v; want %q without local auto-inclusion", g.Name, g, want[i]) + } + } + if !d.Alias.IncludeAllProxies || !slices.Equal(d.Alias.Proxies, []string{"DIRECT"}) || !d.Copy.IncludeAll || !d.Copy.IncludeAllProxies || !slices.Equal(d.Copy.Proxies, []string{"REJECT"}) || !d.Flag || d.Member != "REJECT" { + t.Fatalf("source values changed: %+v\n%s", d, out) + } + for _, comment := range []string{"# shared list", "# anchored member"} { + if !strings.Contains(out, comment) { + t.Fatalf("lost %q:\n%s", comment, out) + } + } + }) + t.Run("invalid expression is rejected without its text", func(t *testing.T) { + const text = head + " include-all-proxies: true\n filter: '.*`(private-pattern'\n" + out, err := ApplyMihomoTemplate(text, []MihomoServer{serverNode(t, "private-node")}, MihomoOptions{}) + if len(out) != 0 || err == nil || !strings.Contains(err.Error(), "invalid filter") || strings.Contains(err.Error(), "private-") { + t.Fatalf("output = %q, error = %v", out, err) + } + if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "invalid filter") { + t.Fatalf("save validation error = %v", err) + } + }) + t.Run("expired filter budget", func(t *testing.T) { + f := mihomoGroupFilters{ + compiled: map[string]*regexp2.Regexp{".*": regexp2.MustCompile(".*", regexp2.None)}, + deadline: time.Now().Add(-time.Second), + } + got, err := f.orderedMembers(tplGroup{Filter: ".*", Proxies: []string{"DIRECT"}}, []string{"Zulu"}, nil) + if got != nil || !errors.Is(err, errMihomoFilterBudget) { + t.Fatalf("members = %q, error = %v", got, err) + } + }) +} From d46d589b7c085bc3402c4fcb7394bbd6bcd2b64a Mon Sep 17 00:00:00 2001 From: Morvex885 <278529280+Morvex885@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:44:05 +0300 Subject: [PATCH 2/9] Resolve Mihomo YAML aliases used as mapping keys --- internal/panel/subsettings/mihomo.go | 15 +++++++-- .../subsettings/mihomo_ordered_groups_test.go | 31 +++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/internal/panel/subsettings/mihomo.go b/internal/panel/subsettings/mihomo.go index c7599a858..006f0c584 100644 --- a/internal/panel/subsettings/mihomo.go +++ b/internal/panel/subsettings/mihomo.go @@ -202,10 +202,19 @@ func parseDocument(text string) (doc, root *yaml.Node, err error) { return doc, doc.Content[0], nil } +// yaml.v3 resolves aliases when decoding mapping keys. Use the same key +// when editing the node tree, without replacing the alias in the document. +func mappingKey(n *yaml.Node) *yaml.Node { + if n.Kind == yaml.AliasNode { + return n.Alias + } + return n +} + // rootValue is the value of a key of the root mapping and the index of that value in root.Content; nil, -1 when the key is absent. func rootValue(root *yaml.Node, key string) (*yaml.Node, int) { for i := 0; i+1 < len(root.Content); i += 2 { - if k := root.Content[i]; k.Kind == yaml.ScalarNode && k.Value == key { + if k := mappingKey(root.Content[i]); k.Kind == yaml.ScalarNode && k.Value == key { return root.Content[i+1], i + 1 } } @@ -221,9 +230,9 @@ func checkRootShape(root *yaml.Node) error { return fmt.Errorf("line %d: the root must be a mapping (key: value lines)", root.Line) } for i := 0; i+1 < len(root.Content); i += 2 { - k, v := root.Content[i], root.Content[i+1] + k, v := mappingKey(root.Content[i]), root.Content[i+1] if k.Kind == yaml.ScalarNode && (k.ShortTag() == "!!merge" || k.Value == "<<") && k.Style == 0 { - return fmt.Errorf("line %d: a merge key `<<` at the root is not supported", k.Line) + return fmt.Errorf("line %d: a merge key `<<` at the root is not supported", root.Content[i].Line) } if k.Kind != yaml.ScalarNode || (k.Value != "proxies" && k.Value != "proxy-groups") { continue diff --git a/internal/panel/subsettings/mihomo_ordered_groups_test.go b/internal/panel/subsettings/mihomo_ordered_groups_test.go index b3f339099..487b74efb 100644 --- a/internal/panel/subsettings/mihomo_ordered_groups_test.go +++ b/internal/panel/subsettings/mihomo_ordered_groups_test.go @@ -119,6 +119,37 @@ x-member: *member } } }) + t.Run("alias keys at the root and inside a group", func(t *testing.T) { + const text = `x-groups-key: &groups-key proxy-groups +x-proxies-key: &proxies-key proxies +x-include-key: &include-key include-all-proxies +*groups-key: + - name: Pick + type: select + *include-key: true + *proxies-key: [DIRECT] +` + out, _ := apply(t, text, MihomoOptions{}, "Zulu", "Alpha") + info, err := loadTemplate(out) + if err != nil { + t.Fatal(err) + } + if got := info.groups[0]; got.IncludeAllProxies || !slices.Equal(got.Proxies, []string{"DIRECT", "Zulu", "Alpha"}) { + t.Fatalf("group = %+v", got) + } + if err := CheckMihomoTemplate(out, false); err != nil { + t.Fatal(err) + } + }) + t.Run("an alias key does not bypass the root shape check", func(t *testing.T) { + const text = `x-key: &key proxy-groups +x-list: &list [{name: Pick, type: select, include-all-proxies: true}] +*key: *list +` + if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "must be a list written out") { + t.Fatalf("save validation error = %v", err) + } + }) t.Run("invalid expression is rejected without its text", func(t *testing.T) { const text = head + " include-all-proxies: true\n filter: '.*`(private-pattern'\n" out, err := ApplyMihomoTemplate(text, []MihomoServer{serverNode(t, "private-node")}, MihomoOptions{}) From 1bc2af7d7146a426291a5b4d7344b84c011248de Mon Sep 17 00:00:00 2001 From: Morvex885 <278529280+Morvex885@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:58:31 +0300 Subject: [PATCH 3/9] Make ordered Mihomo groups a Mistgate opt-in Keep native Mihomo auto-inclusion unchanged. Use x-mistgate-ordered-proxies in new templates and strip it from the emitted YAML. Refs #92. --- docs/en/guide/subscriptions.md | 25 +++--- docs/ru/guide/subscriptions.md | 25 +++--- docs/zh/guide/subscriptions.md | 25 +++--- internal/panel/subs/mihomo_node_order_test.go | 4 +- internal/panel/subs/mihomo_order_core_test.go | 14 +++- internal/panel/subs/mihomo_preview_test.go | 5 +- .../panel/subs/mihomo_template_core_test.go | 2 +- .../subs/mihomo_template_internal_test.go | 2 +- internal/panel/subs/mihomo_template_test.go | 10 ++- .../subs/testdata/mihomo_template_pc.out.yaml | 2 - .../subs/testdata/mihomo_template_pc.yaml | 4 +- .../testdata/mihomo_template_router.out.yaml | 2 - .../subs/testdata/mihomo_template_router.yaml | 4 +- internal/panel/subsettings/mihomo.go | 44 +++++++--- .../subsettings/mihomo_ordered_groups.go | 83 ++++++++++--------- .../subsettings/mihomo_ordered_groups_test.go | 82 +++++++++++++----- web/src/i18n/subs.ts | 10 +-- web/src/screens/subscriptions/mihomo.test.tsx | 4 +- web/src/screens/subscriptions/model.ts | 7 +- 19 files changed, 226 insertions(+), 128 deletions(-) diff --git a/docs/en/guide/subscriptions.md b/docs/en/guide/subscriptions.md index 86f47e9dd..d45bab663 100644 --- a/docs/en/guide/subscriptions.md +++ b/docs/en/guide/subscriptions.md @@ -323,7 +323,7 @@ The panel touches three keys of the root and leaves the rest as you wrote it, wi | Key | What the panel does | |:--|:--| | `proxies` | Puts the person's servers **first**, before the proxies you wrote. A missing key (or `null`) is created. | -| `proxy-groups` | Adds the group `Auto` at the end while **Automatic server choice** is on and the template has no group of that name, even for a person with one server, so that your groups can refer to it. It is a `url-test` over the person's servers (not over your own `proxies`). | +| `proxy-groups` | Expands groups that opt in to panel order (see below). Also adds `Auto` at the end while **Automatic server choice** is on and the template has no group of that name, even for a person with one server, so your groups can refer to it. It is a `url-test` over the person's servers (not over your own `proxies`). | | `dns` | Only when the template has none: the resolvers of the person's DNS preset, with `respect-rules: true`. Nothing else of the preset is added (see below). | Everything else is yours: `rules`, `rule-providers`, `proxy-providers`, `tun`, the ports. The rules of the person's DNS preset (blocked ads, the split, countries) are **not** added to a template, because the order of the rules and the `MATCH` are yours; write them in the template if you need them. When the template has its own `dns`, the person's DNS preset and their pick on the page do not apply to the Mihomo apps (the other apps keep them). @@ -332,14 +332,17 @@ The panel names the person's servers by the [server name template](#names-texts) ### Getting the servers into your groups -Do not write a server's name in a group: the servers differ from person to person, and a name a person does not have makes Mihomo refuse the whole file. The save refuses it too. Ask Mihomo for the servers instead: +Do not write a person's server name in a group: the servers differ from person to person, and a name a person does not have makes Mihomo refuse the whole file. The save refuses it too. You can refer to `Auto` for speed-based selection over the person's servers when the panel adds that group. -- `include-all-proxies: true` adds the person's servers in panel order after the group's explicit members, then template proxies in declaration order; -- `filter` and `exclude-filter` (regular expressions) narrow them by name, for example `filter: "Germany"`; -- `include-all: true` also adds providers from `proxy-providers`; with an explicit `use` list, providers follow the local proxies in the listed order; -- the group `Auto` is the person's servers by speed. +To use panel order, set `x-mistgate-ordered-proxies: true` on each proxy group you want to change. New templates start with this flag in their `Proxy` group. When rendering a subscription or preview, Mistgate keeps the entries already listed in the group's `proxies`, then appends the person's matching servers in panel order, then matching proxies declared in the template in declaration order, without adding names already present. Mistgate leaves the flag in the saved template but removes it from the rendered YAML. If no members match and the group has neither explicit members nor providers, the panel uses `empty-fallback`, or `COMPATIBLE` if it is not set. -When `filter` contains multiple backtick-separated expressions, their priority takes precedence over source order: in a mixed group Mihomo collects matches for the first expression across all sources before moving to the next. +Saved templates are not migrated. Without the opt-in, `include-all-proxies` and `include-all` keep their native Mihomo behavior, which sorts the automatically included local proxies by name. To switch an existing group: + +- Replace `include-all-proxies: true` with `x-mistgate-ordered-proxies: true`. Keep any existing `include-all-providers` or `use` as written. +- Replace `include-all: true` with `x-mistgate-ordered-proxies: true` and `include-all-providers: true` to keep all providers. To use only selected providers in a specific order instead, leave `include-all-providers` off and list them in `use`. When all providers are enabled, Mihomo ignores `use`. +- Remove or set to `false` both native local inclusion flags, including any inherited through `<<`: the panel rejects either one set to `true` alongside the opt-in. Check the preview, save, then refresh the subscription in the app. + +With the opt-in, the panel applies `filter` to the final names of the proxies it adds, not to the members you listed explicitly. Providers stay dynamic in Mihomo; the panel leaves `filter`, `exclude-filter` and `exclude-type` in the output. You can use `filter: "Germany"` to match by name, not by IP or actual location. When `filter` contains multiple backtick-separated expressions, their priority takes precedence over source order: in a mixed group, Mihomo collects matches for the first expression across sources before moving to the next. A client's display sort by name or latency can differ from the order the core uses, including for `fallback`. A template for the group `ROUTER`, written with made-up names: @@ -353,11 +356,11 @@ mode: rule proxy-groups: - name: Proxy type: select - include-all-proxies: true + x-mistgate-ordered-proxies: true proxies: [Auto, DIRECT] # Auto is the group the panel adds - name: Germany type: url-test - include-all-proxies: true + x-mistgate-ordered-proxies: true filter: "Germany" url: https://www.gstatic.com/generate_204 interval: 300 @@ -378,7 +381,7 @@ rules: - MATCH,Proxy ``` -A person in `ROUTER` gets this text with their servers at the top of `proxies`, `Auto` at the end of `proxy-groups` and a `dns` section, and nothing else changed. +A person in `ROUTER` gets their servers at the top of `proxies`, expanded `Proxy` and `Germany` member lists, `Auto` at the end of `proxy-groups`, and a `dns` section. ### What a save checks @@ -392,7 +395,7 @@ The save refuses a template, with the line in the message, when: - a group refers in its `proxies` to a name that is no proxy or group of the template, no core name and not `Auto` (while the panel adds that group), or in `use` to a provider you did not define; - the panel cannot build a profile from it with two sample servers. -Other findings do not stop a save and show in the preview as **Worth a look**: no group takes the person's servers (add `include-all-proxies` or refer to `Auto`); the template has its own `dns`; the person's DNS preset has ad, split or country rules that the template does not get; the template has its own `Auto`, so the panel adds none; a rule sends to a name that is nothing in the template; no group is chosen. The panel does not check the rest of Mihomo's keys: run the file in Mihomo for that. +Other findings do not stop a save and show in the preview as **Worth a look**: no group takes the person's servers (add `x-mistgate-ordered-proxies: true` or refer to `Auto`); the template has its own `dns`; the person's DNS preset has ad, split or country rules that the template does not get; the template has its own `Auto`, so the panel adds none; a rule sends to a name that is nothing in the template; no group is chosen. The panel does not check the rest of Mihomo's keys: run the file in Mihomo for that. ### Preview diff --git a/docs/ru/guide/subscriptions.md b/docs/ru/guide/subscriptions.md index 752e74884..4c32049d0 100644 --- a/docs/ru/guide/subscriptions.md +++ b/docs/ru/guide/subscriptions.md @@ -323,7 +323,7 @@ tproxy-port: 1181 | Ключ | Что делает панель | |:--|:--| | `proxies` | Ставит серверы человека **в начало**, перед вашими прокси. Если ключа нет (или он `null`), создаёт его. | -| `proxy-groups` | Добавляет в конец группу `Auto`, пока включён **Автоматический выбор сервера** и в шаблоне нет группы с таким именем, — даже человеку с одним сервером, чтобы ваши группы могли на неё ссылаться. Это `url-test` по серверам человека (не по вашим `proxies`). | +| `proxy-groups` | Формирует списки участников тех групп, для которых включён порядок панели (см. ниже). Пока включён **Автовыбор сервера** и в шаблоне нет группы `Auto`, добавляет её в конец — даже человеку с одним сервером, чтобы ваши группы могли на неё ссылаться. Это `url-test` по серверам человека (не по вашим `proxies`). | | `dns` | Только если в шаблоне его нет: резолверы из DNS-пресета человека с `respect-rules: true`. Ничего больше из пресета не добавляется (см. ниже). | Всё остальное ваше: `rules`, `rule-providers`, `proxy-providers`, `tun`, порты. Правила DNS-пресета человека (блокировка рекламы, разделение, страны) в шаблон **не** добавляются: порядок правил и `MATCH` ваши, нужное напишите в шаблоне. Если в шаблоне есть свой `dns`, DNS-пресет человека и его выбор на странице к приложениям Mihomo не применяются (остальные приложения их сохраняют). @@ -332,14 +332,17 @@ tproxy-port: 1181 ### Как попасть серверам в ваши группы -Не пишите в группе имя сервера: у людей разные серверы, а имя, которого у человека нет, заставит Mihomo отвергнуть весь файл. Сохранение такое тоже отклонит. Серверы запрашивайте средствами Mihomo: +Не пишите в группе имя сервера человека: у людей разные серверы, а имя, которого у человека нет, заставит Mihomo отвергнуть весь файл. Сохранение такое тоже отклонит. Когда панель добавляет `Auto`, на эту группу можно сослаться для выбора сервера человека по скорости. -- `include-all-proxies: true` добавляет после явных участников группы серверы человека в порядке панели, затем прокси шаблона в порядке объявления; -- `filter` и `exclude-filter` (регулярные выражения) отбирают их по имени, например `filter: "Germany"`; -- `include-all: true` также подключает провайдеров из `proxy-providers`; со списком `use` провайдеры идут в указанном порядке после локальных прокси; -- группа `Auto` — серверы человека по скорости. +Чтобы использовать порядок панели, задайте `x-mistgate-ordered-proxies: true` в каждой нужной группе прокси. В новом шаблоне этот флаг уже стоит в группе `Proxy`. При сборке подписки или превью Mistgate сохраняет явно перечисленных участников группы, затем добавляет подходящие серверы человека в порядке панели, а после них — подходящие прокси шаблона в порядке объявления. Имена, которые уже есть в списке, не добавляются повторно. Флаг остаётся в сохранённом шаблоне, но не попадает в итоговый YAML. Если нет ни совпадений, ни явных участников, ни подключённых провайдеров, панель подставляет `empty-fallback`, а если он не задан — `COMPATIBLE`. -Если в `filter` несколько выражений через обратную кавычку, их приоритет важнее порядка источников: в смешанной группе Mihomo сначала собирает совпадения с первым выражением по всем источникам, затем со следующим. +Сохранённые шаблоны не меняются автоматически. Без нового флага `include-all-proxies` и `include-all` работают как обычно: Mihomo сортирует автоматически добавленные локальные прокси по имени. Чтобы перевести существующую группу на порядок панели: + +- Замените `include-all-proxies: true` на `x-mistgate-ordered-proxies: true`. Оставьте имеющиеся `include-all-providers` и `use` как есть. +- Замените `include-all: true` на `x-mistgate-ordered-proxies: true` и `include-all-providers: true`, чтобы сохранить всех провайдеров. Если нужно выбрать только отдельных провайдеров в заданном порядке, не включайте `include-all-providers` и перечислите их в `use`. Когда включены все провайдеры, Mihomo игнорирует `use`. +- Удалите оба встроенных флага автодобавления локальных прокси или задайте им `false`, в том числе если они унаследованы через `<<`: панель отклоняет сочетание нового флага с любым из них, если оба включены. Проверьте превью, сохраните шаблон и обновите подписку в приложении. + +С новым флагом панель применяет `filter` к итоговым именам добавляемых прокси, но не к участникам, которых вы перечислили сами. Провайдеры по-прежнему обновляются в Mihomo; панель оставляет в итоговом YAML `filter`, `exclude-filter` и `exclude-type`. Например, `filter: "Germany"` проверяет имя, а не IP или фактическое местоположение. Если в `filter` несколько выражений через обратную кавычку, их приоритет важнее порядка источников: в смешанной группе Mihomo сначала собирает совпадения с первым выражением по всем источникам, затем со следующим. Сортировка в приложении по имени или задержке может отличаться от порядка ядра, в том числе для `fallback`. Шаблон для группы `ROUTER` на выдуманных именах: @@ -353,11 +356,11 @@ mode: rule proxy-groups: - name: Proxy type: select - include-all-proxies: true + x-mistgate-ordered-proxies: true proxies: [Auto, DIRECT] # Auto is the group the panel adds - name: Germany type: url-test - include-all-proxies: true + x-mistgate-ordered-proxies: true filter: "Germany" url: https://www.gstatic.com/generate_204 interval: 300 @@ -378,7 +381,7 @@ rules: - MATCH,Proxy ``` -Человек из `ROUTER` получит этот текст с его серверами в начале `proxies`, `Auto` в конце `proxy-groups` и секцией `dns`, остальное без изменений. +Человек из `ROUTER` получит свои серверы в начале `proxies`, заполненные списки участников групп `Proxy` и `Germany`, группу `Auto` в конце `proxy-groups` и секцию `dns`. ### Что проверяет сохранение @@ -392,7 +395,7 @@ rules: - в `proxies` группы названо то, чего нет среди прокси и групп шаблона, имён ядра и `Auto` (пока панель эту группу добавляет), или в `use` — провайдер, которого вы не описали; - панель не может собрать из него профиль с двумя пробными серверами. -Остальные находки сохранение не останавливают и показываются в превью как **Стоит посмотреть**: ни одна группа не берёт серверы человека (добавьте `include-all-proxies` или сошлитесь на `Auto`); в шаблоне свой `dns`; в DNS-пресете человека есть правила рекламы, разделения или стран, которых в шаблоне не будет; в шаблоне свой `Auto`, поэтому панель своего не добавляет; правило ведёт к имени, которого нет в шаблоне; не выбрана ни одна группа. Остальные ключи Mihomo панель не проверяет: для этого прогоните файл через Mihomo. +Остальные находки сохранение не останавливают и показываются в превью как **Стоит посмотреть**: ни одна группа не берёт серверы человека (добавьте `x-mistgate-ordered-proxies: true` или сошлитесь на `Auto`); в шаблоне свой `dns`; в DNS-пресете человека есть правила рекламы, разделения или стран, которых в шаблоне не будет; в шаблоне свой `Auto`, поэтому панель своего не добавляет; правило ведёт к имени, которого нет в шаблоне; не выбрана ни одна группа. Остальные ключи Mihomo панель не проверяет: для этого прогоните файл через Mihomo. ### Превью diff --git a/docs/zh/guide/subscriptions.md b/docs/zh/guide/subscriptions.md index acfcc32bb..8db461bce 100644 --- a/docs/zh/guide/subscriptions.md +++ b/docs/zh/guide/subscriptions.md @@ -321,7 +321,7 @@ tproxy-port: 1181 | 键 | 面板的处理 | |:--|:--| | `proxies` | 把用户的服务器放在**最前面**,排在你写的代理之前。没有该键(或为 `null`)时会创建。 | -| `proxy-groups` | 只要**自动选择服务器**已开启且模板里没有同名分组,就在末尾加入 `Auto` 分组,即使用户只有一台服务器,这样你的分组才能引用它。它是针对用户服务器(而不是你自己的 `proxies`)的 `url-test`。 | +| `proxy-groups` | 为启用了面板顺序的代理组生成成员列表(见下文)。只要**自动选择服务器**已开启且模板里没有同名分组,就在末尾加入 `Auto` 分组,即使用户只有一台服务器,这样你的分组也能引用它。它是针对用户服务器(而不是你自己的 `proxies`)的 `url-test`。 | | `dns` | 仅当模板里没有时:使用该用户 DNS 预设的解析器,并带 `respect-rules: true`。预设的其他内容都不会加入(见下)。 | 其余一切由你决定:`rules`、`rule-providers`、`proxy-providers`、`tun`、端口。用户 DNS 预设的规则(屏蔽广告、分流、国家)**不会**加入模板,因为规则的顺序和 `MATCH` 由你决定;需要的话请自己写进模板。模板里有自己的 `dns` 时,用户的 DNS 预设及其在页面上的选择不会作用于 Mihomo 类应用(其他应用仍然使用)。 @@ -330,14 +330,17 @@ tproxy-port: 1181 ### 让服务器进入你的分组 -不要在分组里写服务器名称:每个人的服务器不同,用户没有的名称会让 Mihomo 拒绝整个文件,保存时也会被拒绝。请让 Mihomo 自己取服务器: +不要在分组里写用户的服务器名称:每个人的服务器不同,用户没有的名称会让 Mihomo 拒绝整个文件,保存时也会被拒绝。如果面板会添加 `Auto`,可以引用该分组,按速度选择用户的服务器。 -- `include-all-proxies: true` 先保留分组中明确列出的成员,再按面板顺序加入用户的服务器,最后按声明顺序加入模板中的代理; -- `filter` 和 `exclude-filter`(正则表达式)按名称筛选,例如 `filter: "Germany"`; -- `include-all: true` 还会加入 `proxy-providers` 中的提供者;使用显式的 `use` 列表时,提供者在本地代理之后按列表顺序加入; -- `Auto` 分组是按速度选择的用户服务器。 +要使用面板顺序,请在每个需要的代理组中设置 `x-mistgate-ordered-proxies: true`。新模板的 `Proxy` 组默认带有此标记。生成订阅或预览时,Mistgate 保留组内 `proxies` 中明确列出的成员,再按面板顺序加入匹配的用户服务器,最后按声明顺序加入模板中匹配的代理,不重复添加已有名称。该标记保留在已保存的模板中,不会出现在生成的 YAML 中。如果没有匹配项、没有显式成员,也没有启用任何提供者,面板会使用 `empty-fallback`,未设置时则使用 `COMPATIBLE`。 -如果 `filter` 包含多个用反引号分隔的表达式,表达式的优先级高于来源顺序:在混合分组中,Mihomo 先收集所有来源中匹配第一个表达式的代理,再处理下一个表达式。 +已保存的模板不会自动迁移。未启用新标记时,`include-all-proxies` 和 `include-all` 保持 Mihomo 的原有行为:自动加入的本地代理按名称排序。要将现有代理组改为使用面板顺序: + +- 将 `include-all-proxies: true` 替换为 `x-mistgate-ordered-proxies: true`。保留已有的 `include-all-providers` 和 `use`。 +- 将 `include-all: true` 替换为 `x-mistgate-ordered-proxies: true` 和 `include-all-providers: true`,以保留所有提供者。如果只想按指定顺序使用选定的提供者,请不要开启 `include-all-providers`,而是在 `use` 中列出它们。启用全部提供者时,Mihomo 会忽略 `use`。 +- 移除两个原生的本地代理自动加入选项,或将它们设为 `false`,包括通过 `<<` 继承的选项。启用新标记时,这两个选项中任意一个为 `true` 都会被面板拒绝。检查预览并保存,然后在应用中刷新订阅。 + +启用新标记后,面板会用 `filter` 匹配自动加入的代理的最终名称,不筛选你明确列出的成员。提供者仍由 Mihomo 动态更新,面板会在输出中保留 `filter`、`exclude-filter` 和 `exclude-type`。例如,`filter: "Germany"` 匹配的是名称,而不是 IP 或实际位置。如果 `filter` 包含多个用反引号分隔的表达式,表达式的优先级高于来源顺序:在混合分组中,Mihomo 先收集所有来源中匹配第一个表达式的代理,再处理下一个表达式。应用按名称或延迟显示的顺序可能不同于内核使用的顺序,`fallback` 组也是如此。 下面是用虚构名称写的 `ROUTER` 分组模板: @@ -351,11 +354,11 @@ mode: rule proxy-groups: - name: Proxy type: select - include-all-proxies: true + x-mistgate-ordered-proxies: true proxies: [Auto, DIRECT] # Auto is the group the panel adds - name: Germany type: url-test - include-all-proxies: true + x-mistgate-ordered-proxies: true filter: "Germany" url: https://www.gstatic.com/generate_204 interval: 300 @@ -376,7 +379,7 @@ rules: - MATCH,Proxy ``` -`ROUTER` 中的用户会得到这段文本:其服务器位于 `proxies` 开头,`Auto` 在 `proxy-groups` 末尾,并多出一个 `dns` 段,其余不变。 +`ROUTER` 中的用户会在 `proxies` 开头收到自己的服务器,得到已填入成员的 `Proxy` 和 `Germany` 组、位于 `proxy-groups` 末尾的 `Auto` 组,以及 `dns` 段。 ### 保存时会检查什么 @@ -390,7 +393,7 @@ rules: - 分组的 `proxies` 里引用了既不是模板中的代理或分组、也不是内核名称、更不是 `Auto`(只要面板会添加该分组)的名称,或 `use` 里引用了你没有定义的 provider; - 面板无法用两台示例服务器据此生成配置。 -其他发现不会阻止保存,会在预览中显示为**值得一看**:没有分组取用户的服务器(请加 `include-all-proxies` 或引用 `Auto`);模板有自己的 `dns`;用户的 DNS 预设含有模板得不到的广告、分流或国家规则;模板有自己的 `Auto`,所以面板不再添加;某条规则指向模板里不存在的名称;没有选择任何分组。面板不检查 Mihomo 的其余键:请用 Mihomo 自己运行一遍该文件。 +其他发现不会阻止保存,会在预览中显示为**值得一看**:没有分组取用户的服务器(请加 `x-mistgate-ordered-proxies: true` 或引用 `Auto`);模板有自己的 `dns`;用户的 DNS 预设含有模板得不到的广告、分流或国家规则;模板有自己的 `Auto`,所以面板不再添加;某条规则指向模板里不存在的名称;没有选择任何分组。面板不检查 Mihomo 的其余键:请用 Mihomo 自己运行一遍该文件。 ### 预览 diff --git a/internal/panel/subs/mihomo_node_order_test.go b/internal/panel/subs/mihomo_node_order_test.go index 4dbedc7cf..401008b67 100644 --- a/internal/panel/subs/mihomo_node_order_test.go +++ b/internal/panel/subs/mihomo_node_order_test.go @@ -179,7 +179,7 @@ func TestMihomoNodeOrderWithWarmViewsAndTemplatePreview(t *testing.T) { proxy-groups: - name: Work type: select - include-all-proxies: true + x-mistgate-ordered-proxies: true proxies: [authored-z, DIRECT] rules: - MATCH,Work @@ -209,7 +209,7 @@ rules: } return answerOf(t, resp.Yaml) } - // Save the old include-all-proxies form once; neither order change should require editing it. + // Save the opted-in template once; neither order change should require editing it. r.save(t, nameByProfile, &adminv1.MihomoTemplate{Name: "work", Yaml: draft, GroupIds: []string{r.group2}}) assertTemplate(answerOf(t, r.body(t, token)), geo) assertTemplate(previewAnswer(user), geo) diff --git a/internal/panel/subs/mihomo_order_core_test.go b/internal/panel/subs/mihomo_order_core_test.go index 28f7964ba..3129b7adf 100644 --- a/internal/panel/subs/mihomo_order_core_test.go +++ b/internal/panel/subs/mihomo_order_core_test.go @@ -80,18 +80,21 @@ proxy-providers: proxy-groups: - name: Auto type: fallback - include-all-proxies: true + x-mistgate-ordered-proxies: true use: [oversecure, pasha-main] url: %[1]q expected-status: '204' - name: AI Auto type: fallback - include-all-proxies: true + x-mistgate-ordered-proxies: true use: [pasha-main, oversecure] filter: %[2]q exclude-filter: '(^| )RU( |$)' url: %[1]q expected-status: '204' + - name: Native all proxies + type: select + include-all-proxies: true - name: Provider only type: select use: [pasha-main, oversecure] @@ -101,6 +104,12 @@ rules: ['MATCH,Auto'] if !used { t.Fatal("the built-in profile was sent") } + if strings.Contains(out, "x-mistgate-ordered-proxies:") || !strings.Contains(out, "include-all-proxies: true") { + t.Fatal("rendered profile must strip Mistgate's directive and retain the native flag") + } + + alphabetical := slices.Clone(p.names) + slices.Sort(alphabetical) got := orderedMihomoCoreProxies(t, bin, dir, out, healthURL, p.names) for _, want := range []struct { @@ -116,6 +125,7 @@ rules: ['MATCH,Auto'] "DE-2 socks5", "DE-2 http", "LV socks5", "LV http", "DE-1 socks5", "DE-1 http", "Pasha DE", "Oversecure DE", }}, {"Provider only", "Selector", []string{"Pasha DE", "Pasha KZ", "Pasha RU", "Oversecure DE", "Oversecure KZ", "Oversecure RU"}}, + {"Native all proxies", "Selector", alphabetical}, } { g := got[want.group] if g.Type != want.kind || !slices.Equal(g.All, want.all) || g.Now != want.all[0] { diff --git a/internal/panel/subs/mihomo_preview_test.go b/internal/panel/subs/mihomo_preview_test.go index 4360d5fed..abe3ab1ef 100644 --- a/internal/panel/subs/mihomo_preview_test.go +++ b/internal/panel/subs/mihomo_preview_test.go @@ -113,7 +113,7 @@ func TestPreviewMihomoTemplate(t *testing.T) { func TestPreviewMihomoShowsEmojiInNames(t *testing.T) { r := newTemplateRig(t, nil) - const draft = "mode: rule\nproxy-groups:\n - name: 🌍 VPN\n type: select\n include-all-proxies: true\nrules:\n - MATCH,🌍 VPN\n" + const draft = "mode: rule\nproxy-groups:\n - name: 🌍 VPN\n type: select\n x-mistgate-ordered-proxies: true\nrules:\n - MATCH,🌍 VPN\n" r.save(t, func(s *adminv1.SubscriptionSettings) { s.ServerNameTemplate = "🇫🇮 {profile}" }, routerTemplate(r, r.group2)) alice, _ := r.newUser("alice", nil) resp, err := r.preview(t, r.previewService(t, plainPreset), alice, draft, r.group2) @@ -128,6 +128,9 @@ func TestPreviewMihomoShowsEmojiInNames(t *testing.T) { len(a.Groups) == 0 || a.Groups[0].Name != "🌍 VPN" || len(a.Rules) == 0 || a.Rules[0] != "MATCH,🌍 VPN" { t.Fatal("the Unicode preview did not preserve the names and rule") } + if got, want := a.Groups[0].Proxies, a.Proxies[0]["name"].(string); len(got) == 0 || got[0] != want { + t.Errorf("the Unicode proxy name was not preserved in the group: got %q, first member should be %q", got, want) + } } // A preview writes nothing: not a device, not a credential, not the mark that the link was fetched. diff --git a/internal/panel/subs/mihomo_template_core_test.go b/internal/panel/subs/mihomo_template_core_test.go index 87aeedd70..b85ec7744 100644 --- a/internal/panel/subs/mihomo_template_core_test.go +++ b/internal/panel/subs/mihomo_template_core_test.go @@ -21,7 +21,7 @@ func TestMihomoCoreAcceptsTemplates(t *testing.T) { {"router with one server", router, func(p *mihomoProfile) { p.lines, p.names = p.lines[:1], p.names[:1] }}, {"router without Auto", strings.Replace(router, "proxies: [Auto, DIRECT] # the panel's Auto group", "proxies: [DIRECT]", 1), func(p *mihomoProfile) { p.autoSelect = false }}, {"pc with its own dns and a filter that matches nothing", pc, nil}, - {"a group of only the servers", "proxy-groups:\n - name: Proxy\n type: select\n include-all-proxies: true\nrules:\n - MATCH,Proxy\n", nil}, + {"a native include-all-proxies group", "proxy-groups:\n - name: Proxy\n type: select\n include-all-proxies: true\nrules:\n - MATCH,Proxy\n", nil}, {"a template of one key", "mixed-port: 7890\n", nil}, } { t.Run(c.name, func(t *testing.T) { diff --git a/internal/panel/subs/mihomo_template_internal_test.go b/internal/panel/subs/mihomo_template_internal_test.go index 47e1623dd..3b02624ef 100644 --- a/internal/panel/subs/mihomo_template_internal_test.go +++ b/internal/panel/subs/mihomo_template_internal_test.go @@ -328,7 +328,7 @@ func TestMihomoTemplateKeepsTheText(t *testing.T) { func TestMihomoTemplateDoesNotFoldLongLines(t *testing.T) { long := "DOMAIN-SUFFIX," + strings.Repeat("a", 280) + ".example.com,Proxy" regex := "(?i)" + strings.Repeat("alpha|", 60) + "omega" - tpl := "proxy-groups:\n - name: Proxy\n type: select\n include-all-proxies: true\n filter: \"" + regex + "\"\nrules:\n - " + long + "\n - MATCH,Proxy\n" + tpl := "proxy-groups:\n - name: Proxy\n type: select\n x-mistgate-ordered-proxies: true\n filter: \"" + regex + "\"\nrules:\n - " + long + "\n - MATCH,Proxy\n" out, _ := templated(t, tpl, mihomoProfile{title: "T", lines: []string{fixture(t, hy2Line)}, autoSelect: true}) if !strings.Contains(out, "\n - "+long+"\n") || !strings.Contains(out, "filter: \""+regex+"\"\n") { t.Errorf("a long line was folded:\n%s", out) diff --git a/internal/panel/subs/mihomo_template_test.go b/internal/panel/subs/mihomo_template_test.go index 0d127d648..da24b8540 100644 --- a/internal/panel/subs/mihomo_template_test.go +++ b/internal/panel/subs/mihomo_template_test.go @@ -302,7 +302,7 @@ dns: proxy-groups: - name: Proxy type: select - include-all-proxies: true + x-mistgate-ordered-proxies: true proxies: - DIRECT # @mistgate-if [%[2]q] @@ -367,9 +367,15 @@ rules: t.Errorf("wrong effective profile:\n%s", output) } groups := doc["proxy-groups"].([]any) - if got := groups[0].(map[string]any)["proxies"]; !reflect.DeepEqual(got, wantMembers) { + proxyGroup := groups[0].(map[string]any) + if got := proxyGroup["proxies"]; !reflect.DeepEqual(got, wantMembers) { t.Errorf("Proxy members = %v, want %v", got, wantMembers) } + for _, key := range []string{"x-mistgate-ordered-proxies", "include-all-proxies", "include-all", "include-all-providers"} { + if v, present := proxyGroup[key]; present { + t.Errorf("rendered Proxy group has unexpected %s: %v", key, v) + } + } var desktop bool for _, g := range groups { m := g.(map[string]any) diff --git a/internal/panel/subs/testdata/mihomo_template_pc.out.yaml b/internal/panel/subs/testdata/mihomo_template_pc.out.yaml index 8847b8d6b..9fbddbe1e 100644 --- a/internal/panel/subs/testdata/mihomo_template_pc.out.yaml +++ b/internal/panel/subs/testdata/mihomo_template_pc.out.yaml @@ -67,7 +67,6 @@ proxies: proxy-groups: - name: Servers type: select - include-all-proxies: false proxies: - "\U0001F1E9\U0001F1EA de1 · hy2" - "\U0001F1F3\U0001F1F1 nl1 · awg" @@ -78,7 +77,6 @@ proxy-groups: proxies: [office-socks, DIRECT] - name: Nobody type: url-test - include-all-proxies: false filter: "no-such-server" proxies: - "COMPATIBLE" diff --git a/internal/panel/subs/testdata/mihomo_template_pc.yaml b/internal/panel/subs/testdata/mihomo_template_pc.yaml index 1b973c30b..c7b86eff3 100644 --- a/internal/panel/subs/testdata/mihomo_template_pc.yaml +++ b/internal/panel/subs/testdata/mihomo_template_pc.yaml @@ -18,14 +18,14 @@ proxies: proxy-groups: - name: Servers type: select - include-all-proxies: true + x-mistgate-ordered-proxies: true - name: Work type: select use: [office] proxies: [office-socks, DIRECT] - name: Nobody type: url-test - include-all-proxies: true + x-mistgate-ordered-proxies: true filter: "no-such-server" dns: diff --git a/internal/panel/subs/testdata/mihomo_template_router.out.yaml b/internal/panel/subs/testdata/mihomo_template_router.out.yaml index 13974a467..b1c94c0a7 100644 --- a/internal/panel/subs/testdata/mihomo_template_router.out.yaml +++ b/internal/panel/subs/testdata/mihomo_template_router.out.yaml @@ -13,12 +13,10 @@ x-check: &check proxy-groups: - name: Proxy type: select - include-all-proxies: false proxies: [Auto, DIRECT, "\U0001F1E9\U0001F1EA de1 · hy2", "\U0001F1F3\U0001F1F1 nl1 · awg"] # the panel's Auto group - name: Fast <<: *check type: url-test - include-all-proxies: false filter: "(?i)de|nl" proxies: - "\U0001F1E9\U0001F1EA de1 · hy2" diff --git a/internal/panel/subs/testdata/mihomo_template_router.yaml b/internal/panel/subs/testdata/mihomo_template_router.yaml index 4d9684129..beb112364 100644 --- a/internal/panel/subs/testdata/mihomo_template_router.yaml +++ b/internal/panel/subs/testdata/mihomo_template_router.yaml @@ -15,12 +15,12 @@ x-check: &check proxy-groups: - name: Proxy type: select - include-all-proxies: true + x-mistgate-ordered-proxies: true proxies: [Auto, DIRECT] # the panel's Auto group - name: Fast <<: *check type: url-test - include-all-proxies: true + x-mistgate-ordered-proxies: true filter: "(?i)de|nl" rule-providers: diff --git a/internal/panel/subsettings/mihomo.go b/internal/panel/subsettings/mihomo.go index 006f0c584..27cb0e63b 100644 --- a/internal/panel/subsettings/mihomo.go +++ b/internal/panel/subsettings/mihomo.go @@ -22,8 +22,8 @@ import ( // the save is the trust boundary. Names of servers are hostile input: they enter the document as yaml.Node values with a quoted // style, never as text. // -// The panel touches three keys of the root: `proxies` (the person's servers go first), `proxy-groups` (automatic local members -// follow the person's server order, and an `Auto` group may be added) and `dns` (added only when the template has none). +// The panel touches three keys of the root: `proxies` (the person's servers go first), `proxy-groups` (groups may opt in to +// ordered local members, and an `Auto` group may be added) and `dns` (added only when the template has none). // The rest is encoded back as it was read, comments and anchors included. // Limits enforced by Validate. @@ -263,6 +263,7 @@ type tplGroup struct { IncludeAllProviders bool `yaml:"include-all-providers"` IncludeAll bool `yaml:"include-all"` EmptyFallback string `yaml:"empty-fallback"` + OrderedProxies bool `yaml:"x-mistgate-ordered-proxies"` } // tplInfo is a template read for the keys the panel works on. @@ -315,6 +316,9 @@ func loadTemplate(text string) (*tplInfo, error) { if g.Type == "" { return nil, fmt.Errorf("proxy-groups[%d] %q: a type is required", i, g.Name) } + if g.OrderedProxies && (g.IncludeAllProxies || g.IncludeAll) { + return nil, fmt.Errorf("proxy-groups[%d]: %s cannot be enabled with include-all-proxies or include-all; use include-all-providers to add all external providers", i, mihomoOrderedProxiesKey) + } } return t, nil } @@ -333,7 +337,7 @@ func (t *tplInfo) checkRefs(autoOn bool) error { if m == AutoName { return fmt.Errorf("proxy-groups[%d] %q: refers to Auto, which the panel adds only while automatic server selection is on (or define a group named Auto)", i, g.Name) } - return fmt.Errorf("proxy-groups[%d] %q: proxies: %q is not a proxy or group of this template (take servers with include-all-proxies or filter)", i, g.Name, m) + return fmt.Errorf("proxy-groups[%d] %q: proxies: %q is not a proxy or group of this template (take servers with %s or include-all-proxies)", i, g.Name, m, mihomoOrderedProxiesKey) } for _, u := range g.Use { if !loaded { @@ -542,7 +546,11 @@ func ApplyMihomoTemplate(text string, servers []MihomoServer, opt MihomoOptions) t.root.Content[i] = opt.DNS } } - prepareMihomoYAML(t.doc) + var removedAnchors map[*yaml.Node]bool + prepareMihomoYAML(t.doc, &removedAnchors) + if len(removedAnchors) != 0 { + restoreMihomoYAMLAnchors(t.doc, removedAnchors) + } var buf bytes.Buffer enc := yaml.NewEncoder(&buf) enc.SetIndent(2) @@ -555,10 +563,9 @@ func ApplyMihomoTemplate(text string, servers []MihomoServer, opt MihomoOptions) return buf.Bytes(), nil } -// Write plain merge keys for YAML readers that do not accept an explicit merge tag. -// yaml.v3 can add a newline when emitting folded scalars with keep chomping. -// Emit those values literally instead. Do not follow aliases: the target is already in the tree. -func prepareMihomoYAML(n *yaml.Node) { +// The output omits the Mistgate group directive, including from shared group +// defaults. Emit plain merge keys and avoid yaml.v3's folded keep-chomping bug. +func prepareMihomoYAML(n *yaml.Node, removedAnchors *map[*yaml.Node]bool) { if n.Kind == yaml.ScalarNode { if n.Tag == "!!merge" && n.Value == "<<" { n.Tag = "" @@ -567,8 +574,25 @@ func prepareMihomoYAML(n *yaml.Node) { n.Style = (n.Style &^ yaml.FoldedStyle) | yaml.LiteralStyle } } + if n.Kind == yaml.MappingNode { + kept := n.Content[:0] + for i := 0; i < len(n.Content); i += 2 { + k, v := n.Content[i], n.Content[i+1] + prepareMihomoYAML(k, removedAnchors) + prepareMihomoYAML(v, removedAnchors) + if key := mappingKey(k); key.Kind == yaml.ScalarNode && key.Value == mihomoOrderedProxiesKey { + markRemovedMihomoAnchors(k, removedAnchors) + markRemovedMihomoAnchors(v, removedAnchors) + } else { + kept = append(kept, k, v) + } + } + clear(n.Content[len(kept):]) + n.Content = kept + return + } for _, c := range n.Content { - prepareMihomoYAML(c) + prepareMihomoYAML(c, removedAnchors) } } @@ -585,7 +609,7 @@ func MihomoTemplateWarnings(text string, autoOn bool) []MihomoWarning { ownAuto := t.names[AutoName] takes := false for _, g := range t.groups { - takes = takes || g.IncludeAllProxies || g.IncludeAll || (autoOn && !ownAuto && slices.Contains(g.Proxies, AutoName)) + takes = takes || g.OrderedProxies || g.IncludeAllProxies || g.IncludeAll || (autoOn && !ownAuto && slices.Contains(g.Proxies, AutoName)) } if !takes { out = append(out, MihomoWarning{Code: WarnNoServerGroup}) diff --git a/internal/panel/subsettings/mihomo_ordered_groups.go b/internal/panel/subsettings/mihomo_ordered_groups.go index ec5dcd9f8..7f61099de 100644 --- a/internal/panel/subsettings/mihomo_ordered_groups.go +++ b/internal/panel/subsettings/mihomo_ordered_groups.go @@ -10,6 +10,8 @@ import ( "gopkg.in/yaml.v3" ) +const mihomoOrderedProxiesKey = "x-mistgate-ordered-proxies" + const mihomoFilterBudget = 250 * time.Millisecond var errMihomoFilterBudget = errors.New("filter exceeded the matching time limit") @@ -95,7 +97,7 @@ func expandOrderedMihomoGroups(t *tplInfo, names []string) error { var filters mihomoGroupFilters providerCount := -1 for i, g := range t.groups { - if !g.IncludeAll && !g.IncludeAllProxies { + if !g.OrderedProxies { continue } members, err := filters.orderedMembers(g, names, t.proxies) @@ -104,7 +106,7 @@ func expandOrderedMihomoGroups(t *tplInfo, names []string) error { } if len(members) == 0 { count := len(g.Use) - if g.IncludeAll || g.IncludeAllProviders { + if g.IncludeAllProviders { if providerCount < 0 { var providers map[string]yaml.Node if v, _ := rootValue(t.root, "proxy-providers"); v != nil { @@ -126,41 +128,29 @@ func expandOrderedMihomoGroups(t *tplInfo, names []string) error { } group := groups.Content[i] - if group.Kind == yaml.AliasNode || group.Anchor != "" || - groupValueHasAnchor(group, "proxies") || - g.IncludeAllProxies && groupValueHasAnchor(group, "include-all-proxies") || - g.IncludeAll && (groupValueHasAnchor(group, "include-all") || groupValueHasAnchor(group, "include-all-providers")) { + old, index := rootValue(group, "proxies") + if group.Kind == yaml.AliasNode || group.Anchor != "" || old != nil && hasYAMLAnchor(old) { // Keep original anchor definitions inline and before their readers. A // local merge overlay changes this group without changing what any alias sees. group = mapOf(&yaml.Node{Kind: yaml.ScalarNode, Tag: "!!merge", Value: "<<"}, group) groups.Content[i] = group + old = nil } - seq := quotedSeqOf(members) - if old, _ := rootValue(group, "proxies"); old != nil && old.Kind == yaml.SequenceNode { - // Keep the authored scalars and their comments. The decoded list - // can be shorter than the YAML sequence (e.g. a null item). - seq.Style = old.Style - seq.Content = append(old.Content, seq.Content[len(g.Proxies):]...) - } - setGroupValue(group, "proxies", seq) - if g.IncludeAllProxies { - setGroupBool(group, "include-all-proxies", false) - } - if g.IncludeAll { - setGroupBool(group, "include-all", false) - if !g.IncludeAllProviders { - setGroupBool(group, "include-all-providers", true) - } + if old == nil { + group.Content = append(group.Content, strNode("proxies"), quotedSeqOf(members)) + } else if old.Kind == yaml.SequenceNode { + // This list has no anchors of its own; keep the authored items, + // including nulls and comments that the decoded list omits. + old.Content = append(old.Content, quotedSeqOf(members[len(g.Proxies):]).Content...) + } else { + seq := quotedSeqOf(members) + copyYAMLComments(seq, old) + group.Content[index] = seq } } return nil } -func groupValueHasAnchor(group *yaml.Node, key string) bool { - v, _ := rootValue(group, key) - return v != nil && hasYAMLAnchor(v) -} - func hasYAMLAnchor(node *yaml.Node) bool { if node.Anchor != "" { return true @@ -177,19 +167,36 @@ func copyYAMLComments(dst, src *yaml.Node) { dst.HeadComment, dst.LineComment, dst.FootComment = src.HeadComment, src.LineComment, src.FootComment } -func setGroupValue(group *yaml.Node, key string, value *yaml.Node) { - if old, i := rootValue(group, key); old != nil { - copyYAMLComments(value, old) - group.Content[i] = value - } else { - group.Content = append(group.Content, strNode(key), value) +func markRemovedMihomoAnchors(n *yaml.Node, removed *map[*yaml.Node]bool) { + if n.Anchor != "" { + if *removed == nil { + *removed = make(map[*yaml.Node]bool) + } + (*removed)[n] = false + } + for _, c := range n.Content { + markRemovedMihomoAnchors(c, removed) } } -func setGroupBool(group *yaml.Node, key string, enabled bool) { - value := "false" - if enabled { - value = "true" +// Move an anchor from the dropped directive to its first remaining use. +// Later references still use the original anchor name. +func restoreMihomoYAMLAnchors(n *yaml.Node, removed map[*yaml.Node]bool) *yaml.Node { + if n.Kind == yaml.AliasNode { + emitted, missing := removed[n.Alias] + if !missing || emitted { + return n + } + n = n.Alias + } + if emitted, missing := removed[n]; missing { + if emitted { + return &yaml.Node{Kind: yaml.AliasNode, Value: n.Anchor, Alias: n} + } + removed[n] = true + } + for i, child := range n.Content { + n.Content[i] = restoreMihomoYAMLAnchors(child, removed) } - setGroupValue(group, key, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!bool", Value: value}) + return n } diff --git a/internal/panel/subsettings/mihomo_ordered_groups_test.go b/internal/panel/subsettings/mihomo_ordered_groups_test.go index 487b74efb..02fd81d3a 100644 --- a/internal/panel/subsettings/mihomo_ordered_groups_test.go +++ b/internal/panel/subsettings/mihomo_ordered_groups_test.go @@ -27,17 +27,19 @@ proxy-groups: providers bool use []string }{ - {"explicit and unique final names", " proxies: [Static, DIRECT]\n include-all-proxies: true\n", []string{"Static", "DIRECT", "Zulu", "Static ·", "Alpha", "Zulu ·", "Another"}, false, nil}, - {"ordered overlapping expressions with lookahead", " proxies: [DIRECT]\n include-all-proxies: true\n filter: '^Z(?=ulu ·$)`^[AZ]`.*'\n", []string{"DIRECT", "Zulu ·", "Zulu", "Alpha", "Another", "Static ·", "Static"}, false, nil}, - {"empty with reject", " include-all-proxies: true\n filter: '^Nothing$'\n empty-fallback: REJECT\n", []string{"REJECT"}, false, nil}, - {"empty by default", " include-all-proxies: true\n filter: '^Nothing$'\n", []string{"COMPATIBLE"}, false, nil}, - {"empty locals with explicit provider", " include-all-proxies: true\n filter: '^Nothing$'\n use: [Example]\n", nil, false, []string{"Example"}}, - {"include all implies providers", " include-all: true\n include-all-providers: false\n filter: '^Nothing$'\n", nil, true, nil}, - {"include all providers without locals", " include-all-proxies: true\n include-all-providers: true\n filter: '^Nothing$'\n", nil, true, nil}, + {"explicit and unique final names", " proxies: [Static, DIRECT]\n x-mistgate-ordered-proxies: true\n", []string{"Static", "DIRECT", "Zulu", "Static ·", "Alpha", "Zulu ·", "Another"}, false, nil}, + {"ordered overlapping expressions with lookahead", " proxies: [DIRECT]\n x-mistgate-ordered-proxies: true\n filter: '^Z(?=ulu ·$)`^[AZ]`.*'\n", []string{"DIRECT", "Zulu ·", "Zulu", "Alpha", "Another", "Static ·", "Static"}, false, nil}, + {"empty with reject", " x-mistgate-ordered-proxies: true\n filter: '^Nothing$'\n empty-fallback: REJECT\n", []string{"REJECT"}, false, nil}, + {"empty by default", " x-mistgate-ordered-proxies: true\n filter: '^Nothing$'\n", []string{"COMPATIBLE"}, false, nil}, + {"empty locals with explicit provider", " x-mistgate-ordered-proxies: true\n filter: '^Nothing$'\n use: [Example]\n", nil, false, []string{"Example"}}, + {"include all providers without locals", " x-mistgate-ordered-proxies: true\n include-all-providers: true\n filter: '^Nothing$'\n", nil, true, nil}, {"provider only", " use: [Example]\n", nil, false, []string{"Example"}}, } { t.Run(tc.name, func(t *testing.T) { out, _ := apply(t, head+tc.fields, MihomoOptions{}, "Zulu", "Static", "Alpha", "Zulu") + if strings.Contains(out, mihomoOrderedProxiesKey) { + t.Fatalf("Mistgate group flag reached the subscription:\n%s", out) + } info, err := loadTemplate(out) if err != nil { t.Fatal(err) @@ -48,11 +50,43 @@ proxy-groups: } }) } + t.Run("native flags are not expanded", func(t *testing.T) { + for _, native := range []string{"include-all-proxies", "include-all"} { + base := head + " proxies: [DIRECT]\n " + native + ": true\n" + for _, suffix := range []string{"", " x-mistgate-ordered-proxies: false\n"} { + out, _ := apply(t, base+suffix, MihomoOptions{}, "Zulu", "Alpha") + if !strings.Contains(out, native+": true") || strings.Contains(out, mihomoOrderedProxiesKey) { + t.Fatalf("native group flags changed:\n%s", out) + } + info, err := loadTemplate(out) + if err != nil { + t.Fatal(err) + } + if got := info.groups[0].Proxies; !slices.Equal(got, []string{"DIRECT"}) { + t.Fatalf("native group gained members: %q", got) + } + } + } + }) + t.Run("conflicting native flags are rejected", func(t *testing.T) { + for _, flag := range []string{"include-all-proxies", "include-all"} { + text := head + " x-mistgate-ordered-proxies: true\n " + flag + ": true\n" + if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "cannot be enabled with") { + t.Fatalf("%s: save validation error = %v", flag, err) + } + } + }) + t.Run("ordered proxies suppress the no-servers warning", func(t *testing.T) { + if got := MihomoTemplateWarnings(head+" x-mistgate-ordered-proxies: true\n", false); len(got) != 0 { + t.Fatalf("warnings = %+v", got) + } + }) t.Run("include all providers ignores use when provider map is empty", func(t *testing.T) { out, _ := apply(t, `proxy-groups: - name: Pick type: select - include-all: true + x-mistgate-ordered-proxies: true + include-all-providers: true use: [Ignored] filter: '^Nothing$' `, MihomoOptions{}, "Zulu") @@ -67,7 +101,7 @@ proxy-groups: t.Run("aliases and inherited flags stay local", func(t *testing.T) { const text = `x-default: &default type: select - include-all-proxies: true + x-mistgate-ordered-proxies: true proxies: &shared [DIRECT] # shared list x-group: &aliased <<: *default @@ -77,7 +111,7 @@ proxy-groups: - &original <<: *default name: Changed - include-all: &flag true + x-mistgate-ordered-proxies: &flag true proxies: &list - &member REJECT # anchored member - name: Outside @@ -85,21 +119,26 @@ proxy-groups: proxies: *list - name: Inherited <<: *default - include-all-proxies: false + x-mistgate-ordered-proxies: false x-copy: *original x-flag: *flag +x-flag-copy: *flag x-member: *member ` out, _ := apply(t, text, MihomoOptions{}, "Zulu", "Alpha") + if strings.Contains(out, mihomoOrderedProxiesKey) { + t.Fatalf("Mistgate group flag reached the subscription:\n%s", out) + } if err := CheckMihomoTemplate(out, false); err != nil { t.Fatalf("changed output does not pass validation: %v\n%s", err, out) } var d struct { - Groups []tplGroup `yaml:"proxy-groups"` - Alias tplGroup `yaml:"x-group"` - Copy tplGroup `yaml:"x-copy"` - Flag bool `yaml:"x-flag"` - Member string `yaml:"x-member"` + Groups []tplGroup `yaml:"proxy-groups"` + Alias tplGroup `yaml:"x-group"` + Copy tplGroup `yaml:"x-copy"` + Flag bool `yaml:"x-flag"` + FlagCopy bool `yaml:"x-flag-copy"` + Member string `yaml:"x-member"` } if err := yaml.Unmarshal([]byte(out), &d); err != nil { t.Fatal(err) @@ -110,7 +149,7 @@ x-member: *member t.Fatalf("group %s = %+v; want %q without local auto-inclusion", g.Name, g, want[i]) } } - if !d.Alias.IncludeAllProxies || !slices.Equal(d.Alias.Proxies, []string{"DIRECT"}) || !d.Copy.IncludeAll || !d.Copy.IncludeAllProxies || !slices.Equal(d.Copy.Proxies, []string{"REJECT"}) || !d.Flag || d.Member != "REJECT" { + if !slices.Equal(d.Alias.Proxies, []string{"DIRECT"}) || !slices.Equal(d.Copy.Proxies, []string{"REJECT"}) || !d.Flag || !d.FlagCopy || d.Member != "REJECT" { t.Fatalf("source values changed: %+v\n%s", d, out) } for _, comment := range []string{"# shared list", "# anchored member"} { @@ -122,7 +161,7 @@ x-member: *member t.Run("alias keys at the root and inside a group", func(t *testing.T) { const text = `x-groups-key: &groups-key proxy-groups x-proxies-key: &proxies-key proxies -x-include-key: &include-key include-all-proxies +x-include-key: &include-key x-mistgate-ordered-proxies *groups-key: - name: Pick type: select @@ -130,11 +169,14 @@ x-include-key: &include-key include-all-proxies *proxies-key: [DIRECT] ` out, _ := apply(t, text, MihomoOptions{}, "Zulu", "Alpha") + if strings.Contains(out, "*include-key:") { + t.Fatalf("Mistgate group flag reached the subscription:\n%s", out) + } info, err := loadTemplate(out) if err != nil { t.Fatal(err) } - if got := info.groups[0]; got.IncludeAllProxies || !slices.Equal(got.Proxies, []string{"DIRECT", "Zulu", "Alpha"}) { + if got := info.groups[0]; got.OrderedProxies || !slices.Equal(got.Proxies, []string{"DIRECT", "Zulu", "Alpha"}) { t.Fatalf("group = %+v", got) } if err := CheckMihomoTemplate(out, false); err != nil { @@ -151,7 +193,7 @@ x-list: &list [{name: Pick, type: select, include-all-proxies: true}] } }) t.Run("invalid expression is rejected without its text", func(t *testing.T) { - const text = head + " include-all-proxies: true\n filter: '.*`(private-pattern'\n" + const text = head + " x-mistgate-ordered-proxies: true\n filter: '.*`(private-pattern'\n" out, err := ApplyMihomoTemplate(text, []MihomoServer{serverNode(t, "private-node")}, MihomoOptions{}) if len(out) != 0 || err == nil || !strings.Contains(err.Error(), "invalid filter") || strings.Contains(err.Error(), "private-") { t.Fatalf("output = %q, error = %v", out, err) diff --git a/web/src/i18n/subs.ts b/web/src/i18n/subs.ts index 72603540d..95ee412ed 100644 --- a/web/src/i18n/subs.ts +++ b/web/src/i18n/subs.ts @@ -38,7 +38,7 @@ export const en = { "subs.mt.err.nameTaken": "Another template has this name (letter case does not matter).", "subs.mt.err.empty": "The text is empty.", "subs.mt.err.big": "This text is {n} KiB. One template is up to {max} KiB.", - "subs.mt.warn.no_server_group": "No group takes the person's servers. Add include-all-proxies: true to a group or refer to Auto, otherwise there is nothing to connect to.", + "subs.mt.warn.no_server_group": "No group takes the person's servers. Add x-mistgate-ordered-proxies: true to a group or refer to Auto, otherwise there is nothing to connect to.", "subs.mt.warn.own_dns": "The template has its own dns section, so the DNS preset of the person is not applied to it.", "subs.mt.warn.preset_rules_skipped": "The DNS preset of this person has ad, split or country rules, and a template does not get them. Write them into the template if you need them.", "subs.mt.warn.own_auto": "The template has its own Auto group, so the panel adds none.", @@ -440,7 +440,7 @@ export const ru: Record = { "subs.mt.err.nameTaken": "Такое название уже есть (регистр не важен).", "subs.mt.err.empty": "Текст пуст.", "subs.mt.err.big": "Текст занимает {n} КиБ. Один шаблон — до {max} КиБ.", - "subs.mt.warn.no_server_group": "Ни одна группа не берёт серверы человека. Добавь в группу include-all-proxies: true или сошлись на Auto, иначе подключаться будет не к чему.", + "subs.mt.warn.no_server_group": "Ни одна группа не берёт серверы человека. Добавь в группу x-mistgate-ordered-proxies: true или сошлись на Auto, иначе подключаться будет не к чему.", "subs.mt.warn.own_dns": "В шаблоне есть свой раздел dns, поэтому DNS-пресет человека к нему не применяется.", "subs.mt.warn.preset_rules_skipped": "В DNS-пресете этого человека есть правила рекламы, разделения или стран, а шаблон их не получает. Если они нужны, впиши их в шаблон.", "subs.mt.warn.own_auto": "В шаблоне есть своя группа Auto, поэтому панель свою не добавляет.", @@ -835,7 +835,7 @@ export const zh: typeof en = { "subs.mt.err.nameTaken": "已有同名模板(不区分大小写)。", "subs.mt.err.empty": "文本为空。", "subs.mt.err.big": "文本为 {n} KiB。单个模板最多 {max} KiB。", - "subs.mt.warn.no_server_group": "没有任何组使用用户的服务器。请在某个组里加上 include-all-proxies: true,或引用 Auto,否则无处可连。", + "subs.mt.warn.no_server_group": "没有任何组使用用户的服务器。请在某个组里加上 x-mistgate-ordered-proxies: true,或引用 Auto,否则无处可连。", "subs.mt.warn.own_dns": "模板有自己的 dns 部分,因此不会应用用户的 DNS 预设。", "subs.mt.warn.preset_rules_skipped": "此用户的 DNS 预设包含广告、分流或国家规则,而模板不会得到这些规则。需要的话请写进模板。", "subs.mt.warn.own_auto": "模板有自己的 Auto 组,因此面板不再添加。", @@ -1230,7 +1230,7 @@ export const fa: Record = { "subs.mt.err.nameTaken": "قالب دیگری همین نام را دارد (حروف بزرگ و کوچک فرقی ندارند).", "subs.mt.err.empty": "متن خالی است.", "subs.mt.err.big": "این متن {n} کیبی‌بایت است. هر قالب حداکثر {max} کیبی‌بایت می‌تواند باشد.", - "subs.mt.warn.no_server_group": "هیچ گروهی سرورهای فرد را نمی‌گیرد. در یک گروه include-all-proxies: true بگذارید یا به Auto ارجاع دهید، وگرنه چیزی برای اتصال نیست.", + "subs.mt.warn.no_server_group": "هیچ گروهی سرورهای فرد را نمی‌گیرد. در یک گروه x-mistgate-ordered-proxies: true بگذارید یا به Auto ارجاع دهید، وگرنه چیزی برای اتصال نیست.", "subs.mt.warn.own_dns": "قالب بخش dns خودش را دارد، پس پیش‌تنظیم DNS فرد روی آن اعمال نمی‌شود.", "subs.mt.warn.preset_rules_skipped": "پیش‌تنظیم DNS این فرد قواعد تبلیغ، تفکیک یا کشور دارد و قالب آن‌ها را نمی‌گیرد. اگر لازم‌اند، در قالب بنویسید.", "subs.mt.warn.own_auto": "قالب گروه Auto خودش را دارد، پس پنل گروهی اضافه نمی‌کند.", @@ -1617,7 +1617,7 @@ export const tr: Record = { "subs.mt.err.nameTaken": "Başka bir şablonda aynı ad var (büyük küçük harf fark etmez).", "subs.mt.err.empty": "Metin boş.", "subs.mt.err.big": "Bu metin {n} KiB. Bir şablon en çok {max} KiB olabilir.", - "subs.mt.warn.no_server_group": "Hiçbir grup kişinin sunucularını almıyor. Bir gruba include-all-proxies: true ekle ya da Auto'ya başvur, yoksa bağlanacak bir şey kalmaz.", + "subs.mt.warn.no_server_group": "Hiçbir grup kişinin sunucularını almıyor. Bir gruba x-mistgate-ordered-proxies: true ekle ya da Auto'ya başvur, yoksa bağlanacak bir şey kalmaz.", "subs.mt.warn.own_dns": "Şablonun kendi dns bölümü var, bu yüzden kişinin DNS ön ayarı ona uygulanmaz.", "subs.mt.warn.preset_rules_skipped": "Bu kişinin DNS ön ayarında reklam, ayırma ya da ülke kuralları var ve şablon bunları almaz. Gerekiyorsa şablona kendin yaz.", "subs.mt.warn.own_auto": "Şablonun kendi Auto grubu var, bu yüzden panel eklemez.", diff --git a/web/src/screens/subscriptions/mihomo.test.tsx b/web/src/screens/subscriptions/mihomo.test.tsx index 1b4e6f698..dfb4fe65e 100644 --- a/web/src/screens/subscriptions/mihomo.test.tsx +++ b/web/src/screens/subscriptions/mihomo.test.tsx @@ -680,10 +680,10 @@ describe("the pieces the form says early", () => { expect(templateRefusal("invalid subscription settings: mihomo_templates[2].group_ids: the group \"g\" is already in the template \"A\"")).toMatchObject({ index: 2 }); expect(templateRefusal("invalid subscription settings: mihomo_templates: 300000 bytes of text in all")).toEqual({ text: "mihomo_templates: 300000 bytes of text in all" }); }); - it("starts a new template with a group over every server, and Auto only while the panel adds it", () => { + it("starts a new template with a group in panel order, and Auto only while the panel adds it", () => { expect(starterTemplate(true)).toContain("proxies: [Auto, DIRECT]"); expect(starterTemplate(false)).toContain("proxies: [DIRECT]"); - expect(starterTemplate(false)).toContain("include-all-proxies: true"); + expect(starterTemplate(false)).toMatch(/^ x-mistgate-ordered-proxies: true$/m); }); it("ships an inert group example that can be enabled for an assigned group", () => { const starter = starterTemplate(true); diff --git a/web/src/screens/subscriptions/model.ts b/web/src/screens/subscriptions/model.ts index 1a6dd1766..ab7b977a2 100644 --- a/web/src/screens/subscriptions/model.ts +++ b/web/src/screens/subscriptions/model.ts @@ -747,8 +747,9 @@ export function textKey(s: string): string { /** The text a new template starts with: one select group over every server of the person (and Auto while the panel adds it). */ export const starterTemplate = (auto: boolean): string => [ - "# The panel puts the person's servers at the start of `proxies` (the key may be missing).", - "# Groups take them with include-all-proxies or filter.", + "# Use x-mistgate-ordered-proxies: true to include each person's servers in panel order.", + "# Mistgate puts explicit group members first, then the person's servers, then template proxies.", + "# This flag is only for templates; don't combine it with include-all-proxies or include-all.", "mixed-port: 7890", "mode: rule", "", @@ -761,7 +762,7 @@ export const starterTemplate = (auto: boolean): string => "proxy-groups:", " - name: Proxy", " type: select", - " include-all-proxies: true", + " x-mistgate-ordered-proxies: true", ` proxies: [${auto ? "Auto, " : ""}DIRECT]`, "rules:", " - MATCH,Proxy", From 54918555523eb5a8937fa115e593dc7dc9607896 Mon Sep 17 00:00:00 2001 From: Morvex885 <278529280+Morvex885@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:02:31 +0300 Subject: [PATCH 4/9] Preserve native Mihomo provider flag compatibility --- .../panel/subs/mihomo_template_core_test.go | 1 + internal/panel/subsettings/mihomo.go | 17 +++--- .../subsettings/mihomo_ordered_groups.go | 58 +++++++++++++++---- .../subsettings/mihomo_ordered_groups_test.go | 34 ++++++++++- 4 files changed, 86 insertions(+), 24 deletions(-) diff --git a/internal/panel/subs/mihomo_template_core_test.go b/internal/panel/subs/mihomo_template_core_test.go index b85ec7744..1446f9158 100644 --- a/internal/panel/subs/mihomo_template_core_test.go +++ b/internal/panel/subs/mihomo_template_core_test.go @@ -22,6 +22,7 @@ func TestMihomoCoreAcceptsTemplates(t *testing.T) { {"router without Auto", strings.Replace(router, "proxies: [Auto, DIRECT] # the panel's Auto group", "proxies: [DIRECT]", 1), func(p *mihomoProfile) { p.autoSelect = false }}, {"pc with its own dns and a filter that matches nothing", pc, nil}, {"a native include-all-proxies group", "proxy-groups:\n - name: Proxy\n type: select\n include-all-proxies: true\nrules:\n - MATCH,Proxy\n", nil}, + {"a native integer provider flag", "proxy-groups:\n - name: Proxy\n type: select\n include-all-providers: 1\n proxies: [DIRECT]\nrules:\n - MATCH,Proxy\n", nil}, {"a template of one key", "mixed-port: 7890\n", nil}, } { t.Run(c.name, func(t *testing.T) { diff --git a/internal/panel/subsettings/mihomo.go b/internal/panel/subsettings/mihomo.go index 27cb0e63b..7463c9d58 100644 --- a/internal/panel/subsettings/mihomo.go +++ b/internal/panel/subsettings/mihomo.go @@ -254,16 +254,13 @@ type tplNamed struct { } type tplGroup struct { - Name string `yaml:"name"` - Type string `yaml:"type"` - Proxies []string `yaml:"proxies"` - Use []string `yaml:"use"` - Filter string `yaml:"filter"` - IncludeAllProxies bool `yaml:"include-all-proxies"` - IncludeAllProviders bool `yaml:"include-all-providers"` - IncludeAll bool `yaml:"include-all"` - EmptyFallback string `yaml:"empty-fallback"` - OrderedProxies bool `yaml:"x-mistgate-ordered-proxies"` + Name string `yaml:"name"` + Type string `yaml:"type"` + Proxies []string `yaml:"proxies"` + Use []string `yaml:"use"` + IncludeAllProxies bool `yaml:"include-all-proxies"` + IncludeAll bool `yaml:"include-all"` + OrderedProxies bool `yaml:"x-mistgate-ordered-proxies"` } // tplInfo is a template read for the keys the panel works on. diff --git a/internal/panel/subsettings/mihomo_ordered_groups.go b/internal/panel/subsettings/mihomo_ordered_groups.go index 7f61099de..898f2ddb4 100644 --- a/internal/panel/subsettings/mihomo_ordered_groups.go +++ b/internal/panel/subsettings/mihomo_ordered_groups.go @@ -37,21 +37,21 @@ func (f *mihomoGroupFilters) match(pattern, name string) (bool, error) { return matched, nil } -func (f *mihomoGroupFilters) orderedMembers(g tplGroup, names []string, static []tplNamed) ([]string, error) { - members := make([]string, 0, len(g.Proxies)+len(names)+len(static)) - members = append(members, g.Proxies...) +func (f *mihomoGroupFilters) orderedMembers(authored, names []string, static []tplNamed, filter string) ([]string, error) { + members := make([]string, 0, len(authored)+len(names)+len(static)) + members = append(members, authored...) seen := make(map[string]bool, cap(members)) for _, name := range members { seen[name] = true } - if g.Filter != "" && f.compiled == nil { + if filter != "" && f.compiled == nil { f.compiled = make(map[string]*regexp2.Regexp) f.deadline = time.Now().Add(mihomoFilterBudget) } // For an empty filter the single empty expression means no matching is needed. // In a nonempty filter, an empty component is a real regexp, just as in Mihomo. - for pattern := range strings.SplitSeq(g.Filter, "`") { - if g.Filter != "" && f.compiled[pattern] == nil { + for pattern := range strings.SplitSeq(filter, "`") { + if filter != "" && f.compiled[pattern] == nil { if time.Until(f.deadline) <= 0 { return nil, errMihomoFilterBudget } @@ -65,7 +65,7 @@ func (f *mihomoGroupFilters) orderedMembers(g tplGroup, names []string, static [ if seen[name] { return nil } - if g.Filter != "" { + if filter != "" { matched, err := f.match(pattern, name) if err != nil || !matched { return err @@ -85,13 +85,43 @@ func (f *mihomoGroupFilters) orderedMembers(g tplGroup, names []string, static [ return nil, err } } - if g.Filter != "" && time.Until(f.deadline) <= 0 { + if filter != "" && time.Until(f.deadline) <= 0 { return nil, errMihomoFilterBudget } } return members, nil } +// These options are read only when Mistgate expands the group. +type mihomoOrderedOptions struct { + Filter string `yaml:"filter"` + EmptyFallback string `yaml:"empty-fallback"` + IncludeAllProviders mihomoProviderFlag `yaml:"include-all-providers"` +} + +type mihomoProviderFlag bool + +func (enabled *mihomoProviderFlag) UnmarshalYAML(n *yaml.Node) error { + // Mihomo's weak bool decoder accepts a YAML boolean or any integer. + var value any + if err := n.Decode(&value); err != nil { + return err + } + switch v := value.(type) { + case bool: + *enabled = mihomoProviderFlag(v) + case int: + *enabled = v != 0 + case int64: + *enabled = v != 0 + case uint64: + *enabled = v != 0 + default: + return fmt.Errorf("line %d: include-all-providers must be a boolean or an integer", n.Line) + } + return nil +} + func expandOrderedMihomoGroups(t *tplInfo, names []string) error { groups, _ := rootValue(t.root, "proxy-groups") var filters mihomoGroupFilters @@ -100,13 +130,18 @@ func expandOrderedMihomoGroups(t *tplInfo, names []string) error { if !g.OrderedProxies { continue } - members, err := filters.orderedMembers(g, names, t.proxies) + group := groups.Content[i] + var opt mihomoOrderedOptions + if err := group.Decode(&opt); err != nil { + return mihomoYAMLDiagnostic{err: err, prefix: fmt.Sprintf("proxy-groups[%d]: ", i)} + } + members, err := filters.orderedMembers(g.Proxies, names, t.proxies, opt.Filter) if err != nil { return fmt.Errorf("proxy-groups[%d]: %w", i, err) } if len(members) == 0 { count := len(g.Use) - if g.IncludeAllProviders { + if opt.IncludeAllProviders { if providerCount < 0 { var providers map[string]yaml.Node if v, _ := rootValue(t.root, "proxy-providers"); v != nil { @@ -119,7 +154,7 @@ func expandOrderedMihomoGroups(t *tplInfo, names []string) error { count = providerCount } if count == 0 { - fallback := g.EmptyFallback + fallback := opt.EmptyFallback if fallback == "" { fallback = "COMPATIBLE" } @@ -127,7 +162,6 @@ func expandOrderedMihomoGroups(t *tplInfo, names []string) error { } } - group := groups.Content[i] old, index := rootValue(group, "proxies") if group.Kind == yaml.AliasNode || group.Anchor != "" || old != nil && hasYAMLAnchor(old) { // Keep original anchor definitions inline and before their readers. A diff --git a/internal/panel/subsettings/mihomo_ordered_groups_test.go b/internal/panel/subsettings/mihomo_ordered_groups_test.go index 02fd81d3a..664a177ea 100644 --- a/internal/panel/subsettings/mihomo_ordered_groups_test.go +++ b/internal/panel/subsettings/mihomo_ordered_groups_test.go @@ -45,7 +45,8 @@ proxy-groups: t.Fatal(err) } g := info.groups[0] - if !slices.Equal(g.Proxies, tc.want) || g.IncludeAll || g.IncludeAllProxies || g.IncludeAllProviders != tc.providers || !slices.Equal(g.Use, tc.use) { + if !slices.Equal(g.Proxies, tc.want) || g.IncludeAll || g.IncludeAllProxies || + strings.Contains(out, "include-all-providers: true") != tc.providers || !slices.Equal(g.Use, tc.use) { t.Fatalf("group = %+v; want members %q, include-all-providers %t, use %q", g, tc.want, tc.providers, tc.use) } }) @@ -68,6 +69,35 @@ proxy-groups: } } }) + t.Run("Mihomo integer provider flags", func(t *testing.T) { + for _, tc := range []struct { + name, fields, providers string + members []string + }{ + {"native", " proxies: [DIRECT]\n", "1", []string{"DIRECT"}}, + {"opted in", " x-mistgate-ordered-proxies: true\n filter: '^Nothing$'\n", "1", nil}, + {"disabled", " x-mistgate-ordered-proxies: true\n filter: '^Nothing$'\n", "0", []string{"COMPATIBLE"}}, + } { + t.Run(tc.name, func(t *testing.T) { + providerFlag := " include-all-providers: " + tc.providers + "\n" + text := head + tc.fields + providerFlag + if err := CheckMihomoTemplate(text, false); err != nil { + t.Fatal(err) + } + out, _ := apply(t, text, MihomoOptions{}, "Zulu") + info, err := loadTemplate(out) + if err != nil { + t.Fatal(err) + } + if got := info.groups[0].Proxies; !slices.Equal(got, tc.members) { + t.Fatalf("members = %q, want %q", got, tc.members) + } + if !strings.Contains(out, providerFlag) { + t.Fatalf("provider flag changed:\n%s", out) + } + }) + } + }) t.Run("conflicting native flags are rejected", func(t *testing.T) { for _, flag := range []string{"include-all-proxies", "include-all"} { text := head + " x-mistgate-ordered-proxies: true\n " + flag + ": true\n" @@ -207,7 +237,7 @@ x-list: &list [{name: Pick, type: select, include-all-proxies: true}] compiled: map[string]*regexp2.Regexp{".*": regexp2.MustCompile(".*", regexp2.None)}, deadline: time.Now().Add(-time.Second), } - got, err := f.orderedMembers(tplGroup{Filter: ".*", Proxies: []string{"DIRECT"}}, []string{"Zulu"}, nil) + got, err := f.orderedMembers([]string{"DIRECT"}, []string{"Zulu"}, nil, ".*") if got != nil || !errors.Is(err, errMihomoFilterBudget) { t.Fatalf("members = %q, error = %v", got, err) } From e37de60ca0315dacccbd2fa77aab2eb1f6ce0582 Mon Sep 17 00:00:00 2001 From: Morvex885 <278529280+Morvex885@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:05:59 +0300 Subject: [PATCH 5/9] Use mistgate-ordered-proxies as the template flag --- docs/en/guide/subscriptions.md | 12 +++---- docs/ru/guide/subscriptions.md | 12 +++---- docs/zh/guide/subscriptions.md | 12 +++---- internal/panel/subs/mihomo_node_order_test.go | 2 +- internal/panel/subs/mihomo_order_core_test.go | 6 ++-- internal/panel/subs/mihomo_preview_test.go | 2 +- .../subs/mihomo_template_internal_test.go | 2 +- internal/panel/subs/mihomo_template_test.go | 4 +-- .../subs/testdata/mihomo_template_pc.yaml | 4 +-- .../subs/testdata/mihomo_template_router.yaml | 4 +-- internal/panel/subsettings/mihomo.go | 2 +- .../subsettings/mihomo_ordered_groups.go | 2 +- .../subsettings/mihomo_ordered_groups_test.go | 34 +++++++++---------- web/src/i18n/subs.ts | 10 +++--- web/src/screens/subscriptions/mihomo.test.tsx | 2 +- web/src/screens/subscriptions/model.ts | 4 +-- 16 files changed, 57 insertions(+), 57 deletions(-) diff --git a/docs/en/guide/subscriptions.md b/docs/en/guide/subscriptions.md index d45bab663..5f8fc5604 100644 --- a/docs/en/guide/subscriptions.md +++ b/docs/en/guide/subscriptions.md @@ -334,12 +334,12 @@ The panel names the person's servers by the [server name template](#names-texts) Do not write a person's server name in a group: the servers differ from person to person, and a name a person does not have makes Mihomo refuse the whole file. The save refuses it too. You can refer to `Auto` for speed-based selection over the person's servers when the panel adds that group. -To use panel order, set `x-mistgate-ordered-proxies: true` on each proxy group you want to change. New templates start with this flag in their `Proxy` group. When rendering a subscription or preview, Mistgate keeps the entries already listed in the group's `proxies`, then appends the person's matching servers in panel order, then matching proxies declared in the template in declaration order, without adding names already present. Mistgate leaves the flag in the saved template but removes it from the rendered YAML. If no members match and the group has neither explicit members nor providers, the panel uses `empty-fallback`, or `COMPATIBLE` if it is not set. +To use panel order, set `mistgate-ordered-proxies: true` on each proxy group you want to change. New templates start with this flag in their `Proxy` group. When rendering a subscription or preview, Mistgate keeps the entries already listed in the group's `proxies`, then appends the person's matching servers in panel order, then matching proxies declared in the template in declaration order, without adding names already present. Mistgate leaves the flag in the saved template but removes it from the rendered YAML. If no members match and the group has neither explicit members nor providers, the panel uses `empty-fallback`, or `COMPATIBLE` if it is not set. Saved templates are not migrated. Without the opt-in, `include-all-proxies` and `include-all` keep their native Mihomo behavior, which sorts the automatically included local proxies by name. To switch an existing group: -- Replace `include-all-proxies: true` with `x-mistgate-ordered-proxies: true`. Keep any existing `include-all-providers` or `use` as written. -- Replace `include-all: true` with `x-mistgate-ordered-proxies: true` and `include-all-providers: true` to keep all providers. To use only selected providers in a specific order instead, leave `include-all-providers` off and list them in `use`. When all providers are enabled, Mihomo ignores `use`. +- Replace `include-all-proxies: true` with `mistgate-ordered-proxies: true`. Keep any existing `include-all-providers` or `use` as written. +- Replace `include-all: true` with `mistgate-ordered-proxies: true` and `include-all-providers: true` to keep all providers. To use only selected providers in a specific order instead, leave `include-all-providers` off and list them in `use`. When all providers are enabled, Mihomo ignores `use`. - Remove or set to `false` both native local inclusion flags, including any inherited through `<<`: the panel rejects either one set to `true` alongside the opt-in. Check the preview, save, then refresh the subscription in the app. With the opt-in, the panel applies `filter` to the final names of the proxies it adds, not to the members you listed explicitly. Providers stay dynamic in Mihomo; the panel leaves `filter`, `exclude-filter` and `exclude-type` in the output. You can use `filter: "Germany"` to match by name, not by IP or actual location. When `filter` contains multiple backtick-separated expressions, their priority takes precedence over source order: in a mixed group, Mihomo collects matches for the first expression across sources before moving to the next. A client's display sort by name or latency can differ from the order the core uses, including for `fallback`. @@ -356,11 +356,11 @@ mode: rule proxy-groups: - name: Proxy type: select - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true proxies: [Auto, DIRECT] # Auto is the group the panel adds - name: Germany type: url-test - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true filter: "Germany" url: https://www.gstatic.com/generate_204 interval: 300 @@ -395,7 +395,7 @@ The save refuses a template, with the line in the message, when: - a group refers in its `proxies` to a name that is no proxy or group of the template, no core name and not `Auto` (while the panel adds that group), or in `use` to a provider you did not define; - the panel cannot build a profile from it with two sample servers. -Other findings do not stop a save and show in the preview as **Worth a look**: no group takes the person's servers (add `x-mistgate-ordered-proxies: true` or refer to `Auto`); the template has its own `dns`; the person's DNS preset has ad, split or country rules that the template does not get; the template has its own `Auto`, so the panel adds none; a rule sends to a name that is nothing in the template; no group is chosen. The panel does not check the rest of Mihomo's keys: run the file in Mihomo for that. +Other findings do not stop a save and show in the preview as **Worth a look**: no group takes the person's servers (add `mistgate-ordered-proxies: true` or refer to `Auto`); the template has its own `dns`; the person's DNS preset has ad, split or country rules that the template does not get; the template has its own `Auto`, so the panel adds none; a rule sends to a name that is nothing in the template; no group is chosen. The panel does not check the rest of Mihomo's keys: run the file in Mihomo for that. ### Preview diff --git a/docs/ru/guide/subscriptions.md b/docs/ru/guide/subscriptions.md index 4c32049d0..efdd5be1d 100644 --- a/docs/ru/guide/subscriptions.md +++ b/docs/ru/guide/subscriptions.md @@ -334,12 +334,12 @@ tproxy-port: 1181 Не пишите в группе имя сервера человека: у людей разные серверы, а имя, которого у человека нет, заставит Mihomo отвергнуть весь файл. Сохранение такое тоже отклонит. Когда панель добавляет `Auto`, на эту группу можно сослаться для выбора сервера человека по скорости. -Чтобы использовать порядок панели, задайте `x-mistgate-ordered-proxies: true` в каждой нужной группе прокси. В новом шаблоне этот флаг уже стоит в группе `Proxy`. При сборке подписки или превью Mistgate сохраняет явно перечисленных участников группы, затем добавляет подходящие серверы человека в порядке панели, а после них — подходящие прокси шаблона в порядке объявления. Имена, которые уже есть в списке, не добавляются повторно. Флаг остаётся в сохранённом шаблоне, но не попадает в итоговый YAML. Если нет ни совпадений, ни явных участников, ни подключённых провайдеров, панель подставляет `empty-fallback`, а если он не задан — `COMPATIBLE`. +Чтобы использовать порядок панели, задайте `mistgate-ordered-proxies: true` в каждой нужной группе прокси. В новом шаблоне этот флаг уже стоит в группе `Proxy`. При сборке подписки или превью Mistgate сохраняет явно перечисленных участников группы, затем добавляет подходящие серверы человека в порядке панели, а после них — подходящие прокси шаблона в порядке объявления. Имена, которые уже есть в списке, не добавляются повторно. Флаг остаётся в сохранённом шаблоне, но не попадает в итоговый YAML. Если нет ни совпадений, ни явных участников, ни подключённых провайдеров, панель подставляет `empty-fallback`, а если он не задан — `COMPATIBLE`. Сохранённые шаблоны не меняются автоматически. Без нового флага `include-all-proxies` и `include-all` работают как обычно: Mihomo сортирует автоматически добавленные локальные прокси по имени. Чтобы перевести существующую группу на порядок панели: -- Замените `include-all-proxies: true` на `x-mistgate-ordered-proxies: true`. Оставьте имеющиеся `include-all-providers` и `use` как есть. -- Замените `include-all: true` на `x-mistgate-ordered-proxies: true` и `include-all-providers: true`, чтобы сохранить всех провайдеров. Если нужно выбрать только отдельных провайдеров в заданном порядке, не включайте `include-all-providers` и перечислите их в `use`. Когда включены все провайдеры, Mihomo игнорирует `use`. +- Замените `include-all-proxies: true` на `mistgate-ordered-proxies: true`. Оставьте имеющиеся `include-all-providers` и `use` как есть. +- Замените `include-all: true` на `mistgate-ordered-proxies: true` и `include-all-providers: true`, чтобы сохранить всех провайдеров. Если нужно выбрать только отдельных провайдеров в заданном порядке, не включайте `include-all-providers` и перечислите их в `use`. Когда включены все провайдеры, Mihomo игнорирует `use`. - Удалите оба встроенных флага автодобавления локальных прокси или задайте им `false`, в том числе если они унаследованы через `<<`: панель отклоняет сочетание нового флага с любым из них, если оба включены. Проверьте превью, сохраните шаблон и обновите подписку в приложении. С новым флагом панель применяет `filter` к итоговым именам добавляемых прокси, но не к участникам, которых вы перечислили сами. Провайдеры по-прежнему обновляются в Mihomo; панель оставляет в итоговом YAML `filter`, `exclude-filter` и `exclude-type`. Например, `filter: "Germany"` проверяет имя, а не IP или фактическое местоположение. Если в `filter` несколько выражений через обратную кавычку, их приоритет важнее порядка источников: в смешанной группе Mihomo сначала собирает совпадения с первым выражением по всем источникам, затем со следующим. Сортировка в приложении по имени или задержке может отличаться от порядка ядра, в том числе для `fallback`. @@ -356,11 +356,11 @@ mode: rule proxy-groups: - name: Proxy type: select - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true proxies: [Auto, DIRECT] # Auto is the group the panel adds - name: Germany type: url-test - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true filter: "Germany" url: https://www.gstatic.com/generate_204 interval: 300 @@ -395,7 +395,7 @@ rules: - в `proxies` группы названо то, чего нет среди прокси и групп шаблона, имён ядра и `Auto` (пока панель эту группу добавляет), или в `use` — провайдер, которого вы не описали; - панель не может собрать из него профиль с двумя пробными серверами. -Остальные находки сохранение не останавливают и показываются в превью как **Стоит посмотреть**: ни одна группа не берёт серверы человека (добавьте `x-mistgate-ordered-proxies: true` или сошлитесь на `Auto`); в шаблоне свой `dns`; в DNS-пресете человека есть правила рекламы, разделения или стран, которых в шаблоне не будет; в шаблоне свой `Auto`, поэтому панель своего не добавляет; правило ведёт к имени, которого нет в шаблоне; не выбрана ни одна группа. Остальные ключи Mihomo панель не проверяет: для этого прогоните файл через Mihomo. +Остальные находки сохранение не останавливают и показываются в превью как **Стоит посмотреть**: ни одна группа не берёт серверы человека (добавьте `mistgate-ordered-proxies: true` или сошлитесь на `Auto`); в шаблоне свой `dns`; в DNS-пресете человека есть правила рекламы, разделения или стран, которых в шаблоне не будет; в шаблоне свой `Auto`, поэтому панель своего не добавляет; правило ведёт к имени, которого нет в шаблоне; не выбрана ни одна группа. Остальные ключи Mihomo панель не проверяет: для этого прогоните файл через Mihomo. ### Превью diff --git a/docs/zh/guide/subscriptions.md b/docs/zh/guide/subscriptions.md index 8db461bce..89fa12a47 100644 --- a/docs/zh/guide/subscriptions.md +++ b/docs/zh/guide/subscriptions.md @@ -332,12 +332,12 @@ tproxy-port: 1181 不要在分组里写用户的服务器名称:每个人的服务器不同,用户没有的名称会让 Mihomo 拒绝整个文件,保存时也会被拒绝。如果面板会添加 `Auto`,可以引用该分组,按速度选择用户的服务器。 -要使用面板顺序,请在每个需要的代理组中设置 `x-mistgate-ordered-proxies: true`。新模板的 `Proxy` 组默认带有此标记。生成订阅或预览时,Mistgate 保留组内 `proxies` 中明确列出的成员,再按面板顺序加入匹配的用户服务器,最后按声明顺序加入模板中匹配的代理,不重复添加已有名称。该标记保留在已保存的模板中,不会出现在生成的 YAML 中。如果没有匹配项、没有显式成员,也没有启用任何提供者,面板会使用 `empty-fallback`,未设置时则使用 `COMPATIBLE`。 +要使用面板顺序,请在每个需要的代理组中设置 `mistgate-ordered-proxies: true`。新模板的 `Proxy` 组默认带有此标记。生成订阅或预览时,Mistgate 保留组内 `proxies` 中明确列出的成员,再按面板顺序加入匹配的用户服务器,最后按声明顺序加入模板中匹配的代理,不重复添加已有名称。该标记保留在已保存的模板中,不会出现在生成的 YAML 中。如果没有匹配项、没有显式成员,也没有启用任何提供者,面板会使用 `empty-fallback`,未设置时则使用 `COMPATIBLE`。 已保存的模板不会自动迁移。未启用新标记时,`include-all-proxies` 和 `include-all` 保持 Mihomo 的原有行为:自动加入的本地代理按名称排序。要将现有代理组改为使用面板顺序: -- 将 `include-all-proxies: true` 替换为 `x-mistgate-ordered-proxies: true`。保留已有的 `include-all-providers` 和 `use`。 -- 将 `include-all: true` 替换为 `x-mistgate-ordered-proxies: true` 和 `include-all-providers: true`,以保留所有提供者。如果只想按指定顺序使用选定的提供者,请不要开启 `include-all-providers`,而是在 `use` 中列出它们。启用全部提供者时,Mihomo 会忽略 `use`。 +- 将 `include-all-proxies: true` 替换为 `mistgate-ordered-proxies: true`。保留已有的 `include-all-providers` 和 `use`。 +- 将 `include-all: true` 替换为 `mistgate-ordered-proxies: true` 和 `include-all-providers: true`,以保留所有提供者。如果只想按指定顺序使用选定的提供者,请不要开启 `include-all-providers`,而是在 `use` 中列出它们。启用全部提供者时,Mihomo 会忽略 `use`。 - 移除两个原生的本地代理自动加入选项,或将它们设为 `false`,包括通过 `<<` 继承的选项。启用新标记时,这两个选项中任意一个为 `true` 都会被面板拒绝。检查预览并保存,然后在应用中刷新订阅。 启用新标记后,面板会用 `filter` 匹配自动加入的代理的最终名称,不筛选你明确列出的成员。提供者仍由 Mihomo 动态更新,面板会在输出中保留 `filter`、`exclude-filter` 和 `exclude-type`。例如,`filter: "Germany"` 匹配的是名称,而不是 IP 或实际位置。如果 `filter` 包含多个用反引号分隔的表达式,表达式的优先级高于来源顺序:在混合分组中,Mihomo 先收集所有来源中匹配第一个表达式的代理,再处理下一个表达式。应用按名称或延迟显示的顺序可能不同于内核使用的顺序,`fallback` 组也是如此。 @@ -354,11 +354,11 @@ mode: rule proxy-groups: - name: Proxy type: select - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true proxies: [Auto, DIRECT] # Auto is the group the panel adds - name: Germany type: url-test - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true filter: "Germany" url: https://www.gstatic.com/generate_204 interval: 300 @@ -393,7 +393,7 @@ rules: - 分组的 `proxies` 里引用了既不是模板中的代理或分组、也不是内核名称、更不是 `Auto`(只要面板会添加该分组)的名称,或 `use` 里引用了你没有定义的 provider; - 面板无法用两台示例服务器据此生成配置。 -其他发现不会阻止保存,会在预览中显示为**值得一看**:没有分组取用户的服务器(请加 `x-mistgate-ordered-proxies: true` 或引用 `Auto`);模板有自己的 `dns`;用户的 DNS 预设含有模板得不到的广告、分流或国家规则;模板有自己的 `Auto`,所以面板不再添加;某条规则指向模板里不存在的名称;没有选择任何分组。面板不检查 Mihomo 的其余键:请用 Mihomo 自己运行一遍该文件。 +其他发现不会阻止保存,会在预览中显示为**值得一看**:没有分组取用户的服务器(请加 `mistgate-ordered-proxies: true` 或引用 `Auto`);模板有自己的 `dns`;用户的 DNS 预设含有模板得不到的广告、分流或国家规则;模板有自己的 `Auto`,所以面板不再添加;某条规则指向模板里不存在的名称;没有选择任何分组。面板不检查 Mihomo 的其余键:请用 Mihomo 自己运行一遍该文件。 ### 预览 diff --git a/internal/panel/subs/mihomo_node_order_test.go b/internal/panel/subs/mihomo_node_order_test.go index 401008b67..0b4579753 100644 --- a/internal/panel/subs/mihomo_node_order_test.go +++ b/internal/panel/subs/mihomo_node_order_test.go @@ -179,7 +179,7 @@ func TestMihomoNodeOrderWithWarmViewsAndTemplatePreview(t *testing.T) { proxy-groups: - name: Work type: select - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true proxies: [authored-z, DIRECT] rules: - MATCH,Work diff --git a/internal/panel/subs/mihomo_order_core_test.go b/internal/panel/subs/mihomo_order_core_test.go index 3129b7adf..f884d6242 100644 --- a/internal/panel/subs/mihomo_order_core_test.go +++ b/internal/panel/subs/mihomo_order_core_test.go @@ -80,13 +80,13 @@ proxy-providers: proxy-groups: - name: Auto type: fallback - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true use: [oversecure, pasha-main] url: %[1]q expected-status: '204' - name: AI Auto type: fallback - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true use: [pasha-main, oversecure] filter: %[2]q exclude-filter: '(^| )RU( |$)' @@ -104,7 +104,7 @@ rules: ['MATCH,Auto'] if !used { t.Fatal("the built-in profile was sent") } - if strings.Contains(out, "x-mistgate-ordered-proxies:") || !strings.Contains(out, "include-all-proxies: true") { + if strings.Contains(out, "mistgate-ordered-proxies:") || !strings.Contains(out, "include-all-proxies: true") { t.Fatal("rendered profile must strip Mistgate's directive and retain the native flag") } diff --git a/internal/panel/subs/mihomo_preview_test.go b/internal/panel/subs/mihomo_preview_test.go index abe3ab1ef..151275619 100644 --- a/internal/panel/subs/mihomo_preview_test.go +++ b/internal/panel/subs/mihomo_preview_test.go @@ -113,7 +113,7 @@ func TestPreviewMihomoTemplate(t *testing.T) { func TestPreviewMihomoShowsEmojiInNames(t *testing.T) { r := newTemplateRig(t, nil) - const draft = "mode: rule\nproxy-groups:\n - name: 🌍 VPN\n type: select\n x-mistgate-ordered-proxies: true\nrules:\n - MATCH,🌍 VPN\n" + const draft = "mode: rule\nproxy-groups:\n - name: 🌍 VPN\n type: select\n mistgate-ordered-proxies: true\nrules:\n - MATCH,🌍 VPN\n" r.save(t, func(s *adminv1.SubscriptionSettings) { s.ServerNameTemplate = "🇫🇮 {profile}" }, routerTemplate(r, r.group2)) alice, _ := r.newUser("alice", nil) resp, err := r.preview(t, r.previewService(t, plainPreset), alice, draft, r.group2) diff --git a/internal/panel/subs/mihomo_template_internal_test.go b/internal/panel/subs/mihomo_template_internal_test.go index 3b02624ef..5a6067377 100644 --- a/internal/panel/subs/mihomo_template_internal_test.go +++ b/internal/panel/subs/mihomo_template_internal_test.go @@ -328,7 +328,7 @@ func TestMihomoTemplateKeepsTheText(t *testing.T) { func TestMihomoTemplateDoesNotFoldLongLines(t *testing.T) { long := "DOMAIN-SUFFIX," + strings.Repeat("a", 280) + ".example.com,Proxy" regex := "(?i)" + strings.Repeat("alpha|", 60) + "omega" - tpl := "proxy-groups:\n - name: Proxy\n type: select\n x-mistgate-ordered-proxies: true\n filter: \"" + regex + "\"\nrules:\n - " + long + "\n - MATCH,Proxy\n" + tpl := "proxy-groups:\n - name: Proxy\n type: select\n mistgate-ordered-proxies: true\n filter: \"" + regex + "\"\nrules:\n - " + long + "\n - MATCH,Proxy\n" out, _ := templated(t, tpl, mihomoProfile{title: "T", lines: []string{fixture(t, hy2Line)}, autoSelect: true}) if !strings.Contains(out, "\n - "+long+"\n") || !strings.Contains(out, "filter: \""+regex+"\"\n") { t.Errorf("a long line was folded:\n%s", out) diff --git a/internal/panel/subs/mihomo_template_test.go b/internal/panel/subs/mihomo_template_test.go index da24b8540..9dee4e9d5 100644 --- a/internal/panel/subs/mihomo_template_test.go +++ b/internal/panel/subs/mihomo_template_test.go @@ -302,7 +302,7 @@ dns: proxy-groups: - name: Proxy type: select - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true proxies: - DIRECT # @mistgate-if [%[2]q] @@ -371,7 +371,7 @@ rules: if got := proxyGroup["proxies"]; !reflect.DeepEqual(got, wantMembers) { t.Errorf("Proxy members = %v, want %v", got, wantMembers) } - for _, key := range []string{"x-mistgate-ordered-proxies", "include-all-proxies", "include-all", "include-all-providers"} { + for _, key := range []string{"mistgate-ordered-proxies", "include-all-proxies", "include-all", "include-all-providers"} { if v, present := proxyGroup[key]; present { t.Errorf("rendered Proxy group has unexpected %s: %v", key, v) } diff --git a/internal/panel/subs/testdata/mihomo_template_pc.yaml b/internal/panel/subs/testdata/mihomo_template_pc.yaml index c7b86eff3..af13d9113 100644 --- a/internal/panel/subs/testdata/mihomo_template_pc.yaml +++ b/internal/panel/subs/testdata/mihomo_template_pc.yaml @@ -18,14 +18,14 @@ proxies: proxy-groups: - name: Servers type: select - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true - name: Work type: select use: [office] proxies: [office-socks, DIRECT] - name: Nobody type: url-test - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true filter: "no-such-server" dns: diff --git a/internal/panel/subs/testdata/mihomo_template_router.yaml b/internal/panel/subs/testdata/mihomo_template_router.yaml index beb112364..30a2a03b9 100644 --- a/internal/panel/subs/testdata/mihomo_template_router.yaml +++ b/internal/panel/subs/testdata/mihomo_template_router.yaml @@ -15,12 +15,12 @@ x-check: &check proxy-groups: - name: Proxy type: select - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true proxies: [Auto, DIRECT] # the panel's Auto group - name: Fast <<: *check type: url-test - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true filter: "(?i)de|nl" rule-providers: diff --git a/internal/panel/subsettings/mihomo.go b/internal/panel/subsettings/mihomo.go index 7463c9d58..8074be485 100644 --- a/internal/panel/subsettings/mihomo.go +++ b/internal/panel/subsettings/mihomo.go @@ -260,7 +260,7 @@ type tplGroup struct { Use []string `yaml:"use"` IncludeAllProxies bool `yaml:"include-all-proxies"` IncludeAll bool `yaml:"include-all"` - OrderedProxies bool `yaml:"x-mistgate-ordered-proxies"` + OrderedProxies bool `yaml:"mistgate-ordered-proxies"` } // tplInfo is a template read for the keys the panel works on. diff --git a/internal/panel/subsettings/mihomo_ordered_groups.go b/internal/panel/subsettings/mihomo_ordered_groups.go index 898f2ddb4..a6cdc39b8 100644 --- a/internal/panel/subsettings/mihomo_ordered_groups.go +++ b/internal/panel/subsettings/mihomo_ordered_groups.go @@ -10,7 +10,7 @@ import ( "gopkg.in/yaml.v3" ) -const mihomoOrderedProxiesKey = "x-mistgate-ordered-proxies" +const mihomoOrderedProxiesKey = "mistgate-ordered-proxies" const mihomoFilterBudget = 250 * time.Millisecond diff --git a/internal/panel/subsettings/mihomo_ordered_groups_test.go b/internal/panel/subsettings/mihomo_ordered_groups_test.go index 664a177ea..7ce831ffb 100644 --- a/internal/panel/subsettings/mihomo_ordered_groups_test.go +++ b/internal/panel/subsettings/mihomo_ordered_groups_test.go @@ -27,12 +27,12 @@ proxy-groups: providers bool use []string }{ - {"explicit and unique final names", " proxies: [Static, DIRECT]\n x-mistgate-ordered-proxies: true\n", []string{"Static", "DIRECT", "Zulu", "Static ·", "Alpha", "Zulu ·", "Another"}, false, nil}, - {"ordered overlapping expressions with lookahead", " proxies: [DIRECT]\n x-mistgate-ordered-proxies: true\n filter: '^Z(?=ulu ·$)`^[AZ]`.*'\n", []string{"DIRECT", "Zulu ·", "Zulu", "Alpha", "Another", "Static ·", "Static"}, false, nil}, - {"empty with reject", " x-mistgate-ordered-proxies: true\n filter: '^Nothing$'\n empty-fallback: REJECT\n", []string{"REJECT"}, false, nil}, - {"empty by default", " x-mistgate-ordered-proxies: true\n filter: '^Nothing$'\n", []string{"COMPATIBLE"}, false, nil}, - {"empty locals with explicit provider", " x-mistgate-ordered-proxies: true\n filter: '^Nothing$'\n use: [Example]\n", nil, false, []string{"Example"}}, - {"include all providers without locals", " x-mistgate-ordered-proxies: true\n include-all-providers: true\n filter: '^Nothing$'\n", nil, true, nil}, + {"explicit and unique final names", " proxies: [Static, DIRECT]\n mistgate-ordered-proxies: true\n", []string{"Static", "DIRECT", "Zulu", "Static ·", "Alpha", "Zulu ·", "Another"}, false, nil}, + {"ordered overlapping expressions with lookahead", " proxies: [DIRECT]\n mistgate-ordered-proxies: true\n filter: '^Z(?=ulu ·$)`^[AZ]`.*'\n", []string{"DIRECT", "Zulu ·", "Zulu", "Alpha", "Another", "Static ·", "Static"}, false, nil}, + {"empty with reject", " mistgate-ordered-proxies: true\n filter: '^Nothing$'\n empty-fallback: REJECT\n", []string{"REJECT"}, false, nil}, + {"empty by default", " mistgate-ordered-proxies: true\n filter: '^Nothing$'\n", []string{"COMPATIBLE"}, false, nil}, + {"empty locals with explicit provider", " mistgate-ordered-proxies: true\n filter: '^Nothing$'\n use: [Example]\n", nil, false, []string{"Example"}}, + {"include all providers without locals", " mistgate-ordered-proxies: true\n include-all-providers: true\n filter: '^Nothing$'\n", nil, true, nil}, {"provider only", " use: [Example]\n", nil, false, []string{"Example"}}, } { t.Run(tc.name, func(t *testing.T) { @@ -54,7 +54,7 @@ proxy-groups: t.Run("native flags are not expanded", func(t *testing.T) { for _, native := range []string{"include-all-proxies", "include-all"} { base := head + " proxies: [DIRECT]\n " + native + ": true\n" - for _, suffix := range []string{"", " x-mistgate-ordered-proxies: false\n"} { + for _, suffix := range []string{"", " mistgate-ordered-proxies: false\n"} { out, _ := apply(t, base+suffix, MihomoOptions{}, "Zulu", "Alpha") if !strings.Contains(out, native+": true") || strings.Contains(out, mihomoOrderedProxiesKey) { t.Fatalf("native group flags changed:\n%s", out) @@ -75,8 +75,8 @@ proxy-groups: members []string }{ {"native", " proxies: [DIRECT]\n", "1", []string{"DIRECT"}}, - {"opted in", " x-mistgate-ordered-proxies: true\n filter: '^Nothing$'\n", "1", nil}, - {"disabled", " x-mistgate-ordered-proxies: true\n filter: '^Nothing$'\n", "0", []string{"COMPATIBLE"}}, + {"opted in", " mistgate-ordered-proxies: true\n filter: '^Nothing$'\n", "1", nil}, + {"disabled", " mistgate-ordered-proxies: true\n filter: '^Nothing$'\n", "0", []string{"COMPATIBLE"}}, } { t.Run(tc.name, func(t *testing.T) { providerFlag := " include-all-providers: " + tc.providers + "\n" @@ -100,14 +100,14 @@ proxy-groups: }) t.Run("conflicting native flags are rejected", func(t *testing.T) { for _, flag := range []string{"include-all-proxies", "include-all"} { - text := head + " x-mistgate-ordered-proxies: true\n " + flag + ": true\n" + text := head + " mistgate-ordered-proxies: true\n " + flag + ": true\n" if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "cannot be enabled with") { t.Fatalf("%s: save validation error = %v", flag, err) } } }) t.Run("ordered proxies suppress the no-servers warning", func(t *testing.T) { - if got := MihomoTemplateWarnings(head+" x-mistgate-ordered-proxies: true\n", false); len(got) != 0 { + if got := MihomoTemplateWarnings(head+" mistgate-ordered-proxies: true\n", false); len(got) != 0 { t.Fatalf("warnings = %+v", got) } }) @@ -115,7 +115,7 @@ proxy-groups: out, _ := apply(t, `proxy-groups: - name: Pick type: select - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true include-all-providers: true use: [Ignored] filter: '^Nothing$' @@ -131,7 +131,7 @@ proxy-groups: t.Run("aliases and inherited flags stay local", func(t *testing.T) { const text = `x-default: &default type: select - x-mistgate-ordered-proxies: true + mistgate-ordered-proxies: true proxies: &shared [DIRECT] # shared list x-group: &aliased <<: *default @@ -141,7 +141,7 @@ proxy-groups: - &original <<: *default name: Changed - x-mistgate-ordered-proxies: &flag true + mistgate-ordered-proxies: &flag true proxies: &list - &member REJECT # anchored member - name: Outside @@ -149,7 +149,7 @@ proxy-groups: proxies: *list - name: Inherited <<: *default - x-mistgate-ordered-proxies: false + mistgate-ordered-proxies: false x-copy: *original x-flag: *flag x-flag-copy: *flag @@ -191,7 +191,7 @@ x-member: *member t.Run("alias keys at the root and inside a group", func(t *testing.T) { const text = `x-groups-key: &groups-key proxy-groups x-proxies-key: &proxies-key proxies -x-include-key: &include-key x-mistgate-ordered-proxies +x-include-key: &include-key mistgate-ordered-proxies *groups-key: - name: Pick type: select @@ -223,7 +223,7 @@ x-list: &list [{name: Pick, type: select, include-all-proxies: true}] } }) t.Run("invalid expression is rejected without its text", func(t *testing.T) { - const text = head + " x-mistgate-ordered-proxies: true\n filter: '.*`(private-pattern'\n" + const text = head + " mistgate-ordered-proxies: true\n filter: '.*`(private-pattern'\n" out, err := ApplyMihomoTemplate(text, []MihomoServer{serverNode(t, "private-node")}, MihomoOptions{}) if len(out) != 0 || err == nil || !strings.Contains(err.Error(), "invalid filter") || strings.Contains(err.Error(), "private-") { t.Fatalf("output = %q, error = %v", out, err) diff --git a/web/src/i18n/subs.ts b/web/src/i18n/subs.ts index 95ee412ed..a56bdb850 100644 --- a/web/src/i18n/subs.ts +++ b/web/src/i18n/subs.ts @@ -38,7 +38,7 @@ export const en = { "subs.mt.err.nameTaken": "Another template has this name (letter case does not matter).", "subs.mt.err.empty": "The text is empty.", "subs.mt.err.big": "This text is {n} KiB. One template is up to {max} KiB.", - "subs.mt.warn.no_server_group": "No group takes the person's servers. Add x-mistgate-ordered-proxies: true to a group or refer to Auto, otherwise there is nothing to connect to.", + "subs.mt.warn.no_server_group": "No group takes the person's servers. Add mistgate-ordered-proxies: true to a group or refer to Auto, otherwise there is nothing to connect to.", "subs.mt.warn.own_dns": "The template has its own dns section, so the DNS preset of the person is not applied to it.", "subs.mt.warn.preset_rules_skipped": "The DNS preset of this person has ad, split or country rules, and a template does not get them. Write them into the template if you need them.", "subs.mt.warn.own_auto": "The template has its own Auto group, so the panel adds none.", @@ -440,7 +440,7 @@ export const ru: Record = { "subs.mt.err.nameTaken": "Такое название уже есть (регистр не важен).", "subs.mt.err.empty": "Текст пуст.", "subs.mt.err.big": "Текст занимает {n} КиБ. Один шаблон — до {max} КиБ.", - "subs.mt.warn.no_server_group": "Ни одна группа не берёт серверы человека. Добавь в группу x-mistgate-ordered-proxies: true или сошлись на Auto, иначе подключаться будет не к чему.", + "subs.mt.warn.no_server_group": "Ни одна группа не берёт серверы человека. Добавь в группу mistgate-ordered-proxies: true или сошлись на Auto, иначе подключаться будет не к чему.", "subs.mt.warn.own_dns": "В шаблоне есть свой раздел dns, поэтому DNS-пресет человека к нему не применяется.", "subs.mt.warn.preset_rules_skipped": "В DNS-пресете этого человека есть правила рекламы, разделения или стран, а шаблон их не получает. Если они нужны, впиши их в шаблон.", "subs.mt.warn.own_auto": "В шаблоне есть своя группа Auto, поэтому панель свою не добавляет.", @@ -835,7 +835,7 @@ export const zh: typeof en = { "subs.mt.err.nameTaken": "已有同名模板(不区分大小写)。", "subs.mt.err.empty": "文本为空。", "subs.mt.err.big": "文本为 {n} KiB。单个模板最多 {max} KiB。", - "subs.mt.warn.no_server_group": "没有任何组使用用户的服务器。请在某个组里加上 x-mistgate-ordered-proxies: true,或引用 Auto,否则无处可连。", + "subs.mt.warn.no_server_group": "没有任何组使用用户的服务器。请在某个组里加上 mistgate-ordered-proxies: true,或引用 Auto,否则无处可连。", "subs.mt.warn.own_dns": "模板有自己的 dns 部分,因此不会应用用户的 DNS 预设。", "subs.mt.warn.preset_rules_skipped": "此用户的 DNS 预设包含广告、分流或国家规则,而模板不会得到这些规则。需要的话请写进模板。", "subs.mt.warn.own_auto": "模板有自己的 Auto 组,因此面板不再添加。", @@ -1230,7 +1230,7 @@ export const fa: Record = { "subs.mt.err.nameTaken": "قالب دیگری همین نام را دارد (حروف بزرگ و کوچک فرقی ندارند).", "subs.mt.err.empty": "متن خالی است.", "subs.mt.err.big": "این متن {n} کیبی‌بایت است. هر قالب حداکثر {max} کیبی‌بایت می‌تواند باشد.", - "subs.mt.warn.no_server_group": "هیچ گروهی سرورهای فرد را نمی‌گیرد. در یک گروه x-mistgate-ordered-proxies: true بگذارید یا به Auto ارجاع دهید، وگرنه چیزی برای اتصال نیست.", + "subs.mt.warn.no_server_group": "هیچ گروهی سرورهای فرد را نمی‌گیرد. در یک گروه mistgate-ordered-proxies: true بگذارید یا به Auto ارجاع دهید، وگرنه چیزی برای اتصال نیست.", "subs.mt.warn.own_dns": "قالب بخش dns خودش را دارد، پس پیش‌تنظیم DNS فرد روی آن اعمال نمی‌شود.", "subs.mt.warn.preset_rules_skipped": "پیش‌تنظیم DNS این فرد قواعد تبلیغ، تفکیک یا کشور دارد و قالب آن‌ها را نمی‌گیرد. اگر لازم‌اند، در قالب بنویسید.", "subs.mt.warn.own_auto": "قالب گروه Auto خودش را دارد، پس پنل گروهی اضافه نمی‌کند.", @@ -1617,7 +1617,7 @@ export const tr: Record = { "subs.mt.err.nameTaken": "Başka bir şablonda aynı ad var (büyük küçük harf fark etmez).", "subs.mt.err.empty": "Metin boş.", "subs.mt.err.big": "Bu metin {n} KiB. Bir şablon en çok {max} KiB olabilir.", - "subs.mt.warn.no_server_group": "Hiçbir grup kişinin sunucularını almıyor. Bir gruba x-mistgate-ordered-proxies: true ekle ya da Auto'ya başvur, yoksa bağlanacak bir şey kalmaz.", + "subs.mt.warn.no_server_group": "Hiçbir grup kişinin sunucularını almıyor. Bir gruba mistgate-ordered-proxies: true ekle ya da Auto'ya başvur, yoksa bağlanacak bir şey kalmaz.", "subs.mt.warn.own_dns": "Şablonun kendi dns bölümü var, bu yüzden kişinin DNS ön ayarı ona uygulanmaz.", "subs.mt.warn.preset_rules_skipped": "Bu kişinin DNS ön ayarında reklam, ayırma ya da ülke kuralları var ve şablon bunları almaz. Gerekiyorsa şablona kendin yaz.", "subs.mt.warn.own_auto": "Şablonun kendi Auto grubu var, bu yüzden panel eklemez.", diff --git a/web/src/screens/subscriptions/mihomo.test.tsx b/web/src/screens/subscriptions/mihomo.test.tsx index dfb4fe65e..dfe595d08 100644 --- a/web/src/screens/subscriptions/mihomo.test.tsx +++ b/web/src/screens/subscriptions/mihomo.test.tsx @@ -683,7 +683,7 @@ describe("the pieces the form says early", () => { it("starts a new template with a group in panel order, and Auto only while the panel adds it", () => { expect(starterTemplate(true)).toContain("proxies: [Auto, DIRECT]"); expect(starterTemplate(false)).toContain("proxies: [DIRECT]"); - expect(starterTemplate(false)).toMatch(/^ x-mistgate-ordered-proxies: true$/m); + expect(starterTemplate(false)).toMatch(/^ mistgate-ordered-proxies: true$/m); }); it("ships an inert group example that can be enabled for an assigned group", () => { const starter = starterTemplate(true); diff --git a/web/src/screens/subscriptions/model.ts b/web/src/screens/subscriptions/model.ts index ab7b977a2..75e996e79 100644 --- a/web/src/screens/subscriptions/model.ts +++ b/web/src/screens/subscriptions/model.ts @@ -747,7 +747,7 @@ export function textKey(s: string): string { /** The text a new template starts with: one select group over every server of the person (and Auto while the panel adds it). */ export const starterTemplate = (auto: boolean): string => [ - "# Use x-mistgate-ordered-proxies: true to include each person's servers in panel order.", + "# Use mistgate-ordered-proxies: true to include each person's servers in panel order.", "# Mistgate puts explicit group members first, then the person's servers, then template proxies.", "# This flag is only for templates; don't combine it with include-all-proxies or include-all.", "mixed-port: 7890", @@ -762,7 +762,7 @@ export const starterTemplate = (auto: boolean): string => "proxy-groups:", " - name: Proxy", " type: select", - " x-mistgate-ordered-proxies: true", + " mistgate-ordered-proxies: true", ` proxies: [${auto ? "Auto, " : ""}DIRECT]`, "rules:", " - MATCH,Proxy", From f3acd3c06eb0f6f35cc9af6835ab78f8debc6e2b Mon Sep 17 00:00:00 2001 From: Morvex885 <278529280+Morvex885@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:34:36 +0300 Subject: [PATCH 6/9] Address Mihomo ordered group review findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep directive removal within groups and their defaults. Match the core’s option lookup and scalar types, and reject provider-name conflicts. Validate boolean opt-in and source locations; bound regexp polling and surface preview timeouts without exposing filter or node text. --- internal/panel/subs/mihomo.go | 7 +- internal/panel/subs/mihomo_order_core_test.go | 39 +++- internal/panel/subs/mihomo_preview.go | 8 +- .../subs/mihomo_template_internal_test.go | 6 +- internal/panel/subs/subs.go | 2 +- internal/panel/subsettings/mihomo.go | 116 ++++++----- .../subsettings/mihomo_ordered_groups.go | 196 ++++++++++++++---- .../subsettings/mihomo_ordered_groups_test.go | 56 ++++- 8 files changed, 317 insertions(+), 113 deletions(-) diff --git a/internal/panel/subs/mihomo.go b/internal/panel/subs/mihomo.go index 367492f0e..55754b8c3 100644 --- a/internal/panel/subs/mihomo.go +++ b/internal/panel/subs/mihomo.go @@ -127,13 +127,16 @@ func (p mihomoProfile) servers() []subsettings.MihomoServer { // is what a person gets when there is no template (tplText ""), when they get a note instead of servers (the note must be seen: a // template's groups would hide it), when none of their servers can be used, and when the template does not build (a stored text that // this version cannot read: a log line with the template's name, never its text). tplName is for that line only. -// selected is the source after group selection, for preview warnings even if no servers could be inserted. -func (p mihomoProfile) render(tplName, tplText string) (body []byte, selected string, templated bool, err error) { +// Draft previews report filter budget exhaustion instead of falling back. selected is the source after group selection, +// for preview warnings even if no servers could be inserted. +func (p mihomoProfile) render(tplName, tplText string, draft bool) (body []byte, selected string, templated bool, err error) { if tplText != "" && !p.note { body, selected, err = p.buildFromTemplate(tplText) switch { case err == nil: return body, selected, true, nil + case draft && errors.Is(err, subsettings.ErrMihomoFilterBudget): + return nil, selected, false, err case errors.Is(err, subsettings.ErrNoServers): default: if p.log != nil { diff --git a/internal/panel/subs/mihomo_order_core_test.go b/internal/panel/subs/mihomo_order_core_test.go index f884d6242..a8b7cd69c 100644 --- a/internal/panel/subs/mihomo_order_core_test.go +++ b/internal/panel/subs/mihomo_order_core_test.go @@ -68,8 +68,10 @@ func TestMihomoCoreOrderedGroups(t *testing.T) { log-level: info geo-auto-update: false unified-delay: false +proxies: + - {name: '16', type: http, server: 127.0.0.1, port: %[3]d} proxy-providers: - pasha-main: + mistgate-ordered-proxies: type: file path: pasha.yaml health-check: {enable: true, url: %[1]q, expected-status: '204'} @@ -81,13 +83,13 @@ proxy-groups: - name: Auto type: fallback mistgate-ordered-proxies: true - use: [oversecure, pasha-main] + use: [oversecure, mistgate-ordered-proxies] url: %[1]q expected-status: '204' - name: AI Auto type: fallback mistgate-ordered-proxies: true - use: [pasha-main, oversecure] + use: [mistgate-ordered-proxies, oversecure] filter: %[2]q exclude-filter: '(^| )RU( |$)' url: %[1]q @@ -97,18 +99,34 @@ proxy-groups: include-all-proxies: true - name: Provider only type: select - use: [pasha-main, oversecure] + use: [mistgate-ordered-proxies, oversecure] + - name: Numeric filter and folded proxies key + type: select + mistgate-ordered-proxies: true + PROXIES: [DIRECT] + filter: 0x10 + - name: Numeric fallback + type: select + mistgate-ordered-proxies: true + filter: '^No match$' + empty-fallback: 0x10 + - name: Exact proxies key + type: select + mistgate-ordered-proxies: true + PROXIES: [REJECT] + proxies: [DIRECT] + filter: '^KZ' rules: ['MATCH,Auto'] -`, healthURL, "KZ`.*") +`, healthURL, "KZ`.*", httpPort) out, used := templated(t, tpl, p) if !used { t.Fatal("the built-in profile was sent") } - if strings.Contains(out, "mistgate-ordered-proxies:") || !strings.Contains(out, "include-all-proxies: true") { + if strings.Contains(out, "mistgate-ordered-proxies: true") || !strings.Contains(out, "include-all-proxies: true") { t.Fatal("rendered profile must strip Mistgate's directive and retain the native flag") } - alphabetical := slices.Clone(p.names) + alphabetical := append(slices.Clone(p.names), "16") slices.Sort(alphabetical) got := orderedMihomoCoreProxies(t, bin, dir, out, healthURL, p.names) @@ -118,14 +136,17 @@ rules: ['MATCH,Auto'] }{ {"Auto", "Fallback", []string{ "DE-2 socks5", "DE-2 http", "LV socks5", "LV http", "DE-1 socks5", "DE-1 http", "KZ socks5", "KZ http", "RU socks5", "RU http", - "Oversecure DE", "Oversecure KZ", "Oversecure RU", "Pasha DE", "Pasha KZ", "Pasha RU", + "16", "Oversecure DE", "Oversecure KZ", "Oversecure RU", "Pasha DE", "Pasha KZ", "Pasha RU", }}, {"AI Auto", "Fallback", []string{ "KZ socks5", "KZ http", "Pasha KZ", "Oversecure KZ", - "DE-2 socks5", "DE-2 http", "LV socks5", "LV http", "DE-1 socks5", "DE-1 http", "Pasha DE", "Oversecure DE", + "DE-2 socks5", "DE-2 http", "LV socks5", "LV http", "DE-1 socks5", "DE-1 http", "16", "Pasha DE", "Oversecure DE", }}, {"Provider only", "Selector", []string{"Pasha DE", "Pasha KZ", "Pasha RU", "Oversecure DE", "Oversecure KZ", "Oversecure RU"}}, {"Native all proxies", "Selector", alphabetical}, + {"Numeric filter and folded proxies key", "Selector", []string{"DIRECT", "16"}}, + {"Numeric fallback", "Selector", []string{"16"}}, + {"Exact proxies key", "Selector", []string{"DIRECT", "KZ socks5", "KZ http"}}, } { g := got[want.group] if g.Type != want.kind || !slices.Equal(g.All, want.all) || g.Now != want.all[0] { diff --git a/internal/panel/subs/mihomo_preview.go b/internal/panel/subs/mihomo_preview.go index d62f74d90..0c11bc4f6 100644 --- a/internal/panel/subs/mihomo_preview.go +++ b/internal/panel/subs/mihomo_preview.go @@ -82,8 +82,14 @@ func (s *Service) PreviewMihomoTemplate(ctx context.Context, req *connect.Reques if !p.note { p.lines = redactedLines(p.lines) } - body, selected, templated, err := p.render("draft", m.Yaml) + body, selected, templated, err := p.render("draft", m.Yaml, true) if err != nil { + if errors.Is(err, subsettings.ErrMihomoFilterBudget) { + if canceled := contextError(err); canceled != nil { + return nil, canceled + } + return nil, connect.NewError(connect.CodeInvalidArgument, err) + } return nil, internal("preview render", err) } if p.note { diff --git a/internal/panel/subs/mihomo_template_internal_test.go b/internal/panel/subs/mihomo_template_internal_test.go index 5a6067377..39f28dafa 100644 --- a/internal/panel/subs/mihomo_template_internal_test.go +++ b/internal/panel/subs/mihomo_template_internal_test.go @@ -35,7 +35,7 @@ var hostileNames = []string{ func templated(t *testing.T, tpl string, p mihomoProfile) (string, bool) { t.Helper() - b, _, used, err := p.render("tpl", tpl) + b, _, used, err := p.render("tpl", tpl, false) if err != nil { t.Fatal(err) } @@ -384,7 +384,7 @@ func TestMihomoTemplateUnusableIsLoggedNotServed(t *testing.T) { var logs bytes.Buffer p := mihomoProfile{title: "T", lines: []string{fixture(t, hy2Line)}, preset: ruSplit(), autoSelect: true, log: slog.New(slog.NewTextHandler(&logs, nil))} want, _ := mihomoProfile{title: "T", lines: p.lines, preset: ruSplit(), autoSelect: true}.build() - out, _, used, err := p.render("Router, v2", text) + out, _, used, err := p.render("Router, v2", text, false) if err != nil || used || string(out) != string(want) { t.Errorf("%s: used %v, err %v", name, used, err) } @@ -423,7 +423,7 @@ func BenchmarkMihomoTemplate(b *testing.B) { b.SetBytes(int64(len(text))) b.ReportAllocs() for i := 0; i < b.N; i++ { - if _, _, used, err := p.render("t", text); err != nil || !used { + if _, _, used, err := p.render("t", text, false); err != nil || !used { b.Fatal(used, err) } } diff --git a/internal/panel/subs/subs.go b/internal/panel/subs/subs.go index a61010335..04b4624ac 100644 --- a/internal/panel/subs/subs.go +++ b/internal/panel/subs/subs.go @@ -782,7 +782,7 @@ func (h *handler) writeMihomo(w http.ResponseWriter, r *http.Request, token stri if t := subsettings.MihomoTemplateFor(set, v.GroupID); t != nil { tplName, tplText = t.Name, t.Yaml } - body, _, _, err := p.render(tplName, tplText) + body, _, _, err := p.render(tplName, tplText, false) if err != nil { h.cfg.Log.Error("mihomo profile", "code", "subscription_mihomo_render_failed", "err", err) http.Error(w, "internal error", http.StatusInternalServerError) diff --git a/internal/panel/subsettings/mihomo.go b/internal/panel/subsettings/mihomo.go index 8074be485..64c420b3b 100644 --- a/internal/panel/subsettings/mihomo.go +++ b/internal/panel/subsettings/mihomo.go @@ -254,21 +254,24 @@ type tplNamed struct { } type tplGroup struct { - Name string `yaml:"name"` - Type string `yaml:"type"` - Proxies []string `yaml:"proxies"` - Use []string `yaml:"use"` - IncludeAllProxies bool `yaml:"include-all-proxies"` - IncludeAll bool `yaml:"include-all"` - OrderedProxies bool `yaml:"mistgate-ordered-proxies"` + Name string `yaml:"name"` + Type string `yaml:"type"` + Proxies []string `yaml:"proxies"` + Use []string `yaml:"use"` + IncludeAllProxies bool `yaml:"include-all-proxies"` + IncludeAll bool `yaml:"include-all"` + OrderedProxies mihomoOrderFlag `yaml:"mistgate-ordered-proxies"` + order *mihomoOrderedOptions } // tplInfo is a template read for the keys the panel works on. type tplInfo struct { - doc, root *yaml.Node - proxies []tplNamed - groups []tplGroup - names map[string]bool // the names of the template's proxies and groups + doc, root *yaml.Node + proxies []tplNamed + groups []tplGroup + names map[string]bool // the names of the template's proxies and groups + providers map[string]yaml.Node + providersRead bool } // loadTemplate reads text as the panel changes it: one document, a mapping, the shape of checkRootShape, the entries of `proxies` and @@ -306,26 +309,52 @@ func loadTemplate(text string) (*tplInfo, error) { return nil, err } } - for i, g := range t.groups { + groupNodes, _ := rootValue(root, "proxy-groups") + for i := range t.groups { + g := &t.groups[i] if err := add("proxy-groups", i, g.Name); err != nil { return nil, err } if g.Type == "" { return nil, fmt.Errorf("proxy-groups[%d] %q: a type is required", i, g.Name) } - if g.OrderedProxies && (g.IncludeAllProxies || g.IncludeAll) { + if !g.OrderedProxies { + continue + } + opt, err := readMihomoOrderedOptions(groupNodes.Content[i], i) + if err != nil { + return nil, err + } + if opt.IncludeAllProxies || opt.IncludeAll { return nil, fmt.Errorf("proxy-groups[%d]: %s cannot be enabled with include-all-proxies or include-all; use include-all-providers to add all external providers", i, mihomoOrderedProxiesKey) } + if err := t.readProxyProviders(); err != nil { + return nil, err + } + if _, exists := t.providers[g.Name]; exists { + return nil, fmt.Errorf("proxy-groups[%d] %q: rename the group or the proxy provider before enabling %s; Mihomo requires distinct names", i, g.Name, mihomoOrderedProxiesKey) + } + g.Proxies, g.Use, g.order = opt.Proxies, opt.Use, opt } return t, nil } +func (t *tplInfo) readProxyProviders() error { + if !t.providersRead { + if v, _ := rootValue(t.root, "proxy-providers"); v != nil { + if err := v.Decode(&t.providers); err != nil { + return mihomoYAMLDiagnostic{err: err, prefix: "proxy-providers: "} + } + } + t.providersRead = true + } + return nil +} + // checkRefs checks what the groups name: every member is a name of the template, of the core, or Auto (when the panel adds it), and // every `use` is a key of proxy-providers. A name that is not there is why a Mihomo core refuses the whole file, and a name of a server // is the usual one: only some people have it. func (t *tplInfo) checkRefs(autoOn bool) error { - var providers map[string]any - loaded := false for i, g := range t.groups { for _, m := range g.Proxies { if t.names[m] || slices.Contains(CoreNames, m) || (autoOn && m == AutoName) { @@ -336,16 +365,14 @@ func (t *tplInfo) checkRefs(autoOn bool) error { } return fmt.Errorf("proxy-groups[%d] %q: proxies: %q is not a proxy or group of this template (take servers with %s or include-all-proxies)", i, g.Name, m, mihomoOrderedProxiesKey) } + if g.order != nil && bool(g.order.IncludeAllProviders) { + continue // Mihomo replaces use with the declared provider keys. + } for _, u := range g.Use { - if !loaded { - loaded = true - if v, _ := rootValue(t.root, "proxy-providers"); v != nil { - if err := v.Decode(&providers); err != nil && !isNull(v) { - return mihomoYAMLDiagnostic{err: err, prefix: "proxy-providers: "} - } - } + if err := t.readProxyProviders(); err != nil { + return err } - if _, ok := providers[u]; !ok { + if _, ok := t.providers[u]; !ok { return fmt.Errorf("proxy-groups[%d] %q: use: %q is not in proxy-providers", i, g.Name, u) } } @@ -415,9 +442,9 @@ func checkMihomoTemplate(ctx context.Context, text string, autoOn bool, sourceEr return err } // A trial build with two servers, as a person would get it: an error of the encoder is found here, not in the apps. - out, err := ApplyMihomoTemplate(text, trialServers(), MihomoOptions{AutoSelect: autoOn}) + out, err := applyLoadedMihomoTemplate(t, trialServers(), MihomoOptions{AutoSelect: autoOn}) if err != nil { - return fmt.Errorf("trial build: %w", err) + return fmt.Errorf("trial build: %w", mapError(err)) } if err := ctx.Err(); err != nil { return err @@ -493,6 +520,10 @@ func ApplyMihomoTemplate(text string, servers []MihomoServer, opt MihomoOptions) if err != nil { return nil, err } + return applyLoadedMihomoTemplate(t, servers, opt) +} + +func applyLoadedMihomoTemplate(t *tplInfo, servers []MihomoServer, opt MihomoOptions) ([]byte, error) { taken := map[string]bool{} for n := range t.names { taken[n] = true @@ -543,11 +574,8 @@ func ApplyMihomoTemplate(text string, servers []MihomoServer, opt MihomoOptions) t.root.Content[i] = opt.DNS } } - var removedAnchors map[*yaml.Node]bool - prepareMihomoYAML(t.doc, &removedAnchors) - if len(removedAnchors) != 0 { - restoreMihomoYAMLAnchors(t.doc, removedAnchors) - } + stripMihomoOrderFlags(t) + prepareMihomoYAML(t.doc) var buf bytes.Buffer enc := yaml.NewEncoder(&buf) enc.SetIndent(2) @@ -560,9 +588,10 @@ func ApplyMihomoTemplate(text string, servers []MihomoServer, opt MihomoOptions) return buf.Bytes(), nil } -// The output omits the Mistgate group directive, including from shared group -// defaults. Emit plain merge keys and avoid yaml.v3's folded keep-chomping bug. -func prepareMihomoYAML(n *yaml.Node, removedAnchors *map[*yaml.Node]bool) { +// Write plain merge keys for YAML readers that do not accept an explicit merge tag. +// yaml.v3 can add a newline when emitting folded scalars with keep chomping. +// Emit those values literally instead. Do not follow aliases: the target is already in the tree. +func prepareMihomoYAML(n *yaml.Node) { if n.Kind == yaml.ScalarNode { if n.Tag == "!!merge" && n.Value == "<<" { n.Tag = "" @@ -571,25 +600,8 @@ func prepareMihomoYAML(n *yaml.Node, removedAnchors *map[*yaml.Node]bool) { n.Style = (n.Style &^ yaml.FoldedStyle) | yaml.LiteralStyle } } - if n.Kind == yaml.MappingNode { - kept := n.Content[:0] - for i := 0; i < len(n.Content); i += 2 { - k, v := n.Content[i], n.Content[i+1] - prepareMihomoYAML(k, removedAnchors) - prepareMihomoYAML(v, removedAnchors) - if key := mappingKey(k); key.Kind == yaml.ScalarNode && key.Value == mihomoOrderedProxiesKey { - markRemovedMihomoAnchors(k, removedAnchors) - markRemovedMihomoAnchors(v, removedAnchors) - } else { - kept = append(kept, k, v) - } - } - clear(n.Content[len(kept):]) - n.Content = kept - return - } for _, c := range n.Content { - prepareMihomoYAML(c, removedAnchors) + prepareMihomoYAML(c) } } @@ -606,7 +618,7 @@ func MihomoTemplateWarnings(text string, autoOn bool) []MihomoWarning { ownAuto := t.names[AutoName] takes := false for _, g := range t.groups { - takes = takes || g.OrderedProxies || g.IncludeAllProxies || g.IncludeAll || (autoOn && !ownAuto && slices.Contains(g.Proxies, AutoName)) + takes = takes || bool(g.OrderedProxies) || g.IncludeAllProxies || g.IncludeAll || (autoOn && !ownAuto && slices.Contains(g.Proxies, AutoName)) } if !takes { out = append(out, MihomoWarning{Code: WarnNoServerGroup}) diff --git a/internal/panel/subsettings/mihomo_ordered_groups.go b/internal/panel/subsettings/mihomo_ordered_groups.go index a6cdc39b8..3d8d91f2d 100644 --- a/internal/panel/subsettings/mihomo_ordered_groups.go +++ b/internal/panel/subsettings/mihomo_ordered_groups.go @@ -3,6 +3,7 @@ package subsettings import ( "errors" "fmt" + "strconv" "strings" "time" @@ -12,9 +13,19 @@ import ( const mihomoOrderedProxiesKey = "mistgate-ordered-proxies" -const mihomoFilterBudget = 250 * time.Millisecond +const ( + mihomoFilterBudget = 250 * time.Millisecond + mihomoFilterClockPeriod = 5 * time.Millisecond + // regexp2 adds a period to the deadline and polls an approximate clock. + mihomoFilterClockSlack = 2*mihomoFilterClockPeriod + time.Millisecond +) + +func init() { + regexp2.SetTimeoutCheckPeriod(mihomoFilterClockPeriod) +} -var errMihomoFilterBudget = errors.New("filter exceeded the matching time limit") +// ErrMihomoFilterBudget is safe to return to the template editor. +var ErrMihomoFilterBudget = errors.New("filter exceeded the matching time limit") // A filter cache belongs to one render. Regexp.MatchTimeout is mutable, so // these expressions cannot be shared across renders. @@ -25,14 +36,14 @@ type mihomoGroupFilters struct { func (f *mihomoGroupFilters) match(pattern, name string) (bool, error) { remaining := time.Until(f.deadline) - if remaining <= 0 { - return false, errMihomoFilterBudget + if remaining <= mihomoFilterClockSlack { + return false, ErrMihomoFilterBudget } re := f.compiled[pattern] - re.MatchTimeout = remaining + re.MatchTimeout = remaining - mihomoFilterClockSlack matched, err := re.MatchString(name) if err != nil || time.Until(f.deadline) <= 0 { - return false, errMihomoFilterBudget + return false, ErrMihomoFilterBudget } return matched, nil } @@ -53,7 +64,7 @@ func (f *mihomoGroupFilters) orderedMembers(authored, names []string, static []t for pattern := range strings.SplitSeq(filter, "`") { if filter != "" && f.compiled[pattern] == nil { if time.Until(f.deadline) <= 0 { - return nil, errMihomoFilterBudget + return nil, ErrMihomoFilterBudget } re, err := regexp2.Compile(pattern, regexp2.None) if err != nil { @@ -86,22 +97,95 @@ func (f *mihomoGroupFilters) orderedMembers(authored, names []string, static []t } } if filter != "" && time.Until(f.deadline) <= 0 { - return nil, errMihomoFilterBudget + return nil, ErrMihomoFilterBudget } } return members, nil } -// These options are read only when Mistgate expands the group. +// These options use the core's effective native keys, only for opted-in groups. type mihomoOrderedOptions struct { - Filter string `yaml:"filter"` - EmptyFallback string `yaml:"empty-fallback"` - IncludeAllProviders mihomoProviderFlag `yaml:"include-all-providers"` + Proxies []string `yaml:"proxies"` + Use []string `yaml:"use"` + Filter mihomoNativeText `yaml:"filter"` + EmptyFallback mihomoNativeText `yaml:"empty-fallback"` + IncludeAllProxies mihomoNativeBool `yaml:"include-all-proxies"` + IncludeAllProviders mihomoNativeBool `yaml:"include-all-providers"` + IncludeAll mihomoNativeBool `yaml:"include-all"` + proxiesKey string +} + +func readMihomoOrderedOptions(group *yaml.Node, index int) (*mihomoOrderedOptions, error) { + prefix := fmt.Sprintf("proxy-groups[%d]: ", index) + var raw map[string]yaml.Node + if err := group.Decode(&raw); err != nil { + return nil, mihomoYAMLDiagnostic{err: err, prefix: prefix} + } + opt := new(mihomoOrderedOptions) + projected := mapOf() + for _, key := range [...]string{"proxies", "use", "filter", "empty-fallback", "include-all-proxies", "include-all-providers", "include-all"} { + actual := key + value, ok := raw[key] + if !ok { + for alias, candidate := range raw { + if !strings.EqualFold(alias, key) { + continue + } + if ok { + return nil, fmt.Errorf("%sambiguous option %s; use the exact spelling", prefix, key) + } + actual, value, ok = alias, candidate, true + } + } + if ok { + if key == "proxies" { + opt.proxiesKey = actual + } + projected.Content = append(projected.Content, strNode(key), &value) + } + } + if err := projected.Decode(opt); err != nil { + return nil, mihomoYAMLDiagnostic{err: err, prefix: prefix} + } + return opt, nil +} + +type mihomoOrderFlag bool + +func (enabled *mihomoOrderFlag) UnmarshalYAML(n *yaml.Node) error { + if n.ShortTag() != "!!bool" { + return fmt.Errorf("line %d: %s must be a YAML boolean", n.Line, mihomoOrderedProxiesKey) + } + return n.Decode((*bool)(enabled)) +} + +type mihomoNativeText string + +func (text *mihomoNativeText) UnmarshalYAML(n *yaml.Node) error { + var value any + if err := n.Decode(&value); err != nil { + return err + } + switch v := value.(type) { + case string: + *text = mihomoNativeText(v) + case int: + *text = mihomoNativeText(strconv.Itoa(v)) + case int64: + *text = mihomoNativeText(strconv.FormatInt(v, 10)) + case uint64: + *text = mihomoNativeText(strconv.FormatUint(v, 10)) + case float64: + *text = mihomoNativeText(strconv.FormatFloat(v, 'E', -1, 64)) + default: + return fmt.Errorf("line %d: expected a string or number", n.Line) + } + return nil } -type mihomoProviderFlag bool +type mihomoNativeBool bool -func (enabled *mihomoProviderFlag) UnmarshalYAML(n *yaml.Node) error { +func (enabled *mihomoNativeBool) UnmarshalYAML(n *yaml.Node) error { // Mihomo's weak bool decoder accepts a YAML boolean or any integer. var value any if err := n.Decode(&value); err != nil { @@ -109,7 +193,7 @@ func (enabled *mihomoProviderFlag) UnmarshalYAML(n *yaml.Node) error { } switch v := value.(type) { case bool: - *enabled = mihomoProviderFlag(v) + *enabled = mihomoNativeBool(v) case int: *enabled = v != 0 case int64: @@ -117,7 +201,7 @@ func (enabled *mihomoProviderFlag) UnmarshalYAML(n *yaml.Node) error { case uint64: *enabled = v != 0 default: - return fmt.Errorf("line %d: include-all-providers must be a boolean or an integer", n.Line) + return fmt.Errorf("line %d: expected a boolean or integer", n.Line) } return nil } @@ -125,36 +209,24 @@ func (enabled *mihomoProviderFlag) UnmarshalYAML(n *yaml.Node) error { func expandOrderedMihomoGroups(t *tplInfo, names []string) error { groups, _ := rootValue(t.root, "proxy-groups") var filters mihomoGroupFilters - providerCount := -1 + // Provider keys were read when the opted-in groups were validated. for i, g := range t.groups { - if !g.OrderedProxies { + if g.order == nil { continue } group := groups.Content[i] - var opt mihomoOrderedOptions - if err := group.Decode(&opt); err != nil { - return mihomoYAMLDiagnostic{err: err, prefix: fmt.Sprintf("proxy-groups[%d]: ", i)} - } - members, err := filters.orderedMembers(g.Proxies, names, t.proxies, opt.Filter) + opt := g.order + members, err := filters.orderedMembers(g.Proxies, names, t.proxies, string(opt.Filter)) if err != nil { return fmt.Errorf("proxy-groups[%d]: %w", i, err) } if len(members) == 0 { count := len(g.Use) if opt.IncludeAllProviders { - if providerCount < 0 { - var providers map[string]yaml.Node - if v, _ := rootValue(t.root, "proxy-providers"); v != nil { - if err := v.Decode(&providers); err != nil { - return mihomoYAMLDiagnostic{err: err, prefix: "proxy-providers: "} - } - } - providerCount = len(providers) - } - count = providerCount + count = len(t.providers) } if count == 0 { - fallback := opt.EmptyFallback + fallback := string(opt.EmptyFallback) if fallback == "" { fallback = "COMPATIBLE" } @@ -162,7 +234,7 @@ func expandOrderedMihomoGroups(t *tplInfo, names []string) error { } } - old, index := rootValue(group, "proxies") + old, index := rootValue(group, opt.proxiesKey) if group.Kind == yaml.AliasNode || group.Anchor != "" || old != nil && hasYAMLAnchor(old) { // Keep original anchor definitions inline and before their readers. A // local merge overlay changes this group without changing what any alias sees. @@ -185,6 +257,60 @@ func expandOrderedMihomoGroups(t *tplInfo, names []string) error { return nil } +// Strip the directive only from group mappings and the defaults they merge. +// An identically named provider or other YAML entry is not a directive. +func stripMihomoOrderFlags(t *tplInfo) { + if len(t.groups) == 0 { + return + } + groups, _ := rootValue(t.root, "proxy-groups") + var seen map[*yaml.Node]bool + var removed map[*yaml.Node]bool + var strip func(*yaml.Node) + strip = func(n *yaml.Node) { + if n.Kind == yaml.AliasNode { + n = n.Alias + } + if n.Anchor != "" { + if seen[n] { + return + } + if seen == nil { + seen = make(map[*yaml.Node]bool) + } + seen[n] = true + } + if n.Kind == yaml.SequenceNode { + for _, child := range n.Content { + strip(child) + } + return + } + if n.Kind != yaml.MappingNode { + return + } + kept := n.Content[:0] + for i := 0; i < len(n.Content); i += 2 { + k, v := n.Content[i], n.Content[i+1] + if key := mappingKey(k); key.Kind == yaml.ScalarNode && key.Value == mihomoOrderedProxiesKey { + markRemovedMihomoAnchors(k, &removed) + markRemovedMihomoAnchors(v, &removed) + continue + } + if k.Kind == yaml.ScalarNode && k.ShortTag() == "!!merge" { + strip(v) + } + kept = append(kept, k, v) + } + clear(n.Content[len(kept):]) + n.Content = kept + } + strip(groups) + if len(removed) != 0 { + restoreMihomoYAMLAnchors(t.doc, removed) + } +} + func hasYAMLAnchor(node *yaml.Node) bool { if node.Anchor != "" { return true diff --git a/internal/panel/subsettings/mihomo_ordered_groups_test.go b/internal/panel/subsettings/mihomo_ordered_groups_test.go index 7ce831ffb..280e1d57e 100644 --- a/internal/panel/subsettings/mihomo_ordered_groups_test.go +++ b/internal/panel/subsettings/mihomo_ordered_groups_test.go @@ -1,6 +1,7 @@ package subsettings import ( + "context" "errors" "slices" "strings" @@ -99,13 +100,46 @@ proxy-groups: } }) t.Run("conflicting native flags are rejected", func(t *testing.T) { - for _, flag := range []string{"include-all-proxies", "include-all"} { + for _, flag := range []string{"include-all-proxies", "include-all", "INCLUDE-ALL-PROXIES", "INCLUDE-ALL"} { text := head + " mistgate-ordered-proxies: true\n " + flag + ": true\n" if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "cannot be enabled with") { t.Fatalf("%s: save validation error = %v", flag, err) } } }) + t.Run("the opt-in must be a YAML boolean", func(t *testing.T) { + for _, value := range []string{`"on"`, `"yes"`, "on", "1"} { + text := head + " mistgate-ordered-proxies: " + value + "\n" + if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "mistgate-ordered-proxies must be a YAML boolean") { + t.Fatalf("%s: save validation error = %v", value, err) + } + } + }) + t.Run("provider names cannot collide with opted-in groups", func(t *testing.T) { + base := strings.Replace(head, "name: Pick", "name: Example", 1) + " use: [Example]\n" + if err := CheckMihomoTemplate(base, false); err != nil { + t.Fatalf("native provider-only group: %v", err) + } + text := base + " mistgate-ordered-proxies: true\n filter: '^not a trial server$'\n" + if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "requires distinct names") { + t.Fatalf("save validation error = %v", err) + } + }) + t.Run("ordered option errors point to the source", func(t *testing.T) { + const text = `# @mistgate-if ["grp_demo"] +mixed-port: 7890 +# @mistgate-end +proxy-groups: + - name: Pick + type: select + mistgate-ordered-proxies: true + filter: [] +` + err := CheckMihomoGroups(context.Background(), text, []string{"grp_demo"}, false) + if err == nil || !strings.Contains(err.Error(), "line 8:") { + t.Fatalf("save validation error = %v, want authored line 8", err) + } + }) t.Run("ordered proxies suppress the no-servers warning", func(t *testing.T) { if got := MihomoTemplateWarnings(head+" mistgate-ordered-proxies: true\n", false); len(got) != 0 { t.Fatalf("warnings = %+v", got) @@ -206,7 +240,7 @@ x-include-key: &include-key mistgate-ordered-proxies if err != nil { t.Fatal(err) } - if got := info.groups[0]; got.OrderedProxies || !slices.Equal(got.Proxies, []string{"DIRECT", "Zulu", "Alpha"}) { + if got := info.groups[0]; bool(got.OrderedProxies) || !slices.Equal(got.Proxies, []string{"DIRECT", "Zulu", "Alpha"}) { t.Fatalf("group = %+v", got) } if err := CheckMihomoTemplate(out, false); err != nil { @@ -232,14 +266,16 @@ x-list: &list [{name: Pick, type: select, include-all-proxies: true}] t.Fatalf("save validation error = %v", err) } }) - t.Run("expired filter budget", func(t *testing.T) { - f := mihomoGroupFilters{ - compiled: map[string]*regexp2.Regexp{".*": regexp2.MustCompile(".*", regexp2.None)}, - deadline: time.Now().Add(-time.Second), - } - got, err := f.orderedMembers([]string{"DIRECT"}, []string{"Zulu"}, nil, ".*") - if got != nil || !errors.Is(err, errMihomoFilterBudget) { - t.Fatalf("members = %q, error = %v", got, err) + t.Run("filter budget reserves clock polling time", func(t *testing.T) { + for _, remaining := range []time.Duration{-time.Second, mihomoFilterClockSlack / 2} { + f := mihomoGroupFilters{ + compiled: map[string]*regexp2.Regexp{".*": regexp2.MustCompile(".*", regexp2.None)}, + deadline: time.Now().Add(remaining), + } + got, err := f.orderedMembers([]string{"DIRECT"}, []string{"Zulu"}, nil, ".*") + if got != nil || !errors.Is(err, ErrMihomoFilterBudget) { + t.Fatalf("members = %q, error = %v", got, err) + } } }) } From 79ba2a4d4e2db21f5b7fbc2de5551e9b7090b651 Mon Sep 17 00:00:00 2001 From: Morvex885 <278529280+Morvex885@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:39:47 +0300 Subject: [PATCH 7/9] Keep Mihomo regex deadlines active on WebAssembly Pin the upstream regexp2 v1.12.0 source with its MIT license. Poll monotonic time on wasm, where background goroutines cannot preempt the interpreter. Test deadline expiry without yielding under the Go js/wasm runner. --- go.mod | 3 + go.sum | 2 - third_party/regexp2/LICENSE | 21 + third_party/regexp2/fastclock.go | 158 ++ third_party/regexp2/fastclock_wasm_test.go | 20 + third_party/regexp2/go.mod | 3 + third_party/regexp2/match.go | 349 +++ third_party/regexp2/regexp.go | 395 ++++ third_party/regexp2/replace.go | 177 ++ third_party/regexp2/runner.go | 1614 ++++++++++++++ third_party/regexp2/syntax/charclass.go | 865 ++++++++ third_party/regexp2/syntax/code.go | 274 +++ third_party/regexp2/syntax/escape.go | 94 + third_party/regexp2/syntax/fuzz.go | 20 + third_party/regexp2/syntax/parser.go | 2262 ++++++++++++++++++++ third_party/regexp2/syntax/prefix.go | 896 ++++++++ third_party/regexp2/syntax/replacerdata.go | 87 + third_party/regexp2/syntax/tree.go | 654 ++++++ third_party/regexp2/syntax/writer.go | 500 +++++ 19 files changed, 8392 insertions(+), 2 deletions(-) create mode 100644 third_party/regexp2/LICENSE create mode 100644 third_party/regexp2/fastclock.go create mode 100644 third_party/regexp2/fastclock_wasm_test.go create mode 100644 third_party/regexp2/go.mod create mode 100644 third_party/regexp2/match.go create mode 100644 third_party/regexp2/regexp.go create mode 100644 third_party/regexp2/replace.go create mode 100644 third_party/regexp2/runner.go create mode 100644 third_party/regexp2/syntax/charclass.go create mode 100644 third_party/regexp2/syntax/code.go create mode 100644 third_party/regexp2/syntax/escape.go create mode 100644 third_party/regexp2/syntax/fuzz.go create mode 100644 third_party/regexp2/syntax/parser.go create mode 100644 third_party/regexp2/syntax/prefix.go create mode 100644 third_party/regexp2/syntax/replacerdata.go create mode 100644 third_party/regexp2/syntax/tree.go create mode 100644 third_party/regexp2/syntax/writer.go diff --git a/go.mod b/go.mod index b6b024ba6..1a2232133 100644 --- a/go.mod +++ b/go.mod @@ -236,3 +236,6 @@ replace github.com/xtls/xray-core => github.com/Mistgate/Xray-core v0.0.0-202611 // a facade without sockets or files (mgdns), a zone responder, hooks for dialing and DNS, limits. From the public fork // github.com/Mistgate/MasterDnsVPN (its MISTGATE.md says what and why). Pin a commit of the fork, not a branch. replace masterdnsvpn-go => github.com/Mistgate/MasterDnsVPN v0.0.0-20261201015347-cb8d620bacc6 + +// regexp2 v1.12.0 (3d5df45b7038) with synchronous deadline checks on single-threaded WebAssembly. +replace github.com/dlclark/regexp2 => ./third_party/regexp2 diff --git a/go.sum b/go.sum index 0e7503620..a7f859729 100644 --- a/go.sum +++ b/go.sum @@ -140,8 +140,6 @@ github.com/descope/virtualwebauthn v1.0.5 h1:fMXji5UMepJC51Ge6d4v5IAjiJQRKmXE9hl github.com/descope/virtualwebauthn v1.0.5/go.mod h1:lLCfN+DpCM3iisM4bCILZlFEWkC1Zo7ZgsxC45CUapI= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= -github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8= -github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= github.com/docker/cli v29.8.0+incompatible h1:ih0c2jq/nN7QfES8zIfwSzIhRScjs4ehER+kZ60aeSk= diff --git a/third_party/regexp2/LICENSE b/third_party/regexp2/LICENSE new file mode 100644 index 000000000..fe83dfdc9 --- /dev/null +++ b/third_party/regexp2/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Doug Clark + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/third_party/regexp2/fastclock.go b/third_party/regexp2/fastclock.go new file mode 100644 index 000000000..70bfbad2a --- /dev/null +++ b/third_party/regexp2/fastclock.go @@ -0,0 +1,158 @@ +package regexp2 + +import ( + "runtime" + "sync" + "sync/atomic" + "time" +) + +// fasttime holds a time value (ticks since clock initialization) +type fasttime int64 + +// fastclock provides a fast clock implementation. +// +// A background goroutine periodically stores the current time +// into an atomic variable. +// +// A deadline can be quickly checked for expiration by comparing +// its value to the clock stored in the atomic variable. +// +// The goroutine automatically stops once clockEnd is reached. +// (clockEnd covers the largest deadline seen so far + some +// extra time). This ensures that if regexp2 with timeouts +// stops being used we will stop background work. +type fastclock struct { + // instances of atomicTime must be at the start of the struct (or at least 64-bit aligned) + // otherwise 32-bit architectures will panic + + current atomicTime // Current time (approximate) + clockEnd atomicTime // When clock updater is supposed to stop (>= any existing deadline) + + // current and clockEnd can be read via atomic loads. + // Reads and writes of other fields require mu to be held. + mu sync.Mutex + start time.Time // Time corresponding to fasttime(0) + running bool // Is a clock updater running? +} + +var fast fastclock + +var wasmClockStart time.Time + +func init() { + if runtime.GOARCH == "wasm" { + wasmClockStart = time.Now() + } +} + +// reached returns true if current time is at or past t. +func (t fasttime) reached() bool { + if runtime.GOARCH == "wasm" { + return durationToTicks(time.Since(wasmClockStart)) >= t + } + return fast.current.read() >= t +} + +// makeDeadline returns a time that is approximately time.Now().Add(d) +func makeDeadline(d time.Duration) fasttime { + // js/wasm cannot run the clock goroutine while the interpreter is busy. + // Poll its monotonic clock directly instead. + if runtime.GOARCH == "wasm" { + return durationToTicks(time.Since(wasmClockStart) + d) + } + // Increase the deadline since the clock we are reading may be + // just about to tick forwards. + end := fast.current.read() + durationToTicks(d+clockPeriod) + + // Start or extend clock if necessary. + if end > fast.clockEnd.read() { + // If time.Since(last use) > timeout, there's a chance that + // fast.current will no longer be updated, which can lead to + // incorrect 'end' calculations that can trigger a false timeout + fast.mu.Lock() + if !fast.running && !fast.start.IsZero() { + // update fast.current + fast.current.write(durationToTicks(time.Since(fast.start))) + // recalculate our end value + end = fast.current.read() + durationToTicks(d+clockPeriod) + } + fast.mu.Unlock() + extendClock(end) + } + + return end +} + +// extendClock ensures that clock is live and will run until at least end. +func extendClock(end fasttime) { + fast.mu.Lock() + defer fast.mu.Unlock() + + if fast.start.IsZero() { + fast.start = time.Now() + } + + // Extend the running time to cover end as well as a bit of slop. + if shutdown := end + durationToTicks(time.Second); shutdown > fast.clockEnd.read() { + fast.clockEnd.write(shutdown) + } + + // Start clock if necessary + if !fast.running { + fast.running = true + go runClock() + } +} + +// stop the timeout clock in the background +// should only used for unit tests to abandon the background goroutine +func stopClock() { + fast.mu.Lock() + if fast.running { + fast.clockEnd.write(fasttime(0)) + } + fast.mu.Unlock() + + // pause until not running + // get and release the lock + isRunning := true + for isRunning { + time.Sleep(clockPeriod / 2) + fast.mu.Lock() + isRunning = fast.running + fast.mu.Unlock() + } +} + +func durationToTicks(d time.Duration) fasttime { + // Downscale nanoseconds to approximately a millisecond so that we can avoid + // overflow even if the caller passes in math.MaxInt64. + return fasttime(d) >> 20 +} + +const DefaultClockPeriod = 100 * time.Millisecond + +// clockPeriod is the approximate interval between updates of approximateClock. +var clockPeriod = DefaultClockPeriod + +func runClock() { + fast.mu.Lock() + defer fast.mu.Unlock() + + for fast.current.read() <= fast.clockEnd.read() { + // Unlock while sleeping. + fast.mu.Unlock() + time.Sleep(clockPeriod) + fast.mu.Lock() + + newTime := durationToTicks(time.Since(fast.start)) + fast.current.write(newTime) + } + fast.running = false +} + +type atomicTime struct{ v int64 } // Should change to atomic.Int64 when we can use go 1.19 + +func (t *atomicTime) read() fasttime { return fasttime(atomic.LoadInt64(&t.v)) } +func (t *atomicTime) write(v fasttime) { atomic.StoreInt64(&t.v, int64(v)) } diff --git a/third_party/regexp2/fastclock_wasm_test.go b/third_party/regexp2/fastclock_wasm_test.go new file mode 100644 index 000000000..3a3a92049 --- /dev/null +++ b/third_party/regexp2/fastclock_wasm_test.go @@ -0,0 +1,20 @@ +//go:build wasm +// +build wasm + +package regexp2 + +import ( + "testing" + "time" +) + +func TestDeadlineWithoutAnotherGoroutine(t *testing.T) { + deadline := makeDeadline(5 * time.Millisecond) + // The matcher must observe expiry even when nothing yields to the scheduler. + end := time.Now().Add(100 * time.Millisecond) + for !deadline.reached() { + if time.Now().After(end) { + t.Fatal("the deadline did not expire on the matching goroutine") + } + } +} diff --git a/third_party/regexp2/go.mod b/third_party/regexp2/go.mod new file mode 100644 index 000000000..9f7f391eb --- /dev/null +++ b/third_party/regexp2/go.mod @@ -0,0 +1,3 @@ +module github.com/dlclark/regexp2 + +go 1.13 diff --git a/third_party/regexp2/match.go b/third_party/regexp2/match.go new file mode 100644 index 000000000..759cf8ccf --- /dev/null +++ b/third_party/regexp2/match.go @@ -0,0 +1,349 @@ +package regexp2 + +import ( + "bytes" + "fmt" +) + +// Match is a single regex result match that contains groups and repeated captures +// +// -Groups +// -Capture +type Match struct { + Group //embeded group 0 + + regex *Regexp + otherGroups []Group + + // input to the match + textpos int + textstart int + + capcount int + caps []int + sparseCaps map[int]int + + // output from the match + matches [][]int + matchcount []int + + // whether we've done any balancing with this match. If we + // have done balancing, we'll need to do extra work in Tidy(). + balancing bool +} + +// Group is an explicit or implit (group 0) matched group within the pattern +type Group struct { + Capture // the last capture of this group is embeded for ease of use + + Name string // group name + Captures []Capture // captures of this group +} + +// Capture is a single capture of text within the larger original string +type Capture struct { + // the original string + text []rune + // Index is the position in the underlying rune slice where the first character of + // captured substring was found. Even if you pass in a string this will be in Runes. + Index int + // Length is the number of runes in the captured substring. + Length int +} + +// String returns the captured text as a String +func (c *Capture) String() string { + return string(c.text[c.Index : c.Index+c.Length]) +} + +// Runes returns the captured text as a rune slice +func (c *Capture) Runes() []rune { + return c.text[c.Index : c.Index+c.Length] +} + +func newMatch(regex *Regexp, capcount int, text []rune, startpos int) *Match { + m := Match{ + regex: regex, + matchcount: make([]int, capcount), + matches: make([][]int, capcount), + textstart: startpos, + balancing: false, + } + m.Name = "0" + m.text = text + m.matches[0] = make([]int, 2) + return &m +} + +func newMatchSparse(regex *Regexp, caps map[int]int, capcount int, text []rune, startpos int) *Match { + m := newMatch(regex, capcount, text, startpos) + m.sparseCaps = caps + return m +} + +func (m *Match) reset(text []rune, textstart int) { + m.text = text + m.textstart = textstart + for i := 0; i < len(m.matchcount); i++ { + m.matchcount[i] = 0 + } + m.balancing = false +} + +func (m *Match) tidy(textpos int) { + + interval := m.matches[0] + m.Index = interval[0] + m.Length = interval[1] + m.textpos = textpos + m.capcount = m.matchcount[0] + //copy our root capture to the list + m.Group.Captures = []Capture{m.Group.Capture} + + if m.balancing { + // The idea here is that we want to compact all of our unbalanced captures. To do that we + // use j basically as a count of how many unbalanced captures we have at any given time + // (really j is an index, but j/2 is the count). First we skip past all of the real captures + // until we find a balance captures. Then we check each subsequent entry. If it's a balance + // capture (it's negative), we decrement j. If it's a real capture, we increment j and copy + // it down to the last free position. + for cap := 0; cap < len(m.matchcount); cap++ { + limit := m.matchcount[cap] * 2 + matcharray := m.matches[cap] + + var i, j int + + for i = 0; i < limit; i++ { + if matcharray[i] < 0 { + break + } + } + + for j = i; i < limit; i++ { + if matcharray[i] < 0 { + // skip negative values + j-- + } else { + // but if we find something positive (an actual capture), copy it back to the last + // unbalanced position. + if i != j { + matcharray[j] = matcharray[i] + } + j++ + } + } + + m.matchcount[cap] = j / 2 + } + + m.balancing = false + } +} + +// isMatched tells if a group was matched by capnum +func (m *Match) isMatched(cap int) bool { + return cap < len(m.matchcount) && m.matchcount[cap] > 0 && m.matches[cap][m.matchcount[cap]*2-1] != (-3+1) +} + +// matchIndex returns the index of the last specified matched group by capnum +func (m *Match) matchIndex(cap int) int { + i := m.matches[cap][m.matchcount[cap]*2-2] + if i >= 0 { + return i + } + + return m.matches[cap][-3-i] +} + +// matchLength returns the length of the last specified matched group by capnum +func (m *Match) matchLength(cap int) int { + i := m.matches[cap][m.matchcount[cap]*2-1] + if i >= 0 { + return i + } + + return m.matches[cap][-3-i] +} + +// Nonpublic builder: add a capture to the group specified by "c" +func (m *Match) addMatch(c, start, l int) { + + if m.matches[c] == nil { + m.matches[c] = make([]int, 2) + } + + capcount := m.matchcount[c] + + if capcount*2+2 > len(m.matches[c]) { + oldmatches := m.matches[c] + newmatches := make([]int, capcount*8) + copy(newmatches, oldmatches[:capcount*2]) + m.matches[c] = newmatches + } + + m.matches[c][capcount*2] = start + m.matches[c][capcount*2+1] = l + m.matchcount[c] = capcount + 1 + //log.Printf("addMatch: c=%v, i=%v, l=%v ... matches: %v", c, start, l, m.matches) +} + +// Nonpublic builder: Add a capture to balance the specified group. This is used by the +// +// balanced match construct. (?...) +// +// If there were no such thing as backtracking, this would be as simple as calling RemoveMatch(c). +// However, since we have backtracking, we need to keep track of everything. +func (m *Match) balanceMatch(c int) { + m.balancing = true + + // we'll look at the last capture first + capcount := m.matchcount[c] + target := capcount*2 - 2 + + // first see if it is negative, and therefore is a reference to the next available + // capture group for balancing. If it is, we'll reset target to point to that capture. + if m.matches[c][target] < 0 { + target = -3 - m.matches[c][target] + } + + // move back to the previous capture + target -= 2 + + // if the previous capture is a reference, just copy that reference to the end. Otherwise, point to it. + if target >= 0 && m.matches[c][target] < 0 { + m.addMatch(c, m.matches[c][target], m.matches[c][target+1]) + } else { + m.addMatch(c, -3-target, -4-target /* == -3 - (target + 1) */) + } +} + +// Nonpublic builder: removes a group match by capnum +func (m *Match) removeMatch(c int) { + m.matchcount[c]-- +} + +// GroupCount returns the number of groups this match has matched +func (m *Match) GroupCount() int { + return len(m.matchcount) +} + +// GroupByName returns a group based on the name of the group, or nil if the group name does not exist +func (m *Match) GroupByName(name string) *Group { + num := m.regex.GroupNumberFromName(name) + if num < 0 { + return nil + } + return m.GroupByNumber(num) +} + +// GroupByNumber returns a group based on the number of the group, or nil if the group number does not exist +func (m *Match) GroupByNumber(num int) *Group { + // check our sparse map + if m.sparseCaps != nil { + if newNum, ok := m.sparseCaps[num]; ok { + num = newNum + } + } + if num >= len(m.matchcount) || num < 0 { + return nil + } + + if num == 0 { + return &m.Group + } + + m.populateOtherGroups() + + return &m.otherGroups[num-1] +} + +// Groups returns all the capture groups, starting with group 0 (the full match) +func (m *Match) Groups() []Group { + m.populateOtherGroups() + g := make([]Group, len(m.otherGroups)+1) + g[0] = m.Group + copy(g[1:], m.otherGroups) + return g +} + +func (m *Match) populateOtherGroups() { + // Construct all the Group objects first time called + if m.otherGroups == nil { + m.otherGroups = make([]Group, len(m.matchcount)-1) + for i := 0; i < len(m.otherGroups); i++ { + m.otherGroups[i] = newGroup(m.regex.GroupNameFromNumber(i+1), m.text, m.matches[i+1], m.matchcount[i+1]) + } + } +} + +func (m *Match) groupValueAppendToBuf(groupnum int, buf *bytes.Buffer) { + c := m.matchcount[groupnum] + if c == 0 { + return + } + + matches := m.matches[groupnum] + + index := matches[(c-1)*2] + last := index + matches[(c*2)-1] + + for ; index < last; index++ { + buf.WriteRune(m.text[index]) + } +} + +func newGroup(name string, text []rune, caps []int, capcount int) Group { + g := Group{} + g.text = text + if capcount > 0 { + g.Index = caps[(capcount-1)*2] + g.Length = caps[(capcount*2)-1] + } + g.Name = name + g.Captures = make([]Capture, capcount) + for i := 0; i < capcount; i++ { + g.Captures[i] = Capture{ + text: text, + Index: caps[i*2], + Length: caps[i*2+1], + } + } + //log.Printf("newGroup! capcount %v, %+v", capcount, g) + + return g +} + +func (m *Match) dump() string { + buf := &bytes.Buffer{} + buf.WriteRune('\n') + if len(m.sparseCaps) > 0 { + for k, v := range m.sparseCaps { + fmt.Fprintf(buf, "Slot %v -> %v\n", k, v) + } + } + + for i, g := range m.Groups() { + fmt.Fprintf(buf, "Group %v (%v), %v caps:\n", i, g.Name, len(g.Captures)) + + for _, c := range g.Captures { + fmt.Fprintf(buf, " (%v, %v) %v\n", c.Index, c.Length, c.String()) + } + } + /* + for i := 0; i < len(m.matchcount); i++ { + fmt.Fprintf(buf, "\nGroup %v (%v):\n", i, m.regex.GroupNameFromNumber(i)) + + for j := 0; j < m.matchcount[i]; j++ { + text := "" + + if m.matches[i][j*2] >= 0 { + start := m.matches[i][j*2] + text = m.text[start : start+m.matches[i][j*2+1]] + } + + fmt.Fprintf(buf, " (%v, %v) %v\n", m.matches[i][j*2], m.matches[i][j*2+1], text) + } + } + */ + return buf.String() +} diff --git a/third_party/regexp2/regexp.go b/third_party/regexp2/regexp.go new file mode 100644 index 000000000..a7ddbaf35 --- /dev/null +++ b/third_party/regexp2/regexp.go @@ -0,0 +1,395 @@ +/* +Package regexp2 is a regexp package that has an interface similar to Go's framework regexp engine but uses a +more feature full regex engine behind the scenes. + +It doesn't have constant time guarantees, but it allows backtracking and is compatible with Perl5 and .NET. +You'll likely be better off with the RE2 engine from the regexp package and should only use this if you +need to write very complex patterns or require compatibility with .NET. +*/ +package regexp2 + +import ( + "errors" + "math" + "strconv" + "sync" + "time" + + "github.com/dlclark/regexp2/syntax" +) + +var ( + // DefaultMatchTimeout used when running regexp matches -- "forever" + DefaultMatchTimeout = time.Duration(math.MaxInt64) + // DefaultUnmarshalOptions used when unmarshaling a regex from text + DefaultUnmarshalOptions = None +) + +// Regexp is the representation of a compiled regular expression. +// A Regexp is safe for concurrent use by multiple goroutines. +type Regexp struct { + // A match will time out if it takes (approximately) more than + // MatchTimeout. This is a safety check in case the match + // encounters catastrophic backtracking. The default value + // (DefaultMatchTimeout) causes all time out checking to be + // suppressed. + MatchTimeout time.Duration + + // read-only after Compile + pattern string // as passed to Compile + options RegexOptions // options + + caps map[int]int // capnum->index + capnames map[string]int //capture group name -> index + capslist []string //sorted list of capture group names + capsize int // size of the capture array + + code *syntax.Code // compiled program + + // cache of machines for running regexp + muRun *sync.Mutex + runner []*runner +} + +// Compile parses a regular expression and returns, if successful, +// a Regexp object that can be used to match against text. +func Compile(expr string, opt RegexOptions) (*Regexp, error) { + // parse it + tree, err := syntax.Parse(expr, syntax.RegexOptions(opt)) + if err != nil { + return nil, err + } + + // translate it to code + code, err := syntax.Write(tree) + if err != nil { + return nil, err + } + + // return it + return &Regexp{ + pattern: expr, + options: opt, + caps: code.Caps, + capnames: tree.Capnames, + capslist: tree.Caplist, + capsize: code.Capsize, + code: code, + MatchTimeout: DefaultMatchTimeout, + muRun: &sync.Mutex{}, + }, nil +} + +// MustCompile is like Compile but panics if the expression cannot be parsed. +// It simplifies safe initialization of global variables holding compiled regular +// expressions. +func MustCompile(str string, opt RegexOptions) *Regexp { + regexp, error := Compile(str, opt) + if error != nil { + panic(`regexp2: Compile(` + quote(str) + `): ` + error.Error()) + } + return regexp +} + +// Escape adds backslashes to any special characters in the input string +func Escape(input string) string { + return syntax.Escape(input) +} + +// Unescape removes any backslashes from previously-escaped special characters in the input string +func Unescape(input string) (string, error) { + return syntax.Unescape(input) +} + +// SetTimeoutPeriod is a debug function that sets the frequency of the timeout goroutine's sleep cycle. +// Defaults to 100ms. The only benefit of setting this lower is that the 1 background goroutine that manages +// timeouts may exit slightly sooner after all the timeouts have expired. See Github issue #63 +func SetTimeoutCheckPeriod(d time.Duration) { + clockPeriod = d +} + +// StopTimeoutClock should only be used in unit tests to prevent the timeout clock goroutine +// from appearing like a leaking goroutine +func StopTimeoutClock() { + stopClock() +} + +// String returns the source text used to compile the regular expression. +func (re *Regexp) String() string { + return re.pattern +} + +func quote(s string) string { + if strconv.CanBackquote(s) { + return "`" + s + "`" + } + return strconv.Quote(s) +} + +// RegexOptions impact the runtime and parsing behavior +// for each specific regex. They are setable in code as well +// as in the regex pattern itself. +type RegexOptions int32 + +const ( + None RegexOptions = 0x0 + IgnoreCase = 0x0001 // "i" + Multiline = 0x0002 // "m" + ExplicitCapture = 0x0004 // "n" + Compiled = 0x0008 // "c" + Singleline = 0x0010 // "s" + IgnorePatternWhitespace = 0x0020 // "x" + RightToLeft = 0x0040 // "r" + Debug = 0x0080 // "d" + ECMAScript = 0x0100 // "e" + RE2 = 0x0200 // RE2 (regexp package) compatibility mode + Unicode = 0x0400 // "u" +) + +func (re *Regexp) RightToLeft() bool { + return re.options&RightToLeft != 0 +} + +func (re *Regexp) Debug() bool { + return re.options&Debug != 0 +} + +// Replace searches the input string and replaces each match found with the replacement text. +// Count will limit the number of matches attempted and startAt will allow +// us to skip past possible matches at the start of the input (left or right depending on RightToLeft option). +// Set startAt and count to -1 to go through the whole string +func (re *Regexp) Replace(input, replacement string, startAt, count int) (string, error) { + data, err := syntax.NewReplacerData(replacement, re.caps, re.capsize, re.capnames, syntax.RegexOptions(re.options)) + if err != nil { + return "", err + } + //TODO: cache ReplacerData + + return replace(re, data, nil, input, startAt, count) +} + +// ReplaceFunc searches the input string and replaces each match found using the string from the evaluator +// Count will limit the number of matches attempted and startAt will allow +// us to skip past possible matches at the start of the input (left or right depending on RightToLeft option). +// Set startAt and count to -1 to go through the whole string. +func (re *Regexp) ReplaceFunc(input string, evaluator MatchEvaluator, startAt, count int) (string, error) { + return replace(re, nil, evaluator, input, startAt, count) +} + +// FindStringMatch searches the input string for a Regexp match +func (re *Regexp) FindStringMatch(s string) (*Match, error) { + // convert string to runes + return re.run(false, -1, getRunes(s)) +} + +// FindRunesMatch searches the input rune slice for a Regexp match +func (re *Regexp) FindRunesMatch(r []rune) (*Match, error) { + return re.run(false, -1, r) +} + +// FindStringMatchStartingAt searches the input string for a Regexp match starting at the startAt index +func (re *Regexp) FindStringMatchStartingAt(s string, startAt int) (*Match, error) { + if startAt > len(s) { + return nil, errors.New("startAt must be less than the length of the input string") + } + r, startAt := re.getRunesAndStart(s, startAt) + if startAt == -1 { + // we didn't find our start index in the string -- that's a problem + return nil, errors.New("startAt must align to the start of a valid rune in the input string") + } + + return re.run(false, startAt, r) +} + +// FindRunesMatchStartingAt searches the input rune slice for a Regexp match starting at the startAt index +func (re *Regexp) FindRunesMatchStartingAt(r []rune, startAt int) (*Match, error) { + return re.run(false, startAt, r) +} + +// FindNextMatch returns the next match in the same input string as the match parameter. +// Will return nil if there is no next match or if given a nil match. +func (re *Regexp) FindNextMatch(m *Match) (*Match, error) { + if m == nil { + return nil, nil + } + + // If previous match was empty, advance by one before matching to prevent + // infinite loop + startAt := m.textpos + if m.Length == 0 { + if m.textpos == len(m.text) { + return nil, nil + } + + if re.RightToLeft() { + startAt-- + } else { + startAt++ + } + } + return re.run(false, startAt, m.text) +} + +// MatchString return true if the string matches the regex +// error will be set if a timeout occurs +func (re *Regexp) MatchString(s string) (bool, error) { + m, err := re.run(true, -1, getRunes(s)) + if err != nil { + return false, err + } + return m != nil, nil +} + +func (re *Regexp) getRunesAndStart(s string, startAt int) ([]rune, int) { + if startAt < 0 { + if re.RightToLeft() { + r := getRunes(s) + return r, len(r) + } + return getRunes(s), 0 + } + ret := make([]rune, len(s)) + i := 0 + runeIdx := -1 + for strIdx, r := range s { + if strIdx == startAt { + runeIdx = i + } + ret[i] = r + i++ + } + if startAt == len(s) { + runeIdx = i + } + return ret[:i], runeIdx +} + +func getRunes(s string) []rune { + return []rune(s) +} + +// MatchRunes return true if the runes matches the regex +// error will be set if a timeout occurs +func (re *Regexp) MatchRunes(r []rune) (bool, error) { + m, err := re.run(true, -1, r) + if err != nil { + return false, err + } + return m != nil, nil +} + +// GetGroupNames Returns the set of strings used to name capturing groups in the expression. +func (re *Regexp) GetGroupNames() []string { + var result []string + + if re.capslist == nil { + result = make([]string, re.capsize) + + for i := 0; i < len(result); i++ { + result[i] = strconv.Itoa(i) + } + } else { + result = make([]string, len(re.capslist)) + copy(result, re.capslist) + } + + return result +} + +// GetGroupNumbers returns the integer group numbers corresponding to a group name. +func (re *Regexp) GetGroupNumbers() []int { + var result []int + + if re.caps == nil { + result = make([]int, re.capsize) + + for i := 0; i < len(result); i++ { + result[i] = i + } + } else { + result = make([]int, len(re.caps)) + + for k, v := range re.caps { + result[v] = k + } + } + + return result +} + +// GroupNameFromNumber retrieves a group name that corresponds to a group number. +// It will return "" for and unknown group number. Unnamed groups automatically +// receive a name that is the decimal string equivalent of its number. +func (re *Regexp) GroupNameFromNumber(i int) string { + if re.capslist == nil { + if i >= 0 && i < re.capsize { + return strconv.Itoa(i) + } + + return "" + } + + if re.caps != nil { + var ok bool + if i, ok = re.caps[i]; !ok { + return "" + } + } + + if i >= 0 && i < len(re.capslist) { + return re.capslist[i] + } + + return "" +} + +// GroupNumberFromName returns a group number that corresponds to a group name. +// Returns -1 if the name is not a recognized group name. Numbered groups +// automatically get a group name that is the decimal string equivalent of its number. +func (re *Regexp) GroupNumberFromName(name string) int { + // look up name if we have a hashtable of names + if re.capnames != nil { + if k, ok := re.capnames[name]; ok { + return k + } + + return -1 + } + + // convert to an int if it looks like a number + result := 0 + for i := 0; i < len(name); i++ { + ch := name[i] + + if ch > '9' || ch < '0' { + return -1 + } + + result *= 10 + result += int(ch - '0') + } + + // return int if it's in range + if result >= 0 && result < re.capsize { + return result + } + + return -1 +} + +// MarshalText implements [encoding.TextMarshaler]. The output +// matches that of calling the [Regexp.String] method. +func (re *Regexp) MarshalText() ([]byte, error) { + return []byte(re.String()), nil +} + +// UnmarshalText implements [encoding.TextUnmarshaler] by calling +// [Compile] on the encoded value. +func (re *Regexp) UnmarshalText(text []byte) error { + newRE, err := Compile(string(text), DefaultUnmarshalOptions) + if err != nil { + return err + } + *re = *newRE + return nil +} diff --git a/third_party/regexp2/replace.go b/third_party/regexp2/replace.go new file mode 100644 index 000000000..0376bd9d3 --- /dev/null +++ b/third_party/regexp2/replace.go @@ -0,0 +1,177 @@ +package regexp2 + +import ( + "bytes" + "errors" + + "github.com/dlclark/regexp2/syntax" +) + +const ( + replaceSpecials = 4 + replaceLeftPortion = -1 + replaceRightPortion = -2 + replaceLastGroup = -3 + replaceWholeString = -4 +) + +// MatchEvaluator is a function that takes a match and returns a replacement string to be used +type MatchEvaluator func(Match) string + +// Three very similar algorithms appear below: replace (pattern), +// replace (evaluator), and split. + +// Replace Replaces all occurrences of the regex in the string with the +// replacement pattern. +// +// Note that the special case of no matches is handled on its own: +// with no matches, the input string is returned unchanged. +// The right-to-left case is split out because StringBuilder +// doesn't handle right-to-left string building directly very well. +func replace(regex *Regexp, data *syntax.ReplacerData, evaluator MatchEvaluator, input string, startAt, count int) (string, error) { + if count < -1 { + return "", errors.New("Count too small") + } + if count == 0 { + return "", nil + } + + m, err := regex.FindStringMatchStartingAt(input, startAt) + + if err != nil { + return "", err + } + if m == nil { + return input, nil + } + + buf := &bytes.Buffer{} + text := m.text + + if !regex.RightToLeft() { + prevat := 0 + for m != nil { + if m.Index != prevat { + buf.WriteString(string(text[prevat:m.Index])) + } + prevat = m.Index + m.Length + if evaluator == nil { + replacementImpl(data, buf, m) + } else { + buf.WriteString(evaluator(*m)) + } + + count-- + if count == 0 { + break + } + m, err = regex.FindNextMatch(m) + if err != nil { + return "", nil + } + } + + if prevat < len(text) { + buf.WriteString(string(text[prevat:])) + } + } else { + prevat := len(text) + var al []string + + for m != nil { + if m.Index+m.Length != prevat { + al = append(al, string(text[m.Index+m.Length:prevat])) + } + prevat = m.Index + if evaluator == nil { + replacementImplRTL(data, &al, m) + } else { + al = append(al, evaluator(*m)) + } + + count-- + if count == 0 { + break + } + m, err = regex.FindNextMatch(m) + if err != nil { + return "", nil + } + } + + if prevat > 0 { + buf.WriteString(string(text[:prevat])) + } + + for i := len(al) - 1; i >= 0; i-- { + buf.WriteString(al[i]) + } + } + + return buf.String(), nil +} + +// Given a Match, emits into the StringBuilder the evaluated +// substitution pattern. +func replacementImpl(data *syntax.ReplacerData, buf *bytes.Buffer, m *Match) { + for _, r := range data.Rules { + + if r >= 0 { // string lookup + buf.WriteString(data.Strings[r]) + } else if r < -replaceSpecials { // group lookup + m.groupValueAppendToBuf(-replaceSpecials-1-r, buf) + } else { + switch -replaceSpecials - 1 - r { // special insertion patterns + case replaceLeftPortion: + for i := 0; i < m.Index; i++ { + buf.WriteRune(m.text[i]) + } + case replaceRightPortion: + for i := m.Index + m.Length; i < len(m.text); i++ { + buf.WriteRune(m.text[i]) + } + case replaceLastGroup: + m.groupValueAppendToBuf(m.GroupCount()-1, buf) + case replaceWholeString: + for i := 0; i < len(m.text); i++ { + buf.WriteRune(m.text[i]) + } + } + } + } +} + +func replacementImplRTL(data *syntax.ReplacerData, al *[]string, m *Match) { + l := *al + buf := &bytes.Buffer{} + + for _, r := range data.Rules { + buf.Reset() + if r >= 0 { // string lookup + l = append(l, data.Strings[r]) + } else if r < -replaceSpecials { // group lookup + m.groupValueAppendToBuf(-replaceSpecials-1-r, buf) + l = append(l, buf.String()) + } else { + switch -replaceSpecials - 1 - r { // special insertion patterns + case replaceLeftPortion: + for i := 0; i < m.Index; i++ { + buf.WriteRune(m.text[i]) + } + case replaceRightPortion: + for i := m.Index + m.Length; i < len(m.text); i++ { + buf.WriteRune(m.text[i]) + } + case replaceLastGroup: + m.groupValueAppendToBuf(m.GroupCount()-1, buf) + case replaceWholeString: + for i := 0; i < len(m.text); i++ { + buf.WriteRune(m.text[i]) + } + } + l = append(l, buf.String()) + } + } + + *al = l +} diff --git a/third_party/regexp2/runner.go b/third_party/regexp2/runner.go new file mode 100644 index 000000000..4bb0dfa1a --- /dev/null +++ b/third_party/regexp2/runner.go @@ -0,0 +1,1614 @@ +package regexp2 + +import ( + "bytes" + "errors" + "fmt" + "math" + "strconv" + "strings" + "time" + "unicode" + + "github.com/dlclark/regexp2/syntax" +) + +type runner struct { + re *Regexp + code *syntax.Code + + runtextstart int // starting point for search + + runtext []rune // text to search + runtextpos int // current position in text + runtextend int + + // The backtracking stack. Opcodes use this to store data regarding + // what they have matched and where to backtrack to. Each "frame" on + // the stack takes the form of [CodePosition Data1 Data2...], where + // CodePosition is the position of the current opcode and + // the data values are all optional. The CodePosition can be negative, and + // these values (also called "back2") are used by the BranchMark family of opcodes + // to indicate whether they are backtracking after a successful or failed + // match. + // When we backtrack, we pop the CodePosition off the stack, set the current + // instruction pointer to that code position, and mark the opcode + // with a backtracking flag ("Back"). Each opcode then knows how to + // handle its own data. + runtrack []int + runtrackpos int + + // This stack is used to track text positions across different opcodes. + // For example, in /(a*b)+/, the parentheses result in a SetMark/CaptureMark + // pair. SetMark records the text position before we match a*b. Then + // CaptureMark uses that position to figure out where the capture starts. + // Opcodes which push onto this stack are always paired with other opcodes + // which will pop the value from it later. A successful match should mean + // that this stack is empty. + runstack []int + runstackpos int + + // The crawl stack is used to keep track of captures. Every time a group + // has a capture, we push its group number onto the runcrawl stack. In + // the case of a balanced match, we push BOTH groups onto the stack. + runcrawl []int + runcrawlpos int + + runtrackcount int // count of states that may do backtracking + + runmatch *Match // result object + + ignoreTimeout bool + timeout time.Duration // timeout in milliseconds (needed for actual) + deadline fasttime + + operator syntax.InstOp + codepos int + rightToLeft bool + caseInsensitive bool +} + +// run searches for matches and can continue from the previous match +// +// quick is usually false, but can be true to not return matches, just put it in caches +// textstart is -1 to start at the "beginning" (depending on Right-To-Left), otherwise an index in input +// input is the string to search for our regex pattern +func (re *Regexp) run(quick bool, textstart int, input []rune) (*Match, error) { + + // get a cached runner + runner := re.getRunner() + defer re.putRunner(runner) + + if textstart < 0 { + if re.RightToLeft() { + textstart = len(input) + } else { + textstart = 0 + } + } + + return runner.scan(input, textstart, quick, re.MatchTimeout) +} + +// Scans the string to find the first match. Uses the Match object +// both to feed text in and as a place to store matches that come out. +// +// All the action is in the Go() method. Our +// responsibility is to load up the class members before +// calling Go. +// +// The optimizer can compute a set of candidate starting characters, +// and we could use a separate method Skip() that will quickly scan past +// any characters that we know can't match. +func (r *runner) scan(rt []rune, textstart int, quick bool, timeout time.Duration) (*Match, error) { + r.timeout = timeout + r.ignoreTimeout = (time.Duration(math.MaxInt64) == timeout) + r.runtextstart = textstart + r.runtext = rt + r.runtextend = len(rt) + + stoppos := r.runtextend + bump := 1 + + if r.re.RightToLeft() { + bump = -1 + stoppos = 0 + } + + r.runtextpos = textstart + initted := false + + r.startTimeoutWatch() + for { + if r.re.Debug() { + //fmt.Printf("\nSearch content: %v\n", string(r.runtext)) + fmt.Printf("\nSearch range: from 0 to %v\n", r.runtextend) + fmt.Printf("Firstchar search starting at %v stopping at %v\n", r.runtextpos, stoppos) + } + + if r.findFirstChar() { + if err := r.checkTimeout(); err != nil { + return nil, err + } + + if !initted { + r.initMatch() + initted = true + } + + if r.re.Debug() { + fmt.Printf("Executing engine starting at %v\n\n", r.runtextpos) + } + + if err := r.execute(); err != nil { + return nil, err + } + + if r.runmatch.matchcount[0] > 0 { + // We'll return a match even if it touches a previous empty match + return r.tidyMatch(quick), nil + } + + // reset state for another go + r.runtrackpos = len(r.runtrack) + r.runstackpos = len(r.runstack) + r.runcrawlpos = len(r.runcrawl) + } + + // failure! + + if r.runtextpos == stoppos { + r.tidyMatch(true) + return nil, nil + } + + // Recognize leading []* and various anchors, and bump on failure accordingly + + // r.bump by one and start again + + r.runtextpos += bump + } + // We never get here +} + +func (r *runner) execute() error { + + r.goTo(0) + + for { + + if r.re.Debug() { + r.dumpState() + } + + if err := r.checkTimeout(); err != nil { + return err + } + + switch r.operator { + case syntax.Stop: + return nil + + case syntax.Nothing: + break + + case syntax.Goto: + r.goTo(r.operand(0)) + continue + + case syntax.Testref: + if !r.runmatch.isMatched(r.operand(0)) { + break + } + r.advance(1) + continue + + case syntax.Lazybranch: + r.trackPush1(r.textPos()) + r.advance(1) + continue + + case syntax.Lazybranch | syntax.Back: + r.trackPop() + r.textto(r.trackPeek()) + r.goTo(r.operand(0)) + continue + + case syntax.Setmark: + r.stackPush(r.textPos()) + r.trackPush() + r.advance(0) + continue + + case syntax.Nullmark: + r.stackPush(-1) + r.trackPush() + r.advance(0) + continue + + case syntax.Setmark | syntax.Back, syntax.Nullmark | syntax.Back: + r.stackPop() + break + + case syntax.Getmark: + r.stackPop() + r.trackPush1(r.stackPeek()) + r.textto(r.stackPeek()) + r.advance(0) + continue + + case syntax.Getmark | syntax.Back: + r.trackPop() + r.stackPush(r.trackPeek()) + break + + case syntax.Capturemark: + if r.operand(1) != -1 && !r.runmatch.isMatched(r.operand(1)) { + break + } + r.stackPop() + if r.operand(1) != -1 { + r.transferCapture(r.operand(0), r.operand(1), r.stackPeek(), r.textPos()) + } else { + r.capture(r.operand(0), r.stackPeek(), r.textPos()) + } + r.trackPush1(r.stackPeek()) + + r.advance(2) + + continue + + case syntax.Capturemark | syntax.Back: + r.trackPop() + r.stackPush(r.trackPeek()) + r.uncapture() + if r.operand(0) != -1 && r.operand(1) != -1 { + r.uncapture() + } + + break + + case syntax.Branchmark: + r.stackPop() + + matched := r.textPos() - r.stackPeek() + + if matched != 0 { // Nonempty match -> loop now + r.trackPush2(r.stackPeek(), r.textPos()) // Save old mark, textpos + r.stackPush(r.textPos()) // Make new mark + r.goTo(r.operand(0)) // Loop + } else { // Empty match -> straight now + r.trackPushNeg1(r.stackPeek()) // Save old mark + r.advance(1) // Straight + } + continue + + case syntax.Branchmark | syntax.Back: + r.trackPopN(2) + r.stackPop() + r.textto(r.trackPeekN(1)) // Recall position + r.trackPushNeg1(r.trackPeek()) // Save old mark + r.advance(1) // Straight + continue + + case syntax.Branchmark | syntax.Back2: + r.trackPop() + r.stackPush(r.trackPeek()) // Recall old mark + break // Backtrack + + case syntax.Lazybranchmark: + { + // We hit this the first time through a lazy loop and after each + // successful match of the inner expression. It simply continues + // on and doesn't loop. + r.stackPop() + + oldMarkPos := r.stackPeek() + + if r.textPos() != oldMarkPos { // Nonempty match -> try to loop again by going to 'back' state + if oldMarkPos != -1 { + r.trackPush2(oldMarkPos, r.textPos()) // Save old mark, textpos + } else { + r.trackPush2(r.textPos(), r.textPos()) + } + } else { + // The inner expression found an empty match, so we'll go directly to 'back2' if we + // backtrack. Don't touch the grouping stack here; instead, record the old mark and + // a flag indicating that backtracking doesn't need to pop a grouping stack frame. + r.trackPushNeg2(oldMarkPos, 0) + } + r.advance(1) + continue + } + + case syntax.Lazybranchmark | syntax.Back: + + // After the first time, Lazybranchmark | syntax.Back occurs + // with each iteration of the loop, and therefore with every attempted + // match of the inner expression. We'll try to match the inner expression, + // then go back to Lazybranchmark if successful. If the inner expression + // fails, we go to Lazybranchmark | syntax.Back2 + + r.trackPopN(2) + pos := r.trackPeekN(1) + r.trackPushNeg2(r.trackPeek(), 1) // Save old mark, note that we pushed a new mark + r.stackPush(pos) // Make new mark + r.textto(pos) // Recall position + r.goTo(r.operand(0)) // Loop + continue + + case syntax.Lazybranchmark | syntax.Back2: + // The lazy loop has failed. We'll do a true backtrack and + // start over before the lazy loop. + r.trackPopN(2) + oldMark := r.trackPeek() + needsPop := r.trackPeekN(1) + if needsPop != 0 { + r.stackPop() + } + r.stackPush(oldMark) // Recall old mark + break + + case syntax.Setcount: + r.stackPush2(r.textPos(), r.operand(0)) + r.trackPush() + r.advance(1) + continue + + case syntax.Nullcount: + r.stackPush2(-1, r.operand(0)) + r.trackPush() + r.advance(1) + continue + + case syntax.Setcount | syntax.Back: + r.stackPopN(2) + break + + case syntax.Nullcount | syntax.Back: + r.stackPopN(2) + break + + case syntax.Branchcount: + // r.stackPush: + // 0: Mark + // 1: Count + + r.stackPopN(2) + mark := r.stackPeek() + count := r.stackPeekN(1) + matched := r.textPos() - mark + + if count >= r.operand(1) || (matched == 0 && count >= 0) { // Max loops or empty match -> straight now + r.trackPushNeg2(mark, count) // Save old mark, count + r.advance(2) // Straight + } else { // Nonempty match -> count+loop now + r.trackPush1(mark) // remember mark + r.stackPush2(r.textPos(), count+1) // Make new mark, incr count + r.goTo(r.operand(0)) // Loop + } + continue + + case syntax.Branchcount | syntax.Back: + // r.trackPush: + // 0: Previous mark + // r.stackPush: + // 0: Mark (= current pos, discarded) + // 1: Count + r.trackPop() + r.stackPopN(2) + if r.stackPeekN(1) > 0 { // Positive -> can go straight + r.textto(r.stackPeek()) // Zap to mark + r.trackPushNeg2(r.trackPeek(), r.stackPeekN(1)-1) // Save old mark, old count + r.advance(2) // Straight + continue + } + r.stackPush2(r.trackPeek(), r.stackPeekN(1)-1) // recall old mark, old count + break + + case syntax.Branchcount | syntax.Back2: + // r.trackPush: + // 0: Previous mark + // 1: Previous count + r.trackPopN(2) + r.stackPush2(r.trackPeek(), r.trackPeekN(1)) // Recall old mark, old count + break // Backtrack + + case syntax.Lazybranchcount: + // r.stackPush: + // 0: Mark + // 1: Count + + r.stackPopN(2) + mark := r.stackPeek() + count := r.stackPeekN(1) + + if count < 0 { // Negative count -> loop now + r.trackPushNeg1(mark) // Save old mark + r.stackPush2(r.textPos(), count+1) // Make new mark, incr count + r.goTo(r.operand(0)) // Loop + } else { // Nonneg count -> straight now + r.trackPush3(mark, count, r.textPos()) // Save mark, count, position + r.advance(2) // Straight + } + continue + + case syntax.Lazybranchcount | syntax.Back: + // r.trackPush: + // 0: Mark + // 1: Count + // 2: r.textPos + + r.trackPopN(3) + mark := r.trackPeek() + textpos := r.trackPeekN(2) + + if r.trackPeekN(1) < r.operand(1) && textpos != mark { // Under limit and not empty match -> loop + r.textto(textpos) // Recall position + r.stackPush2(textpos, r.trackPeekN(1)+1) // Make new mark, incr count + r.trackPushNeg1(mark) // Save old mark + r.goTo(r.operand(0)) // Loop + continue + } else { // Max loops or empty match -> backtrack + r.stackPush2(r.trackPeek(), r.trackPeekN(1)) // Recall old mark, count + break // backtrack + } + + case syntax.Lazybranchcount | syntax.Back2: + // r.trackPush: + // 0: Previous mark + // r.stackPush: + // 0: Mark (== current pos, discarded) + // 1: Count + r.trackPop() + r.stackPopN(2) + r.stackPush2(r.trackPeek(), r.stackPeekN(1)-1) // Recall old mark, count + break // Backtrack + + case syntax.Setjump: + r.stackPush2(r.trackpos(), r.crawlpos()) + r.trackPush() + r.advance(0) + continue + + case syntax.Setjump | syntax.Back: + r.stackPopN(2) + break + + case syntax.Backjump: + // r.stackPush: + // 0: Saved trackpos + // 1: r.crawlpos + r.stackPopN(2) + r.trackto(r.stackPeek()) + + for r.crawlpos() != r.stackPeekN(1) { + r.uncapture() + } + + break + + case syntax.Forejump: + // r.stackPush: + // 0: Saved trackpos + // 1: r.crawlpos + r.stackPopN(2) + r.trackto(r.stackPeek()) + r.trackPush1(r.stackPeekN(1)) + r.advance(0) + continue + + case syntax.Forejump | syntax.Back: + // r.trackPush: + // 0: r.crawlpos + r.trackPop() + + for r.crawlpos() != r.trackPeek() { + r.uncapture() + } + + break + + case syntax.Bol: + if r.leftchars() > 0 && r.charAt(r.textPos()-1) != '\n' { + break + } + r.advance(0) + continue + + case syntax.Eol: + if r.rightchars() > 0 && r.charAt(r.textPos()) != '\n' { + break + } + r.advance(0) + continue + + case syntax.Boundary: + if !r.isBoundary(r.textPos(), 0, r.runtextend) { + break + } + r.advance(0) + continue + + case syntax.Nonboundary: + if r.isBoundary(r.textPos(), 0, r.runtextend) { + break + } + r.advance(0) + continue + + case syntax.ECMABoundary: + if !r.isECMABoundary(r.textPos(), 0, r.runtextend) { + break + } + r.advance(0) + continue + + case syntax.NonECMABoundary: + if r.isECMABoundary(r.textPos(), 0, r.runtextend) { + break + } + r.advance(0) + continue + + case syntax.Beginning: + if r.leftchars() > 0 { + break + } + r.advance(0) + continue + + case syntax.Start: + if r.textPos() != r.textstart() { + break + } + r.advance(0) + continue + + case syntax.EndZ: + rchars := r.rightchars() + if rchars > 1 { + break + } + // RE2 and EcmaScript define $ as "asserts position at the end of the string" + // PCRE/.NET adds "or before the line terminator right at the end of the string (if any)" + if (r.re.options & (RE2 | ECMAScript)) != 0 { + // RE2/Ecmascript mode + if rchars > 0 { + break + } + } else if rchars == 1 && r.charAt(r.textPos()) != '\n' { + // "regular" mode + break + } + + r.advance(0) + continue + + case syntax.End: + if r.rightchars() > 0 { + break + } + r.advance(0) + continue + + case syntax.One: + if r.forwardchars() < 1 || r.forwardcharnext() != rune(r.operand(0)) { + break + } + + r.advance(1) + continue + + case syntax.Notone: + if r.forwardchars() < 1 || r.forwardcharnext() == rune(r.operand(0)) { + break + } + + r.advance(1) + continue + + case syntax.Set: + + if r.forwardchars() < 1 || !r.code.Sets[r.operand(0)].CharIn(r.forwardcharnext()) { + break + } + + r.advance(1) + continue + + case syntax.Multi: + if !r.runematch(r.code.Strings[r.operand(0)]) { + break + } + + r.advance(1) + continue + + case syntax.Ref: + + capnum := r.operand(0) + + if r.runmatch.isMatched(capnum) { + if !r.refmatch(r.runmatch.matchIndex(capnum), r.runmatch.matchLength(capnum)) { + break + } + } else { + if (r.re.options & ECMAScript) == 0 { + break + } + } + + r.advance(1) + continue + + case syntax.Onerep: + + c := r.operand(1) + + if r.forwardchars() < c { + break + } + + ch := rune(r.operand(0)) + + for c > 0 { + if r.forwardcharnext() != ch { + goto BreakBackward + } + c-- + } + + r.advance(2) + continue + + case syntax.Notonerep: + + c := r.operand(1) + + if r.forwardchars() < c { + break + } + ch := rune(r.operand(0)) + + for c > 0 { + if r.forwardcharnext() == ch { + goto BreakBackward + } + c-- + } + + r.advance(2) + continue + + case syntax.Setrep: + + c := r.operand(1) + + if r.forwardchars() < c { + break + } + + set := r.code.Sets[r.operand(0)] + + for c > 0 { + if !set.CharIn(r.forwardcharnext()) { + goto BreakBackward + } + c-- + } + + r.advance(2) + continue + + case syntax.Oneloop: + + c := r.operand(1) + + if c > r.forwardchars() { + c = r.forwardchars() + } + + ch := rune(r.operand(0)) + i := c + + for ; i > 0; i-- { + if r.forwardcharnext() != ch { + r.backwardnext() + break + } + } + + if c > i { + r.trackPush2(c-i-1, r.textPos()-r.bump()) + } + + r.advance(2) + continue + + case syntax.Notoneloop: + + c := r.operand(1) + + if c > r.forwardchars() { + c = r.forwardchars() + } + + ch := rune(r.operand(0)) + i := c + + for ; i > 0; i-- { + if r.forwardcharnext() == ch { + r.backwardnext() + break + } + } + + if c > i { + r.trackPush2(c-i-1, r.textPos()-r.bump()) + } + + r.advance(2) + continue + + case syntax.Setloop: + + c := r.operand(1) + + if c > r.forwardchars() { + c = r.forwardchars() + } + + set := r.code.Sets[r.operand(0)] + i := c + + for ; i > 0; i-- { + if !set.CharIn(r.forwardcharnext()) { + r.backwardnext() + break + } + } + + if c > i { + r.trackPush2(c-i-1, r.textPos()-r.bump()) + } + + r.advance(2) + continue + + case syntax.Oneloop | syntax.Back, syntax.Notoneloop | syntax.Back: + + r.trackPopN(2) + i := r.trackPeek() + pos := r.trackPeekN(1) + + r.textto(pos) + + if i > 0 { + r.trackPush2(i-1, pos-r.bump()) + } + + r.advance(2) + continue + + case syntax.Setloop | syntax.Back: + + r.trackPopN(2) + i := r.trackPeek() + pos := r.trackPeekN(1) + + r.textto(pos) + + if i > 0 { + r.trackPush2(i-1, pos-r.bump()) + } + + r.advance(2) + continue + + case syntax.Onelazy, syntax.Notonelazy: + + c := r.operand(1) + + if c > r.forwardchars() { + c = r.forwardchars() + } + + if c > 0 { + r.trackPush2(c-1, r.textPos()) + } + + r.advance(2) + continue + + case syntax.Setlazy: + + c := r.operand(1) + + if c > r.forwardchars() { + c = r.forwardchars() + } + + if c > 0 { + r.trackPush2(c-1, r.textPos()) + } + + r.advance(2) + continue + + case syntax.Onelazy | syntax.Back: + + r.trackPopN(2) + pos := r.trackPeekN(1) + r.textto(pos) + + if r.forwardcharnext() != rune(r.operand(0)) { + break + } + + i := r.trackPeek() + + if i > 0 { + r.trackPush2(i-1, pos+r.bump()) + } + + r.advance(2) + continue + + case syntax.Notonelazy | syntax.Back: + + r.trackPopN(2) + pos := r.trackPeekN(1) + r.textto(pos) + + if r.forwardcharnext() == rune(r.operand(0)) { + break + } + + i := r.trackPeek() + + if i > 0 { + r.trackPush2(i-1, pos+r.bump()) + } + + r.advance(2) + continue + + case syntax.Setlazy | syntax.Back: + + r.trackPopN(2) + pos := r.trackPeekN(1) + r.textto(pos) + + if !r.code.Sets[r.operand(0)].CharIn(r.forwardcharnext()) { + break + } + + i := r.trackPeek() + + if i > 0 { + r.trackPush2(i-1, pos+r.bump()) + } + + r.advance(2) + continue + + default: + return errors.New("unknown state in regex runner") + } + + BreakBackward: + ; + + // "break Backward" comes here: + r.backtrack() + } +} + +// increase the size of stack and track storage +func (r *runner) ensureStorage() { + if r.runstackpos < r.runtrackcount*4 { + doubleIntSlice(&r.runstack, &r.runstackpos) + } + if r.runtrackpos < r.runtrackcount*4 { + doubleIntSlice(&r.runtrack, &r.runtrackpos) + } +} + +func doubleIntSlice(s *[]int, pos *int) { + oldLen := len(*s) + newS := make([]int, oldLen*2) + + copy(newS[oldLen:], *s) + *pos += oldLen + *s = newS +} + +// Save a number on the longjump unrolling stack +func (r *runner) crawl(i int) { + if r.runcrawlpos == 0 { + doubleIntSlice(&r.runcrawl, &r.runcrawlpos) + } + r.runcrawlpos-- + r.runcrawl[r.runcrawlpos] = i +} + +// Remove a number from the longjump unrolling stack +func (r *runner) popcrawl() int { + val := r.runcrawl[r.runcrawlpos] + r.runcrawlpos++ + return val +} + +// Get the height of the stack +func (r *runner) crawlpos() int { + return len(r.runcrawl) - r.runcrawlpos +} + +func (r *runner) advance(i int) { + r.codepos += (i + 1) + r.setOperator(r.code.Codes[r.codepos]) +} + +func (r *runner) goTo(newpos int) { + // when branching backward or in place, ensure storage + if newpos <= r.codepos { + r.ensureStorage() + } + + r.setOperator(r.code.Codes[newpos]) + r.codepos = newpos +} + +func (r *runner) textto(newpos int) { + r.runtextpos = newpos +} + +func (r *runner) trackto(newpos int) { + r.runtrackpos = len(r.runtrack) - newpos +} + +func (r *runner) textstart() int { + return r.runtextstart +} + +func (r *runner) textPos() int { + return r.runtextpos +} + +// push onto the backtracking stack +func (r *runner) trackpos() int { + return len(r.runtrack) - r.runtrackpos +} + +func (r *runner) trackPush() { + r.runtrackpos-- + r.runtrack[r.runtrackpos] = r.codepos +} + +func (r *runner) trackPush1(I1 int) { + r.runtrackpos-- + r.runtrack[r.runtrackpos] = I1 + r.runtrackpos-- + r.runtrack[r.runtrackpos] = r.codepos +} + +func (r *runner) trackPush2(I1, I2 int) { + r.runtrackpos-- + r.runtrack[r.runtrackpos] = I1 + r.runtrackpos-- + r.runtrack[r.runtrackpos] = I2 + r.runtrackpos-- + r.runtrack[r.runtrackpos] = r.codepos +} + +func (r *runner) trackPush3(I1, I2, I3 int) { + r.runtrackpos-- + r.runtrack[r.runtrackpos] = I1 + r.runtrackpos-- + r.runtrack[r.runtrackpos] = I2 + r.runtrackpos-- + r.runtrack[r.runtrackpos] = I3 + r.runtrackpos-- + r.runtrack[r.runtrackpos] = r.codepos +} + +func (r *runner) trackPushNeg1(I1 int) { + r.runtrackpos-- + r.runtrack[r.runtrackpos] = I1 + r.runtrackpos-- + r.runtrack[r.runtrackpos] = -r.codepos +} + +func (r *runner) trackPushNeg2(I1, I2 int) { + r.runtrackpos-- + r.runtrack[r.runtrackpos] = I1 + r.runtrackpos-- + r.runtrack[r.runtrackpos] = I2 + r.runtrackpos-- + r.runtrack[r.runtrackpos] = -r.codepos +} + +func (r *runner) backtrack() { + newpos := r.runtrack[r.runtrackpos] + r.runtrackpos++ + + if r.re.Debug() { + if newpos < 0 { + fmt.Printf(" Backtracking (back2) to code position %v\n", -newpos) + } else { + fmt.Printf(" Backtracking to code position %v\n", newpos) + } + } + + if newpos < 0 { + newpos = -newpos + r.setOperator(r.code.Codes[newpos] | syntax.Back2) + } else { + r.setOperator(r.code.Codes[newpos] | syntax.Back) + } + + // When branching backward, ensure storage + if newpos < r.codepos { + r.ensureStorage() + } + + r.codepos = newpos +} + +func (r *runner) setOperator(op int) { + r.caseInsensitive = (0 != (op & syntax.Ci)) + r.rightToLeft = (0 != (op & syntax.Rtl)) + r.operator = syntax.InstOp(op & ^(syntax.Rtl | syntax.Ci)) +} + +func (r *runner) trackPop() { + r.runtrackpos++ +} + +// pop framesize items from the backtracking stack +func (r *runner) trackPopN(framesize int) { + r.runtrackpos += framesize +} + +// Technically we are actually peeking at items already popped. So if you want to +// get and pop the top item from the stack, you do +// r.trackPop(); +// r.trackPeek(); +func (r *runner) trackPeek() int { + return r.runtrack[r.runtrackpos-1] +} + +// get the ith element down on the backtracking stack +func (r *runner) trackPeekN(i int) int { + return r.runtrack[r.runtrackpos-i-1] +} + +// Push onto the grouping stack +func (r *runner) stackPush(I1 int) { + r.runstackpos-- + r.runstack[r.runstackpos] = I1 +} + +func (r *runner) stackPush2(I1, I2 int) { + r.runstackpos-- + r.runstack[r.runstackpos] = I1 + r.runstackpos-- + r.runstack[r.runstackpos] = I2 +} + +func (r *runner) stackPop() { + r.runstackpos++ +} + +// pop framesize items from the grouping stack +func (r *runner) stackPopN(framesize int) { + r.runstackpos += framesize +} + +// Technically we are actually peeking at items already popped. So if you want to +// get and pop the top item from the stack, you do +// r.stackPop(); +// r.stackPeek(); +func (r *runner) stackPeek() int { + return r.runstack[r.runstackpos-1] +} + +// get the ith element down on the grouping stack +func (r *runner) stackPeekN(i int) int { + return r.runstack[r.runstackpos-i-1] +} + +func (r *runner) operand(i int) int { + return r.code.Codes[r.codepos+i+1] +} + +func (r *runner) leftchars() int { + return r.runtextpos +} + +func (r *runner) rightchars() int { + return r.runtextend - r.runtextpos +} + +func (r *runner) bump() int { + if r.rightToLeft { + return -1 + } + return 1 +} + +func (r *runner) forwardchars() int { + if r.rightToLeft { + return r.runtextpos + } + return r.runtextend - r.runtextpos +} + +func (r *runner) forwardcharnext() rune { + var ch rune + if r.rightToLeft { + r.runtextpos-- + ch = r.runtext[r.runtextpos] + } else { + ch = r.runtext[r.runtextpos] + r.runtextpos++ + } + + if r.caseInsensitive { + return unicode.ToLower(ch) + } + return ch +} + +func (r *runner) runematch(str []rune) bool { + var pos int + + c := len(str) + if !r.rightToLeft { + if r.runtextend-r.runtextpos < c { + return false + } + + pos = r.runtextpos + c + } else { + if r.runtextpos-0 < c { + return false + } + + pos = r.runtextpos + } + + if !r.caseInsensitive { + for c != 0 { + c-- + pos-- + if str[c] != r.runtext[pos] { + return false + } + } + } else { + for c != 0 { + c-- + pos-- + if str[c] != unicode.ToLower(r.runtext[pos]) { + return false + } + } + } + + if !r.rightToLeft { + pos += len(str) + } + + r.runtextpos = pos + + return true +} + +func (r *runner) refmatch(index, len int) bool { + var c, pos, cmpos int + + if !r.rightToLeft { + if r.runtextend-r.runtextpos < len { + return false + } + + pos = r.runtextpos + len + } else { + if r.runtextpos-0 < len { + return false + } + + pos = r.runtextpos + } + cmpos = index + len + + c = len + + if !r.caseInsensitive { + for c != 0 { + c-- + cmpos-- + pos-- + if r.runtext[cmpos] != r.runtext[pos] { + return false + } + + } + } else { + for c != 0 { + c-- + cmpos-- + pos-- + + if unicode.ToLower(r.runtext[cmpos]) != unicode.ToLower(r.runtext[pos]) { + return false + } + } + } + + if !r.rightToLeft { + pos += len + } + + r.runtextpos = pos + + return true +} + +func (r *runner) backwardnext() { + if r.rightToLeft { + r.runtextpos++ + } else { + r.runtextpos-- + } +} + +func (r *runner) charAt(j int) rune { + return r.runtext[j] +} + +func (r *runner) findFirstChar() bool { + + if 0 != (r.code.Anchors & (syntax.AnchorBeginning | syntax.AnchorStart | syntax.AnchorEndZ | syntax.AnchorEnd)) { + if !r.code.RightToLeft { + if (0 != (r.code.Anchors&syntax.AnchorBeginning) && r.runtextpos > 0) || + (0 != (r.code.Anchors&syntax.AnchorStart) && r.runtextpos > r.runtextstart) { + r.runtextpos = r.runtextend + return false + } + if 0 != (r.code.Anchors&syntax.AnchorEndZ) && r.runtextpos < r.runtextend-1 { + r.runtextpos = r.runtextend - 1 + } else if 0 != (r.code.Anchors&syntax.AnchorEnd) && r.runtextpos < r.runtextend { + r.runtextpos = r.runtextend + } + } else { + if (0 != (r.code.Anchors&syntax.AnchorEnd) && r.runtextpos < r.runtextend) || + (0 != (r.code.Anchors&syntax.AnchorEndZ) && (r.runtextpos < r.runtextend-1 || + (r.runtextpos == r.runtextend-1 && r.charAt(r.runtextpos) != '\n'))) || + (0 != (r.code.Anchors&syntax.AnchorStart) && r.runtextpos < r.runtextstart) { + r.runtextpos = 0 + return false + } + if 0 != (r.code.Anchors&syntax.AnchorBeginning) && r.runtextpos > 0 { + r.runtextpos = 0 + } + } + + if r.code.BmPrefix != nil { + return r.code.BmPrefix.IsMatch(r.runtext, r.runtextpos, 0, r.runtextend) + } + + return true // found a valid start or end anchor + } else if r.code.BmPrefix != nil { + r.runtextpos = r.code.BmPrefix.Scan(r.runtext, r.runtextpos, 0, r.runtextend) + + if r.runtextpos == -1 { + if r.code.RightToLeft { + r.runtextpos = 0 + } else { + r.runtextpos = r.runtextend + } + return false + } + + return true + } else if r.code.FcPrefix == nil { + return true + } + + r.rightToLeft = r.code.RightToLeft + r.caseInsensitive = r.code.FcPrefix.CaseInsensitive + + set := r.code.FcPrefix.PrefixSet + if set.IsSingleton() { + ch := set.SingletonChar() + for i := r.forwardchars(); i > 0; i-- { + if ch == r.forwardcharnext() { + r.backwardnext() + return true + } + } + } else { + for i := r.forwardchars(); i > 0; i-- { + n := r.forwardcharnext() + //fmt.Printf("%v in %v: %v\n", string(n), set.String(), set.CharIn(n)) + if set.CharIn(n) { + r.backwardnext() + return true + } + } + } + + return false +} + +func (r *runner) initMatch() { + // Use a hashtable'ed Match object if the capture numbers are sparse + + if r.runmatch == nil { + if r.re.caps != nil { + r.runmatch = newMatchSparse(r.re, r.re.caps, r.re.capsize, r.runtext, r.runtextstart) + } else { + r.runmatch = newMatch(r.re, r.re.capsize, r.runtext, r.runtextstart) + } + } else { + r.runmatch.reset(r.runtext, r.runtextstart) + } + + // note we test runcrawl, because it is the last one to be allocated + // If there is an alloc failure in the middle of the three allocations, + // we may still return to reuse this instance, and we want to behave + // as if the allocations didn't occur. (we used to test _trackcount != 0) + + if r.runcrawl != nil { + r.runtrackpos = len(r.runtrack) + r.runstackpos = len(r.runstack) + r.runcrawlpos = len(r.runcrawl) + return + } + + r.initTrackCount() + + tracksize := r.runtrackcount * 8 + stacksize := r.runtrackcount * 8 + + if tracksize < 32 { + tracksize = 32 + } + if stacksize < 16 { + stacksize = 16 + } + + r.runtrack = make([]int, tracksize) + r.runtrackpos = tracksize + + r.runstack = make([]int, stacksize) + r.runstackpos = stacksize + + r.runcrawl = make([]int, 32) + r.runcrawlpos = 32 +} + +func (r *runner) tidyMatch(quick bool) *Match { + if !quick { + match := r.runmatch + + r.runmatch = nil + + match.tidy(r.runtextpos) + return match + } else { + // send back our match -- it's not leaving the package, so it's safe to not clean it up + // this reduces allocs for frequent calls to the "IsMatch" bool-only functions + return r.runmatch + } +} + +// capture captures a subexpression. Note that the +// capnum used here has already been mapped to a non-sparse +// index (by the code generator RegexWriter). +func (r *runner) capture(capnum, start, end int) { + if end < start { + T := end + end = start + start = T + } + + r.crawl(capnum) + r.runmatch.addMatch(capnum, start, end-start) +} + +// transferCapture captures a subexpression. Note that the +// capnum used here has already been mapped to a non-sparse +// index (by the code generator RegexWriter). +func (r *runner) transferCapture(capnum, uncapnum, start, end int) { + var start2, end2 int + + // these are the two intervals that are cancelling each other + + if end < start { + T := end + end = start + start = T + } + + start2 = r.runmatch.matchIndex(uncapnum) + end2 = start2 + r.runmatch.matchLength(uncapnum) + + // The new capture gets the innermost defined interval + + if start >= end2 { + end = start + start = end2 + } else if end <= start2 { + start = start2 + } else { + if end > end2 { + end = end2 + } + if start2 > start { + start = start2 + } + } + + r.crawl(uncapnum) + r.runmatch.balanceMatch(uncapnum) + + if capnum != -1 { + r.crawl(capnum) + r.runmatch.addMatch(capnum, start, end-start) + } +} + +// revert the last capture +func (r *runner) uncapture() { + capnum := r.popcrawl() + r.runmatch.removeMatch(capnum) +} + +//debug + +func (r *runner) dumpState() { + back := "" + if r.operator&syntax.Back != 0 { + back = " Back" + } + if r.operator&syntax.Back2 != 0 { + back += " Back2" + } + fmt.Printf("Text: %v\nTrack: %v\nStack: %v\n %s%s\n\n", + r.textposDescription(), + r.stackDescription(r.runtrack, r.runtrackpos), + r.stackDescription(r.runstack, r.runstackpos), + r.code.OpcodeDescription(r.codepos), + back) +} + +func (r *runner) stackDescription(a []int, index int) string { + buf := &bytes.Buffer{} + + fmt.Fprintf(buf, "%v/%v", len(a)-index, len(a)) + if buf.Len() < 8 { + buf.WriteString(strings.Repeat(" ", 8-buf.Len())) + } + + buf.WriteRune('(') + for i := index; i < len(a); i++ { + if i > index { + buf.WriteRune(' ') + } + + buf.WriteString(strconv.Itoa(a[i])) + } + + buf.WriteRune(')') + + return buf.String() +} + +func (r *runner) textposDescription() string { + buf := &bytes.Buffer{} + + buf.WriteString(strconv.Itoa(r.runtextpos)) + + if buf.Len() < 8 { + buf.WriteString(strings.Repeat(" ", 8-buf.Len())) + } + + if r.runtextpos > 0 { + buf.WriteString(syntax.CharDescription(r.runtext[r.runtextpos-1])) + } else { + buf.WriteRune('^') + } + + buf.WriteRune('>') + + for i := r.runtextpos; i < r.runtextend; i++ { + buf.WriteString(syntax.CharDescription(r.runtext[i])) + } + if buf.Len() >= 64 { + buf.Truncate(61) + buf.WriteString("...") + } else { + buf.WriteRune('$') + } + + return buf.String() +} + +// decide whether the pos +// at the specified index is a boundary or not. It's just not worth +// emitting inline code for this logic. +func (r *runner) isBoundary(index, startpos, endpos int) bool { + return (index > startpos && syntax.IsWordChar(r.runtext[index-1])) != + (index < endpos && syntax.IsWordChar(r.runtext[index])) +} + +func (r *runner) isECMABoundary(index, startpos, endpos int) bool { + return (index > startpos && syntax.IsECMAWordChar(r.runtext[index-1])) != + (index < endpos && syntax.IsECMAWordChar(r.runtext[index])) +} + +func (r *runner) startTimeoutWatch() { + if r.ignoreTimeout { + return + } + r.deadline = makeDeadline(r.timeout) +} + +func (r *runner) checkTimeout() error { + if r.ignoreTimeout || !r.deadline.reached() { + return nil + } + + if r.re.Debug() { + //Debug.WriteLine("") + //Debug.WriteLine("RegEx match timeout occurred!") + //Debug.WriteLine("Specified timeout: " + TimeSpan.FromMilliseconds(_timeout).ToString()) + //Debug.WriteLine("Timeout check frequency: " + TimeoutCheckFrequency) + //Debug.WriteLine("Search pattern: " + _runregex._pattern) + //Debug.WriteLine("Input: " + r.runtext) + //Debug.WriteLine("About to throw RegexMatchTimeoutException.") + } + + return fmt.Errorf("match timeout after %v on input `%v`", r.timeout, string(r.runtext)) +} + +func (r *runner) initTrackCount() { + r.runtrackcount = r.code.TrackCount +} + +// getRunner returns a run to use for matching re. +// It uses the re's runner cache if possible, to avoid +// unnecessary allocation. +func (re *Regexp) getRunner() *runner { + re.muRun.Lock() + if n := len(re.runner); n > 0 { + z := re.runner[n-1] + re.runner = re.runner[:n-1] + re.muRun.Unlock() + return z + } + re.muRun.Unlock() + z := &runner{ + re: re, + code: re.code, + } + return z +} + +// putRunner returns a runner to the re's cache. +// There is no attempt to limit the size of the cache, so it will +// grow to the maximum number of simultaneous matches +// run using re. (The cache empties when re gets garbage collected.) +func (re *Regexp) putRunner(r *runner) { + re.muRun.Lock() + r.runtext = nil + if r.runmatch != nil { + r.runmatch.text = nil + } + re.runner = append(re.runner, r) + re.muRun.Unlock() +} diff --git a/third_party/regexp2/syntax/charclass.go b/third_party/regexp2/syntax/charclass.go new file mode 100644 index 000000000..6881a0e29 --- /dev/null +++ b/third_party/regexp2/syntax/charclass.go @@ -0,0 +1,865 @@ +package syntax + +import ( + "bytes" + "encoding/binary" + "fmt" + "sort" + "unicode" + "unicode/utf8" +) + +// CharSet combines start-end rune ranges and unicode categories representing a set of characters +type CharSet struct { + ranges []singleRange + categories []category + sub *CharSet //optional subtractor + negate bool + anything bool +} + +type category struct { + negate bool + cat string +} + +type singleRange struct { + first rune + last rune +} + +const ( + spaceCategoryText = " " + wordCategoryText = "W" +) + +var ( + ecmaSpace = []rune{0x0009, 0x000e, 0x0020, 0x0021, 0x00a0, 0x00a1, 0x1680, 0x1681, 0x2000, 0x200b, 0x2028, 0x202a, 0x202f, 0x2030, 0x205f, 0x2060, 0x3000, 0x3001, 0xfeff, 0xff00} + ecmaWord = []rune{0x0030, 0x003a, 0x0041, 0x005b, 0x005f, 0x0060, 0x0061, 0x007b} + ecmaDigit = []rune{0x0030, 0x003a} + + re2Space = []rune{0x0009, 0x000b, 0x000c, 0x000e, 0x0020, 0x0021} +) + +var ( + AnyClass = getCharSetFromOldString([]rune{0}, false) + ECMAAnyClass = getCharSetFromOldString([]rune{0, 0x000a, 0x000b, 0x000d, 0x000e}, false) + NoneClass = getCharSetFromOldString(nil, false) + ECMAWordClass = getCharSetFromOldString(ecmaWord, false) + NotECMAWordClass = getCharSetFromOldString(ecmaWord, true) + ECMASpaceClass = getCharSetFromOldString(ecmaSpace, false) + NotECMASpaceClass = getCharSetFromOldString(ecmaSpace, true) + ECMADigitClass = getCharSetFromOldString(ecmaDigit, false) + NotECMADigitClass = getCharSetFromOldString(ecmaDigit, true) + + WordClass = getCharSetFromCategoryString(false, false, wordCategoryText) + NotWordClass = getCharSetFromCategoryString(true, false, wordCategoryText) + SpaceClass = getCharSetFromCategoryString(false, false, spaceCategoryText) + NotSpaceClass = getCharSetFromCategoryString(true, false, spaceCategoryText) + DigitClass = getCharSetFromCategoryString(false, false, "Nd") + NotDigitClass = getCharSetFromCategoryString(false, true, "Nd") + + RE2SpaceClass = getCharSetFromOldString(re2Space, false) + NotRE2SpaceClass = getCharSetFromOldString(re2Space, true) +) + +var unicodeCategories = func() map[string]*unicode.RangeTable { + retVal := make(map[string]*unicode.RangeTable) + for k, v := range unicode.Scripts { + retVal[k] = v + } + for k, v := range unicode.Categories { + retVal[k] = v + } + for k, v := range unicode.Properties { + retVal[k] = v + } + return retVal +}() + +func getCharSetFromCategoryString(negateSet bool, negateCat bool, cats ...string) func() *CharSet { + if negateCat && negateSet { + panic("BUG! You should only negate the set OR the category in a constant setup, but not both") + } + + c := CharSet{negate: negateSet} + + c.categories = make([]category, len(cats)) + for i, cat := range cats { + c.categories[i] = category{cat: cat, negate: negateCat} + } + return func() *CharSet { + //make a copy each time + local := c + //return that address + return &local + } +} + +func getCharSetFromOldString(setText []rune, negate bool) func() *CharSet { + c := CharSet{} + if len(setText) > 0 { + fillFirst := false + l := len(setText) + if negate { + if setText[0] == 0 { + setText = setText[1:] + } else { + l++ + fillFirst = true + } + } + + if l%2 == 0 { + c.ranges = make([]singleRange, l/2) + } else { + c.ranges = make([]singleRange, l/2+1) + } + + first := true + if fillFirst { + c.ranges[0] = singleRange{first: 0} + first = false + } + + i := 0 + for _, r := range setText { + if first { + // lower bound in a new range + c.ranges[i] = singleRange{first: r} + first = false + } else { + c.ranges[i].last = r - 1 + i++ + first = true + } + } + if !first { + c.ranges[i].last = utf8.MaxRune + } + } + + return func() *CharSet { + local := c + return &local + } +} + +// Copy makes a deep copy to prevent accidental mutation of a set +func (c CharSet) Copy() CharSet { + ret := CharSet{ + anything: c.anything, + negate: c.negate, + } + + ret.ranges = append(ret.ranges, c.ranges...) + ret.categories = append(ret.categories, c.categories...) + + if c.sub != nil { + sub := c.sub.Copy() + ret.sub = &sub + } + + return ret +} + +// gets a human-readable description for a set string +func (c CharSet) String() string { + buf := &bytes.Buffer{} + buf.WriteRune('[') + + if c.IsNegated() { + buf.WriteRune('^') + } + + for _, r := range c.ranges { + + buf.WriteString(CharDescription(r.first)) + if r.first != r.last { + if r.last-r.first != 1 { + //groups that are 1 char apart skip the dash + buf.WriteRune('-') + } + buf.WriteString(CharDescription(r.last)) + } + } + + for _, c := range c.categories { + buf.WriteString(c.String()) + } + + if c.sub != nil { + buf.WriteRune('-') + buf.WriteString(c.sub.String()) + } + + buf.WriteRune(']') + + return buf.String() +} + +// mapHashFill converts a charset into a buffer for use in maps +func (c CharSet) mapHashFill(buf *bytes.Buffer) { + if c.negate { + buf.WriteByte(0) + } else { + buf.WriteByte(1) + } + + binary.Write(buf, binary.LittleEndian, len(c.ranges)) + binary.Write(buf, binary.LittleEndian, len(c.categories)) + for _, r := range c.ranges { + buf.WriteRune(r.first) + buf.WriteRune(r.last) + } + for _, ct := range c.categories { + buf.WriteString(ct.cat) + if ct.negate { + buf.WriteByte(1) + } else { + buf.WriteByte(0) + } + } + + if c.sub != nil { + c.sub.mapHashFill(buf) + } +} + +// CharIn returns true if the rune is in our character set (either ranges or categories). +// It handles negations and subtracted sub-charsets. +func (c CharSet) CharIn(ch rune) bool { + val := false + // in s && !s.subtracted + + //check ranges + for _, r := range c.ranges { + if ch < r.first { + continue + } + if ch <= r.last { + val = true + break + } + } + + //check categories if we haven't already found a range + if !val && len(c.categories) > 0 { + for _, ct := range c.categories { + // special categories...then unicode + if ct.cat == spaceCategoryText { + if unicode.IsSpace(ch) { + // we found a space so we're done + // negate means this is a "bad" thing + val = !ct.negate + break + } else if ct.negate { + val = true + break + } + } else if ct.cat == wordCategoryText { + if IsWordChar(ch) { + val = !ct.negate + break + } else if ct.negate { + val = true + break + } + } else if unicode.Is(unicodeCategories[ct.cat], ch) { + // if we're in this unicode category then we're done + // if negate=true on this category then we "failed" our test + // otherwise we're good that we found it + val = !ct.negate + break + } else if ct.negate { + val = true + break + } + } + } + + // negate the whole char set + if c.negate { + val = !val + } + + // get subtracted recurse + if val && c.sub != nil { + val = !c.sub.CharIn(ch) + } + + //log.Printf("Char '%v' in %v == %v", string(ch), c.String(), val) + return val +} + +func (c category) String() string { + switch c.cat { + case spaceCategoryText: + if c.negate { + return "\\S" + } + return "\\s" + case wordCategoryText: + if c.negate { + return "\\W" + } + return "\\w" + } + if _, ok := unicodeCategories[c.cat]; ok { + + if c.negate { + return "\\P{" + c.cat + "}" + } + return "\\p{" + c.cat + "}" + } + return "Unknown category: " + c.cat +} + +// CharDescription Produces a human-readable description for a single character. +func CharDescription(ch rune) string { + /*if ch == '\\' { + return "\\\\" + } + + if ch > ' ' && ch <= '~' { + return string(ch) + } else if ch == '\n' { + return "\\n" + } else if ch == ' ' { + return "\\ " + }*/ + + b := &bytes.Buffer{} + escape(b, ch, false) //fmt.Sprintf("%U", ch) + return b.String() +} + +// According to UTS#18 Unicode Regular Expressions (http://www.unicode.org/reports/tr18/) +// RL 1.4 Simple Word Boundaries The class of includes all Alphabetic +// values from the Unicode character database, from UnicodeData.txt [UData], plus the U+200C +// ZERO WIDTH NON-JOINER and U+200D ZERO WIDTH JOINER. +func IsWordChar(r rune) bool { + //"L", "Mn", "Nd", "Pc" + return unicode.In(r, + unicode.Categories["L"], unicode.Categories["Mn"], + unicode.Categories["Nd"], unicode.Categories["Pc"]) || r == '\u200D' || r == '\u200C' + //return 'A' <= r && r <= 'Z' || 'a' <= r && r <= 'z' || '0' <= r && r <= '9' || r == '_' +} + +func IsECMAWordChar(r rune) bool { + return unicode.In(r, + unicode.Categories["L"], unicode.Categories["Mn"], + unicode.Categories["Nd"], unicode.Categories["Pc"]) + + //return 'A' <= r && r <= 'Z' || 'a' <= r && r <= 'z' || '0' <= r && r <= '9' || r == '_' +} + +// SingletonChar will return the char from the first range without validation. +// It assumes you have checked for IsSingleton or IsSingletonInverse and will panic given bad input +func (c CharSet) SingletonChar() rune { + return c.ranges[0].first +} + +func (c CharSet) IsSingleton() bool { + return !c.negate && //negated is multiple chars + len(c.categories) == 0 && len(c.ranges) == 1 && // multiple ranges and unicode classes represent multiple chars + c.sub == nil && // subtraction means we've got multiple chars + c.ranges[0].first == c.ranges[0].last // first and last equal means we're just 1 char +} + +func (c CharSet) IsSingletonInverse() bool { + return c.negate && //same as above, but requires negated + len(c.categories) == 0 && len(c.ranges) == 1 && // multiple ranges and unicode classes represent multiple chars + c.sub == nil && // subtraction means we've got multiple chars + c.ranges[0].first == c.ranges[0].last // first and last equal means we're just 1 char +} + +func (c CharSet) IsMergeable() bool { + return !c.IsNegated() && !c.HasSubtraction() +} + +func (c CharSet) IsNegated() bool { + return c.negate +} + +func (c CharSet) HasSubtraction() bool { + return c.sub != nil +} + +func (c CharSet) IsEmpty() bool { + return len(c.ranges) == 0 && len(c.categories) == 0 && c.sub == nil +} + +func (c *CharSet) addDigit(ecma, negate bool, pattern string) { + if ecma { + if negate { + c.addRanges(NotECMADigitClass().ranges) + } else { + c.addRanges(ECMADigitClass().ranges) + } + } else { + c.addCategories(category{cat: "Nd", negate: negate}) + } +} + +func (c *CharSet) addChar(ch rune) { + c.addRange(ch, ch) +} + +func (c *CharSet) addSpace(ecma, re2, negate bool) { + if ecma { + if negate { + c.addRanges(NotECMASpaceClass().ranges) + } else { + c.addRanges(ECMASpaceClass().ranges) + } + } else if re2 { + if negate { + c.addRanges(NotRE2SpaceClass().ranges) + } else { + c.addRanges(RE2SpaceClass().ranges) + } + } else { + c.addCategories(category{cat: spaceCategoryText, negate: negate}) + } +} + +func (c *CharSet) addWord(ecma, negate bool) { + if ecma { + if negate { + c.addRanges(NotECMAWordClass().ranges) + } else { + c.addRanges(ECMAWordClass().ranges) + } + } else { + c.addCategories(category{cat: wordCategoryText, negate: negate}) + } +} + +// Add set ranges and categories into ours -- no deduping or anything +func (c *CharSet) addSet(set CharSet) { + if c.anything { + return + } + if set.anything { + c.makeAnything() + return + } + // just append here to prevent double-canon + c.ranges = append(c.ranges, set.ranges...) + c.addCategories(set.categories...) + c.canonicalize() +} + +func (c *CharSet) makeAnything() { + c.anything = true + c.categories = []category{} + c.ranges = AnyClass().ranges +} + +func (c *CharSet) addCategories(cats ...category) { + // don't add dupes and remove positive+negative + if c.anything { + // if we've had a previous positive+negative group then + // just return, we're as broad as we can get + return + } + + for _, ct := range cats { + found := false + for _, ct2 := range c.categories { + if ct.cat == ct2.cat { + if ct.negate != ct2.negate { + // oposite negations...this mean we just + // take us as anything and move on + c.makeAnything() + return + } + found = true + break + } + } + + if !found { + c.categories = append(c.categories, ct) + } + } +} + +// Merges new ranges to our own +func (c *CharSet) addRanges(ranges []singleRange) { + if c.anything { + return + } + c.ranges = append(c.ranges, ranges...) + c.canonicalize() +} + +// Merges everything but the new ranges into our own +func (c *CharSet) addNegativeRanges(ranges []singleRange) { + if c.anything { + return + } + + var hi rune + + // convert incoming ranges into opposites, assume they are in order + for _, r := range ranges { + if hi < r.first { + c.ranges = append(c.ranges, singleRange{hi, r.first - 1}) + } + hi = r.last + 1 + } + + if hi < utf8.MaxRune { + c.ranges = append(c.ranges, singleRange{hi, utf8.MaxRune}) + } + + c.canonicalize() +} + +func isValidUnicodeCat(catName string) bool { + _, ok := unicodeCategories[catName] + return ok +} + +func (c *CharSet) addCategory(categoryName string, negate, caseInsensitive bool, pattern string) { + if !isValidUnicodeCat(categoryName) { + // unknown unicode category, script, or property "blah" + panic(fmt.Errorf("Unknown unicode category, script, or property '%v'", categoryName)) + + } + + if caseInsensitive && (categoryName == "Ll" || categoryName == "Lu" || categoryName == "Lt") { + // when RegexOptions.IgnoreCase is specified then {Ll} {Lu} and {Lt} cases should all match + c.addCategories( + category{cat: "Ll", negate: negate}, + category{cat: "Lu", negate: negate}, + category{cat: "Lt", negate: negate}) + } + c.addCategories(category{cat: categoryName, negate: negate}) +} + +func (c *CharSet) addSubtraction(sub *CharSet) { + c.sub = sub +} + +func (c *CharSet) addRange(chMin, chMax rune) { + c.ranges = append(c.ranges, singleRange{first: chMin, last: chMax}) + c.canonicalize() +} + +func (c *CharSet) addNamedASCII(name string, negate bool) bool { + var rs []singleRange + + switch name { + case "alnum": + rs = []singleRange{singleRange{'0', '9'}, singleRange{'A', 'Z'}, singleRange{'a', 'z'}} + case "alpha": + rs = []singleRange{singleRange{'A', 'Z'}, singleRange{'a', 'z'}} + case "ascii": + rs = []singleRange{singleRange{0, 0x7f}} + case "blank": + rs = []singleRange{singleRange{'\t', '\t'}, singleRange{' ', ' '}} + case "cntrl": + rs = []singleRange{singleRange{0, 0x1f}, singleRange{0x7f, 0x7f}} + case "digit": + c.addDigit(false, negate, "") + case "graph": + rs = []singleRange{singleRange{'!', '~'}} + case "lower": + rs = []singleRange{singleRange{'a', 'z'}} + case "print": + rs = []singleRange{singleRange{' ', '~'}} + case "punct": //[!-/:-@[-`{-~] + rs = []singleRange{singleRange{'!', '/'}, singleRange{':', '@'}, singleRange{'[', '`'}, singleRange{'{', '~'}} + case "space": + c.addSpace(true, false, negate) + case "upper": + rs = []singleRange{singleRange{'A', 'Z'}} + case "word": + c.addWord(true, negate) + case "xdigit": + rs = []singleRange{singleRange{'0', '9'}, singleRange{'A', 'F'}, singleRange{'a', 'f'}} + default: + return false + } + + if len(rs) > 0 { + if negate { + c.addNegativeRanges(rs) + } else { + c.addRanges(rs) + } + } + + return true +} + +type singleRangeSorter []singleRange + +func (p singleRangeSorter) Len() int { return len(p) } +func (p singleRangeSorter) Less(i, j int) bool { return p[i].first < p[j].first } +func (p singleRangeSorter) Swap(i, j int) { p[i], p[j] = p[j], p[i] } + +// Logic to reduce a character class to a unique, sorted form. +func (c *CharSet) canonicalize() { + var i, j int + var last rune + + // + // Find and eliminate overlapping or abutting ranges + // + + if len(c.ranges) > 1 { + sort.Sort(singleRangeSorter(c.ranges)) + + done := false + + for i, j = 1, 0; ; i++ { + for last = c.ranges[j].last; ; i++ { + if i == len(c.ranges) || last == utf8.MaxRune { + done = true + break + } + + CurrentRange := c.ranges[i] + if CurrentRange.first > last+1 { + break + } + + if last < CurrentRange.last { + last = CurrentRange.last + } + } + + c.ranges[j] = singleRange{first: c.ranges[j].first, last: last} + + j++ + + if done { + break + } + + if j < i { + c.ranges[j] = c.ranges[i] + } + } + + c.ranges = append(c.ranges[:j], c.ranges[len(c.ranges):]...) + } +} + +// Adds to the class any lowercase versions of characters already +// in the class. Used for case-insensitivity. +func (c *CharSet) addLowercase() { + if c.anything { + return + } + toAdd := []singleRange{} + for i := 0; i < len(c.ranges); i++ { + r := c.ranges[i] + if r.first == r.last { + lower := unicode.ToLower(r.first) + c.ranges[i] = singleRange{first: lower, last: lower} + } else { + toAdd = append(toAdd, r) + } + } + + for _, r := range toAdd { + c.addLowercaseRange(r.first, r.last) + } + c.canonicalize() +} + +/************************************************************************** + Let U be the set of Unicode character values and let L be the lowercase + function, mapping from U to U. To perform case insensitive matching of + character sets, we need to be able to map an interval I in U, say + + I = [chMin, chMax] = { ch : chMin <= ch <= chMax } + + to a set A such that A contains L(I) and A is contained in the union of + I and L(I). + + The table below partitions U into intervals on which L is non-decreasing. + Thus, for any interval J = [a, b] contained in one of these intervals, + L(J) is contained in [L(a), L(b)]. + + It is also true that for any such J, [L(a), L(b)] is contained in the + union of J and L(J). This does not follow from L being non-decreasing on + these intervals. It follows from the nature of the L on each interval. + On each interval, L has one of the following forms: + + (1) L(ch) = constant (LowercaseSet) + (2) L(ch) = ch + offset (LowercaseAdd) + (3) L(ch) = ch | 1 (LowercaseBor) + (4) L(ch) = ch + (ch & 1) (LowercaseBad) + + It is easy to verify that for any of these forms [L(a), L(b)] is + contained in the union of [a, b] and L([a, b]). +***************************************************************************/ + +const ( + LowercaseSet = 0 // Set to arg. + LowercaseAdd = 1 // Add arg. + LowercaseBor = 2 // Bitwise or with 1. + LowercaseBad = 3 // Bitwise and with 1 and add original. +) + +type lcMap struct { + chMin, chMax rune + op, data int32 +} + +var lcTable = []lcMap{ + lcMap{'\u0041', '\u005A', LowercaseAdd, 32}, + lcMap{'\u00C0', '\u00DE', LowercaseAdd, 32}, + lcMap{'\u0100', '\u012E', LowercaseBor, 0}, + lcMap{'\u0130', '\u0130', LowercaseSet, 0x0069}, + lcMap{'\u0132', '\u0136', LowercaseBor, 0}, + lcMap{'\u0139', '\u0147', LowercaseBad, 0}, + lcMap{'\u014A', '\u0176', LowercaseBor, 0}, + lcMap{'\u0178', '\u0178', LowercaseSet, 0x00FF}, + lcMap{'\u0179', '\u017D', LowercaseBad, 0}, + lcMap{'\u0181', '\u0181', LowercaseSet, 0x0253}, + lcMap{'\u0182', '\u0184', LowercaseBor, 0}, + lcMap{'\u0186', '\u0186', LowercaseSet, 0x0254}, + lcMap{'\u0187', '\u0187', LowercaseSet, 0x0188}, + lcMap{'\u0189', '\u018A', LowercaseAdd, 205}, + lcMap{'\u018B', '\u018B', LowercaseSet, 0x018C}, + lcMap{'\u018E', '\u018E', LowercaseSet, 0x01DD}, + lcMap{'\u018F', '\u018F', LowercaseSet, 0x0259}, + lcMap{'\u0190', '\u0190', LowercaseSet, 0x025B}, + lcMap{'\u0191', '\u0191', LowercaseSet, 0x0192}, + lcMap{'\u0193', '\u0193', LowercaseSet, 0x0260}, + lcMap{'\u0194', '\u0194', LowercaseSet, 0x0263}, + lcMap{'\u0196', '\u0196', LowercaseSet, 0x0269}, + lcMap{'\u0197', '\u0197', LowercaseSet, 0x0268}, + lcMap{'\u0198', '\u0198', LowercaseSet, 0x0199}, + lcMap{'\u019C', '\u019C', LowercaseSet, 0x026F}, + lcMap{'\u019D', '\u019D', LowercaseSet, 0x0272}, + lcMap{'\u019F', '\u019F', LowercaseSet, 0x0275}, + lcMap{'\u01A0', '\u01A4', LowercaseBor, 0}, + lcMap{'\u01A7', '\u01A7', LowercaseSet, 0x01A8}, + lcMap{'\u01A9', '\u01A9', LowercaseSet, 0x0283}, + lcMap{'\u01AC', '\u01AC', LowercaseSet, 0x01AD}, + lcMap{'\u01AE', '\u01AE', LowercaseSet, 0x0288}, + lcMap{'\u01AF', '\u01AF', LowercaseSet, 0x01B0}, + lcMap{'\u01B1', '\u01B2', LowercaseAdd, 217}, + lcMap{'\u01B3', '\u01B5', LowercaseBad, 0}, + lcMap{'\u01B7', '\u01B7', LowercaseSet, 0x0292}, + lcMap{'\u01B8', '\u01B8', LowercaseSet, 0x01B9}, + lcMap{'\u01BC', '\u01BC', LowercaseSet, 0x01BD}, + lcMap{'\u01C4', '\u01C5', LowercaseSet, 0x01C6}, + lcMap{'\u01C7', '\u01C8', LowercaseSet, 0x01C9}, + lcMap{'\u01CA', '\u01CB', LowercaseSet, 0x01CC}, + lcMap{'\u01CD', '\u01DB', LowercaseBad, 0}, + lcMap{'\u01DE', '\u01EE', LowercaseBor, 0}, + lcMap{'\u01F1', '\u01F2', LowercaseSet, 0x01F3}, + lcMap{'\u01F4', '\u01F4', LowercaseSet, 0x01F5}, + lcMap{'\u01FA', '\u0216', LowercaseBor, 0}, + lcMap{'\u0386', '\u0386', LowercaseSet, 0x03AC}, + lcMap{'\u0388', '\u038A', LowercaseAdd, 37}, + lcMap{'\u038C', '\u038C', LowercaseSet, 0x03CC}, + lcMap{'\u038E', '\u038F', LowercaseAdd, 63}, + lcMap{'\u0391', '\u03AB', LowercaseAdd, 32}, + lcMap{'\u03E2', '\u03EE', LowercaseBor, 0}, + lcMap{'\u0401', '\u040F', LowercaseAdd, 80}, + lcMap{'\u0410', '\u042F', LowercaseAdd, 32}, + lcMap{'\u0460', '\u0480', LowercaseBor, 0}, + lcMap{'\u0490', '\u04BE', LowercaseBor, 0}, + lcMap{'\u04C1', '\u04C3', LowercaseBad, 0}, + lcMap{'\u04C7', '\u04C7', LowercaseSet, 0x04C8}, + lcMap{'\u04CB', '\u04CB', LowercaseSet, 0x04CC}, + lcMap{'\u04D0', '\u04EA', LowercaseBor, 0}, + lcMap{'\u04EE', '\u04F4', LowercaseBor, 0}, + lcMap{'\u04F8', '\u04F8', LowercaseSet, 0x04F9}, + lcMap{'\u0531', '\u0556', LowercaseAdd, 48}, + lcMap{'\u10A0', '\u10C5', LowercaseAdd, 48}, + lcMap{'\u1E00', '\u1EF8', LowercaseBor, 0}, + lcMap{'\u1F08', '\u1F0F', LowercaseAdd, -8}, + lcMap{'\u1F18', '\u1F1F', LowercaseAdd, -8}, + lcMap{'\u1F28', '\u1F2F', LowercaseAdd, -8}, + lcMap{'\u1F38', '\u1F3F', LowercaseAdd, -8}, + lcMap{'\u1F48', '\u1F4D', LowercaseAdd, -8}, + lcMap{'\u1F59', '\u1F59', LowercaseSet, 0x1F51}, + lcMap{'\u1F5B', '\u1F5B', LowercaseSet, 0x1F53}, + lcMap{'\u1F5D', '\u1F5D', LowercaseSet, 0x1F55}, + lcMap{'\u1F5F', '\u1F5F', LowercaseSet, 0x1F57}, + lcMap{'\u1F68', '\u1F6F', LowercaseAdd, -8}, + lcMap{'\u1F88', '\u1F8F', LowercaseAdd, -8}, + lcMap{'\u1F98', '\u1F9F', LowercaseAdd, -8}, + lcMap{'\u1FA8', '\u1FAF', LowercaseAdd, -8}, + lcMap{'\u1FB8', '\u1FB9', LowercaseAdd, -8}, + lcMap{'\u1FBA', '\u1FBB', LowercaseAdd, -74}, + lcMap{'\u1FBC', '\u1FBC', LowercaseSet, 0x1FB3}, + lcMap{'\u1FC8', '\u1FCB', LowercaseAdd, -86}, + lcMap{'\u1FCC', '\u1FCC', LowercaseSet, 0x1FC3}, + lcMap{'\u1FD8', '\u1FD9', LowercaseAdd, -8}, + lcMap{'\u1FDA', '\u1FDB', LowercaseAdd, -100}, + lcMap{'\u1FE8', '\u1FE9', LowercaseAdd, -8}, + lcMap{'\u1FEA', '\u1FEB', LowercaseAdd, -112}, + lcMap{'\u1FEC', '\u1FEC', LowercaseSet, 0x1FE5}, + lcMap{'\u1FF8', '\u1FF9', LowercaseAdd, -128}, + lcMap{'\u1FFA', '\u1FFB', LowercaseAdd, -126}, + lcMap{'\u1FFC', '\u1FFC', LowercaseSet, 0x1FF3}, + lcMap{'\u2160', '\u216F', LowercaseAdd, 16}, + lcMap{'\u24B6', '\u24D0', LowercaseAdd, 26}, + lcMap{'\uFF21', '\uFF3A', LowercaseAdd, 32}, +} + +func (c *CharSet) addLowercaseRange(chMin, chMax rune) { + var i, iMax, iMid int + var chMinT, chMaxT rune + var lc lcMap + + for i, iMax = 0, len(lcTable); i < iMax; { + iMid = (i + iMax) / 2 + if lcTable[iMid].chMax < chMin { + i = iMid + 1 + } else { + iMax = iMid + } + } + + for ; i < len(lcTable); i++ { + lc = lcTable[i] + if lc.chMin > chMax { + return + } + chMinT = lc.chMin + if chMinT < chMin { + chMinT = chMin + } + + chMaxT = lc.chMax + if chMaxT > chMax { + chMaxT = chMax + } + + switch lc.op { + case LowercaseSet: + chMinT = rune(lc.data) + chMaxT = rune(lc.data) + break + case LowercaseAdd: + chMinT += lc.data + chMaxT += lc.data + break + case LowercaseBor: + chMinT |= 1 + chMaxT |= 1 + break + case LowercaseBad: + chMinT += (chMinT & 1) + chMaxT += (chMaxT & 1) + break + } + + if chMinT < chMin || chMaxT > chMax { + c.addRange(chMinT, chMaxT) + } + } +} diff --git a/third_party/regexp2/syntax/code.go b/third_party/regexp2/syntax/code.go new file mode 100644 index 000000000..686e822af --- /dev/null +++ b/third_party/regexp2/syntax/code.go @@ -0,0 +1,274 @@ +package syntax + +import ( + "bytes" + "fmt" + "math" +) + +// similar to prog.go in the go regex package...also with comment 'may not belong in this package' + +// File provides operator constants for use by the Builder and the Machine. + +// Implementation notes: +// +// Regexps are built into RegexCodes, which contain an operation array, +// a string table, and some constants. +// +// Each operation is one of the codes below, followed by the integer +// operands specified for each op. +// +// Strings and sets are indices into a string table. + +type InstOp int + +const ( + // lef/back operands description + + Onerep InstOp = 0 // lef,back char,min,max a {n} + Notonerep = 1 // lef,back char,min,max .{n} + Setrep = 2 // lef,back set,min,max [\d]{n} + + Oneloop = 3 // lef,back char,min,max a {,n} + Notoneloop = 4 // lef,back char,min,max .{,n} + Setloop = 5 // lef,back set,min,max [\d]{,n} + + Onelazy = 6 // lef,back char,min,max a {,n}? + Notonelazy = 7 // lef,back char,min,max .{,n}? + Setlazy = 8 // lef,back set,min,max [\d]{,n}? + + One = 9 // lef char a + Notone = 10 // lef char [^a] + Set = 11 // lef set [a-z\s] \w \s \d + + Multi = 12 // lef string abcd + Ref = 13 // lef group \# + + Bol = 14 // ^ + Eol = 15 // $ + Boundary = 16 // \b + Nonboundary = 17 // \B + Beginning = 18 // \A + Start = 19 // \G + EndZ = 20 // \Z + End = 21 // \Z + + Nothing = 22 // Reject! + + // Primitive control structures + + Lazybranch = 23 // back jump straight first + Branchmark = 24 // back jump branch first for loop + Lazybranchmark = 25 // back jump straight first for loop + Nullcount = 26 // back val set counter, null mark + Setcount = 27 // back val set counter, make mark + Branchcount = 28 // back jump,limit branch++ if zero<=c impl group slots + Capsize int // number of impl group slots + FcPrefix *Prefix // the set of candidate first characters (may be null) + BmPrefix *BmPrefix // the fixed prefix string as a Boyer-Moore machine (may be null) + Anchors AnchorLoc // the set of zero-length start anchors (RegexFCD.Bol, etc) + RightToLeft bool // true if right to left +} + +func opcodeBacktracks(op InstOp) bool { + op &= Mask + + switch op { + case Oneloop, Notoneloop, Setloop, Onelazy, Notonelazy, Setlazy, Lazybranch, Branchmark, Lazybranchmark, + Nullcount, Setcount, Branchcount, Lazybranchcount, Setmark, Capturemark, Getmark, Setjump, Backjump, + Forejump, Goto: + return true + + default: + return false + } +} + +func opcodeSize(op InstOp) int { + op &= Mask + + switch op { + case Nothing, Bol, Eol, Boundary, Nonboundary, ECMABoundary, NonECMABoundary, Beginning, Start, EndZ, + End, Nullmark, Setmark, Getmark, Setjump, Backjump, Forejump, Stop: + return 1 + + case One, Notone, Multi, Ref, Testref, Goto, Nullcount, Setcount, Lazybranch, Branchmark, Lazybranchmark, + Prune, Set: + return 2 + + case Capturemark, Branchcount, Lazybranchcount, Onerep, Notonerep, Oneloop, Notoneloop, Onelazy, Notonelazy, + Setlazy, Setrep, Setloop: + return 3 + + default: + panic(fmt.Errorf("Unexpected op code: %v", op)) + } +} + +var codeStr = []string{ + "Onerep", "Notonerep", "Setrep", + "Oneloop", "Notoneloop", "Setloop", + "Onelazy", "Notonelazy", "Setlazy", + "One", "Notone", "Set", + "Multi", "Ref", + "Bol", "Eol", "Boundary", "Nonboundary", "Beginning", "Start", "EndZ", "End", + "Nothing", + "Lazybranch", "Branchmark", "Lazybranchmark", + "Nullcount", "Setcount", "Branchcount", "Lazybranchcount", + "Nullmark", "Setmark", "Capturemark", "Getmark", + "Setjump", "Backjump", "Forejump", "Testref", "Goto", + "Prune", "Stop", + "ECMABoundary", "NonECMABoundary", +} + +func operatorDescription(op InstOp) string { + desc := codeStr[op&Mask] + if (op & Ci) != 0 { + desc += "-Ci" + } + if (op & Rtl) != 0 { + desc += "-Rtl" + } + if (op & Back) != 0 { + desc += "-Back" + } + if (op & Back2) != 0 { + desc += "-Back2" + } + + return desc +} + +// OpcodeDescription is a humman readable string of the specific offset +func (c *Code) OpcodeDescription(offset int) string { + buf := &bytes.Buffer{} + + op := InstOp(c.Codes[offset]) + fmt.Fprintf(buf, "%06d ", offset) + + if opcodeBacktracks(op & Mask) { + buf.WriteString("*") + } else { + buf.WriteString(" ") + } + buf.WriteString(operatorDescription(op)) + buf.WriteString("(") + op &= Mask + + switch op { + case One, Notone, Onerep, Notonerep, Oneloop, Notoneloop, Onelazy, Notonelazy: + buf.WriteString("Ch = ") + buf.WriteString(CharDescription(rune(c.Codes[offset+1]))) + + case Set, Setrep, Setloop, Setlazy: + buf.WriteString("Set = ") + buf.WriteString(c.Sets[c.Codes[offset+1]].String()) + + case Multi: + fmt.Fprintf(buf, "String = %s", string(c.Strings[c.Codes[offset+1]])) + + case Ref, Testref: + fmt.Fprintf(buf, "Index = %d", c.Codes[offset+1]) + + case Capturemark: + fmt.Fprintf(buf, "Index = %d", c.Codes[offset+1]) + if c.Codes[offset+2] != -1 { + fmt.Fprintf(buf, ", Unindex = %d", c.Codes[offset+2]) + } + + case Nullcount, Setcount: + fmt.Fprintf(buf, "Value = %d", c.Codes[offset+1]) + + case Goto, Lazybranch, Branchmark, Lazybranchmark, Branchcount, Lazybranchcount: + fmt.Fprintf(buf, "Addr = %d", c.Codes[offset+1]) + } + + switch op { + case Onerep, Notonerep, Oneloop, Notoneloop, Onelazy, Notonelazy, Setrep, Setloop, Setlazy: + buf.WriteString(", Rep = ") + if c.Codes[offset+2] == math.MaxInt32 { + buf.WriteString("inf") + } else { + fmt.Fprintf(buf, "%d", c.Codes[offset+2]) + } + + case Branchcount, Lazybranchcount: + buf.WriteString(", Limit = ") + if c.Codes[offset+2] == math.MaxInt32 { + buf.WriteString("inf") + } else { + fmt.Fprintf(buf, "%d", c.Codes[offset+2]) + } + + } + + buf.WriteString(")") + + return buf.String() +} + +func (c *Code) Dump() string { + buf := &bytes.Buffer{} + + if c.RightToLeft { + fmt.Fprintln(buf, "Direction: right-to-left") + } else { + fmt.Fprintln(buf, "Direction: left-to-right") + } + if c.FcPrefix == nil { + fmt.Fprintln(buf, "Firstchars: n/a") + } else { + fmt.Fprintf(buf, "Firstchars: %v\n", c.FcPrefix.PrefixSet.String()) + } + + if c.BmPrefix == nil { + fmt.Fprintln(buf, "Prefix: n/a") + } else { + fmt.Fprintf(buf, "Prefix: %v\n", Escape(c.BmPrefix.String())) + } + + fmt.Fprintf(buf, "Anchors: %v\n", c.Anchors) + fmt.Fprintln(buf) + + if c.BmPrefix != nil { + fmt.Fprintln(buf, "BoyerMoore:") + fmt.Fprintln(buf, c.BmPrefix.Dump(" ")) + } + for i := 0; i < len(c.Codes); i += opcodeSize(InstOp(c.Codes[i])) { + fmt.Fprintln(buf, c.OpcodeDescription(i)) + } + + return buf.String() +} diff --git a/third_party/regexp2/syntax/escape.go b/third_party/regexp2/syntax/escape.go new file mode 100644 index 000000000..609df1073 --- /dev/null +++ b/third_party/regexp2/syntax/escape.go @@ -0,0 +1,94 @@ +package syntax + +import ( + "bytes" + "strconv" + "strings" + "unicode" +) + +func Escape(input string) string { + b := &bytes.Buffer{} + for _, r := range input { + escape(b, r, false) + } + return b.String() +} + +const meta = `\.+*?()|[]{}^$# ` + +func escape(b *bytes.Buffer, r rune, force bool) { + if unicode.IsPrint(r) { + if strings.IndexRune(meta, r) >= 0 || force { + b.WriteRune('\\') + } + b.WriteRune(r) + return + } + + switch r { + case '\a': + b.WriteString(`\a`) + case '\f': + b.WriteString(`\f`) + case '\n': + b.WriteString(`\n`) + case '\r': + b.WriteString(`\r`) + case '\t': + b.WriteString(`\t`) + case '\v': + b.WriteString(`\v`) + default: + if r < 0x100 { + b.WriteString(`\x`) + s := strconv.FormatInt(int64(r), 16) + if len(s) == 1 { + b.WriteRune('0') + } + b.WriteString(s) + break + } + b.WriteString(`\u`) + b.WriteString(strconv.FormatInt(int64(r), 16)) + } +} + +func Unescape(input string) (string, error) { + idx := strings.IndexRune(input, '\\') + // no slashes means no unescape needed + if idx == -1 { + return input, nil + } + + buf := bytes.NewBufferString(input[:idx]) + // get the runes for the rest of the string -- we're going full parser scan on this + + p := parser{} + p.setPattern(input[idx+1:]) + for { + if p.rightMost() { + return "", p.getErr(ErrIllegalEndEscape) + } + r, err := p.scanCharEscape() + if err != nil { + return "", err + } + buf.WriteRune(r) + // are we done? + if p.rightMost() { + return buf.String(), nil + } + + r = p.moveRightGetChar() + for r != '\\' { + buf.WriteRune(r) + if p.rightMost() { + // we're done, no more slashes + return buf.String(), nil + } + // keep scanning until we get another slash + r = p.moveRightGetChar() + } + } +} diff --git a/third_party/regexp2/syntax/fuzz.go b/third_party/regexp2/syntax/fuzz.go new file mode 100644 index 000000000..ee863866d --- /dev/null +++ b/third_party/regexp2/syntax/fuzz.go @@ -0,0 +1,20 @@ +// +build gofuzz + +package syntax + +// Fuzz is the input point for go-fuzz +func Fuzz(data []byte) int { + sdata := string(data) + tree, err := Parse(sdata, RegexOptions(0)) + if err != nil { + return 0 + } + + // translate it to code + _, err = Write(tree) + if err != nil { + panic(err) + } + + return 1 +} diff --git a/third_party/regexp2/syntax/parser.go b/third_party/regexp2/syntax/parser.go new file mode 100644 index 000000000..4ff0aaa83 --- /dev/null +++ b/third_party/regexp2/syntax/parser.go @@ -0,0 +1,2262 @@ +package syntax + +import ( + "fmt" + "math" + "os" + "sort" + "strconv" + "unicode" +) + +type RegexOptions int32 + +const ( + IgnoreCase RegexOptions = 0x0001 // "i" + Multiline = 0x0002 // "m" + ExplicitCapture = 0x0004 // "n" + Compiled = 0x0008 // "c" + Singleline = 0x0010 // "s" + IgnorePatternWhitespace = 0x0020 // "x" + RightToLeft = 0x0040 // "r" + Debug = 0x0080 // "d" + ECMAScript = 0x0100 // "e" + RE2 = 0x0200 // RE2 compat mode + Unicode = 0x0400 // "u" +) + +func optionFromCode(ch rune) RegexOptions { + // case-insensitive + switch ch { + case 'i', 'I': + return IgnoreCase + case 'r', 'R': + return RightToLeft + case 'm', 'M': + return Multiline + case 'n', 'N': + return ExplicitCapture + case 's', 'S': + return Singleline + case 'x', 'X': + return IgnorePatternWhitespace + case 'd', 'D': + return Debug + case 'e', 'E': + return ECMAScript + case 'u', 'U': + return Unicode + default: + return 0 + } +} + +// An Error describes a failure to parse a regular expression +// and gives the offending expression. +type Error struct { + Code ErrorCode + Expr string + Args []interface{} +} + +func (e *Error) Error() string { + if len(e.Args) == 0 { + return "error parsing regexp: " + e.Code.String() + " in `" + e.Expr + "`" + } + return "error parsing regexp: " + fmt.Sprintf(e.Code.String(), e.Args...) + " in `" + e.Expr + "`" +} + +// An ErrorCode describes a failure to parse a regular expression. +type ErrorCode string + +const ( + // internal issue + ErrInternalError ErrorCode = "regexp/syntax: internal error" + // Parser errors + ErrUnterminatedComment = "unterminated comment" + ErrInvalidCharRange = "invalid character class range" + ErrInvalidRepeatSize = "invalid repeat count" + ErrInvalidUTF8 = "invalid UTF-8" + ErrCaptureGroupOutOfRange = "capture group number out of range" + ErrUnexpectedParen = "unexpected )" + ErrMissingParen = "missing closing )" + ErrMissingBrace = "missing closing }" + ErrInvalidRepeatOp = "invalid nested repetition operator" + ErrMissingRepeatArgument = "missing argument to repetition operator" + ErrConditionalExpression = "illegal conditional (?(...)) expression" + ErrTooManyAlternates = "too many | in (?()|)" + ErrUnrecognizedGrouping = "unrecognized grouping construct: (%v" + ErrInvalidGroupName = "invalid group name: group names must begin with a word character and have a matching terminator" + ErrCapNumNotZero = "capture number cannot be zero" + ErrUndefinedBackRef = "reference to undefined group number %v" + ErrUndefinedNameRef = "reference to undefined group name %v" + ErrAlternationCantCapture = "alternation conditions do not capture and cannot be named" + ErrAlternationCantHaveComment = "alternation conditions cannot be comments" + ErrMalformedReference = "(?(%v) ) malformed" + ErrUndefinedReference = "(?(%v) ) reference to undefined group" + ErrIllegalEndEscape = "illegal \\ at end of pattern" + ErrMalformedSlashP = "malformed \\p{X} character escape" + ErrIncompleteSlashP = "incomplete \\p{X} character escape" + ErrUnknownSlashP = "unknown unicode category, script, or property '%v'" + ErrUnrecognizedEscape = "unrecognized escape sequence \\%v" + ErrMissingControl = "missing control character" + ErrUnrecognizedControl = "unrecognized control character" + ErrTooFewHex = "insufficient hexadecimal digits" + ErrInvalidHex = "hex values may not be larger than 0x10FFFF" + ErrMalformedNameRef = "malformed \\k<...> named back reference" + ErrBadClassInCharRange = "cannot include class \\%v in character range" + ErrUnterminatedBracket = "unterminated [] set" + ErrSubtractionMustBeLast = "a subtraction must be the last element in a character class" + ErrReversedCharRange = "[%c-%c] range in reverse order" +) + +func (e ErrorCode) String() string { + return string(e) +} + +type parser struct { + stack *regexNode + group *regexNode + alternation *regexNode + concatenation *regexNode + unit *regexNode + + patternRaw string + pattern []rune + + currentPos int + specialCase *unicode.SpecialCase + + autocap int + capcount int + captop int + capsize int + + caps map[int]int + capnames map[string]int + + capnumlist []int + capnamelist []string + + options RegexOptions + optionsStack []RegexOptions + ignoreNextParen bool +} + +const ( + maxValueDiv10 int = math.MaxInt32 / 10 + maxValueMod10 = math.MaxInt32 % 10 +) + +// Parse converts a regex string into a parse tree +func Parse(re string, op RegexOptions) (*RegexTree, error) { + p := parser{ + options: op, + caps: make(map[int]int), + } + p.setPattern(re) + + if err := p.countCaptures(); err != nil { + return nil, err + } + + p.reset(op) + root, err := p.scanRegex() + + if err != nil { + return nil, err + } + tree := &RegexTree{ + root: root, + caps: p.caps, + capnumlist: p.capnumlist, + captop: p.captop, + Capnames: p.capnames, + Caplist: p.capnamelist, + options: op, + } + + if tree.options&Debug > 0 { + os.Stdout.WriteString(tree.Dump()) + } + + return tree, nil +} + +func (p *parser) setPattern(pattern string) { + p.patternRaw = pattern + p.pattern = make([]rune, 0, len(pattern)) + + //populate our rune array to handle utf8 encoding + for _, r := range pattern { + p.pattern = append(p.pattern, r) + } +} +func (p *parser) getErr(code ErrorCode, args ...interface{}) error { + return &Error{Code: code, Expr: p.patternRaw, Args: args} +} + +func (p *parser) noteCaptureSlot(i, pos int) { + if _, ok := p.caps[i]; !ok { + // the rhs of the hashtable isn't used in the parser + p.caps[i] = pos + p.capcount++ + + if p.captop <= i { + if i == math.MaxInt32 { + p.captop = i + } else { + p.captop = i + 1 + } + } + } +} + +func (p *parser) noteCaptureName(name string, pos int) { + if p.capnames == nil { + p.capnames = make(map[string]int) + } + + if _, ok := p.capnames[name]; !ok { + p.capnames[name] = pos + p.capnamelist = append(p.capnamelist, name) + } +} + +func (p *parser) assignNameSlots() { + if p.capnames != nil { + for _, name := range p.capnamelist { + for p.isCaptureSlot(p.autocap) { + p.autocap++ + } + pos := p.capnames[name] + p.capnames[name] = p.autocap + p.noteCaptureSlot(p.autocap, pos) + + p.autocap++ + } + } + + // if the caps array has at least one gap, construct the list of used slots + if p.capcount < p.captop { + p.capnumlist = make([]int, p.capcount) + i := 0 + + for k := range p.caps { + p.capnumlist[i] = k + i++ + } + + sort.Ints(p.capnumlist) + } + + // merge capsnumlist into capnamelist + if p.capnames != nil || p.capnumlist != nil { + var oldcapnamelist []string + var next int + var k int + + if p.capnames == nil { + oldcapnamelist = nil + p.capnames = make(map[string]int) + p.capnamelist = []string{} + next = -1 + } else { + oldcapnamelist = p.capnamelist + p.capnamelist = []string{} + next = p.capnames[oldcapnamelist[0]] + } + + for i := 0; i < p.capcount; i++ { + j := i + if p.capnumlist != nil { + j = p.capnumlist[i] + } + + if next == j { + p.capnamelist = append(p.capnamelist, oldcapnamelist[k]) + k++ + + if k == len(oldcapnamelist) { + next = -1 + } else { + next = p.capnames[oldcapnamelist[k]] + } + + } else { + //feature: culture? + str := strconv.Itoa(j) + p.capnamelist = append(p.capnamelist, str) + p.capnames[str] = j + } + } + } +} + +func (p *parser) consumeAutocap() int { + r := p.autocap + p.autocap++ + return r +} + +// CountCaptures is a prescanner for deducing the slots used for +// captures by doing a partial tokenization of the pattern. +func (p *parser) countCaptures() error { + var ch rune + + p.noteCaptureSlot(0, 0) + + p.autocap = 1 + + for p.charsRight() > 0 { + pos := p.textpos() + ch = p.moveRightGetChar() + switch ch { + case '\\': + if p.charsRight() > 0 { + p.scanBackslash(true) + } + + case '#': + if p.useOptionX() { + p.moveLeft() + p.scanBlank() + } + + case '[': + p.scanCharSet(false, true) + + case ')': + if !p.emptyOptionsStack() { + p.popOptions() + } + + case '(': + if p.charsRight() >= 2 && p.rightChar(1) == '#' && p.rightChar(0) == '?' { + p.moveLeft() + p.scanBlank() + } else { + p.pushOptions() + if p.charsRight() > 0 && p.rightChar(0) == '?' { + // we have (?... + p.moveRight(1) + + if p.charsRight() > 1 && (p.rightChar(0) == '<' || p.rightChar(0) == '\'') { + // named group: (?<... or (?'... + + p.moveRight(1) + ch = p.rightChar(0) + + if ch != '0' && IsWordChar(ch) { + if ch >= '1' && ch <= '9' { + dec, err := p.scanDecimal() + if err != nil { + return err + } + p.noteCaptureSlot(dec, pos) + } else { + p.noteCaptureName(p.scanCapname(), pos) + } + } + } else if p.useRE2() && p.charsRight() > 2 && (p.rightChar(0) == 'P' && p.rightChar(1) == '<') { + // RE2-compat (?P<) + p.moveRight(2) + ch = p.rightChar(0) + if IsWordChar(ch) { + p.noteCaptureName(p.scanCapname(), pos) + } + + } else { + // (?... + + // get the options if it's an option construct (?cimsx-cimsx...) + p.scanOptions() + + if p.charsRight() > 0 { + if p.rightChar(0) == ')' { + // (?cimsx-cimsx) + p.moveRight(1) + p.popKeepOptions() + } else if p.rightChar(0) == '(' { + // alternation construct: (?(foo)yes|no) + // ignore the next paren so we don't capture the condition + p.ignoreNextParen = true + + // break from here so we don't reset ignoreNextParen + continue + } + } + } + } else { + if !p.useOptionN() && !p.ignoreNextParen { + p.noteCaptureSlot(p.consumeAutocap(), pos) + } + } + } + + p.ignoreNextParen = false + + } + } + + p.assignNameSlots() + return nil +} + +func (p *parser) reset(topopts RegexOptions) { + p.currentPos = 0 + p.autocap = 1 + p.ignoreNextParen = false + + if len(p.optionsStack) > 0 { + p.optionsStack = p.optionsStack[:0] + } + + p.options = topopts + p.stack = nil +} + +func (p *parser) scanRegex() (*regexNode, error) { + ch := '@' // nonspecial ch, means at beginning + isQuant := false + + p.startGroup(newRegexNodeMN(ntCapture, p.options, 0, -1)) + + for p.charsRight() > 0 { + wasPrevQuantifier := isQuant + isQuant = false + + if err := p.scanBlank(); err != nil { + return nil, err + } + + startpos := p.textpos() + + // move past all of the normal characters. We'll stop when we hit some kind of control character, + // or if IgnorePatternWhiteSpace is on, we'll stop when we see some whitespace. + if p.useOptionX() { + for p.charsRight() > 0 { + ch = p.rightChar(0) + //UGLY: clean up, this is ugly + if !(!isStopperX(ch) || (ch == '{' && !p.isTrueQuantifier())) { + break + } + p.moveRight(1) + } + } else { + for p.charsRight() > 0 { + ch = p.rightChar(0) + if !(!isSpecial(ch) || ch == '{' && !p.isTrueQuantifier()) { + break + } + p.moveRight(1) + } + } + + endpos := p.textpos() + + p.scanBlank() + + if p.charsRight() == 0 { + ch = '!' // nonspecial, means at end + } else if ch = p.rightChar(0); isSpecial(ch) { + isQuant = isQuantifier(ch) + p.moveRight(1) + } else { + ch = ' ' // nonspecial, means at ordinary char + } + + if startpos < endpos { + cchUnquantified := endpos - startpos + if isQuant { + cchUnquantified-- + } + wasPrevQuantifier = false + + if cchUnquantified > 0 { + p.addToConcatenate(startpos, cchUnquantified, false) + } + + if isQuant { + p.addUnitOne(p.charAt(endpos - 1)) + } + } + + switch ch { + case '!': + goto BreakOuterScan + + case ' ': + goto ContinueOuterScan + + case '[': + cc, err := p.scanCharSet(p.useOptionI(), false) + if err != nil { + return nil, err + } + p.addUnitSet(cc) + + case '(': + p.pushOptions() + + if grouper, err := p.scanGroupOpen(); err != nil { + return nil, err + } else if grouper == nil { + p.popKeepOptions() + } else { + p.pushGroup() + p.startGroup(grouper) + } + + continue + + case '|': + p.addAlternate() + goto ContinueOuterScan + + case ')': + if p.emptyStack() { + return nil, p.getErr(ErrUnexpectedParen) + } + + if err := p.addGroup(); err != nil { + return nil, err + } + if err := p.popGroup(); err != nil { + return nil, err + } + p.popOptions() + + if p.unit == nil { + goto ContinueOuterScan + } + + case '\\': + n, err := p.scanBackslash(false) + if err != nil { + return nil, err + } + p.addUnitNode(n) + + case '^': + if p.useOptionM() { + p.addUnitType(ntBol) + } else { + p.addUnitType(ntBeginning) + } + + case '$': + if p.useOptionM() { + p.addUnitType(ntEol) + } else { + p.addUnitType(ntEndZ) + } + + case '.': + if p.useOptionS() { + p.addUnitSet(AnyClass()) + } else if p.useOptionE() { + p.addUnitSet(ECMAAnyClass()) + } else { + p.addUnitNotone('\n') + } + + case '{', '*', '+', '?': + if p.unit == nil { + if wasPrevQuantifier { + return nil, p.getErr(ErrInvalidRepeatOp) + } else { + return nil, p.getErr(ErrMissingRepeatArgument) + } + } + p.moveLeft() + + default: + return nil, p.getErr(ErrInternalError) + } + + if err := p.scanBlank(); err != nil { + return nil, err + } + + if p.charsRight() > 0 { + isQuant = p.isTrueQuantifier() + } + if p.charsRight() == 0 || !isQuant { + //maintain odd C# assignment order -- not sure if required, could clean up? + p.addConcatenate() + goto ContinueOuterScan + } + + ch = p.moveRightGetChar() + + // Handle quantifiers + for p.unit != nil { + var min, max int + var lazy bool + + switch ch { + case '*': + min = 0 + max = math.MaxInt32 + + case '?': + min = 0 + max = 1 + + case '+': + min = 1 + max = math.MaxInt32 + + case '{': + { + var err error + startpos = p.textpos() + if min, err = p.scanDecimal(); err != nil { + return nil, err + } + max = min + if startpos < p.textpos() { + if p.charsRight() > 0 && p.rightChar(0) == ',' { + p.moveRight(1) + if p.charsRight() == 0 || p.rightChar(0) == '}' { + max = math.MaxInt32 + } else { + if max, err = p.scanDecimal(); err != nil { + return nil, err + } + } + } + } + + if startpos == p.textpos() || p.charsRight() == 0 || p.moveRightGetChar() != '}' { + p.addConcatenate() + p.textto(startpos - 1) + goto ContinueOuterScan + } + } + + default: + return nil, p.getErr(ErrInternalError) + } + + if err := p.scanBlank(); err != nil { + return nil, err + } + + if p.charsRight() == 0 || p.rightChar(0) != '?' { + lazy = false + } else { + p.moveRight(1) + lazy = true + } + + if min > max { + return nil, p.getErr(ErrInvalidRepeatSize) + } + + p.addConcatenate3(lazy, min, max) + } + + ContinueOuterScan: + } + +BreakOuterScan: + ; + + if !p.emptyStack() { + return nil, p.getErr(ErrMissingParen) + } + + if err := p.addGroup(); err != nil { + return nil, err + } + + return p.unit, nil + +} + +/* + * Simple parsing for replacement patterns + */ +func (p *parser) scanReplacement() (*regexNode, error) { + var c, startpos int + + p.concatenation = newRegexNode(ntConcatenate, p.options) + + for { + c = p.charsRight() + if c == 0 { + break + } + + startpos = p.textpos() + + for c > 0 && p.rightChar(0) != '$' { + p.moveRight(1) + c-- + } + + p.addToConcatenate(startpos, p.textpos()-startpos, true) + + if c > 0 { + if p.moveRightGetChar() == '$' { + n, err := p.scanDollar() + if err != nil { + return nil, err + } + p.addUnitNode(n) + } + p.addConcatenate() + } + } + + return p.concatenation, nil +} + +/* + * Scans $ patterns recognized within replacement patterns + */ +func (p *parser) scanDollar() (*regexNode, error) { + if p.charsRight() == 0 { + return newRegexNodeCh(ntOne, p.options, '$'), nil + } + + ch := p.rightChar(0) + angled := false + backpos := p.textpos() + lastEndPos := backpos + + // Note angle + + if ch == '{' && p.charsRight() > 1 { + angled = true + p.moveRight(1) + ch = p.rightChar(0) + } + + // Try to parse backreference: \1 or \{1} or \{cap} + + if ch >= '0' && ch <= '9' { + if !angled && p.useOptionE() { + capnum := -1 + newcapnum := int(ch - '0') + p.moveRight(1) + if p.isCaptureSlot(newcapnum) { + capnum = newcapnum + lastEndPos = p.textpos() + } + + for p.charsRight() > 0 { + ch = p.rightChar(0) + if ch < '0' || ch > '9' { + break + } + digit := int(ch - '0') + if newcapnum > maxValueDiv10 || (newcapnum == maxValueDiv10 && digit > maxValueMod10) { + return nil, p.getErr(ErrCaptureGroupOutOfRange) + } + + newcapnum = newcapnum*10 + digit + + p.moveRight(1) + if p.isCaptureSlot(newcapnum) { + capnum = newcapnum + lastEndPos = p.textpos() + } + } + p.textto(lastEndPos) + if capnum >= 0 { + return newRegexNodeM(ntRef, p.options, capnum), nil + } + } else { + capnum, err := p.scanDecimal() + if err != nil { + return nil, err + } + if !angled || p.charsRight() > 0 && p.moveRightGetChar() == '}' { + if p.isCaptureSlot(capnum) { + return newRegexNodeM(ntRef, p.options, capnum), nil + } + } + } + } else if angled && IsWordChar(ch) { + capname := p.scanCapname() + + if p.charsRight() > 0 && p.moveRightGetChar() == '}' { + if p.isCaptureName(capname) { + return newRegexNodeM(ntRef, p.options, p.captureSlotFromName(capname)), nil + } + } + } else if !angled { + capnum := 1 + + switch ch { + case '$': + p.moveRight(1) + return newRegexNodeCh(ntOne, p.options, '$'), nil + case '&': + capnum = 0 + case '`': + capnum = replaceLeftPortion + case '\'': + capnum = replaceRightPortion + case '+': + capnum = replaceLastGroup + case '_': + capnum = replaceWholeString + } + + if capnum != 1 { + p.moveRight(1) + return newRegexNodeM(ntRef, p.options, capnum), nil + } + } + + // unrecognized $: literalize + + p.textto(backpos) + return newRegexNodeCh(ntOne, p.options, '$'), nil +} + +// scanGroupOpen scans chars following a '(' (not counting the '('), and returns +// a RegexNode for the type of group scanned, or nil if the group +// simply changed options (?cimsx-cimsx) or was a comment (#...). +func (p *parser) scanGroupOpen() (*regexNode, error) { + var ch rune + var nt nodeType + var err error + close := '>' + start := p.textpos() + + // just return a RegexNode if we have: + // 1. "(" followed by nothing + // 2. "(x" where x != ? + // 3. "(?)" + if p.charsRight() == 0 || p.rightChar(0) != '?' || (p.rightChar(0) == '?' && (p.charsRight() > 1 && p.rightChar(1) == ')')) { + if p.useOptionN() || p.ignoreNextParen { + p.ignoreNextParen = false + return newRegexNode(ntGroup, p.options), nil + } + return newRegexNodeMN(ntCapture, p.options, p.consumeAutocap(), -1), nil + } + + p.moveRight(1) + + for { + if p.charsRight() == 0 { + break + } + + switch ch = p.moveRightGetChar(); ch { + case ':': + nt = ntGroup + + case '=': + p.options &= ^RightToLeft + nt = ntRequire + + case '!': + p.options &= ^RightToLeft + nt = ntPrevent + + case '>': + nt = ntGreedy + + case '\'': + close = '\'' + fallthrough + + case '<': + if p.charsRight() == 0 { + goto BreakRecognize + } + + switch ch = p.moveRightGetChar(); ch { + case '=': + if close == '\'' { + goto BreakRecognize + } + + p.options |= RightToLeft + nt = ntRequire + + case '!': + if close == '\'' { + goto BreakRecognize + } + + p.options |= RightToLeft + nt = ntPrevent + + default: + p.moveLeft() + capnum := -1 + uncapnum := -1 + proceed := false + + // grab part before - + + if ch >= '0' && ch <= '9' { + if capnum, err = p.scanDecimal(); err != nil { + return nil, err + } + + if !p.isCaptureSlot(capnum) { + capnum = -1 + } + + // check if we have bogus characters after the number + if p.charsRight() > 0 && !(p.rightChar(0) == close || p.rightChar(0) == '-') { + return nil, p.getErr(ErrInvalidGroupName) + } + if capnum == 0 { + return nil, p.getErr(ErrCapNumNotZero) + } + } else if IsWordChar(ch) { + capname := p.scanCapname() + + if p.isCaptureName(capname) { + capnum = p.captureSlotFromName(capname) + } + + // check if we have bogus character after the name + if p.charsRight() > 0 && !(p.rightChar(0) == close || p.rightChar(0) == '-') { + return nil, p.getErr(ErrInvalidGroupName) + } + } else if ch == '-' { + proceed = true + } else { + // bad group name - starts with something other than a word character and isn't a number + return nil, p.getErr(ErrInvalidGroupName) + } + + // grab part after - if any + + if (capnum != -1 || proceed == true) && p.charsRight() > 0 && p.rightChar(0) == '-' { + p.moveRight(1) + + //no more chars left, no closing char, etc + if p.charsRight() == 0 { + return nil, p.getErr(ErrInvalidGroupName) + } + + ch = p.rightChar(0) + if ch >= '0' && ch <= '9' { + if uncapnum, err = p.scanDecimal(); err != nil { + return nil, err + } + + if !p.isCaptureSlot(uncapnum) { + return nil, p.getErr(ErrUndefinedBackRef, uncapnum) + } + + // check if we have bogus characters after the number + if p.charsRight() > 0 && p.rightChar(0) != close { + return nil, p.getErr(ErrInvalidGroupName) + } + } else if IsWordChar(ch) { + uncapname := p.scanCapname() + + if !p.isCaptureName(uncapname) { + return nil, p.getErr(ErrUndefinedNameRef, uncapname) + } + uncapnum = p.captureSlotFromName(uncapname) + + // check if we have bogus character after the name + if p.charsRight() > 0 && p.rightChar(0) != close { + return nil, p.getErr(ErrInvalidGroupName) + } + } else { + // bad group name - starts with something other than a word character and isn't a number + return nil, p.getErr(ErrInvalidGroupName) + } + } + + // actually make the node + + if (capnum != -1 || uncapnum != -1) && p.charsRight() > 0 && p.moveRightGetChar() == close { + return newRegexNodeMN(ntCapture, p.options, capnum, uncapnum), nil + } + goto BreakRecognize + } + + case '(': + // alternation construct (?(...) | ) + + parenPos := p.textpos() + if p.charsRight() > 0 { + ch = p.rightChar(0) + + // check if the alternation condition is a backref + if ch >= '0' && ch <= '9' { + var capnum int + if capnum, err = p.scanDecimal(); err != nil { + return nil, err + } + if p.charsRight() > 0 && p.moveRightGetChar() == ')' { + if p.isCaptureSlot(capnum) { + return newRegexNodeM(ntTestref, p.options, capnum), nil + } + return nil, p.getErr(ErrUndefinedReference, capnum) + } + + return nil, p.getErr(ErrMalformedReference, capnum) + + } else if IsWordChar(ch) { + capname := p.scanCapname() + + if p.isCaptureName(capname) && p.charsRight() > 0 && p.moveRightGetChar() == ')' { + return newRegexNodeM(ntTestref, p.options, p.captureSlotFromName(capname)), nil + } + } + } + // not a backref + nt = ntTestgroup + p.textto(parenPos - 1) // jump to the start of the parentheses + p.ignoreNextParen = true // but make sure we don't try to capture the insides + + charsRight := p.charsRight() + if charsRight >= 3 && p.rightChar(1) == '?' { + rightchar2 := p.rightChar(2) + // disallow comments in the condition + if rightchar2 == '#' { + return nil, p.getErr(ErrAlternationCantHaveComment) + } + + // disallow named capture group (?<..>..) in the condition + if rightchar2 == '\'' { + return nil, p.getErr(ErrAlternationCantCapture) + } + + if charsRight >= 4 && (rightchar2 == '<' && p.rightChar(3) != '!' && p.rightChar(3) != '=') { + return nil, p.getErr(ErrAlternationCantCapture) + } + } + + case 'P': + if p.useRE2() { + // support for P syntax + if p.charsRight() < 3 { + goto BreakRecognize + } + + ch = p.moveRightGetChar() + if ch != '<' { + goto BreakRecognize + } + + ch = p.moveRightGetChar() + p.moveLeft() + + if IsWordChar(ch) { + capnum := -1 + capname := p.scanCapname() + + if p.isCaptureName(capname) { + capnum = p.captureSlotFromName(capname) + } + + // check if we have bogus character after the name + if p.charsRight() > 0 && p.rightChar(0) != '>' { + return nil, p.getErr(ErrInvalidGroupName) + } + + // actually make the node + + if capnum != -1 && p.charsRight() > 0 && p.moveRightGetChar() == '>' { + return newRegexNodeMN(ntCapture, p.options, capnum, -1), nil + } + goto BreakRecognize + + } else { + // bad group name - starts with something other than a word character and isn't a number + return nil, p.getErr(ErrInvalidGroupName) + } + } + // if we're not using RE2 compat mode then + // we just behave like normal + fallthrough + + default: + p.moveLeft() + + nt = ntGroup + // disallow options in the children of a testgroup node + if p.group.t != ntTestgroup { + p.scanOptions() + } + if p.charsRight() == 0 { + goto BreakRecognize + } + + if ch = p.moveRightGetChar(); ch == ')' { + return nil, nil + } + + if ch != ':' { + goto BreakRecognize + } + + } + + return newRegexNode(nt, p.options), nil + } + +BreakRecognize: + + // break Recognize comes here + + return nil, p.getErr(ErrUnrecognizedGrouping, string(p.pattern[start:p.textpos()])) +} + +// scans backslash specials and basics +func (p *parser) scanBackslash(scanOnly bool) (*regexNode, error) { + + if p.charsRight() == 0 { + return nil, p.getErr(ErrIllegalEndEscape) + } + + switch ch := p.rightChar(0); ch { + case 'b', 'B', 'A', 'G', 'Z', 'z': + p.moveRight(1) + return newRegexNode(p.typeFromCode(ch), p.options), nil + + case 'w': + p.moveRight(1) + if p.useOptionE() || p.useRE2() { + return newRegexNodeSet(ntSet, p.options, ECMAWordClass()), nil + } + return newRegexNodeSet(ntSet, p.options, WordClass()), nil + + case 'W': + p.moveRight(1) + if p.useOptionE() || p.useRE2() { + return newRegexNodeSet(ntSet, p.options, NotECMAWordClass()), nil + } + return newRegexNodeSet(ntSet, p.options, NotWordClass()), nil + + case 's': + p.moveRight(1) + if p.useOptionE() { + return newRegexNodeSet(ntSet, p.options, ECMASpaceClass()), nil + } else if p.useRE2() { + return newRegexNodeSet(ntSet, p.options, RE2SpaceClass()), nil + } + return newRegexNodeSet(ntSet, p.options, SpaceClass()), nil + + case 'S': + p.moveRight(1) + if p.useOptionE() { + return newRegexNodeSet(ntSet, p.options, NotECMASpaceClass()), nil + } else if p.useRE2() { + return newRegexNodeSet(ntSet, p.options, NotRE2SpaceClass()), nil + } + return newRegexNodeSet(ntSet, p.options, NotSpaceClass()), nil + + case 'd': + p.moveRight(1) + if p.useOptionE() || p.useRE2() { + return newRegexNodeSet(ntSet, p.options, ECMADigitClass()), nil + } + return newRegexNodeSet(ntSet, p.options, DigitClass()), nil + + case 'D': + p.moveRight(1) + if p.useOptionE() || p.useRE2() { + return newRegexNodeSet(ntSet, p.options, NotECMADigitClass()), nil + } + return newRegexNodeSet(ntSet, p.options, NotDigitClass()), nil + + case 'p', 'P': + p.moveRight(1) + prop, err := p.parseProperty() + if err != nil { + return nil, err + } + cc := &CharSet{} + cc.addCategory(prop, (ch != 'p'), p.useOptionI(), p.patternRaw) + if p.useOptionI() { + cc.addLowercase() + } + + return newRegexNodeSet(ntSet, p.options, cc), nil + + default: + return p.scanBasicBackslash(scanOnly) + } +} + +// Scans \-style backreferences and character escapes +func (p *parser) scanBasicBackslash(scanOnly bool) (*regexNode, error) { + if p.charsRight() == 0 { + return nil, p.getErr(ErrIllegalEndEscape) + } + angled := false + k := false + close := '\x00' + + backpos := p.textpos() + ch := p.rightChar(0) + + // Allow \k instead of \, which is now deprecated. + + // According to ECMAScript specification, \k is only parsed as a named group reference if + // there is at least one group name in the regexp. + // See https://www.ecma-international.org/ecma-262/#sec-isvalidregularexpressionliteral, step 7. + // Note, during the first (scanOnly) run we may not have all group names scanned, but that's ok. + if ch == 'k' && (!p.useOptionE() || len(p.capnames) > 0) { + if p.charsRight() >= 2 { + p.moveRight(1) + ch = p.moveRightGetChar() + + if ch == '<' || (!p.useOptionE() && ch == '\'') { // No support for \k'name' in ECMAScript + angled = true + if ch == '\'' { + close = '\'' + } else { + close = '>' + } + } + } + + if !angled || p.charsRight() <= 0 { + return nil, p.getErr(ErrMalformedNameRef) + } + + ch = p.rightChar(0) + k = true + + } else if !p.useOptionE() && (ch == '<' || ch == '\'') && p.charsRight() > 1 { // Note angle without \g + angled = true + if ch == '\'' { + close = '\'' + } else { + close = '>' + } + + p.moveRight(1) + ch = p.rightChar(0) + } + + // Try to parse backreference: \<1> or \ + + if angled && ch >= '0' && ch <= '9' { + capnum, err := p.scanDecimal() + if err != nil { + return nil, err + } + + if p.charsRight() > 0 && p.moveRightGetChar() == close { + if p.isCaptureSlot(capnum) { + return newRegexNodeM(ntRef, p.options, capnum), nil + } + return nil, p.getErr(ErrUndefinedBackRef, capnum) + } + } else if !angled && ch >= '1' && ch <= '9' { // Try to parse backreference or octal: \1 + capnum, err := p.scanDecimal() + if err != nil { + return nil, err + } + + if scanOnly { + return nil, nil + } + + if p.isCaptureSlot(capnum) { + return newRegexNodeM(ntRef, p.options, capnum), nil + } + if capnum <= 9 && !p.useOptionE() { + return nil, p.getErr(ErrUndefinedBackRef, capnum) + } + + } else if angled { + capname := p.scanCapname() + + if capname != "" && p.charsRight() > 0 && p.moveRightGetChar() == close { + + if scanOnly { + return nil, nil + } + + if p.isCaptureName(capname) { + return newRegexNodeM(ntRef, p.options, p.captureSlotFromName(capname)), nil + } + return nil, p.getErr(ErrUndefinedNameRef, capname) + } else { + if k { + return nil, p.getErr(ErrMalformedNameRef) + } + } + } + + // Not backreference: must be char code + + p.textto(backpos) + ch, err := p.scanCharEscape() + if err != nil { + return nil, err + } + + if scanOnly { + return nil, nil + } + + if p.useOptionI() { + ch = unicode.ToLower(ch) + } + + return newRegexNodeCh(ntOne, p.options, ch), nil +} + +// Scans X for \p{X} or \P{X} +func (p *parser) parseProperty() (string, error) { + // RE2 and PCRE supports \pX syntax (no {} and only 1 letter unicode cats supported) + // since this is purely additive syntax it's not behind a flag + if p.charsRight() >= 1 && p.rightChar(0) != '{' { + ch := string(p.moveRightGetChar()) + // check if it's a valid cat + if !isValidUnicodeCat(ch) { + return "", p.getErr(ErrUnknownSlashP, ch) + } + return ch, nil + } + + if p.charsRight() < 3 { + return "", p.getErr(ErrIncompleteSlashP) + } + ch := p.moveRightGetChar() + if ch != '{' { + return "", p.getErr(ErrMalformedSlashP) + } + + startpos := p.textpos() + for p.charsRight() > 0 { + ch = p.moveRightGetChar() + if !(IsWordChar(ch) || ch == '-') { + p.moveLeft() + break + } + } + capname := string(p.pattern[startpos:p.textpos()]) + + if p.charsRight() == 0 || p.moveRightGetChar() != '}' { + return "", p.getErr(ErrIncompleteSlashP) + } + + if !isValidUnicodeCat(capname) { + return "", p.getErr(ErrUnknownSlashP, capname) + } + + return capname, nil +} + +// Returns ReNode type for zero-length assertions with a \ code. +func (p *parser) typeFromCode(ch rune) nodeType { + switch ch { + case 'b': + if p.useOptionE() { + return ntECMABoundary + } + return ntBoundary + case 'B': + if p.useOptionE() { + return ntNonECMABoundary + } + return ntNonboundary + case 'A': + return ntBeginning + case 'G': + return ntStart + case 'Z': + return ntEndZ + case 'z': + return ntEnd + default: + return ntNothing + } +} + +// Scans whitespace or x-mode comments. +func (p *parser) scanBlank() error { + if p.useOptionX() { + for { + for p.charsRight() > 0 && isSpace(p.rightChar(0)) { + p.moveRight(1) + } + + if p.charsRight() == 0 { + break + } + + if p.rightChar(0) == '#' { + for p.charsRight() > 0 && p.rightChar(0) != '\n' { + p.moveRight(1) + } + } else if p.charsRight() >= 3 && p.rightChar(2) == '#' && + p.rightChar(1) == '?' && p.rightChar(0) == '(' { + for p.charsRight() > 0 && p.rightChar(0) != ')' { + p.moveRight(1) + } + if p.charsRight() == 0 { + return p.getErr(ErrUnterminatedComment) + } + p.moveRight(1) + } else { + break + } + } + } else { + for { + if p.charsRight() < 3 || p.rightChar(2) != '#' || + p.rightChar(1) != '?' || p.rightChar(0) != '(' { + return nil + } + + for p.charsRight() > 0 && p.rightChar(0) != ')' { + p.moveRight(1) + } + if p.charsRight() == 0 { + return p.getErr(ErrUnterminatedComment) + } + p.moveRight(1) + } + } + return nil +} + +func (p *parser) scanCapname() string { + startpos := p.textpos() + + for p.charsRight() > 0 { + if !IsWordChar(p.moveRightGetChar()) { + p.moveLeft() + break + } + } + + return string(p.pattern[startpos:p.textpos()]) +} + +// Scans contents of [] (not including []'s), and converts to a set. +func (p *parser) scanCharSet(caseInsensitive, scanOnly bool) (*CharSet, error) { + ch := '\x00' + chPrev := '\x00' + inRange := false + firstChar := true + closed := false + + var cc *CharSet + if !scanOnly { + cc = &CharSet{} + } + + if p.charsRight() > 0 && p.rightChar(0) == '^' { + p.moveRight(1) + if !scanOnly { + cc.negate = true + } + } + + for ; p.charsRight() > 0; firstChar = false { + fTranslatedChar := false + ch = p.moveRightGetChar() + if ch == ']' { + if !firstChar { + closed = true + break + } else if p.useOptionE() { + if !scanOnly { + cc.addRanges(NoneClass().ranges) + } + closed = true + break + } + + } else if ch == '\\' && p.charsRight() > 0 { + switch ch = p.moveRightGetChar(); ch { + case 'D', 'd': + if !scanOnly { + if inRange { + return nil, p.getErr(ErrBadClassInCharRange, ch) + } + cc.addDigit(p.useOptionE() || p.useRE2(), ch == 'D', p.patternRaw) + } + continue + + case 'S', 's': + if !scanOnly { + if inRange { + return nil, p.getErr(ErrBadClassInCharRange, ch) + } + cc.addSpace(p.useOptionE(), p.useRE2(), ch == 'S') + } + continue + + case 'W', 'w': + if !scanOnly { + if inRange { + return nil, p.getErr(ErrBadClassInCharRange, ch) + } + + cc.addWord(p.useOptionE() || p.useRE2(), ch == 'W') + } + continue + + case 'p', 'P': + if !scanOnly { + if inRange { + return nil, p.getErr(ErrBadClassInCharRange, ch) + } + prop, err := p.parseProperty() + if err != nil { + return nil, err + } + cc.addCategory(prop, (ch != 'p'), caseInsensitive, p.patternRaw) + } else { + p.parseProperty() + } + + continue + + case '-': + if !scanOnly { + cc.addRange(ch, ch) + } + continue + + default: + p.moveLeft() + var err error + ch, err = p.scanCharEscape() // non-literal character + if err != nil { + return nil, err + } + fTranslatedChar = true + break // this break will only break out of the switch + } + } else if ch == '[' { + // This is code for Posix style properties - [:Ll:] or [:IsTibetan:]. + // It currently doesn't do anything other than skip the whole thing! + if p.charsRight() > 0 && p.rightChar(0) == ':' && !inRange { + savePos := p.textpos() + + p.moveRight(1) + negate := false + if p.charsRight() > 1 && p.rightChar(0) == '^' { + negate = true + p.moveRight(1) + } + + nm := p.scanCapname() // snag the name + if !scanOnly && p.useRE2() { + // look up the name since these are valid for RE2 + // add the group based on the name + if ok := cc.addNamedASCII(nm, negate); !ok { + return nil, p.getErr(ErrInvalidCharRange) + } + } + if p.charsRight() < 2 || p.moveRightGetChar() != ':' || p.moveRightGetChar() != ']' { + p.textto(savePos) + } else if p.useRE2() { + // move on + continue + } + } + } + + if inRange { + inRange = false + if !scanOnly { + if ch == '[' && !fTranslatedChar && !firstChar { + // We thought we were in a range, but we're actually starting a subtraction. + // In that case, we'll add chPrev to our char class, skip the opening [, and + // scan the new character class recursively. + cc.addChar(chPrev) + sub, err := p.scanCharSet(caseInsensitive, false) + if err != nil { + return nil, err + } + cc.addSubtraction(sub) + + if p.charsRight() > 0 && p.rightChar(0) != ']' { + return nil, p.getErr(ErrSubtractionMustBeLast) + } + } else { + // a regular range, like a-z + if chPrev > ch { + return nil, p.getErr(ErrReversedCharRange, chPrev, ch) + } + cc.addRange(chPrev, ch) + } + } + } else if p.charsRight() >= 2 && p.rightChar(0) == '-' && p.rightChar(1) != ']' { + // this could be the start of a range + chPrev = ch + inRange = true + p.moveRight(1) + } else if p.charsRight() >= 1 && ch == '-' && !fTranslatedChar && p.rightChar(0) == '[' && !firstChar { + // we aren't in a range, and now there is a subtraction. Usually this happens + // only when a subtraction follows a range, like [a-z-[b]] + if !scanOnly { + p.moveRight(1) + sub, err := p.scanCharSet(caseInsensitive, false) + if err != nil { + return nil, err + } + cc.addSubtraction(sub) + + if p.charsRight() > 0 && p.rightChar(0) != ']' { + return nil, p.getErr(ErrSubtractionMustBeLast) + } + } else { + p.moveRight(1) + p.scanCharSet(caseInsensitive, true) + } + } else { + if !scanOnly { + cc.addRange(ch, ch) + } + } + } + + if !closed { + return nil, p.getErr(ErrUnterminatedBracket) + } + + if !scanOnly && caseInsensitive { + cc.addLowercase() + } + + return cc, nil +} + +// Scans any number of decimal digits (pegs value at 2^31-1 if too large) +func (p *parser) scanDecimal() (int, error) { + i := 0 + var d int + + for p.charsRight() > 0 { + d = int(p.rightChar(0) - '0') + if d < 0 || d > 9 { + break + } + p.moveRight(1) + + if i > maxValueDiv10 || (i == maxValueDiv10 && d > maxValueMod10) { + return 0, p.getErr(ErrCaptureGroupOutOfRange) + } + + i *= 10 + i += d + } + + return int(i), nil +} + +// Returns true for options allowed only at the top level +func isOnlyTopOption(option RegexOptions) bool { + return option == RightToLeft || option == ECMAScript || option == RE2 +} + +// Scans cimsx-cimsx option string, stops at the first unrecognized char. +func (p *parser) scanOptions() { + + for off := false; p.charsRight() > 0; p.moveRight(1) { + ch := p.rightChar(0) + + if ch == '-' { + off = true + } else if ch == '+' { + off = false + } else { + option := optionFromCode(ch) + if option == 0 || isOnlyTopOption(option) { + return + } + + if off { + p.options &= ^option + } else { + p.options |= option + } + } + } +} + +// Scans \ code for escape codes that map to single unicode chars. +func (p *parser) scanCharEscape() (r rune, err error) { + + ch := p.moveRightGetChar() + + if ch >= '0' && ch <= '7' { + p.moveLeft() + return p.scanOctal(), nil + } + + pos := p.textpos() + + switch ch { + case 'x': + // support for \x{HEX} syntax from Perl and PCRE + if p.charsRight() > 0 && p.rightChar(0) == '{' { + if p.useOptionE() { + return ch, nil + } + p.moveRight(1) + return p.scanHexUntilBrace() + } else { + r, err = p.scanHex(2) + } + case 'u': + // ECMAscript suppot \u{HEX} only if `u` is also set + if p.useOptionE() && p.useOptionU() && p.charsRight() > 0 && p.rightChar(0) == '{' { + p.moveRight(1) + return p.scanHexUntilBrace() + } else { + r, err = p.scanHex(4) + } + case 'a': + return '\u0007', nil + case 'b': + return '\b', nil + case 'e': + return '\u001B', nil + case 'f': + return '\f', nil + case 'n': + return '\n', nil + case 'r': + return '\r', nil + case 't': + return '\t', nil + case 'v': + return '\u000B', nil + case 'c': + r, err = p.scanControl() + default: + if !p.useOptionE() && !p.useRE2() && IsWordChar(ch) { + return 0, p.getErr(ErrUnrecognizedEscape, string(ch)) + } + return ch, nil + } + if err != nil && p.useOptionE() { + p.textto(pos) + return ch, nil + } + return +} + +// Grabs and converts an ascii control character +func (p *parser) scanControl() (rune, error) { + if p.charsRight() <= 0 { + return 0, p.getErr(ErrMissingControl) + } + + ch := p.moveRightGetChar() + + // \ca interpreted as \cA + + if ch >= 'a' && ch <= 'z' { + ch = (ch - ('a' - 'A')) + } + ch = (ch - '@') + if ch >= 0 && ch < ' ' { + return ch, nil + } + + return 0, p.getErr(ErrUnrecognizedControl) + +} + +// Scan hex digits until we hit a closing brace. +// Non-hex digits, hex value too large for UTF-8, or running out of chars are errors +func (p *parser) scanHexUntilBrace() (rune, error) { + // PCRE spec reads like unlimited hex digits are allowed, but unicode has a limit + // so we can enforce that + i := 0 + hasContent := false + + for p.charsRight() > 0 { + ch := p.moveRightGetChar() + if ch == '}' { + // hit our close brace, we're done here + // prevent \x{} + if !hasContent { + return 0, p.getErr(ErrTooFewHex) + } + return rune(i), nil + } + hasContent = true + // no brace needs to be hex digit + d := hexDigit(ch) + if d < 0 { + return 0, p.getErr(ErrMissingBrace) + } + + i *= 0x10 + i += d + + if i > unicode.MaxRune { + return 0, p.getErr(ErrInvalidHex) + } + } + + // we only make it here if we run out of digits without finding the brace + return 0, p.getErr(ErrMissingBrace) +} + +// Scans exactly c hex digits (c=2 for \xFF, c=4 for \uFFFF) +func (p *parser) scanHex(c int) (rune, error) { + + i := 0 + + if p.charsRight() >= c { + for c > 0 { + d := hexDigit(p.moveRightGetChar()) + if d < 0 { + break + } + i *= 0x10 + i += d + c-- + } + } + + if c > 0 { + return 0, p.getErr(ErrTooFewHex) + } + + return rune(i), nil +} + +// Returns n <= 0xF for a hex digit. +func hexDigit(ch rune) int { + + if d := uint(ch - '0'); d <= 9 { + return int(d) + } + + if d := uint(ch - 'a'); d <= 5 { + return int(d + 0xa) + } + + if d := uint(ch - 'A'); d <= 5 { + return int(d + 0xa) + } + + return -1 +} + +// Scans up to three octal digits (stops before exceeding 0377). +func (p *parser) scanOctal() rune { + // Consume octal chars only up to 3 digits and value 0377 + + c := 3 + + if c > p.charsRight() { + c = p.charsRight() + } + + //we know the first char is good because the caller had to check + i := 0 + d := int(p.rightChar(0) - '0') + for c > 0 && d <= 7 && d >= 0 { + if i >= 0x20 && p.useOptionE() { + break + } + i *= 8 + i += d + c-- + + p.moveRight(1) + if !p.rightMost() { + d = int(p.rightChar(0) - '0') + } + } + + // Octal codes only go up to 255. Any larger and the behavior that Perl follows + // is simply to truncate the high bits. + i &= 0xFF + + return rune(i) +} + +// Returns the current parsing position. +func (p *parser) textpos() int { + return p.currentPos +} + +// Zaps to a specific parsing position. +func (p *parser) textto(pos int) { + p.currentPos = pos +} + +// Returns the char at the right of the current parsing position and advances to the right. +func (p *parser) moveRightGetChar() rune { + ch := p.pattern[p.currentPos] + p.currentPos++ + return ch +} + +// Moves the current position to the right. +func (p *parser) moveRight(i int) { + // default would be 1 + p.currentPos += i +} + +// Moves the current parsing position one to the left. +func (p *parser) moveLeft() { + p.currentPos-- +} + +// Returns the char left of the current parsing position. +func (p *parser) charAt(i int) rune { + return p.pattern[i] +} + +// Returns the char i chars right of the current parsing position. +func (p *parser) rightChar(i int) rune { + // default would be 0 + return p.pattern[p.currentPos+i] +} + +// Number of characters to the right of the current parsing position. +func (p *parser) charsRight() int { + return len(p.pattern) - p.currentPos +} + +func (p *parser) rightMost() bool { + return p.currentPos == len(p.pattern) +} + +// Looks up the slot number for a given name +func (p *parser) captureSlotFromName(capname string) int { + return p.capnames[capname] +} + +// True if the capture slot was noted +func (p *parser) isCaptureSlot(i int) bool { + if p.caps != nil { + _, ok := p.caps[i] + return ok + } + + return (i >= 0 && i < p.capsize) +} + +// Looks up the slot number for a given name +func (p *parser) isCaptureName(capname string) bool { + if p.capnames == nil { + return false + } + + _, ok := p.capnames[capname] + return ok +} + +// option shortcuts + +// True if N option disabling '(' autocapture is on. +func (p *parser) useOptionN() bool { + return (p.options & ExplicitCapture) != 0 +} + +// True if I option enabling case-insensitivity is on. +func (p *parser) useOptionI() bool { + return (p.options & IgnoreCase) != 0 +} + +// True if M option altering meaning of $ and ^ is on. +func (p *parser) useOptionM() bool { + return (p.options & Multiline) != 0 +} + +// True if S option altering meaning of . is on. +func (p *parser) useOptionS() bool { + return (p.options & Singleline) != 0 +} + +// True if X option enabling whitespace/comment mode is on. +func (p *parser) useOptionX() bool { + return (p.options & IgnorePatternWhitespace) != 0 +} + +// True if E option enabling ECMAScript behavior on. +func (p *parser) useOptionE() bool { + return (p.options & ECMAScript) != 0 +} + +// true to use RE2 compatibility parsing behavior. +func (p *parser) useRE2() bool { + return (p.options & RE2) != 0 +} + +// True if U option enabling ECMAScript's Unicode behavior on. +func (p *parser) useOptionU() bool { + return (p.options & Unicode) != 0 +} + +// True if options stack is empty. +func (p *parser) emptyOptionsStack() bool { + return len(p.optionsStack) == 0 +} + +// Finish the current quantifiable (when a quantifier is not found or is not possible) +func (p *parser) addConcatenate() { + // The first (| inside a Testgroup group goes directly to the group + p.concatenation.addChild(p.unit) + p.unit = nil +} + +// Finish the current quantifiable (when a quantifier is found) +func (p *parser) addConcatenate3(lazy bool, min, max int) { + p.concatenation.addChild(p.unit.makeQuantifier(lazy, min, max)) + p.unit = nil +} + +// Sets the current unit to a single char node +func (p *parser) addUnitOne(ch rune) { + if p.useOptionI() { + ch = unicode.ToLower(ch) + } + + p.unit = newRegexNodeCh(ntOne, p.options, ch) +} + +// Sets the current unit to a single inverse-char node +func (p *parser) addUnitNotone(ch rune) { + if p.useOptionI() { + ch = unicode.ToLower(ch) + } + + p.unit = newRegexNodeCh(ntNotone, p.options, ch) +} + +// Sets the current unit to a single set node +func (p *parser) addUnitSet(set *CharSet) { + p.unit = newRegexNodeSet(ntSet, p.options, set) +} + +// Sets the current unit to a subtree +func (p *parser) addUnitNode(node *regexNode) { + p.unit = node +} + +// Sets the current unit to an assertion of the specified type +func (p *parser) addUnitType(t nodeType) { + p.unit = newRegexNode(t, p.options) +} + +// Finish the current group (in response to a ')' or end) +func (p *parser) addGroup() error { + if p.group.t == ntTestgroup || p.group.t == ntTestref { + p.group.addChild(p.concatenation.reverseLeft()) + if (p.group.t == ntTestref && len(p.group.children) > 2) || len(p.group.children) > 3 { + return p.getErr(ErrTooManyAlternates) + } + } else { + p.alternation.addChild(p.concatenation.reverseLeft()) + p.group.addChild(p.alternation) + } + + p.unit = p.group + return nil +} + +// Pops the option stack, but keeps the current options unchanged. +func (p *parser) popKeepOptions() { + lastIdx := len(p.optionsStack) - 1 + p.optionsStack = p.optionsStack[:lastIdx] +} + +// Recalls options from the stack. +func (p *parser) popOptions() { + lastIdx := len(p.optionsStack) - 1 + // get the last item on the stack and then remove it by reslicing + p.options = p.optionsStack[lastIdx] + p.optionsStack = p.optionsStack[:lastIdx] +} + +// Saves options on a stack. +func (p *parser) pushOptions() { + p.optionsStack = append(p.optionsStack, p.options) +} + +// Add a string to the last concatenate. +func (p *parser) addToConcatenate(pos, cch int, isReplacement bool) { + var node *regexNode + + if cch == 0 { + return + } + + if cch > 1 { + str := make([]rune, cch) + copy(str, p.pattern[pos:pos+cch]) + + if p.useOptionI() && !isReplacement { + // We do the ToLower character by character for consistency. With surrogate chars, doing + // a ToLower on the entire string could actually change the surrogate pair. This is more correct + // linguistically, but since Regex doesn't support surrogates, it's more important to be + // consistent. + for i := 0; i < len(str); i++ { + str[i] = unicode.ToLower(str[i]) + } + } + + node = newRegexNodeStr(ntMulti, p.options, str) + } else { + ch := p.charAt(pos) + + if p.useOptionI() && !isReplacement { + ch = unicode.ToLower(ch) + } + + node = newRegexNodeCh(ntOne, p.options, ch) + } + + p.concatenation.addChild(node) +} + +// Push the parser state (in response to an open paren) +func (p *parser) pushGroup() { + p.group.next = p.stack + p.alternation.next = p.group + p.concatenation.next = p.alternation + p.stack = p.concatenation +} + +// Remember the pushed state (in response to a ')') +func (p *parser) popGroup() error { + p.concatenation = p.stack + p.alternation = p.concatenation.next + p.group = p.alternation.next + p.stack = p.group.next + + // The first () inside a Testgroup group goes directly to the group + if p.group.t == ntTestgroup && len(p.group.children) == 0 { + if p.unit == nil { + return p.getErr(ErrConditionalExpression) + } + + p.group.addChild(p.unit) + p.unit = nil + } + return nil +} + +// True if the group stack is empty. +func (p *parser) emptyStack() bool { + return p.stack == nil +} + +// Start a new round for the parser state (in response to an open paren or string start) +func (p *parser) startGroup(openGroup *regexNode) { + p.group = openGroup + p.alternation = newRegexNode(ntAlternate, p.options) + p.concatenation = newRegexNode(ntConcatenate, p.options) +} + +// Finish the current concatenation (in response to a |) +func (p *parser) addAlternate() { + // The | parts inside a Testgroup group go directly to the group + + if p.group.t == ntTestgroup || p.group.t == ntTestref { + p.group.addChild(p.concatenation.reverseLeft()) + } else { + p.alternation.addChild(p.concatenation.reverseLeft()) + } + + p.concatenation = newRegexNode(ntConcatenate, p.options) +} + +// For categorizing ascii characters. + +const ( + Q byte = 5 // quantifier + S = 4 // ordinary stopper + Z = 3 // ScanBlank stopper + X = 2 // whitespace + E = 1 // should be escaped +) + +var _category = []byte{ + //01 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F + 0, 0, 0, 0, 0, 0, 0, 0, 0, X, X, X, X, X, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + // ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? + X, 0, 0, Z, S, 0, 0, 0, S, S, Q, Q, 0, 0, S, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Q, + //@A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, S, S, 0, S, 0, + //'a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Q, S, 0, 0, 0, +} + +func isSpace(ch rune) bool { + return (ch <= ' ' && _category[ch] == X) +} + +// Returns true for those characters that terminate a string of ordinary chars. +func isSpecial(ch rune) bool { + return (ch <= '|' && _category[ch] >= S) +} + +// Returns true for those characters that terminate a string of ordinary chars. +func isStopperX(ch rune) bool { + return (ch <= '|' && _category[ch] >= X) +} + +// Returns true for those characters that begin a quantifier. +func isQuantifier(ch rune) bool { + return (ch <= '{' && _category[ch] >= Q) +} + +func (p *parser) isTrueQuantifier() bool { + nChars := p.charsRight() + if nChars == 0 { + return false + } + + startpos := p.textpos() + ch := p.charAt(startpos) + if ch != '{' { + return ch <= '{' && _category[ch] >= Q + } + + //UGLY: this is ugly -- the original code was ugly too + pos := startpos + for { + nChars-- + if nChars <= 0 { + break + } + pos++ + ch = p.charAt(pos) + if ch < '0' || ch > '9' { + break + } + } + + if nChars == 0 || pos-startpos == 1 { + return false + } + if ch == '}' { + return true + } + if ch != ',' { + return false + } + for { + nChars-- + if nChars <= 0 { + break + } + pos++ + ch = p.charAt(pos) + if ch < '0' || ch > '9' { + break + } + } + + return nChars > 0 && ch == '}' +} diff --git a/third_party/regexp2/syntax/prefix.go b/third_party/regexp2/syntax/prefix.go new file mode 100644 index 000000000..f67168862 --- /dev/null +++ b/third_party/regexp2/syntax/prefix.go @@ -0,0 +1,896 @@ +package syntax + +import ( + "bytes" + "fmt" + "strconv" + "unicode" + "unicode/utf8" +) + +type Prefix struct { + PrefixStr []rune + PrefixSet CharSet + CaseInsensitive bool +} + +// It takes a RegexTree and computes the set of chars that can start it. +func getFirstCharsPrefix(tree *RegexTree) *Prefix { + s := regexFcd{ + fcStack: make([]regexFc, 32), + intStack: make([]int, 32), + } + fc := s.regexFCFromRegexTree(tree) + + if fc == nil || fc.nullable || fc.cc.IsEmpty() { + return nil + } + fcSet := fc.getFirstChars() + return &Prefix{PrefixSet: fcSet, CaseInsensitive: fc.caseInsensitive} +} + +type regexFcd struct { + intStack []int + intDepth int + fcStack []regexFc + fcDepth int + skipAllChildren bool // don't process any more children at the current level + skipchild bool // don't process the current child. + failed bool +} + +/* + * The main FC computation. It does a shortcutted depth-first walk + * through the tree and calls CalculateFC to emits code before + * and after each child of an interior node, and at each leaf. + */ +func (s *regexFcd) regexFCFromRegexTree(tree *RegexTree) *regexFc { + curNode := tree.root + curChild := 0 + + for { + if len(curNode.children) == 0 { + // This is a leaf node + s.calculateFC(curNode.t, curNode, 0) + } else if curChild < len(curNode.children) && !s.skipAllChildren { + // This is an interior node, and we have more children to analyze + s.calculateFC(curNode.t|beforeChild, curNode, curChild) + + if !s.skipchild { + curNode = curNode.children[curChild] + // this stack is how we get a depth first walk of the tree. + s.pushInt(curChild) + curChild = 0 + } else { + curChild++ + s.skipchild = false + } + continue + } + + // This is an interior node where we've finished analyzing all the children, or + // the end of a leaf node. + s.skipAllChildren = false + + if s.intIsEmpty() { + break + } + + curChild = s.popInt() + curNode = curNode.next + + s.calculateFC(curNode.t|afterChild, curNode, curChild) + if s.failed { + return nil + } + + curChild++ + } + + if s.fcIsEmpty() { + return nil + } + + return s.popFC() +} + +// To avoid recursion, we use a simple integer stack. +// This is the push. +func (s *regexFcd) pushInt(I int) { + if s.intDepth >= len(s.intStack) { + expanded := make([]int, s.intDepth*2) + copy(expanded, s.intStack) + s.intStack = expanded + } + + s.intStack[s.intDepth] = I + s.intDepth++ +} + +// True if the stack is empty. +func (s *regexFcd) intIsEmpty() bool { + return s.intDepth == 0 +} + +// This is the pop. +func (s *regexFcd) popInt() int { + s.intDepth-- + return s.intStack[s.intDepth] +} + +// We also use a stack of RegexFC objects. +// This is the push. +func (s *regexFcd) pushFC(fc regexFc) { + if s.fcDepth >= len(s.fcStack) { + expanded := make([]regexFc, s.fcDepth*2) + copy(expanded, s.fcStack) + s.fcStack = expanded + } + + s.fcStack[s.fcDepth] = fc + s.fcDepth++ +} + +// True if the stack is empty. +func (s *regexFcd) fcIsEmpty() bool { + return s.fcDepth == 0 +} + +// This is the pop. +func (s *regexFcd) popFC() *regexFc { + s.fcDepth-- + return &s.fcStack[s.fcDepth] +} + +// This is the top. +func (s *regexFcd) topFC() *regexFc { + return &s.fcStack[s.fcDepth-1] +} + +// Called in Beforechild to prevent further processing of the current child +func (s *regexFcd) skipChild() { + s.skipchild = true +} + +// FC computation and shortcut cases for each node type +func (s *regexFcd) calculateFC(nt nodeType, node *regexNode, CurIndex int) { + //fmt.Printf("NodeType: %v, CurIndex: %v, Desc: %v\n", nt, CurIndex, node.description()) + ci := false + rtl := false + + if nt <= ntRef { + if (node.options & IgnoreCase) != 0 { + ci = true + } + if (node.options & RightToLeft) != 0 { + rtl = true + } + } + + switch nt { + case ntConcatenate | beforeChild, ntAlternate | beforeChild, ntTestref | beforeChild, ntLoop | beforeChild, ntLazyloop | beforeChild: + break + + case ntTestgroup | beforeChild: + if CurIndex == 0 { + s.skipChild() + } + break + + case ntEmpty: + s.pushFC(regexFc{nullable: true}) + break + + case ntConcatenate | afterChild: + if CurIndex != 0 { + child := s.popFC() + cumul := s.topFC() + + s.failed = !cumul.addFC(*child, true) + } + + fc := s.topFC() + if !fc.nullable { + s.skipAllChildren = true + } + break + + case ntTestgroup | afterChild: + if CurIndex > 1 { + child := s.popFC() + cumul := s.topFC() + + s.failed = !cumul.addFC(*child, false) + } + break + + case ntAlternate | afterChild, ntTestref | afterChild: + if CurIndex != 0 { + child := s.popFC() + cumul := s.topFC() + + s.failed = !cumul.addFC(*child, false) + } + break + + case ntLoop | afterChild, ntLazyloop | afterChild: + if node.m == 0 { + fc := s.topFC() + fc.nullable = true + } + break + + case ntGroup | beforeChild, ntGroup | afterChild, ntCapture | beforeChild, ntCapture | afterChild, ntGreedy | beforeChild, ntGreedy | afterChild: + break + + case ntRequire | beforeChild, ntPrevent | beforeChild: + s.skipChild() + s.pushFC(regexFc{nullable: true}) + break + + case ntRequire | afterChild, ntPrevent | afterChild: + break + + case ntOne, ntNotone: + s.pushFC(newRegexFc(node.ch, nt == ntNotone, false, ci)) + break + + case ntOneloop, ntOnelazy: + s.pushFC(newRegexFc(node.ch, false, node.m == 0, ci)) + break + + case ntNotoneloop, ntNotonelazy: + s.pushFC(newRegexFc(node.ch, true, node.m == 0, ci)) + break + + case ntMulti: + if len(node.str) == 0 { + s.pushFC(regexFc{nullable: true}) + } else if !rtl { + s.pushFC(newRegexFc(node.str[0], false, false, ci)) + } else { + s.pushFC(newRegexFc(node.str[len(node.str)-1], false, false, ci)) + } + break + + case ntSet: + s.pushFC(regexFc{cc: node.set.Copy(), nullable: false, caseInsensitive: ci}) + break + + case ntSetloop, ntSetlazy: + s.pushFC(regexFc{cc: node.set.Copy(), nullable: node.m == 0, caseInsensitive: ci}) + break + + case ntRef: + s.pushFC(regexFc{cc: *AnyClass(), nullable: true, caseInsensitive: false}) + break + + case ntNothing, ntBol, ntEol, ntBoundary, ntNonboundary, ntECMABoundary, ntNonECMABoundary, ntBeginning, ntStart, ntEndZ, ntEnd: + s.pushFC(regexFc{nullable: true}) + break + + default: + panic(fmt.Sprintf("unexpected op code: %v", nt)) + } +} + +type regexFc struct { + cc CharSet + nullable bool + caseInsensitive bool +} + +func newRegexFc(ch rune, not, nullable, caseInsensitive bool) regexFc { + r := regexFc{ + caseInsensitive: caseInsensitive, + nullable: nullable, + } + if not { + if ch > 0 { + r.cc.addRange('\x00', ch-1) + } + if ch < 0xFFFF { + r.cc.addRange(ch+1, utf8.MaxRune) + } + } else { + r.cc.addRange(ch, ch) + } + return r +} + +func (r *regexFc) getFirstChars() CharSet { + if r.caseInsensitive { + r.cc.addLowercase() + } + + return r.cc +} + +func (r *regexFc) addFC(fc regexFc, concatenate bool) bool { + if !r.cc.IsMergeable() || !fc.cc.IsMergeable() { + return false + } + + if concatenate { + if !r.nullable { + return true + } + + if !fc.nullable { + r.nullable = false + } + } else { + if fc.nullable { + r.nullable = true + } + } + + r.caseInsensitive = r.caseInsensitive || fc.caseInsensitive + r.cc.addSet(fc.cc) + + return true +} + +// This is a related computation: it takes a RegexTree and computes the +// leading substring if it sees one. It's quite trivial and gives up easily. +func getPrefix(tree *RegexTree) *Prefix { + var concatNode *regexNode + nextChild := 0 + + curNode := tree.root + + for { + switch curNode.t { + case ntConcatenate: + if len(curNode.children) > 0 { + concatNode = curNode + nextChild = 0 + } + + case ntGreedy, ntCapture: + curNode = curNode.children[0] + concatNode = nil + continue + + case ntOneloop, ntOnelazy: + if curNode.m > 0 { + return &Prefix{ + PrefixStr: repeat(curNode.ch, curNode.m), + CaseInsensitive: (curNode.options & IgnoreCase) != 0, + } + } + return nil + + case ntOne: + return &Prefix{ + PrefixStr: []rune{curNode.ch}, + CaseInsensitive: (curNode.options & IgnoreCase) != 0, + } + + case ntMulti: + return &Prefix{ + PrefixStr: curNode.str, + CaseInsensitive: (curNode.options & IgnoreCase) != 0, + } + + case ntBol, ntEol, ntBoundary, ntECMABoundary, ntBeginning, ntStart, + ntEndZ, ntEnd, ntEmpty, ntRequire, ntPrevent: + + default: + return nil + } + + if concatNode == nil || nextChild >= len(concatNode.children) { + return nil + } + + curNode = concatNode.children[nextChild] + nextChild++ + } +} + +// repeat the rune r, c times... up to the max of MaxPrefixSize +func repeat(r rune, c int) []rune { + if c > MaxPrefixSize { + c = MaxPrefixSize + } + + ret := make([]rune, c) + + // binary growth using copy for speed + ret[0] = r + bp := 1 + for bp < len(ret) { + copy(ret[bp:], ret[:bp]) + bp *= 2 + } + + return ret +} + +// BmPrefix precomputes the Boyer-Moore +// tables for fast string scanning. These tables allow +// you to scan for the first occurrence of a string within +// a large body of text without examining every character. +// The performance of the heuristic depends on the actual +// string and the text being searched, but usually, the longer +// the string that is being searched for, the fewer characters +// need to be examined. +type BmPrefix struct { + positive []int + negativeASCII []int + negativeUnicode [][]int + pattern []rune + lowASCII rune + highASCII rune + rightToLeft bool + caseInsensitive bool +} + +func newBmPrefix(pattern []rune, caseInsensitive, rightToLeft bool) *BmPrefix { + + b := &BmPrefix{ + rightToLeft: rightToLeft, + caseInsensitive: caseInsensitive, + pattern: pattern, + } + + if caseInsensitive { + for i := 0; i < len(b.pattern); i++ { + // We do the ToLower character by character for consistency. With surrogate chars, doing + // a ToLower on the entire string could actually change the surrogate pair. This is more correct + // linguistically, but since Regex doesn't support surrogates, it's more important to be + // consistent. + + b.pattern[i] = unicode.ToLower(b.pattern[i]) + } + } + + var beforefirst, last, bump int + var scan, match int + + if !rightToLeft { + beforefirst = -1 + last = len(b.pattern) - 1 + bump = 1 + } else { + beforefirst = len(b.pattern) + last = 0 + bump = -1 + } + + // PART I - the good-suffix shift table + // + // compute the positive requirement: + // if char "i" is the first one from the right that doesn't match, + // then we know the matcher can advance by _positive[i]. + // + // This algorithm is a simplified variant of the standard + // Boyer-Moore good suffix calculation. + + b.positive = make([]int, len(b.pattern)) + + examine := last + ch := b.pattern[examine] + b.positive[examine] = bump + examine -= bump + +Outerloop: + for { + // find an internal char (examine) that matches the tail + + for { + if examine == beforefirst { + break Outerloop + } + if b.pattern[examine] == ch { + break + } + examine -= bump + } + + match = last + scan = examine + + // find the length of the match + for { + if scan == beforefirst || b.pattern[match] != b.pattern[scan] { + // at the end of the match, note the difference in _positive + // this is not the length of the match, but the distance from the internal match + // to the tail suffix. + if b.positive[match] == 0 { + b.positive[match] = match - scan + } + + // System.Diagnostics.Debug.WriteLine("Set positive[" + match + "] to " + (match - scan)); + + break + } + + scan -= bump + match -= bump + } + + examine -= bump + } + + match = last - bump + + // scan for the chars for which there are no shifts that yield a different candidate + + // The inside of the if statement used to say + // "_positive[match] = last - beforefirst;" + // This is slightly less aggressive in how much we skip, but at worst it + // should mean a little more work rather than skipping a potential match. + for match != beforefirst { + if b.positive[match] == 0 { + b.positive[match] = bump + } + + match -= bump + } + + // PART II - the bad-character shift table + // + // compute the negative requirement: + // if char "ch" is the reject character when testing position "i", + // we can slide up by _negative[ch]; + // (_negative[ch] = str.Length - 1 - str.LastIndexOf(ch)) + // + // the lookup table is divided into ASCII and Unicode portions; + // only those parts of the Unicode 16-bit code set that actually + // appear in the string are in the table. (Maximum size with + // Unicode is 65K; ASCII only case is 512 bytes.) + + b.negativeASCII = make([]int, 128) + + for i := 0; i < len(b.negativeASCII); i++ { + b.negativeASCII[i] = last - beforefirst + } + + b.lowASCII = 127 + b.highASCII = 0 + + for examine = last; examine != beforefirst; examine -= bump { + ch = b.pattern[examine] + + switch { + case ch < 128: + if b.lowASCII > ch { + b.lowASCII = ch + } + + if b.highASCII < ch { + b.highASCII = ch + } + + if b.negativeASCII[ch] == last-beforefirst { + b.negativeASCII[ch] = last - examine + } + case ch <= 0xffff: + i, j := ch>>8, ch&0xFF + + if b.negativeUnicode == nil { + b.negativeUnicode = make([][]int, 256) + } + + if b.negativeUnicode[i] == nil { + newarray := make([]int, 256) + + for k := 0; k < len(newarray); k++ { + newarray[k] = last - beforefirst + } + + if i == 0 { + copy(newarray, b.negativeASCII) + //TODO: this line needed? + b.negativeASCII = newarray + } + + b.negativeUnicode[i] = newarray + } + + if b.negativeUnicode[i][j] == last-beforefirst { + b.negativeUnicode[i][j] = last - examine + } + default: + // we can't do the filter because this algo doesn't support + // unicode chars >0xffff + return nil + } + } + + return b +} + +func (b *BmPrefix) String() string { + return string(b.pattern) +} + +// Dump returns the contents of the filter as a human readable string +func (b *BmPrefix) Dump(indent string) string { + buf := &bytes.Buffer{} + + fmt.Fprintf(buf, "%sBM Pattern: %s\n%sPositive: ", indent, string(b.pattern), indent) + for i := 0; i < len(b.positive); i++ { + buf.WriteString(strconv.Itoa(b.positive[i])) + buf.WriteRune(' ') + } + buf.WriteRune('\n') + + if b.negativeASCII != nil { + buf.WriteString(indent) + buf.WriteString("Negative table\n") + for i := 0; i < len(b.negativeASCII); i++ { + if b.negativeASCII[i] != len(b.pattern) { + fmt.Fprintf(buf, "%s %s %s\n", indent, Escape(string(rune(i))), strconv.Itoa(b.negativeASCII[i])) + } + } + } + + return buf.String() +} + +// Scan uses the Boyer-Moore algorithm to find the first occurrence +// of the specified string within text, beginning at index, and +// constrained within beglimit and endlimit. +// +// The direction and case-sensitivity of the match is determined +// by the arguments to the RegexBoyerMoore constructor. +func (b *BmPrefix) Scan(text []rune, index, beglimit, endlimit int) int { + var ( + defadv, test, test2 int + match, startmatch, endmatch int + bump, advance int + chTest rune + unicodeLookup []int + ) + + if !b.rightToLeft { + defadv = len(b.pattern) + startmatch = len(b.pattern) - 1 + endmatch = 0 + test = index + defadv - 1 + bump = 1 + } else { + defadv = -len(b.pattern) + startmatch = 0 + endmatch = -defadv - 1 + test = index + defadv + bump = -1 + } + + chMatch := b.pattern[startmatch] + + for { + if test >= endlimit || test < beglimit { + return -1 + } + + chTest = text[test] + + if b.caseInsensitive { + chTest = unicode.ToLower(chTest) + } + + if chTest != chMatch { + if chTest < 128 { + advance = b.negativeASCII[chTest] + } else if chTest < 0xffff && len(b.negativeUnicode) > 0 { + unicodeLookup = b.negativeUnicode[chTest>>8] + if len(unicodeLookup) > 0 { + advance = unicodeLookup[chTest&0xFF] + } else { + advance = defadv + } + } else { + advance = defadv + } + + test += advance + } else { // if (chTest == chMatch) + test2 = test + match = startmatch + + for { + if match == endmatch { + if b.rightToLeft { + return test2 + 1 + } else { + return test2 + } + } + + match -= bump + test2 -= bump + + chTest = text[test2] + + if b.caseInsensitive { + chTest = unicode.ToLower(chTest) + } + + if chTest != b.pattern[match] { + advance = b.positive[match] + if chTest < 128 { + test2 = (match - startmatch) + b.negativeASCII[chTest] + } else if chTest < 0xffff && len(b.negativeUnicode) > 0 { + unicodeLookup = b.negativeUnicode[chTest>>8] + if len(unicodeLookup) > 0 { + test2 = (match - startmatch) + unicodeLookup[chTest&0xFF] + } else { + test += advance + break + } + } else { + test += advance + break + } + + if b.rightToLeft { + if test2 < advance { + advance = test2 + } + } else if test2 > advance { + advance = test2 + } + + test += advance + break + } + } + } + } +} + +// When a regex is anchored, we can do a quick IsMatch test instead of a Scan +func (b *BmPrefix) IsMatch(text []rune, index, beglimit, endlimit int) bool { + if !b.rightToLeft { + if index < beglimit || endlimit-index < len(b.pattern) { + return false + } + + return b.matchPattern(text, index) + } else { + if index > endlimit || index-beglimit < len(b.pattern) { + return false + } + + return b.matchPattern(text, index-len(b.pattern)) + } +} + +func (b *BmPrefix) matchPattern(text []rune, index int) bool { + if len(text)-index < len(b.pattern) { + return false + } + + if b.caseInsensitive { + for i := 0; i < len(b.pattern); i++ { + //Debug.Assert(textinfo.ToLower(_pattern[i]) == _pattern[i], "pattern should be converted to lower case in constructor!"); + if unicode.ToLower(text[index+i]) != b.pattern[i] { + return false + } + } + return true + } else { + for i := 0; i < len(b.pattern); i++ { + if text[index+i] != b.pattern[i] { + return false + } + } + return true + } +} + +type AnchorLoc int16 + +// where the regex can be pegged +const ( + AnchorBeginning AnchorLoc = 0x0001 + AnchorBol = 0x0002 + AnchorStart = 0x0004 + AnchorEol = 0x0008 + AnchorEndZ = 0x0010 + AnchorEnd = 0x0020 + AnchorBoundary = 0x0040 + AnchorECMABoundary = 0x0080 +) + +func getAnchors(tree *RegexTree) AnchorLoc { + + var concatNode *regexNode + nextChild, result := 0, AnchorLoc(0) + + curNode := tree.root + + for { + switch curNode.t { + case ntConcatenate: + if len(curNode.children) > 0 { + concatNode = curNode + nextChild = 0 + } + + case ntGreedy, ntCapture: + curNode = curNode.children[0] + concatNode = nil + continue + + case ntBol, ntEol, ntBoundary, ntECMABoundary, ntBeginning, + ntStart, ntEndZ, ntEnd: + return result | anchorFromType(curNode.t) + + case ntEmpty, ntRequire, ntPrevent: + + default: + return result + } + + if concatNode == nil || nextChild >= len(concatNode.children) { + return result + } + + curNode = concatNode.children[nextChild] + nextChild++ + } +} + +func anchorFromType(t nodeType) AnchorLoc { + switch t { + case ntBol: + return AnchorBol + case ntEol: + return AnchorEol + case ntBoundary: + return AnchorBoundary + case ntECMABoundary: + return AnchorECMABoundary + case ntBeginning: + return AnchorBeginning + case ntStart: + return AnchorStart + case ntEndZ: + return AnchorEndZ + case ntEnd: + return AnchorEnd + default: + return 0 + } +} + +// anchorDescription returns a human-readable description of the anchors +func (anchors AnchorLoc) String() string { + buf := &bytes.Buffer{} + + if 0 != (anchors & AnchorBeginning) { + buf.WriteString(", Beginning") + } + if 0 != (anchors & AnchorStart) { + buf.WriteString(", Start") + } + if 0 != (anchors & AnchorBol) { + buf.WriteString(", Bol") + } + if 0 != (anchors & AnchorBoundary) { + buf.WriteString(", Boundary") + } + if 0 != (anchors & AnchorECMABoundary) { + buf.WriteString(", ECMABoundary") + } + if 0 != (anchors & AnchorEol) { + buf.WriteString(", Eol") + } + if 0 != (anchors & AnchorEnd) { + buf.WriteString(", End") + } + if 0 != (anchors & AnchorEndZ) { + buf.WriteString(", EndZ") + } + + // trim off comma + if buf.Len() >= 2 { + return buf.String()[2:] + } + return "None" +} diff --git a/third_party/regexp2/syntax/replacerdata.go b/third_party/regexp2/syntax/replacerdata.go new file mode 100644 index 000000000..bcf4d3f25 --- /dev/null +++ b/third_party/regexp2/syntax/replacerdata.go @@ -0,0 +1,87 @@ +package syntax + +import ( + "bytes" + "errors" +) + +type ReplacerData struct { + Rep string + Strings []string + Rules []int +} + +const ( + replaceSpecials = 4 + replaceLeftPortion = -1 + replaceRightPortion = -2 + replaceLastGroup = -3 + replaceWholeString = -4 +) + +//ErrReplacementError is a general error during parsing the replacement text +var ErrReplacementError = errors.New("Replacement pattern error.") + +// NewReplacerData will populate a reusable replacer data struct based on the given replacement string +// and the capture group data from a regexp +func NewReplacerData(rep string, caps map[int]int, capsize int, capnames map[string]int, op RegexOptions) (*ReplacerData, error) { + p := parser{ + options: op, + caps: caps, + capsize: capsize, + capnames: capnames, + } + p.setPattern(rep) + concat, err := p.scanReplacement() + if err != nil { + return nil, err + } + + if concat.t != ntConcatenate { + panic(ErrReplacementError) + } + + sb := &bytes.Buffer{} + var ( + strings []string + rules []int + ) + + for _, child := range concat.children { + switch child.t { + case ntMulti: + child.writeStrToBuf(sb) + + case ntOne: + sb.WriteRune(child.ch) + + case ntRef: + if sb.Len() > 0 { + rules = append(rules, len(strings)) + strings = append(strings, sb.String()) + sb.Reset() + } + slot := child.m + + if len(caps) > 0 && slot >= 0 { + slot = caps[slot] + } + + rules = append(rules, -replaceSpecials-1-slot) + + default: + panic(ErrReplacementError) + } + } + + if sb.Len() > 0 { + rules = append(rules, len(strings)) + strings = append(strings, sb.String()) + } + + return &ReplacerData{ + Rep: rep, + Strings: strings, + Rules: rules, + }, nil +} diff --git a/third_party/regexp2/syntax/tree.go b/third_party/regexp2/syntax/tree.go new file mode 100644 index 000000000..ea2882931 --- /dev/null +++ b/third_party/regexp2/syntax/tree.go @@ -0,0 +1,654 @@ +package syntax + +import ( + "bytes" + "fmt" + "math" + "strconv" +) + +type RegexTree struct { + root *regexNode + caps map[int]int + capnumlist []int + captop int + Capnames map[string]int + Caplist []string + options RegexOptions +} + +// It is built into a parsed tree for a regular expression. + +// Implementation notes: +// +// Since the node tree is a temporary data structure only used +// during compilation of the regexp to integer codes, it's +// designed for clarity and convenience rather than +// space efficiency. +// +// RegexNodes are built into a tree, linked by the n.children list. +// Each node also has a n.parent and n.ichild member indicating +// its parent and which child # it is in its parent's list. +// +// RegexNodes come in as many types as there are constructs in +// a regular expression, for example, "concatenate", "alternate", +// "one", "rept", "group". There are also node types for basic +// peephole optimizations, e.g., "onerep", "notsetrep", etc. +// +// Because perl 5 allows "lookback" groups that scan backwards, +// each node also gets a "direction". Normally the value of +// boolean n.backward = false. +// +// During parsing, top-level nodes are also stacked onto a parse +// stack (a stack of trees). For this purpose we have a n.next +// pointer. [Note that to save a few bytes, we could overload the +// n.parent pointer instead.] +// +// On the parse stack, each tree has a "role" - basically, the +// nonterminal in the grammar that the parser has currently +// assigned to the tree. That code is stored in n.role. +// +// Finally, some of the different kinds of nodes have data. +// Two integers (for the looping constructs) are stored in +// n.operands, an an object (either a string or a set) +// is stored in n.data +type regexNode struct { + t nodeType + children []*regexNode + str []rune + set *CharSet + ch rune + m int + n int + options RegexOptions + next *regexNode +} + +type nodeType int32 + +const ( + // The following are leaves, and correspond to primitive operations + + ntOnerep nodeType = 0 // lef,back char,min,max a {n} + ntNotonerep = 1 // lef,back char,min,max .{n} + ntSetrep = 2 // lef,back set,min,max [\d]{n} + ntOneloop = 3 // lef,back char,min,max a {,n} + ntNotoneloop = 4 // lef,back char,min,max .{,n} + ntSetloop = 5 // lef,back set,min,max [\d]{,n} + ntOnelazy = 6 // lef,back char,min,max a {,n}? + ntNotonelazy = 7 // lef,back char,min,max .{,n}? + ntSetlazy = 8 // lef,back set,min,max [\d]{,n}? + ntOne = 9 // lef char a + ntNotone = 10 // lef char [^a] + ntSet = 11 // lef set [a-z\s] \w \s \d + ntMulti = 12 // lef string abcd + ntRef = 13 // lef group \# + ntBol = 14 // ^ + ntEol = 15 // $ + ntBoundary = 16 // \b + ntNonboundary = 17 // \B + ntBeginning = 18 // \A + ntStart = 19 // \G + ntEndZ = 20 // \Z + ntEnd = 21 // \Z + + // Interior nodes do not correspond to primitive operations, but + // control structures compositing other operations + + // Concat and alternate take n children, and can run forward or backwards + + ntNothing = 22 // [] + ntEmpty = 23 // () + ntAlternate = 24 // a|b + ntConcatenate = 25 // ab + ntLoop = 26 // m,x * + ? {,} + ntLazyloop = 27 // m,x *? +? ?? {,}? + ntCapture = 28 // n () + ntGroup = 29 // (?:) + ntRequire = 30 // (?=) (?<=) + ntPrevent = 31 // (?!) (?) (?<) + ntTestref = 33 // (?(n) | ) + ntTestgroup = 34 // (?(...) | ) + + ntECMABoundary = 41 // \b + ntNonECMABoundary = 42 // \B +) + +func newRegexNode(t nodeType, opt RegexOptions) *regexNode { + return ®exNode{ + t: t, + options: opt, + } +} + +func newRegexNodeCh(t nodeType, opt RegexOptions, ch rune) *regexNode { + return ®exNode{ + t: t, + options: opt, + ch: ch, + } +} + +func newRegexNodeStr(t nodeType, opt RegexOptions, str []rune) *regexNode { + return ®exNode{ + t: t, + options: opt, + str: str, + } +} + +func newRegexNodeSet(t nodeType, opt RegexOptions, set *CharSet) *regexNode { + return ®exNode{ + t: t, + options: opt, + set: set, + } +} + +func newRegexNodeM(t nodeType, opt RegexOptions, m int) *regexNode { + return ®exNode{ + t: t, + options: opt, + m: m, + } +} +func newRegexNodeMN(t nodeType, opt RegexOptions, m, n int) *regexNode { + return ®exNode{ + t: t, + options: opt, + m: m, + n: n, + } +} + +func (n *regexNode) writeStrToBuf(buf *bytes.Buffer) { + for i := 0; i < len(n.str); i++ { + buf.WriteRune(n.str[i]) + } +} + +func (n *regexNode) addChild(child *regexNode) { + reduced := child.reduce() + n.children = append(n.children, reduced) + reduced.next = n +} + +func (n *regexNode) insertChildren(afterIndex int, nodes []*regexNode) { + newChildren := make([]*regexNode, 0, len(n.children)+len(nodes)) + n.children = append(append(append(newChildren, n.children[:afterIndex]...), nodes...), n.children[afterIndex:]...) +} + +// removes children including the start but not the end index +func (n *regexNode) removeChildren(startIndex, endIndex int) { + n.children = append(n.children[:startIndex], n.children[endIndex:]...) +} + +// Pass type as OneLazy or OneLoop +func (n *regexNode) makeRep(t nodeType, min, max int) { + n.t += (t - ntOne) + n.m = min + n.n = max +} + +func (n *regexNode) reduce() *regexNode { + switch n.t { + case ntAlternate: + return n.reduceAlternation() + + case ntConcatenate: + return n.reduceConcatenation() + + case ntLoop, ntLazyloop: + return n.reduceRep() + + case ntGroup: + return n.reduceGroup() + + case ntSet, ntSetloop: + return n.reduceSet() + + default: + return n + } +} + +// Basic optimization. Single-letter alternations can be replaced +// by faster set specifications, and nested alternations with no +// intervening operators can be flattened: +// +// a|b|c|def|g|h -> [a-c]|def|[gh] +// apple|(?:orange|pear)|grape -> apple|orange|pear|grape +func (n *regexNode) reduceAlternation() *regexNode { + if len(n.children) == 0 { + return newRegexNode(ntNothing, n.options) + } + + wasLastSet := false + lastNodeCannotMerge := false + var optionsLast RegexOptions + var i, j int + + for i, j = 0, 0; i < len(n.children); i, j = i+1, j+1 { + at := n.children[i] + + if j < i { + n.children[j] = at + } + + for { + if at.t == ntAlternate { + for k := 0; k < len(at.children); k++ { + at.children[k].next = n + } + n.insertChildren(i+1, at.children) + + j-- + } else if at.t == ntSet || at.t == ntOne { + // Cannot merge sets if L or I options differ, or if either are negated. + optionsAt := at.options & (RightToLeft | IgnoreCase) + + if at.t == ntSet { + if !wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge || !at.set.IsMergeable() { + wasLastSet = true + lastNodeCannotMerge = !at.set.IsMergeable() + optionsLast = optionsAt + break + } + } else if !wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge { + wasLastSet = true + lastNodeCannotMerge = false + optionsLast = optionsAt + break + } + + // The last node was a Set or a One, we're a Set or One and our options are the same. + // Merge the two nodes. + j-- + prev := n.children[j] + + var prevCharClass *CharSet + if prev.t == ntOne { + prevCharClass = &CharSet{} + prevCharClass.addChar(prev.ch) + } else { + prevCharClass = prev.set + } + + if at.t == ntOne { + prevCharClass.addChar(at.ch) + } else { + prevCharClass.addSet(*at.set) + } + + prev.t = ntSet + prev.set = prevCharClass + } else if at.t == ntNothing { + j-- + } else { + wasLastSet = false + lastNodeCannotMerge = false + } + break + } + } + + if j < i { + n.removeChildren(j, i) + } + + return n.stripEnation(ntNothing) +} + +// Basic optimization. Adjacent strings can be concatenated. +// +// (?:abc)(?:def) -> abcdef +func (n *regexNode) reduceConcatenation() *regexNode { + // Eliminate empties and concat adjacent strings/chars + + var optionsLast RegexOptions + var optionsAt RegexOptions + var i, j int + + if len(n.children) == 0 { + return newRegexNode(ntEmpty, n.options) + } + + wasLastString := false + + for i, j = 0, 0; i < len(n.children); i, j = i+1, j+1 { + var at, prev *regexNode + + at = n.children[i] + + if j < i { + n.children[j] = at + } + + if at.t == ntConcatenate && + ((at.options & RightToLeft) == (n.options & RightToLeft)) { + for k := 0; k < len(at.children); k++ { + at.children[k].next = n + } + + //insert at.children at i+1 index in n.children + n.insertChildren(i+1, at.children) + + j-- + } else if at.t == ntMulti || at.t == ntOne { + // Cannot merge strings if L or I options differ + optionsAt = at.options & (RightToLeft | IgnoreCase) + + if !wasLastString || optionsLast != optionsAt { + wasLastString = true + optionsLast = optionsAt + continue + } + + j-- + prev = n.children[j] + + if prev.t == ntOne { + prev.t = ntMulti + prev.str = []rune{prev.ch} + } + + if (optionsAt & RightToLeft) == 0 { + if at.t == ntOne { + prev.str = append(prev.str, at.ch) + } else { + prev.str = append(prev.str, at.str...) + } + } else { + if at.t == ntOne { + // insert at the front by expanding our slice, copying the data over, and then setting the value + prev.str = append(prev.str, 0) + copy(prev.str[1:], prev.str) + prev.str[0] = at.ch + } else { + //insert at the front...this one we'll make a new slice and copy both into it + merge := make([]rune, len(prev.str)+len(at.str)) + copy(merge, at.str) + copy(merge[len(at.str):], prev.str) + prev.str = merge + } + } + } else if at.t == ntEmpty { + j-- + } else { + wasLastString = false + } + } + + if j < i { + // remove indices j through i from the children + n.removeChildren(j, i) + } + + return n.stripEnation(ntEmpty) +} + +// Nested repeaters just get multiplied with each other if they're not +// too lumpy +func (n *regexNode) reduceRep() *regexNode { + + u := n + t := n.t + min := n.m + max := n.n + + for { + if len(u.children) == 0 { + break + } + + child := u.children[0] + + // multiply reps of the same type only + if child.t != t { + childType := child.t + + if !(childType >= ntOneloop && childType <= ntSetloop && t == ntLoop || + childType >= ntOnelazy && childType <= ntSetlazy && t == ntLazyloop) { + break + } + } + + // child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})? + // [but things like (a {2,})+ are not too lumpy...] + if u.m == 0 && child.m > 1 || child.n < child.m*2 { + break + } + + u = child + if u.m > 0 { + if (math.MaxInt32-1)/u.m < min { + u.m = math.MaxInt32 + } else { + u.m = u.m * min + } + } + if u.n > 0 { + if (math.MaxInt32-1)/u.n < max { + u.n = math.MaxInt32 + } else { + u.n = u.n * max + } + } + } + + if math.MaxInt32 == min { + return newRegexNode(ntNothing, n.options) + } + return u + +} + +// Simple optimization. If a concatenation or alternation has only +// one child strip out the intermediate node. If it has zero children, +// turn it into an empty. +func (n *regexNode) stripEnation(emptyType nodeType) *regexNode { + switch len(n.children) { + case 0: + return newRegexNode(emptyType, n.options) + case 1: + return n.children[0] + default: + return n + } +} + +func (n *regexNode) reduceGroup() *regexNode { + u := n + + for u.t == ntGroup { + u = u.children[0] + } + + return u +} + +// Simple optimization. If a set is a singleton, an inverse singleton, +// or empty, it's transformed accordingly. +func (n *regexNode) reduceSet() *regexNode { + // Extract empty-set, one and not-one case as special + + if n.set == nil { + n.t = ntNothing + } else if n.set.IsSingleton() { + n.ch = n.set.SingletonChar() + n.set = nil + n.t += (ntOne - ntSet) + } else if n.set.IsSingletonInverse() { + n.ch = n.set.SingletonChar() + n.set = nil + n.t += (ntNotone - ntSet) + } + + return n +} + +func (n *regexNode) reverseLeft() *regexNode { + if n.options&RightToLeft != 0 && n.t == ntConcatenate && len(n.children) > 0 { + //reverse children order + for left, right := 0, len(n.children)-1; left < right; left, right = left+1, right-1 { + n.children[left], n.children[right] = n.children[right], n.children[left] + } + } + + return n +} + +func (n *regexNode) makeQuantifier(lazy bool, min, max int) *regexNode { + if min == 0 && max == 0 { + return newRegexNode(ntEmpty, n.options) + } + + if min == 1 && max == 1 { + return n + } + + switch n.t { + case ntOne, ntNotone, ntSet: + if lazy { + n.makeRep(Onelazy, min, max) + } else { + n.makeRep(Oneloop, min, max) + } + return n + + default: + var t nodeType + if lazy { + t = ntLazyloop + } else { + t = ntLoop + } + result := newRegexNodeMN(t, n.options, min, max) + result.addChild(n) + return result + } +} + +// debug functions + +var typeStr = []string{ + "Onerep", "Notonerep", "Setrep", + "Oneloop", "Notoneloop", "Setloop", + "Onelazy", "Notonelazy", "Setlazy", + "One", "Notone", "Set", + "Multi", "Ref", + "Bol", "Eol", "Boundary", "Nonboundary", + "Beginning", "Start", "EndZ", "End", + "Nothing", "Empty", + "Alternate", "Concatenate", + "Loop", "Lazyloop", + "Capture", "Group", "Require", "Prevent", "Greedy", + "Testref", "Testgroup", + "Unknown", "Unknown", "Unknown", + "Unknown", "Unknown", "Unknown", + "ECMABoundary", "NonECMABoundary", +} + +func (n *regexNode) description() string { + buf := &bytes.Buffer{} + + buf.WriteString(typeStr[n.t]) + + if (n.options & ExplicitCapture) != 0 { + buf.WriteString("-C") + } + if (n.options & IgnoreCase) != 0 { + buf.WriteString("-I") + } + if (n.options & RightToLeft) != 0 { + buf.WriteString("-L") + } + if (n.options & Multiline) != 0 { + buf.WriteString("-M") + } + if (n.options & Singleline) != 0 { + buf.WriteString("-S") + } + if (n.options & IgnorePatternWhitespace) != 0 { + buf.WriteString("-X") + } + if (n.options & ECMAScript) != 0 { + buf.WriteString("-E") + } + + switch n.t { + case ntOneloop, ntNotoneloop, ntOnelazy, ntNotonelazy, ntOne, ntNotone: + buf.WriteString("(Ch = " + CharDescription(n.ch) + ")") + break + case ntCapture: + buf.WriteString("(index = " + strconv.Itoa(n.m) + ", unindex = " + strconv.Itoa(n.n) + ")") + break + case ntRef, ntTestref: + buf.WriteString("(index = " + strconv.Itoa(n.m) + ")") + break + case ntMulti: + fmt.Fprintf(buf, "(String = %s)", string(n.str)) + break + case ntSet, ntSetloop, ntSetlazy: + buf.WriteString("(Set = " + n.set.String() + ")") + break + } + + switch n.t { + case ntOneloop, ntNotoneloop, ntOnelazy, ntNotonelazy, ntSetloop, ntSetlazy, ntLoop, ntLazyloop: + buf.WriteString("(Min = ") + buf.WriteString(strconv.Itoa(n.m)) + buf.WriteString(", Max = ") + if n.n == math.MaxInt32 { + buf.WriteString("inf") + } else { + buf.WriteString(strconv.Itoa(n.n)) + } + buf.WriteString(")") + + break + } + + return buf.String() +} + +var padSpace = []byte(" ") + +func (t *RegexTree) Dump() string { + return t.root.dump() +} + +func (n *regexNode) dump() string { + var stack []int + CurNode := n + CurChild := 0 + + buf := bytes.NewBufferString(CurNode.description()) + buf.WriteRune('\n') + + for { + if CurNode.children != nil && CurChild < len(CurNode.children) { + stack = append(stack, CurChild+1) + CurNode = CurNode.children[CurChild] + CurChild = 0 + + Depth := len(stack) + if Depth > 32 { + Depth = 32 + } + buf.Write(padSpace[:Depth]) + buf.WriteString(CurNode.description()) + buf.WriteRune('\n') + } else { + if len(stack) == 0 { + break + } + + CurChild = stack[len(stack)-1] + stack = stack[:len(stack)-1] + CurNode = CurNode.next + } + } + return buf.String() +} diff --git a/third_party/regexp2/syntax/writer.go b/third_party/regexp2/syntax/writer.go new file mode 100644 index 000000000..a5aa11ca0 --- /dev/null +++ b/third_party/regexp2/syntax/writer.go @@ -0,0 +1,500 @@ +package syntax + +import ( + "bytes" + "fmt" + "math" + "os" +) + +func Write(tree *RegexTree) (*Code, error) { + w := writer{ + intStack: make([]int, 0, 32), + emitted: make([]int, 2), + stringhash: make(map[string]int), + sethash: make(map[string]int), + } + + code, err := w.codeFromTree(tree) + + if tree.options&Debug > 0 && code != nil { + os.Stdout.WriteString(code.Dump()) + os.Stdout.WriteString("\n") + } + + return code, err +} + +type writer struct { + emitted []int + + intStack []int + curpos int + stringhash map[string]int + stringtable [][]rune + sethash map[string]int + settable []*CharSet + counting bool + count int + trackcount int + caps map[int]int +} + +const ( + beforeChild nodeType = 64 + afterChild = 128 + //MaxPrefixSize is the largest number of runes we'll use for a BoyerMoyer prefix + MaxPrefixSize = 50 +) + +// The top level RegexCode generator. It does a depth-first walk +// through the tree and calls EmitFragment to emits code before +// and after each child of an interior node, and at each leaf. +// +// It runs two passes, first to count the size of the generated +// code, and second to generate the code. +// +// We should time it against the alternative, which is +// to just generate the code and grow the array as we go. +func (w *writer) codeFromTree(tree *RegexTree) (*Code, error) { + var ( + curNode *regexNode + curChild int + capsize int + ) + // construct sparse capnum mapping if some numbers are unused + + if tree.capnumlist == nil || tree.captop == len(tree.capnumlist) { + capsize = tree.captop + w.caps = nil + } else { + capsize = len(tree.capnumlist) + w.caps = tree.caps + for i := 0; i < len(tree.capnumlist); i++ { + w.caps[tree.capnumlist[i]] = i + } + } + + w.counting = true + + for { + if !w.counting { + w.emitted = make([]int, w.count) + } + + curNode = tree.root + curChild = 0 + + w.emit1(Lazybranch, 0) + + for { + if len(curNode.children) == 0 { + w.emitFragment(curNode.t, curNode, 0) + } else if curChild < len(curNode.children) { + w.emitFragment(curNode.t|beforeChild, curNode, curChild) + + curNode = curNode.children[curChild] + + w.pushInt(curChild) + curChild = 0 + continue + } + + if w.emptyStack() { + break + } + + curChild = w.popInt() + curNode = curNode.next + + w.emitFragment(curNode.t|afterChild, curNode, curChild) + curChild++ + } + + w.patchJump(0, w.curPos()) + w.emit(Stop) + + if !w.counting { + break + } + + w.counting = false + } + + fcPrefix := getFirstCharsPrefix(tree) + prefix := getPrefix(tree) + rtl := (tree.options & RightToLeft) != 0 + + var bmPrefix *BmPrefix + //TODO: benchmark string prefixes + if prefix != nil && len(prefix.PrefixStr) > 0 && MaxPrefixSize > 0 { + if len(prefix.PrefixStr) > MaxPrefixSize { + // limit prefix changes to 10k + prefix.PrefixStr = prefix.PrefixStr[:MaxPrefixSize] + } + bmPrefix = newBmPrefix(prefix.PrefixStr, prefix.CaseInsensitive, rtl) + } else { + bmPrefix = nil + } + + return &Code{ + Codes: w.emitted, + Strings: w.stringtable, + Sets: w.settable, + TrackCount: w.trackcount, + Caps: w.caps, + Capsize: capsize, + FcPrefix: fcPrefix, + BmPrefix: bmPrefix, + Anchors: getAnchors(tree), + RightToLeft: rtl, + }, nil +} + +// The main RegexCode generator. It does a depth-first walk +// through the tree and calls EmitFragment to emits code before +// and after each child of an interior node, and at each leaf. +func (w *writer) emitFragment(nodetype nodeType, node *regexNode, curIndex int) error { + bits := InstOp(0) + + if nodetype <= ntRef { + if (node.options & RightToLeft) != 0 { + bits |= Rtl + } + if (node.options & IgnoreCase) != 0 { + bits |= Ci + } + } + ntBits := nodeType(bits) + + switch nodetype { + case ntConcatenate | beforeChild, ntConcatenate | afterChild, ntEmpty: + break + + case ntAlternate | beforeChild: + if curIndex < len(node.children)-1 { + w.pushInt(w.curPos()) + w.emit1(Lazybranch, 0) + } + + case ntAlternate | afterChild: + if curIndex < len(node.children)-1 { + lbPos := w.popInt() + w.pushInt(w.curPos()) + w.emit1(Goto, 0) + w.patchJump(lbPos, w.curPos()) + } else { + for i := 0; i < curIndex; i++ { + w.patchJump(w.popInt(), w.curPos()) + } + } + break + + case ntTestref | beforeChild: + if curIndex == 0 { + w.emit(Setjump) + w.pushInt(w.curPos()) + w.emit1(Lazybranch, 0) + w.emit1(Testref, w.mapCapnum(node.m)) + w.emit(Forejump) + } + + case ntTestref | afterChild: + if curIndex == 0 { + branchpos := w.popInt() + w.pushInt(w.curPos()) + w.emit1(Goto, 0) + w.patchJump(branchpos, w.curPos()) + w.emit(Forejump) + if len(node.children) <= 1 { + w.patchJump(w.popInt(), w.curPos()) + } + } else if curIndex == 1 { + w.patchJump(w.popInt(), w.curPos()) + } + + case ntTestgroup | beforeChild: + if curIndex == 0 { + w.emit(Setjump) + w.emit(Setmark) + w.pushInt(w.curPos()) + w.emit1(Lazybranch, 0) + } + + case ntTestgroup | afterChild: + if curIndex == 0 { + w.emit(Getmark) + w.emit(Forejump) + } else if curIndex == 1 { + Branchpos := w.popInt() + w.pushInt(w.curPos()) + w.emit1(Goto, 0) + w.patchJump(Branchpos, w.curPos()) + w.emit(Getmark) + w.emit(Forejump) + if len(node.children) <= 2 { + w.patchJump(w.popInt(), w.curPos()) + } + } else if curIndex == 2 { + w.patchJump(w.popInt(), w.curPos()) + } + + case ntLoop | beforeChild, ntLazyloop | beforeChild: + + if node.n < math.MaxInt32 || node.m > 1 { + if node.m == 0 { + w.emit1(Nullcount, 0) + } else { + w.emit1(Setcount, 1-node.m) + } + } else if node.m == 0 { + w.emit(Nullmark) + } else { + w.emit(Setmark) + } + + if node.m == 0 { + w.pushInt(w.curPos()) + w.emit1(Goto, 0) + } + w.pushInt(w.curPos()) + + case ntLoop | afterChild, ntLazyloop | afterChild: + + startJumpPos := w.curPos() + lazy := (nodetype - (ntLoop | afterChild)) + + if node.n < math.MaxInt32 || node.m > 1 { + if node.n == math.MaxInt32 { + w.emit2(InstOp(Branchcount+lazy), w.popInt(), math.MaxInt32) + } else { + w.emit2(InstOp(Branchcount+lazy), w.popInt(), node.n-node.m) + } + } else { + w.emit1(InstOp(Branchmark+lazy), w.popInt()) + } + + if node.m == 0 { + w.patchJump(w.popInt(), startJumpPos) + } + + case ntGroup | beforeChild, ntGroup | afterChild: + + case ntCapture | beforeChild: + w.emit(Setmark) + + case ntCapture | afterChild: + w.emit2(Capturemark, w.mapCapnum(node.m), w.mapCapnum(node.n)) + + case ntRequire | beforeChild: + // NOTE: the following line causes lookahead/lookbehind to be + // NON-BACKTRACKING. It can be commented out with (*) + w.emit(Setjump) + + w.emit(Setmark) + + case ntRequire | afterChild: + w.emit(Getmark) + + // NOTE: the following line causes lookahead/lookbehind to be + // NON-BACKTRACKING. It can be commented out with (*) + w.emit(Forejump) + + case ntPrevent | beforeChild: + w.emit(Setjump) + w.pushInt(w.curPos()) + w.emit1(Lazybranch, 0) + + case ntPrevent | afterChild: + w.emit(Backjump) + w.patchJump(w.popInt(), w.curPos()) + w.emit(Forejump) + + case ntGreedy | beforeChild: + w.emit(Setjump) + + case ntGreedy | afterChild: + w.emit(Forejump) + + case ntOne, ntNotone: + w.emit1(InstOp(node.t|ntBits), int(node.ch)) + + case ntNotoneloop, ntNotonelazy, ntOneloop, ntOnelazy: + if node.m > 0 { + if node.t == ntOneloop || node.t == ntOnelazy { + w.emit2(Onerep|bits, int(node.ch), node.m) + } else { + w.emit2(Notonerep|bits, int(node.ch), node.m) + } + } + if node.n > node.m { + if node.n == math.MaxInt32 { + w.emit2(InstOp(node.t|ntBits), int(node.ch), math.MaxInt32) + } else { + w.emit2(InstOp(node.t|ntBits), int(node.ch), node.n-node.m) + } + } + + case ntSetloop, ntSetlazy: + if node.m > 0 { + w.emit2(Setrep|bits, w.setCode(node.set), node.m) + } + if node.n > node.m { + if node.n == math.MaxInt32 { + w.emit2(InstOp(node.t|ntBits), w.setCode(node.set), math.MaxInt32) + } else { + w.emit2(InstOp(node.t|ntBits), w.setCode(node.set), node.n-node.m) + } + } + + case ntMulti: + w.emit1(InstOp(node.t|ntBits), w.stringCode(node.str)) + + case ntSet: + w.emit1(InstOp(node.t|ntBits), w.setCode(node.set)) + + case ntRef: + w.emit1(InstOp(node.t|ntBits), w.mapCapnum(node.m)) + + case ntNothing, ntBol, ntEol, ntBoundary, ntNonboundary, ntECMABoundary, ntNonECMABoundary, ntBeginning, ntStart, ntEndZ, ntEnd: + w.emit(InstOp(node.t)) + + default: + return fmt.Errorf("unexpected opcode in regular expression generation: %v", nodetype) + } + + return nil +} + +// To avoid recursion, we use a simple integer stack. +// This is the push. +func (w *writer) pushInt(i int) { + w.intStack = append(w.intStack, i) +} + +// Returns true if the stack is empty. +func (w *writer) emptyStack() bool { + return len(w.intStack) == 0 +} + +// This is the pop. +func (w *writer) popInt() int { + //get our item + idx := len(w.intStack) - 1 + i := w.intStack[idx] + //trim our slice + w.intStack = w.intStack[:idx] + return i +} + +// Returns the current position in the emitted code. +func (w *writer) curPos() int { + return w.curpos +} + +// Fixes up a jump instruction at the specified offset +// so that it jumps to the specified jumpDest. +func (w *writer) patchJump(offset, jumpDest int) { + w.emitted[offset+1] = jumpDest +} + +// Returns an index in the set table for a charset +// uses a map to eliminate duplicates. +func (w *writer) setCode(set *CharSet) int { + if w.counting { + return 0 + } + + buf := &bytes.Buffer{} + + set.mapHashFill(buf) + hash := buf.String() + i, ok := w.sethash[hash] + if !ok { + i = len(w.sethash) + w.sethash[hash] = i + w.settable = append(w.settable, set) + } + return i +} + +// Returns an index in the string table for a string. +// uses a map to eliminate duplicates. +func (w *writer) stringCode(str []rune) int { + if w.counting { + return 0 + } + + hash := string(str) + i, ok := w.stringhash[hash] + if !ok { + i = len(w.stringhash) + w.stringhash[hash] = i + w.stringtable = append(w.stringtable, str) + } + + return i +} + +// When generating code on a regex that uses a sparse set +// of capture slots, we hash them to a dense set of indices +// for an array of capture slots. Instead of doing the hash +// at match time, it's done at compile time, here. +func (w *writer) mapCapnum(capnum int) int { + if capnum == -1 { + return -1 + } + + if w.caps != nil { + return w.caps[capnum] + } + + return capnum +} + +// Emits a zero-argument operation. Note that the emit +// functions all run in two modes: they can emit code, or +// they can just count the size of the code. +func (w *writer) emit(op InstOp) { + if w.counting { + w.count++ + if opcodeBacktracks(op) { + w.trackcount++ + } + return + } + w.emitted[w.curpos] = int(op) + w.curpos++ +} + +// Emits a one-argument operation. +func (w *writer) emit1(op InstOp, opd1 int) { + if w.counting { + w.count += 2 + if opcodeBacktracks(op) { + w.trackcount++ + } + return + } + w.emitted[w.curpos] = int(op) + w.curpos++ + w.emitted[w.curpos] = opd1 + w.curpos++ +} + +// Emits a two-argument operation. +func (w *writer) emit2(op InstOp, opd1, opd2 int) { + if w.counting { + w.count += 3 + if opcodeBacktracks(op) { + w.trackcount++ + } + return + } + w.emitted[w.curpos] = int(op) + w.curpos++ + w.emitted[w.curpos] = opd1 + w.curpos++ + w.emitted[w.curpos] = opd2 + w.curpos++ +} From c78c403db13f0c58165584fecaf68e3d7fe3e1ce Mon Sep 17 00:00:00 2001 From: Morvex885 <278529280+Morvex885@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:36:18 +0300 Subject: [PATCH 8/9] Budget edge admin WASM for ordered Mihomo templates The admin Worker validates and previews unsaved templates using the same regexp2 matching as subscription rendering. Moving it to the public Worker would require a cross-Worker RPC for an owner-only operation. The release-style admin build is 49.4 MiB. Raise only its budget from 49 to 50 MiB, below the 64 MiB Cloudflare ceiling. --- scripts/check-edge-sizes.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/check-edge-sizes.sh b/scripts/check-edge-sizes.sh index e82407d9e..01ec10234 100755 --- a/scripts/check-edge-sizes.sh +++ b/scripts/check-edge-sizes.sh @@ -80,7 +80,10 @@ entries=( # 49 MiB with the probe of a relay leg over the other address family (48.02 MiB measured, 18 KiB over 48): CheckRelay # with other_leg, the leg hints of ListRelayCandidates and the other-leg fields of a relay are admin calls, and the # fleet code that runs the probe is what they call. - "mistgate-edge-admin:49" + # 50 MiB with ordered Mihomo template groups (49.4 MiB measured): the admin Worker needs the same regexp2 + # matching as the public Worker to validate and preview unsaved templates. The public Worker serves saved profiles; + # sending drafts there would add a new cross-Worker RPC for an owner-only operation. + "mistgate-edge-admin:50" # The Provisioner: wireCore plus the SSH client. Measured 29.4 MiB; 31.9 MiB in November 2026 with the panel's SSH key, the # authorized_keys management and the login by an own private key, which need that SSH client and so cannot live elsewhere. "mistgate-edge-provision:35" From b9529ac781a19ea67ed04d8d74e16c1f9eafec94 Mon Sep 17 00:00:00 2001 From: Morvex885 <278529280+Morvex885@users.noreply.github.com> Date: Thu, 3 Dec 2026 14:37:48 +0300 Subject: [PATCH 9/9] Handle Mihomo template filter timeouts without fallback - Use upstream regexp2 and document the Cloudflare Worker CPU limit. - Fail subscription refresh and draft preview when matching times out; validate a long sample name on save. - Cover the failure paths and keep a native group in the golden fixture. --- docs/en/guide/subscriptions.md | 12 +- docs/ru/guide/subscriptions.md | 12 +- docs/zh/guide/subscriptions.md | 12 +- gen/mistgate/admin/v1/subscription.pb.go | 12 +- go.mod | 3 - go.sum | 2 + internal/panel/subs/mihomo.go | 9 +- internal/panel/subs/mihomo_preview.go | 2 +- .../subs/mihomo_template_internal_test.go | 6 +- internal/panel/subs/mihomo_template_test.go | 44 + internal/panel/subs/subs.go | 8 +- .../testdata/mihomo_template_router.out.yaml | 4 +- .../subs/testdata/mihomo_template_router.yaml | 2 +- internal/panel/subsettings/mihomo.go | 40 +- .../subsettings/mihomo_ordered_groups.go | 13 +- .../subsettings/mihomo_ordered_groups_test.go | 33 +- proto/mistgate/admin/v1/subscription.proto | 12 +- scripts/check-edge-sizes.sh | 2 + third_party/regexp2/LICENSE | 21 - third_party/regexp2/fastclock.go | 158 -- third_party/regexp2/fastclock_wasm_test.go | 20 - third_party/regexp2/go.mod | 3 - third_party/regexp2/match.go | 349 --- third_party/regexp2/regexp.go | 395 --- third_party/regexp2/replace.go | 177 -- third_party/regexp2/runner.go | 1614 ------------ third_party/regexp2/syntax/charclass.go | 865 ------- third_party/regexp2/syntax/code.go | 274 -- third_party/regexp2/syntax/escape.go | 94 - third_party/regexp2/syntax/fuzz.go | 20 - third_party/regexp2/syntax/parser.go | 2262 ----------------- third_party/regexp2/syntax/prefix.go | 896 ------- third_party/regexp2/syntax/replacerdata.go | 87 - third_party/regexp2/syntax/tree.go | 654 ----- third_party/regexp2/syntax/writer.go | 500 ---- .../gen/mistgate/admin/v1/subscription_pb.ts | 12 +- 36 files changed, 169 insertions(+), 8460 deletions(-) delete mode 100644 third_party/regexp2/LICENSE delete mode 100644 third_party/regexp2/fastclock.go delete mode 100644 third_party/regexp2/fastclock_wasm_test.go delete mode 100644 third_party/regexp2/go.mod delete mode 100644 third_party/regexp2/match.go delete mode 100644 third_party/regexp2/regexp.go delete mode 100644 third_party/regexp2/replace.go delete mode 100644 third_party/regexp2/runner.go delete mode 100644 third_party/regexp2/syntax/charclass.go delete mode 100644 third_party/regexp2/syntax/code.go delete mode 100644 third_party/regexp2/syntax/escape.go delete mode 100644 third_party/regexp2/syntax/fuzz.go delete mode 100644 third_party/regexp2/syntax/parser.go delete mode 100644 third_party/regexp2/syntax/prefix.go delete mode 100644 third_party/regexp2/syntax/replacerdata.go delete mode 100644 third_party/regexp2/syntax/tree.go delete mode 100644 third_party/regexp2/syntax/writer.go diff --git a/docs/en/guide/subscriptions.md b/docs/en/guide/subscriptions.md index 5f8fc5604..3710837da 100644 --- a/docs/en/guide/subscriptions.md +++ b/docs/en/guide/subscriptions.md @@ -342,7 +342,9 @@ Saved templates are not migrated. Without the opt-in, `include-all-proxies` and - Replace `include-all: true` with `mistgate-ordered-proxies: true` and `include-all-providers: true` to keep all providers. To use only selected providers in a specific order instead, leave `include-all-providers` off and list them in `use`. When all providers are enabled, Mihomo ignores `use`. - Remove or set to `false` both native local inclusion flags, including any inherited through `<<`: the panel rejects either one set to `true` alongside the opt-in. Check the preview, save, then refresh the subscription in the app. -With the opt-in, the panel applies `filter` to the final names of the proxies it adds, not to the members you listed explicitly. Providers stay dynamic in Mihomo; the panel leaves `filter`, `exclude-filter` and `exclude-type` in the output. You can use `filter: "Germany"` to match by name, not by IP or actual location. When `filter` contains multiple backtick-separated expressions, their priority takes precedence over source order: in a mixed group, Mihomo collects matches for the first expression across sources before moving to the next. A client's display sort by name or latency can differ from the order the core uses, including for `fallback`. +With the opt-in, the panel applies `filter` to the final names of the proxies it adds, not to the members you listed explicitly. Providers stay dynamic in Mihomo; the panel leaves `filter`, `exclude-filter` and `exclude-type` in the output. Use `filter: "Germany"` to match by name, not by IP or actual location. With providers and multiple backtick-separated expressions, Mihomo collects matches in expression order across all sources, including explicit members: `Auto` may no longer be first in a `select` group. A client's display sort by name or latency can differ from the order the core uses, including for `fallback`. + +**Before downgrading:** Replace the new flag with `include-all-proxies: true` in groups that rely on it. An older panel does not expand the flag, so a group can be left without members and Mihomo can reject the profile. A template for the group `ROUTER`, written with made-up names: @@ -387,13 +389,17 @@ A person in `ROUTER` gets their servers at the top of `proxies`, expanded `Proxy The limits: 20 templates, 64 KiB each and 256 KiB in all; a name of 1 to 60 characters (the same name in another letter case counts as the same); at most 100 groups in one template; a group in one template only. A group you delete drops out of its template at the next save. -The save refuses a template, with the line in the message, when: +The save refuses a template when: - the text is not valid UTF-8 or YAML, holds a second document (`---`), a key given twice, or aliases that expand far beyond the text; - the root is not a mapping or has `<<`, or `proxies` or `proxy-groups` is not a plain list (an alias there would let the panel change the anchor too); - a proxy has no `name`, a group has no `name` or `type`, names repeat, or one is a core name; - a group refers in its `proxies` to a name that is no proxy or group of the template, no core name and not `Auto` (while the panel adds that group), or in `use` to a provider you did not define; -- the panel cannot build a profile from it with two sample servers. +- `mistgate-ordered-proxies` is not a YAML boolean, or a group enables it alongside `include-all-proxies` or `include-all` or shares its name with a proxy provider; +- an opted-in group has an invalid `filter` regular expression or matching exceeds the time limit; +- the panel cannot build a profile from it with three sample servers, one with a long name. + +If matching runs out of time, the preview reports an error and the subscription refresh fails instead of sending the built-in profile. On Cloudflare Workers the clock does not advance during matching, so the Worker's CPU limit is the backstop. Other findings do not stop a save and show in the preview as **Worth a look**: no group takes the person's servers (add `mistgate-ordered-proxies: true` or refer to `Auto`); the template has its own `dns`; the person's DNS preset has ad, split or country rules that the template does not get; the template has its own `Auto`, so the panel adds none; a rule sends to a name that is nothing in the template; no group is chosen. The panel does not check the rest of Mihomo's keys: run the file in Mihomo for that. diff --git a/docs/ru/guide/subscriptions.md b/docs/ru/guide/subscriptions.md index efdd5be1d..eddcef328 100644 --- a/docs/ru/guide/subscriptions.md +++ b/docs/ru/guide/subscriptions.md @@ -342,7 +342,9 @@ tproxy-port: 1181 - Замените `include-all: true` на `mistgate-ordered-proxies: true` и `include-all-providers: true`, чтобы сохранить всех провайдеров. Если нужно выбрать только отдельных провайдеров в заданном порядке, не включайте `include-all-providers` и перечислите их в `use`. Когда включены все провайдеры, Mihomo игнорирует `use`. - Удалите оба встроенных флага автодобавления локальных прокси или задайте им `false`, в том числе если они унаследованы через `<<`: панель отклоняет сочетание нового флага с любым из них, если оба включены. Проверьте превью, сохраните шаблон и обновите подписку в приложении. -С новым флагом панель применяет `filter` к итоговым именам добавляемых прокси, но не к участникам, которых вы перечислили сами. Провайдеры по-прежнему обновляются в Mihomo; панель оставляет в итоговом YAML `filter`, `exclude-filter` и `exclude-type`. Например, `filter: "Germany"` проверяет имя, а не IP или фактическое местоположение. Если в `filter` несколько выражений через обратную кавычку, их приоритет важнее порядка источников: в смешанной группе Mihomo сначала собирает совпадения с первым выражением по всем источникам, затем со следующим. Сортировка в приложении по имени или задержке может отличаться от порядка ядра, в том числе для `fallback`. +С новым флагом панель применяет `filter` к итоговым именам добавляемых прокси, но не к участникам, которых вы перечислили сами. Провайдеры по-прежнему обновляются в Mihomo; панель оставляет в итоговом YAML `filter`, `exclude-filter` и `exclude-type`. Например, `filter: "Germany"` проверяет имя, а не IP или фактическое местоположение. Если в группе есть провайдеры, а в `filter` — несколько выражений через обратную кавычку, Mihomo собирает совпадения по порядку выражений из всех источников и переставляет даже явных участников: `Auto` может перестать быть первым в группе `select`. Сортировка в приложении по имени или задержке может отличаться от порядка ядра, в том числе для `fallback`. + +**Перед откатом:** замените новый флаг на `include-all-proxies: true` в группах, которые от него зависят. Старая панель не добавит участников по этому флагу, и Mihomo может отклонить профиль с пустой группой. Шаблон для группы `ROUTER` на выдуманных именах: @@ -387,13 +389,17 @@ rules: Пределы: 20 шаблонов, по 64 КиБ каждый и 256 КиБ всего; название от 1 до 60 символов (то же название в другом регистре считается тем же); не больше 100 групп в одном шаблоне; группа — только в одном шаблоне. Удалённая группа выпадает из шаблона при следующем сохранении. -Сохранение отклоняет шаблон, называя строку, если: +Сохранение отклоняет шаблон, если: - текст не является корректным UTF-8 или YAML, содержит второй документ (`---`), дважды заданный ключ или алиасы, которые раскрываются намного больше самого текста; - корень не словарь или содержит `<<`, либо `proxies` или `proxy-groups` не обычный список (алиас там позволил бы панели изменить и якорь); - у прокси нет `name`, у группы нет `name` или `type`, имена повторяются или совпадают с именем ядра; - в `proxies` группы названо то, чего нет среди прокси и групп шаблона, имён ядра и `Auto` (пока панель эту группу добавляет), или в `use` — провайдер, которого вы не описали; -- панель не может собрать из него профиль с двумя пробными серверами. +- `mistgate-ordered-proxies` задан не логическим значением YAML, либо группа включает его вместе с `include-all-proxies` или `include-all` либо называется так же, как прокси-провайдер; +- в группе с новым флагом `filter` содержит недопустимое регулярное выражение или сопоставление превышает лимит времени; +- панель не может собрать профиль с тремя пробными серверами, один из которых имеет длинное имя. + +Если время на сопоставление истекло, превью показывает ошибку, а обновление подписки завершается ошибкой вместо выдачи встроенного профиля. В Cloudflare Workers часы не идут во время сопоставления, поэтому там выполнение ограничивает лимит процессорного времени Worker. Остальные находки сохранение не останавливают и показываются в превью как **Стоит посмотреть**: ни одна группа не берёт серверы человека (добавьте `mistgate-ordered-proxies: true` или сошлитесь на `Auto`); в шаблоне свой `dns`; в DNS-пресете человека есть правила рекламы, разделения или стран, которых в шаблоне не будет; в шаблоне свой `Auto`, поэтому панель своего не добавляет; правило ведёт к имени, которого нет в шаблоне; не выбрана ни одна группа. Остальные ключи Mihomo панель не проверяет: для этого прогоните файл через Mihomo. diff --git a/docs/zh/guide/subscriptions.md b/docs/zh/guide/subscriptions.md index 89fa12a47..c1b4d9e00 100644 --- a/docs/zh/guide/subscriptions.md +++ b/docs/zh/guide/subscriptions.md @@ -340,7 +340,9 @@ tproxy-port: 1181 - 将 `include-all: true` 替换为 `mistgate-ordered-proxies: true` 和 `include-all-providers: true`,以保留所有提供者。如果只想按指定顺序使用选定的提供者,请不要开启 `include-all-providers`,而是在 `use` 中列出它们。启用全部提供者时,Mihomo 会忽略 `use`。 - 移除两个原生的本地代理自动加入选项,或将它们设为 `false`,包括通过 `<<` 继承的选项。启用新标记时,这两个选项中任意一个为 `true` 都会被面板拒绝。检查预览并保存,然后在应用中刷新订阅。 -启用新标记后,面板会用 `filter` 匹配自动加入的代理的最终名称,不筛选你明确列出的成员。提供者仍由 Mihomo 动态更新,面板会在输出中保留 `filter`、`exclude-filter` 和 `exclude-type`。例如,`filter: "Germany"` 匹配的是名称,而不是 IP 或实际位置。如果 `filter` 包含多个用反引号分隔的表达式,表达式的优先级高于来源顺序:在混合分组中,Mihomo 先收集所有来源中匹配第一个表达式的代理,再处理下一个表达式。应用按名称或延迟显示的顺序可能不同于内核使用的顺序,`fallback` 组也是如此。 +启用新标记后,面板会用 `filter` 匹配自动加入的代理的最终名称,不筛选你明确列出的成员。提供者仍由 Mihomo 动态更新,面板会在输出中保留 `filter`、`exclude-filter` 和 `exclude-type`。例如,`filter: "Germany"` 匹配的是名称,而不是 IP 或实际位置。如果分组使用了提供者,且 `filter` 包含多个用反引号分隔的表达式,Mihomo 会按表达式的顺序收集所有来源的匹配项,包括明确列出的成员:`Auto` 可能不再是 `select` 组的第一项。应用按名称或延迟显示的顺序可能不同于内核使用的顺序,`fallback` 组也是如此。 + +**降级前:** 将依赖新标记的分组改用 `include-all-proxies: true`。旧版面板不会根据新标记添加成员,Mihomo 可能拒绝包含空分组的配置。 下面是用虚构名称写的 `ROUTER` 分组模板: @@ -385,13 +387,17 @@ rules: 限制:最多 20 个模板,每个最多 64 KiB,合计最多 256 KiB;名称 1 至 60 个字符(同名但大小写不同视为同一个名称);一个模板最多 100 个分组;一个分组只能在一个模板中。你删除的分组会在下次保存时从模板中去掉。 -出现以下情况时,保存会拒绝该模板,并在提示中给出行号: +出现以下情况时,保存会拒绝该模板: - 文本不是有效的 UTF-8 或 YAML,含有第二个文档(`---`)、重复的键,或展开后远大于文本本身的别名; - 根不是映射或含有 `<<`,或 `proxies`、`proxy-groups` 不是普通列表(那里用别名会让面板连锚点一起改掉); - 代理没有 `name`,分组没有 `name` 或 `type`,名称重复,或与内核名称相同; - 分组的 `proxies` 里引用了既不是模板中的代理或分组、也不是内核名称、更不是 `Auto`(只要面板会添加该分组)的名称,或 `use` 里引用了你没有定义的 provider; -- 面板无法用两台示例服务器据此生成配置。 +- `mistgate-ordered-proxies` 不是 YAML 布尔值,或分组启用该标记时也启用了 `include-all-proxies` 或 `include-all`,或与代理提供者重名; +- 启用了新标记的分组含有无效的 `filter` 正则表达式,或匹配超出时间限制; +- 面板无法用三个示例服务器(其中一个名称较长)生成配置。 + +匹配超时后,预览会报告错误,订阅更新也会失败,而不是返回面板自带的配置。Cloudflare Workers 的时钟在匹配期间不会推进,因此最终由 Worker 的 CPU 时间限制中止执行。 其他发现不会阻止保存,会在预览中显示为**值得一看**:没有分组取用户的服务器(请加 `mistgate-ordered-proxies: true` 或引用 `Auto`);模板有自己的 `dns`;用户的 DNS 预设含有模板得不到的广告、分流或国家规则;模板有自己的 `Auto`,所以面板不再添加;某条规则指向模板里不存在的名称;没有选择任何分组。面板不检查 Mihomo 的其余键:请用 Mihomo 自己运行一遍该文件。 diff --git a/gen/mistgate/admin/v1/subscription.pb.go b/gen/mistgate/admin/v1/subscription.pb.go index 66699ce23..08c90bd7e 100644 --- a/gen/mistgate/admin/v1/subscription.pb.go +++ b/gen/mistgate/admin/v1/subscription.pb.go @@ -789,9 +789,9 @@ func (x *RoutingInfo) GetHeaderBytes() uint32 { // One Mihomo YAML profile of the owner. The panel puts the servers of the person at the start of its `proxies` and, while // link_auto_select is on and the template has no group of that name, adds a url-test group `Auto` over them at the end of its -// `proxy-groups`; groups take the servers with `include-all-proxies` or `filter`. `dns` is added (resolvers of the person's preset, -// respect-rules on) only when the template has none. Everything else is left as written, comments included. The panel never -// fetches a URL of a template. +// `proxy-groups`. Groups can opt in to panel order with `mistgate-ordered-proxies: true`, or let Mihomo include and sort +// servers with `include-all-proxies` or `include-all`. `dns` is added (preset resolvers, respect-rules on) only when the +// template has none. The panel never fetches a URL of a template. // // A save is refused (INVALID_ARGUMENT, the text names the line) unless the text is one valid YAML document that parses in full (no // alias bomb, no repeated key), has a mapping at its root, `proxies` and `proxy-groups` that are lists (or absent) with named @@ -2188,9 +2188,9 @@ func (x *PreviewMihomoTemplateRequest) GetGroupIds() []string { } // One finding that does not stop a save (SubscriptionService words them by code). code is one of: no_server_group (no group takes the -// servers of the person: include-all-proxies, or Auto), own_dns (the person's DNS preset is not applied to this template), -// preset_rules_skipped (the preset has ad, split or country rules that a template does not get), own_auto (the template has its own -// Auto, so the panel adds none), unknown_rule_target (arg: the last field of a rule that names no proxy or group), unused (no group). +// servers of the person: `mistgate-ordered-proxies`, `include-all-proxies`, `include-all`, or `Auto`), own_dns (the person's +// DNS preset is not applied), preset_rules_skipped (the preset's ad, split or country rules are not applied), own_auto (the +// template has its own Auto), unknown_rule_target (arg: the last field of a rule that names no proxy or group), unused (no group). type MihomoWarning struct { state protoimpl.MessageState `protogen:"open.v1"` Code string `protobuf:"bytes,1,opt,name=code,proto3" json:"code,omitempty"` diff --git a/go.mod b/go.mod index 1a2232133..b6b024ba6 100644 --- a/go.mod +++ b/go.mod @@ -236,6 +236,3 @@ replace github.com/xtls/xray-core => github.com/Mistgate/Xray-core v0.0.0-202611 // a facade without sockets or files (mgdns), a zone responder, hooks for dialing and DNS, limits. From the public fork // github.com/Mistgate/MasterDnsVPN (its MISTGATE.md says what and why). Pin a commit of the fork, not a branch. replace masterdnsvpn-go => github.com/Mistgate/MasterDnsVPN v0.0.0-20261201015347-cb8d620bacc6 - -// regexp2 v1.12.0 (3d5df45b7038) with synchronous deadline checks on single-threaded WebAssembly. -replace github.com/dlclark/regexp2 => ./third_party/regexp2 diff --git a/go.sum b/go.sum index a7f859729..0e7503620 100644 --- a/go.sum +++ b/go.sum @@ -140,6 +140,8 @@ github.com/descope/virtualwebauthn v1.0.5 h1:fMXji5UMepJC51Ge6d4v5IAjiJQRKmXE9hl github.com/descope/virtualwebauthn v1.0.5/go.mod h1:lLCfN+DpCM3iisM4bCILZlFEWkC1Zo7ZgsxC45CUapI= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= +github.com/dlclark/regexp2 v1.12.0 h1:0j4c5qQmnC6XOWNjP3PIXURXN2gWx76rd3KvgdPkCz8= +github.com/dlclark/regexp2 v1.12.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= github.com/docker/cli v29.8.0+incompatible h1:ih0c2jq/nN7QfES8zIfwSzIhRScjs4ehER+kZ60aeSk= diff --git a/internal/panel/subs/mihomo.go b/internal/panel/subs/mihomo.go index 55754b8c3..6a65ecf59 100644 --- a/internal/panel/subs/mihomo.go +++ b/internal/panel/subs/mihomo.go @@ -125,17 +125,16 @@ func (p mihomoProfile) servers() []subsettings.MihomoServer { // render is the profile of one person: the template of their group around their servers, else the built-in profile. The built-in one // is what a person gets when there is no template (tplText ""), when they get a note instead of servers (the note must be seen: a -// template's groups would hide it), when none of their servers can be used, and when the template does not build (a stored text that -// this version cannot read: a log line with the template's name, never its text). tplName is for that line only. -// Draft previews report filter budget exhaustion instead of falling back. selected is the source after group selection, +// template's groups would hide it), when none of their servers can be used, and when the template cannot be read. If matching +// runs out of time, return an error instead of replacing the person's profile. selected is the source after group selection, // for preview warnings even if no servers could be inserted. -func (p mihomoProfile) render(tplName, tplText string, draft bool) (body []byte, selected string, templated bool, err error) { +func (p mihomoProfile) render(tplName, tplText string) (body []byte, selected string, templated bool, err error) { if tplText != "" && !p.note { body, selected, err = p.buildFromTemplate(tplText) switch { case err == nil: return body, selected, true, nil - case draft && errors.Is(err, subsettings.ErrMihomoFilterBudget): + case errors.Is(err, subsettings.ErrMihomoFilterBudget): return nil, selected, false, err case errors.Is(err, subsettings.ErrNoServers): default: diff --git a/internal/panel/subs/mihomo_preview.go b/internal/panel/subs/mihomo_preview.go index 0c11bc4f6..8ef8368ef 100644 --- a/internal/panel/subs/mihomo_preview.go +++ b/internal/panel/subs/mihomo_preview.go @@ -82,7 +82,7 @@ func (s *Service) PreviewMihomoTemplate(ctx context.Context, req *connect.Reques if !p.note { p.lines = redactedLines(p.lines) } - body, selected, templated, err := p.render("draft", m.Yaml, true) + body, selected, templated, err := p.render("draft", m.Yaml) if err != nil { if errors.Is(err, subsettings.ErrMihomoFilterBudget) { if canceled := contextError(err); canceled != nil { diff --git a/internal/panel/subs/mihomo_template_internal_test.go b/internal/panel/subs/mihomo_template_internal_test.go index 39f28dafa..5a6067377 100644 --- a/internal/panel/subs/mihomo_template_internal_test.go +++ b/internal/panel/subs/mihomo_template_internal_test.go @@ -35,7 +35,7 @@ var hostileNames = []string{ func templated(t *testing.T, tpl string, p mihomoProfile) (string, bool) { t.Helper() - b, _, used, err := p.render("tpl", tpl, false) + b, _, used, err := p.render("tpl", tpl) if err != nil { t.Fatal(err) } @@ -384,7 +384,7 @@ func TestMihomoTemplateUnusableIsLoggedNotServed(t *testing.T) { var logs bytes.Buffer p := mihomoProfile{title: "T", lines: []string{fixture(t, hy2Line)}, preset: ruSplit(), autoSelect: true, log: slog.New(slog.NewTextHandler(&logs, nil))} want, _ := mihomoProfile{title: "T", lines: p.lines, preset: ruSplit(), autoSelect: true}.build() - out, _, used, err := p.render("Router, v2", text, false) + out, _, used, err := p.render("Router, v2", text) if err != nil || used || string(out) != string(want) { t.Errorf("%s: used %v, err %v", name, used, err) } @@ -423,7 +423,7 @@ func BenchmarkMihomoTemplate(b *testing.B) { b.SetBytes(int64(len(text))) b.ReportAllocs() for i := 0; i < b.N; i++ { - if _, _, used, err := p.render("t", text, false); err != nil || !used { + if _, _, used, err := p.render("t", text); err != nil || !used { b.Fatal(used, err) } } diff --git a/internal/panel/subs/mihomo_template_test.go b/internal/panel/subs/mihomo_template_test.go index 9dee4e9d5..93e17d7ab 100644 --- a/internal/panel/subs/mihomo_template_test.go +++ b/internal/panel/subs/mihomo_template_test.go @@ -2,6 +2,7 @@ package subs_test import ( "bytes" + "errors" "fmt" "log/slog" "net/http" @@ -9,6 +10,7 @@ import ( "os" "path/filepath" "reflect" + "runtime" "slices" "strings" "testing" @@ -534,6 +536,48 @@ func TestMihomoTemplateUnreadableInTheDatabase(t *testing.T) { } } +func TestMihomoTemplateFilterBudget(t *testing.T) { + if runtime.GOOS == "js" { + t.Skip("regexp2 cannot enforce a deadline during synchronous WebAssembly matching") + } + const text = `proxy-groups: + - name: Pick + type: select + mistgate-ordered-proxies: true + filter: '^(b|bb)+$' +rules: ['MATCH,Pick'] +` + r := newTemplateRig(t, nil) + alice, token := r.newUser("alice", nil) + // The filter passes the trial build but not this person's real server name. + name := strings.Repeat("b", 64) + "!" + if _, err := r.st.W.Exec(`UPDATE node SET name = ? WHERE id = 'nod_1'`, name); err != nil { + t.Fatal(err) + } + r.save(t, func(s *adminv1.SubscriptionSettings) { s.ServerNameTemplate = "{node}" }, + &adminv1.MihomoTemplate{Name: "ordered", Yaml: text, GroupIds: []string{r.group2}}) + + t.Run("subscription", func(t *testing.T) { + rec := fetch(r.h, "/"+token, mihomoUA, "Accept-Encoding", "gzip") + if rec.Code != http.StatusInternalServerError || rec.Body.String() != "internal error\n" || + rec.Header().Get("Content-Encoding") != "" { + t.Fatalf("expected an HTTP error without a replacement profile, got %d, %v, %q", rec.Code, rec.Header(), rec.Body) + } + log := r.logs.String() + if !strings.Contains(log, "code=mihomo_template_filter_budget") || + !strings.Contains(log, subsettings.ErrMihomoFilterBudget.Error()) || + strings.Contains(log, "mihomo_template_unusable") || strings.Contains(log, name) || strings.Contains(log, "^(b|bb)+$") { + t.Errorf("expected a distinct, redacted filter budget log, got %q", log) + } + }) + t.Run("preview", func(t *testing.T) { + resp, err := r.preview(t, r.previewService(t, plainPreset), alice, text, r.group2) + if resp != nil || connect.CodeOf(err) != connect.CodeInvalidArgument || !errors.Is(err, subsettings.ErrMihomoFilterBudget) { + t.Fatalf("preview returned %v, %v; want InvalidArgument for the filter budget and no profile", resp, err) + } + }) +} + // The template is read only as text: the panel opens no connection of its own for the URLs in it (the providers are the apps'). func TestMihomoTemplateNeverFetchesItsURLs(t *testing.T) { hit := make(chan string, 4) diff --git a/internal/panel/subs/subs.go b/internal/panel/subs/subs.go index 04b4624ac..26f844122 100644 --- a/internal/panel/subs/subs.go +++ b/internal/panel/subs/subs.go @@ -782,9 +782,13 @@ func (h *handler) writeMihomo(w http.ResponseWriter, r *http.Request, token stri if t := subsettings.MihomoTemplateFor(set, v.GroupID); t != nil { tplName, tplText = t.Name, t.Yaml } - body, _, _, err := p.render(tplName, tplText, false) + body, _, _, err := p.render(tplName, tplText) if err != nil { - h.cfg.Log.Error("mihomo profile", "code", "subscription_mihomo_render_failed", "err", err) + code := "subscription_mihomo_render_failed" + if errors.Is(err, subsettings.ErrMihomoFilterBudget) { + code = "mihomo_template_filter_budget" + } + h.cfg.Log.Error("mihomo profile", "code", code, "err", err) http.Error(w, "internal error", http.StatusInternalServerError) return } diff --git a/internal/panel/subs/testdata/mihomo_template_router.out.yaml b/internal/panel/subs/testdata/mihomo_template_router.out.yaml index b1c94c0a7..97d798aa2 100644 --- a/internal/panel/subs/testdata/mihomo_template_router.out.yaml +++ b/internal/panel/subs/testdata/mihomo_template_router.out.yaml @@ -17,10 +17,8 @@ proxy-groups: - name: Fast <<: *check type: url-test + include-all-proxies: true filter: "(?i)de|nl" - proxies: - - "\U0001F1E9\U0001F1EA de1 · hy2" - - "\U0001F1F3\U0001F1F1 nl1 · awg" - name: "Auto" type: url-test proxies: diff --git a/internal/panel/subs/testdata/mihomo_template_router.yaml b/internal/panel/subs/testdata/mihomo_template_router.yaml index 30a2a03b9..b87432398 100644 --- a/internal/panel/subs/testdata/mihomo_template_router.yaml +++ b/internal/panel/subs/testdata/mihomo_template_router.yaml @@ -20,7 +20,7 @@ proxy-groups: - name: Fast <<: *check type: url-test - mistgate-ordered-proxies: true + include-all-proxies: true filter: "(?i)de|nl" rule-providers: diff --git a/internal/panel/subsettings/mihomo.go b/internal/panel/subsettings/mihomo.go index 64c420b3b..cfbd1680b 100644 --- a/internal/panel/subsettings/mihomo.go +++ b/internal/panel/subsettings/mihomo.go @@ -53,7 +53,6 @@ const ( const ( maxRuleTargetWarnings = 10 autoURL = "https://www.gstatic.com/generate_204" - trialServerCount = 2 ) // MihomoWarning is one finding of a template that does not stop a save: the profile works, and the owner should look. @@ -254,13 +253,13 @@ type tplNamed struct { } type tplGroup struct { - Name string `yaml:"name"` - Type string `yaml:"type"` - Proxies []string `yaml:"proxies"` - Use []string `yaml:"use"` - IncludeAllProxies bool `yaml:"include-all-proxies"` - IncludeAll bool `yaml:"include-all"` - OrderedProxies mihomoOrderFlag `yaml:"mistgate-ordered-proxies"` + Name string `yaml:"name"` + Type string `yaml:"type"` + Proxies []string `yaml:"proxies"` + Use []string `yaml:"use"` + IncludeAllProxies bool `yaml:"include-all-proxies"` + IncludeAll bool `yaml:"include-all"` + OrderedProxies yaml.Node `yaml:"mistgate-ordered-proxies"` order *mihomoOrderedOptions } @@ -318,7 +317,19 @@ func loadTemplate(text string) (*tplInfo, error) { if g.Type == "" { return nil, fmt.Errorf("proxy-groups[%d] %q: a type is required", i, g.Name) } - if !g.OrderedProxies { + // Decode the node so an explicit YAML null is not treated like an omitted flag. + flag := &g.OrderedProxies + if flag.Kind == 0 { + continue + } + if flag.ShortTag() != "!!bool" { + return nil, mihomoYAMLDiagnostic{err: fmt.Errorf("line %d: %s must be a YAML boolean", flag.Line, mihomoOrderedProxiesKey)} + } + var ordered bool + if err := flag.Decode(&ordered); err != nil { + return nil, mihomoYAMLDiagnostic{err: err} + } + if !ordered { continue } opt, err := readMihomoOrderedOptions(groupNodes.Content[i], i) @@ -441,7 +452,7 @@ func checkMihomoTemplate(ctx context.Context, text string, autoOn bool, sourceEr if err := ctx.Err(); err != nil { return err } - // A trial build with two servers, as a person would get it: an error of the encoder is found here, not in the apps. + // Build with sample servers, including a long name to catch filters that are only slow on longer input. out, err := applyLoadedMihomoTemplate(t, trialServers(), MihomoOptions{AutoSelect: autoOn}) if err != nil { return fmt.Errorf("trial build: %w", mapError(err)) @@ -475,9 +486,10 @@ func commentedMihomoMarker(doc *yaml.Node) (string, bool) { } func trialServers() []MihomoServer { - out := make([]MihomoServer, trialServerCount) - for i := range out { - name := "server " + strconv.Itoa(i+1) + const longName = "server 3 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa!" + names := [...]string{"server 1", "server 2", longName} + out := make([]MihomoServer, len(names)) + for i, name := range names { out[i] = MihomoServer{Name: name, Node: mapOf( strNode("name"), quotedNode(name), strNode("type"), strNode("hysteria2"), strNode("server"), quotedNode("example.com"), strNode("port"), intNode(443), strNode("password"), quotedNode("x"))} @@ -618,7 +630,7 @@ func MihomoTemplateWarnings(text string, autoOn bool) []MihomoWarning { ownAuto := t.names[AutoName] takes := false for _, g := range t.groups { - takes = takes || bool(g.OrderedProxies) || g.IncludeAllProxies || g.IncludeAll || (autoOn && !ownAuto && slices.Contains(g.Proxies, AutoName)) + takes = takes || g.order != nil || g.IncludeAllProxies || g.IncludeAll || (autoOn && !ownAuto && slices.Contains(g.Proxies, AutoName)) } if !takes { out = append(out, MihomoWarning{Code: WarnNoServerGroup}) diff --git a/internal/panel/subsettings/mihomo_ordered_groups.go b/internal/panel/subsettings/mihomo_ordered_groups.go index 3d8d91f2d..7dd77196c 100644 --- a/internal/panel/subsettings/mihomo_ordered_groups.go +++ b/internal/panel/subsettings/mihomo_ordered_groups.go @@ -24,11 +24,13 @@ func init() { regexp2.SetTimeoutCheckPeriod(mihomoFilterClockPeriod) } -// ErrMihomoFilterBudget is safe to return to the template editor. +// ErrMihomoFilterBudget does not contain the pattern or server names and is safe to return to the editor and log. var ErrMihomoFilterBudget = errors.New("filter exceeded the matching time limit") // A filter cache belongs to one render. Regexp.MatchTimeout is mutable, so // these expressions cannot be shared across renders. +// The budget uses wall time. On Cloudflare Workers the clock does not advance +// during synchronous matching, so the Worker's CPU limit is the backstop. type mihomoGroupFilters struct { compiled map[string]*regexp2.Regexp deadline time.Time @@ -150,15 +152,6 @@ func readMihomoOrderedOptions(group *yaml.Node, index int) (*mihomoOrderedOption return opt, nil } -type mihomoOrderFlag bool - -func (enabled *mihomoOrderFlag) UnmarshalYAML(n *yaml.Node) error { - if n.ShortTag() != "!!bool" { - return fmt.Errorf("line %d: %s must be a YAML boolean", n.Line, mihomoOrderedProxiesKey) - } - return n.Decode((*bool)(enabled)) -} - type mihomoNativeText string func (text *mihomoNativeText) UnmarshalYAML(n *yaml.Node) error { diff --git a/internal/panel/subsettings/mihomo_ordered_groups_test.go b/internal/panel/subsettings/mihomo_ordered_groups_test.go index 280e1d57e..9091bb409 100644 --- a/internal/panel/subsettings/mihomo_ordered_groups_test.go +++ b/internal/panel/subsettings/mihomo_ordered_groups_test.go @@ -3,6 +3,7 @@ package subsettings import ( "context" "errors" + "runtime" "slices" "strings" "testing" @@ -108,7 +109,7 @@ proxy-groups: } }) t.Run("the opt-in must be a YAML boolean", func(t *testing.T) { - for _, value := range []string{`"on"`, `"yes"`, "on", "1"} { + for _, value := range []string{`"on"`, `"yes"`, "on", "1", "null", "", "[true]"} { text := head + " mistgate-ordered-proxies: " + value + "\n" if err := CheckMihomoTemplate(text, false); err == nil || !strings.Contains(err.Error(), "mistgate-ordered-proxies must be a YAML boolean") { t.Fatalf("%s: save validation error = %v", value, err) @@ -240,7 +241,7 @@ x-include-key: &include-key mistgate-ordered-proxies if err != nil { t.Fatal(err) } - if got := info.groups[0]; bool(got.OrderedProxies) || !slices.Equal(got.Proxies, []string{"DIRECT", "Zulu", "Alpha"}) { + if got := info.groups[0]; got.OrderedProxies.Kind != 0 || !slices.Equal(got.Proxies, []string{"DIRECT", "Zulu", "Alpha"}) { t.Fatalf("group = %+v", got) } if err := CheckMihomoTemplate(out, false); err != nil { @@ -279,3 +280,31 @@ x-list: &list [{name: Pick, type: select, include-all-proxies: true}] } }) } + +func TestMihomoFilterBudgetNative(t *testing.T) { + if runtime.GOOS == "js" { + t.Skip("regexp2 cannot enforce a deadline during synchronous WebAssembly matching") + } + const text = `proxy-groups: + - name: Pick + type: select + mistgate-ordered-proxies: true + filter: '^(\w+\s?)*$' +` + t.Run("render", func(t *testing.T) { + servers := []MihomoServer{serverNode(t, strings.Repeat("a", 64)+"!")} + start := time.Now() + got, err := ApplyMihomoTemplate(text, servers, MihomoOptions{}) + if got != nil || !errors.Is(err, ErrMihomoFilterBudget) { + t.Fatalf("render returned %q, %v; want filter budget error and no profile", got, err) + } + if elapsed := time.Since(start); elapsed >= 800*time.Millisecond { + t.Errorf("render exceeded 800 ms: %s", elapsed) + } + }) + t.Run("save with sample names", func(t *testing.T) { + if err := CheckMihomoTemplate(text, false); !errors.Is(err, ErrMihomoFilterBudget) { + t.Fatalf("save validation returned %v; want filter budget error", err) + } + }) +} diff --git a/proto/mistgate/admin/v1/subscription.proto b/proto/mistgate/admin/v1/subscription.proto index 8b071f2f8..4b8859264 100644 --- a/proto/mistgate/admin/v1/subscription.proto +++ b/proto/mistgate/admin/v1/subscription.proto @@ -137,9 +137,9 @@ message RoutingInfo { // One Mihomo YAML profile of the owner. The panel puts the servers of the person at the start of its `proxies` and, while // link_auto_select is on and the template has no group of that name, adds a url-test group `Auto` over them at the end of its -// `proxy-groups`; groups take the servers with `include-all-proxies` or `filter`. `dns` is added (resolvers of the person's preset, -// respect-rules on) only when the template has none. Everything else is left as written, comments included. The panel never -// fetches a URL of a template. +// `proxy-groups`. Groups can opt in to panel order with `mistgate-ordered-proxies: true`, or let Mihomo include and sort +// servers with `include-all-proxies` or `include-all`. `dns` is added (preset resolvers, respect-rules on) only when the +// template has none. The panel never fetches a URL of a template. // // A save is refused (INVALID_ARGUMENT, the text names the line) unless the text is one valid YAML document that parses in full (no // alias bomb, no repeated key), has a mapping at its root, `proxies` and `proxy-groups` that are lists (or absent) with named @@ -390,9 +390,9 @@ message PreviewMihomoTemplateRequest { } // One finding that does not stop a save (SubscriptionService words them by code). code is one of: no_server_group (no group takes the -// servers of the person: include-all-proxies, or Auto), own_dns (the person's DNS preset is not applied to this template), -// preset_rules_skipped (the preset has ad, split or country rules that a template does not get), own_auto (the template has its own -// Auto, so the panel adds none), unknown_rule_target (arg: the last field of a rule that names no proxy or group), unused (no group). +// servers of the person: `mistgate-ordered-proxies`, `include-all-proxies`, `include-all`, or `Auto`), own_dns (the person's +// DNS preset is not applied), preset_rules_skipped (the preset's ad, split or country rules are not applied), own_auto (the +// template has its own Auto), unknown_rule_target (arg: the last field of a rule that names no proxy or group), unused (no group). message MihomoWarning { string code = 1; string arg = 2; diff --git a/scripts/check-edge-sizes.sh b/scripts/check-edge-sizes.sh index 01ec10234..e9fed3601 100755 --- a/scripts/check-edge-sizes.sh +++ b/scripts/check-edge-sizes.sh @@ -45,6 +45,8 @@ entries=( # 30 MiB in November 2026 (29.01 MiB measured with group blocks in a Mihomo template also in, 13 KiB over 29): the relay # leg's address family (Relay.leg, NodeAddrs.LegHost, the check's family) is subscription code — the relay twin's usability # and its target are built in this Worker, so it cannot move to another role. + # Ordered Mihomo template groups bring the public Worker to 29.8 MiB (228 KiB left): it matches filters against each + # person's proxy names while serving their subscription. "mistgate-edge-public:30" # The agent link: wireCore plus the link driver. Measured 26.4 MiB. # 31 MiB in November 2026 (30.003 MiB measured, 2.9 KiB over 30): nothing of own probes runs here (the service, its diff --git a/third_party/regexp2/LICENSE b/third_party/regexp2/LICENSE deleted file mode 100644 index fe83dfdc9..000000000 --- a/third_party/regexp2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Doug Clark - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/third_party/regexp2/fastclock.go b/third_party/regexp2/fastclock.go deleted file mode 100644 index 70bfbad2a..000000000 --- a/third_party/regexp2/fastclock.go +++ /dev/null @@ -1,158 +0,0 @@ -package regexp2 - -import ( - "runtime" - "sync" - "sync/atomic" - "time" -) - -// fasttime holds a time value (ticks since clock initialization) -type fasttime int64 - -// fastclock provides a fast clock implementation. -// -// A background goroutine periodically stores the current time -// into an atomic variable. -// -// A deadline can be quickly checked for expiration by comparing -// its value to the clock stored in the atomic variable. -// -// The goroutine automatically stops once clockEnd is reached. -// (clockEnd covers the largest deadline seen so far + some -// extra time). This ensures that if regexp2 with timeouts -// stops being used we will stop background work. -type fastclock struct { - // instances of atomicTime must be at the start of the struct (or at least 64-bit aligned) - // otherwise 32-bit architectures will panic - - current atomicTime // Current time (approximate) - clockEnd atomicTime // When clock updater is supposed to stop (>= any existing deadline) - - // current and clockEnd can be read via atomic loads. - // Reads and writes of other fields require mu to be held. - mu sync.Mutex - start time.Time // Time corresponding to fasttime(0) - running bool // Is a clock updater running? -} - -var fast fastclock - -var wasmClockStart time.Time - -func init() { - if runtime.GOARCH == "wasm" { - wasmClockStart = time.Now() - } -} - -// reached returns true if current time is at or past t. -func (t fasttime) reached() bool { - if runtime.GOARCH == "wasm" { - return durationToTicks(time.Since(wasmClockStart)) >= t - } - return fast.current.read() >= t -} - -// makeDeadline returns a time that is approximately time.Now().Add(d) -func makeDeadline(d time.Duration) fasttime { - // js/wasm cannot run the clock goroutine while the interpreter is busy. - // Poll its monotonic clock directly instead. - if runtime.GOARCH == "wasm" { - return durationToTicks(time.Since(wasmClockStart) + d) - } - // Increase the deadline since the clock we are reading may be - // just about to tick forwards. - end := fast.current.read() + durationToTicks(d+clockPeriod) - - // Start or extend clock if necessary. - if end > fast.clockEnd.read() { - // If time.Since(last use) > timeout, there's a chance that - // fast.current will no longer be updated, which can lead to - // incorrect 'end' calculations that can trigger a false timeout - fast.mu.Lock() - if !fast.running && !fast.start.IsZero() { - // update fast.current - fast.current.write(durationToTicks(time.Since(fast.start))) - // recalculate our end value - end = fast.current.read() + durationToTicks(d+clockPeriod) - } - fast.mu.Unlock() - extendClock(end) - } - - return end -} - -// extendClock ensures that clock is live and will run until at least end. -func extendClock(end fasttime) { - fast.mu.Lock() - defer fast.mu.Unlock() - - if fast.start.IsZero() { - fast.start = time.Now() - } - - // Extend the running time to cover end as well as a bit of slop. - if shutdown := end + durationToTicks(time.Second); shutdown > fast.clockEnd.read() { - fast.clockEnd.write(shutdown) - } - - // Start clock if necessary - if !fast.running { - fast.running = true - go runClock() - } -} - -// stop the timeout clock in the background -// should only used for unit tests to abandon the background goroutine -func stopClock() { - fast.mu.Lock() - if fast.running { - fast.clockEnd.write(fasttime(0)) - } - fast.mu.Unlock() - - // pause until not running - // get and release the lock - isRunning := true - for isRunning { - time.Sleep(clockPeriod / 2) - fast.mu.Lock() - isRunning = fast.running - fast.mu.Unlock() - } -} - -func durationToTicks(d time.Duration) fasttime { - // Downscale nanoseconds to approximately a millisecond so that we can avoid - // overflow even if the caller passes in math.MaxInt64. - return fasttime(d) >> 20 -} - -const DefaultClockPeriod = 100 * time.Millisecond - -// clockPeriod is the approximate interval between updates of approximateClock. -var clockPeriod = DefaultClockPeriod - -func runClock() { - fast.mu.Lock() - defer fast.mu.Unlock() - - for fast.current.read() <= fast.clockEnd.read() { - // Unlock while sleeping. - fast.mu.Unlock() - time.Sleep(clockPeriod) - fast.mu.Lock() - - newTime := durationToTicks(time.Since(fast.start)) - fast.current.write(newTime) - } - fast.running = false -} - -type atomicTime struct{ v int64 } // Should change to atomic.Int64 when we can use go 1.19 - -func (t *atomicTime) read() fasttime { return fasttime(atomic.LoadInt64(&t.v)) } -func (t *atomicTime) write(v fasttime) { atomic.StoreInt64(&t.v, int64(v)) } diff --git a/third_party/regexp2/fastclock_wasm_test.go b/third_party/regexp2/fastclock_wasm_test.go deleted file mode 100644 index 3a3a92049..000000000 --- a/third_party/regexp2/fastclock_wasm_test.go +++ /dev/null @@ -1,20 +0,0 @@ -//go:build wasm -// +build wasm - -package regexp2 - -import ( - "testing" - "time" -) - -func TestDeadlineWithoutAnotherGoroutine(t *testing.T) { - deadline := makeDeadline(5 * time.Millisecond) - // The matcher must observe expiry even when nothing yields to the scheduler. - end := time.Now().Add(100 * time.Millisecond) - for !deadline.reached() { - if time.Now().After(end) { - t.Fatal("the deadline did not expire on the matching goroutine") - } - } -} diff --git a/third_party/regexp2/go.mod b/third_party/regexp2/go.mod deleted file mode 100644 index 9f7f391eb..000000000 --- a/third_party/regexp2/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/dlclark/regexp2 - -go 1.13 diff --git a/third_party/regexp2/match.go b/third_party/regexp2/match.go deleted file mode 100644 index 759cf8ccf..000000000 --- a/third_party/regexp2/match.go +++ /dev/null @@ -1,349 +0,0 @@ -package regexp2 - -import ( - "bytes" - "fmt" -) - -// Match is a single regex result match that contains groups and repeated captures -// -// -Groups -// -Capture -type Match struct { - Group //embeded group 0 - - regex *Regexp - otherGroups []Group - - // input to the match - textpos int - textstart int - - capcount int - caps []int - sparseCaps map[int]int - - // output from the match - matches [][]int - matchcount []int - - // whether we've done any balancing with this match. If we - // have done balancing, we'll need to do extra work in Tidy(). - balancing bool -} - -// Group is an explicit or implit (group 0) matched group within the pattern -type Group struct { - Capture // the last capture of this group is embeded for ease of use - - Name string // group name - Captures []Capture // captures of this group -} - -// Capture is a single capture of text within the larger original string -type Capture struct { - // the original string - text []rune - // Index is the position in the underlying rune slice where the first character of - // captured substring was found. Even if you pass in a string this will be in Runes. - Index int - // Length is the number of runes in the captured substring. - Length int -} - -// String returns the captured text as a String -func (c *Capture) String() string { - return string(c.text[c.Index : c.Index+c.Length]) -} - -// Runes returns the captured text as a rune slice -func (c *Capture) Runes() []rune { - return c.text[c.Index : c.Index+c.Length] -} - -func newMatch(regex *Regexp, capcount int, text []rune, startpos int) *Match { - m := Match{ - regex: regex, - matchcount: make([]int, capcount), - matches: make([][]int, capcount), - textstart: startpos, - balancing: false, - } - m.Name = "0" - m.text = text - m.matches[0] = make([]int, 2) - return &m -} - -func newMatchSparse(regex *Regexp, caps map[int]int, capcount int, text []rune, startpos int) *Match { - m := newMatch(regex, capcount, text, startpos) - m.sparseCaps = caps - return m -} - -func (m *Match) reset(text []rune, textstart int) { - m.text = text - m.textstart = textstart - for i := 0; i < len(m.matchcount); i++ { - m.matchcount[i] = 0 - } - m.balancing = false -} - -func (m *Match) tidy(textpos int) { - - interval := m.matches[0] - m.Index = interval[0] - m.Length = interval[1] - m.textpos = textpos - m.capcount = m.matchcount[0] - //copy our root capture to the list - m.Group.Captures = []Capture{m.Group.Capture} - - if m.balancing { - // The idea here is that we want to compact all of our unbalanced captures. To do that we - // use j basically as a count of how many unbalanced captures we have at any given time - // (really j is an index, but j/2 is the count). First we skip past all of the real captures - // until we find a balance captures. Then we check each subsequent entry. If it's a balance - // capture (it's negative), we decrement j. If it's a real capture, we increment j and copy - // it down to the last free position. - for cap := 0; cap < len(m.matchcount); cap++ { - limit := m.matchcount[cap] * 2 - matcharray := m.matches[cap] - - var i, j int - - for i = 0; i < limit; i++ { - if matcharray[i] < 0 { - break - } - } - - for j = i; i < limit; i++ { - if matcharray[i] < 0 { - // skip negative values - j-- - } else { - // but if we find something positive (an actual capture), copy it back to the last - // unbalanced position. - if i != j { - matcharray[j] = matcharray[i] - } - j++ - } - } - - m.matchcount[cap] = j / 2 - } - - m.balancing = false - } -} - -// isMatched tells if a group was matched by capnum -func (m *Match) isMatched(cap int) bool { - return cap < len(m.matchcount) && m.matchcount[cap] > 0 && m.matches[cap][m.matchcount[cap]*2-1] != (-3+1) -} - -// matchIndex returns the index of the last specified matched group by capnum -func (m *Match) matchIndex(cap int) int { - i := m.matches[cap][m.matchcount[cap]*2-2] - if i >= 0 { - return i - } - - return m.matches[cap][-3-i] -} - -// matchLength returns the length of the last specified matched group by capnum -func (m *Match) matchLength(cap int) int { - i := m.matches[cap][m.matchcount[cap]*2-1] - if i >= 0 { - return i - } - - return m.matches[cap][-3-i] -} - -// Nonpublic builder: add a capture to the group specified by "c" -func (m *Match) addMatch(c, start, l int) { - - if m.matches[c] == nil { - m.matches[c] = make([]int, 2) - } - - capcount := m.matchcount[c] - - if capcount*2+2 > len(m.matches[c]) { - oldmatches := m.matches[c] - newmatches := make([]int, capcount*8) - copy(newmatches, oldmatches[:capcount*2]) - m.matches[c] = newmatches - } - - m.matches[c][capcount*2] = start - m.matches[c][capcount*2+1] = l - m.matchcount[c] = capcount + 1 - //log.Printf("addMatch: c=%v, i=%v, l=%v ... matches: %v", c, start, l, m.matches) -} - -// Nonpublic builder: Add a capture to balance the specified group. This is used by the -// -// balanced match construct. (?...) -// -// If there were no such thing as backtracking, this would be as simple as calling RemoveMatch(c). -// However, since we have backtracking, we need to keep track of everything. -func (m *Match) balanceMatch(c int) { - m.balancing = true - - // we'll look at the last capture first - capcount := m.matchcount[c] - target := capcount*2 - 2 - - // first see if it is negative, and therefore is a reference to the next available - // capture group for balancing. If it is, we'll reset target to point to that capture. - if m.matches[c][target] < 0 { - target = -3 - m.matches[c][target] - } - - // move back to the previous capture - target -= 2 - - // if the previous capture is a reference, just copy that reference to the end. Otherwise, point to it. - if target >= 0 && m.matches[c][target] < 0 { - m.addMatch(c, m.matches[c][target], m.matches[c][target+1]) - } else { - m.addMatch(c, -3-target, -4-target /* == -3 - (target + 1) */) - } -} - -// Nonpublic builder: removes a group match by capnum -func (m *Match) removeMatch(c int) { - m.matchcount[c]-- -} - -// GroupCount returns the number of groups this match has matched -func (m *Match) GroupCount() int { - return len(m.matchcount) -} - -// GroupByName returns a group based on the name of the group, or nil if the group name does not exist -func (m *Match) GroupByName(name string) *Group { - num := m.regex.GroupNumberFromName(name) - if num < 0 { - return nil - } - return m.GroupByNumber(num) -} - -// GroupByNumber returns a group based on the number of the group, or nil if the group number does not exist -func (m *Match) GroupByNumber(num int) *Group { - // check our sparse map - if m.sparseCaps != nil { - if newNum, ok := m.sparseCaps[num]; ok { - num = newNum - } - } - if num >= len(m.matchcount) || num < 0 { - return nil - } - - if num == 0 { - return &m.Group - } - - m.populateOtherGroups() - - return &m.otherGroups[num-1] -} - -// Groups returns all the capture groups, starting with group 0 (the full match) -func (m *Match) Groups() []Group { - m.populateOtherGroups() - g := make([]Group, len(m.otherGroups)+1) - g[0] = m.Group - copy(g[1:], m.otherGroups) - return g -} - -func (m *Match) populateOtherGroups() { - // Construct all the Group objects first time called - if m.otherGroups == nil { - m.otherGroups = make([]Group, len(m.matchcount)-1) - for i := 0; i < len(m.otherGroups); i++ { - m.otherGroups[i] = newGroup(m.regex.GroupNameFromNumber(i+1), m.text, m.matches[i+1], m.matchcount[i+1]) - } - } -} - -func (m *Match) groupValueAppendToBuf(groupnum int, buf *bytes.Buffer) { - c := m.matchcount[groupnum] - if c == 0 { - return - } - - matches := m.matches[groupnum] - - index := matches[(c-1)*2] - last := index + matches[(c*2)-1] - - for ; index < last; index++ { - buf.WriteRune(m.text[index]) - } -} - -func newGroup(name string, text []rune, caps []int, capcount int) Group { - g := Group{} - g.text = text - if capcount > 0 { - g.Index = caps[(capcount-1)*2] - g.Length = caps[(capcount*2)-1] - } - g.Name = name - g.Captures = make([]Capture, capcount) - for i := 0; i < capcount; i++ { - g.Captures[i] = Capture{ - text: text, - Index: caps[i*2], - Length: caps[i*2+1], - } - } - //log.Printf("newGroup! capcount %v, %+v", capcount, g) - - return g -} - -func (m *Match) dump() string { - buf := &bytes.Buffer{} - buf.WriteRune('\n') - if len(m.sparseCaps) > 0 { - for k, v := range m.sparseCaps { - fmt.Fprintf(buf, "Slot %v -> %v\n", k, v) - } - } - - for i, g := range m.Groups() { - fmt.Fprintf(buf, "Group %v (%v), %v caps:\n", i, g.Name, len(g.Captures)) - - for _, c := range g.Captures { - fmt.Fprintf(buf, " (%v, %v) %v\n", c.Index, c.Length, c.String()) - } - } - /* - for i := 0; i < len(m.matchcount); i++ { - fmt.Fprintf(buf, "\nGroup %v (%v):\n", i, m.regex.GroupNameFromNumber(i)) - - for j := 0; j < m.matchcount[i]; j++ { - text := "" - - if m.matches[i][j*2] >= 0 { - start := m.matches[i][j*2] - text = m.text[start : start+m.matches[i][j*2+1]] - } - - fmt.Fprintf(buf, " (%v, %v) %v\n", m.matches[i][j*2], m.matches[i][j*2+1], text) - } - } - */ - return buf.String() -} diff --git a/third_party/regexp2/regexp.go b/third_party/regexp2/regexp.go deleted file mode 100644 index a7ddbaf35..000000000 --- a/third_party/regexp2/regexp.go +++ /dev/null @@ -1,395 +0,0 @@ -/* -Package regexp2 is a regexp package that has an interface similar to Go's framework regexp engine but uses a -more feature full regex engine behind the scenes. - -It doesn't have constant time guarantees, but it allows backtracking and is compatible with Perl5 and .NET. -You'll likely be better off with the RE2 engine from the regexp package and should only use this if you -need to write very complex patterns or require compatibility with .NET. -*/ -package regexp2 - -import ( - "errors" - "math" - "strconv" - "sync" - "time" - - "github.com/dlclark/regexp2/syntax" -) - -var ( - // DefaultMatchTimeout used when running regexp matches -- "forever" - DefaultMatchTimeout = time.Duration(math.MaxInt64) - // DefaultUnmarshalOptions used when unmarshaling a regex from text - DefaultUnmarshalOptions = None -) - -// Regexp is the representation of a compiled regular expression. -// A Regexp is safe for concurrent use by multiple goroutines. -type Regexp struct { - // A match will time out if it takes (approximately) more than - // MatchTimeout. This is a safety check in case the match - // encounters catastrophic backtracking. The default value - // (DefaultMatchTimeout) causes all time out checking to be - // suppressed. - MatchTimeout time.Duration - - // read-only after Compile - pattern string // as passed to Compile - options RegexOptions // options - - caps map[int]int // capnum->index - capnames map[string]int //capture group name -> index - capslist []string //sorted list of capture group names - capsize int // size of the capture array - - code *syntax.Code // compiled program - - // cache of machines for running regexp - muRun *sync.Mutex - runner []*runner -} - -// Compile parses a regular expression and returns, if successful, -// a Regexp object that can be used to match against text. -func Compile(expr string, opt RegexOptions) (*Regexp, error) { - // parse it - tree, err := syntax.Parse(expr, syntax.RegexOptions(opt)) - if err != nil { - return nil, err - } - - // translate it to code - code, err := syntax.Write(tree) - if err != nil { - return nil, err - } - - // return it - return &Regexp{ - pattern: expr, - options: opt, - caps: code.Caps, - capnames: tree.Capnames, - capslist: tree.Caplist, - capsize: code.Capsize, - code: code, - MatchTimeout: DefaultMatchTimeout, - muRun: &sync.Mutex{}, - }, nil -} - -// MustCompile is like Compile but panics if the expression cannot be parsed. -// It simplifies safe initialization of global variables holding compiled regular -// expressions. -func MustCompile(str string, opt RegexOptions) *Regexp { - regexp, error := Compile(str, opt) - if error != nil { - panic(`regexp2: Compile(` + quote(str) + `): ` + error.Error()) - } - return regexp -} - -// Escape adds backslashes to any special characters in the input string -func Escape(input string) string { - return syntax.Escape(input) -} - -// Unescape removes any backslashes from previously-escaped special characters in the input string -func Unescape(input string) (string, error) { - return syntax.Unescape(input) -} - -// SetTimeoutPeriod is a debug function that sets the frequency of the timeout goroutine's sleep cycle. -// Defaults to 100ms. The only benefit of setting this lower is that the 1 background goroutine that manages -// timeouts may exit slightly sooner after all the timeouts have expired. See Github issue #63 -func SetTimeoutCheckPeriod(d time.Duration) { - clockPeriod = d -} - -// StopTimeoutClock should only be used in unit tests to prevent the timeout clock goroutine -// from appearing like a leaking goroutine -func StopTimeoutClock() { - stopClock() -} - -// String returns the source text used to compile the regular expression. -func (re *Regexp) String() string { - return re.pattern -} - -func quote(s string) string { - if strconv.CanBackquote(s) { - return "`" + s + "`" - } - return strconv.Quote(s) -} - -// RegexOptions impact the runtime and parsing behavior -// for each specific regex. They are setable in code as well -// as in the regex pattern itself. -type RegexOptions int32 - -const ( - None RegexOptions = 0x0 - IgnoreCase = 0x0001 // "i" - Multiline = 0x0002 // "m" - ExplicitCapture = 0x0004 // "n" - Compiled = 0x0008 // "c" - Singleline = 0x0010 // "s" - IgnorePatternWhitespace = 0x0020 // "x" - RightToLeft = 0x0040 // "r" - Debug = 0x0080 // "d" - ECMAScript = 0x0100 // "e" - RE2 = 0x0200 // RE2 (regexp package) compatibility mode - Unicode = 0x0400 // "u" -) - -func (re *Regexp) RightToLeft() bool { - return re.options&RightToLeft != 0 -} - -func (re *Regexp) Debug() bool { - return re.options&Debug != 0 -} - -// Replace searches the input string and replaces each match found with the replacement text. -// Count will limit the number of matches attempted and startAt will allow -// us to skip past possible matches at the start of the input (left or right depending on RightToLeft option). -// Set startAt and count to -1 to go through the whole string -func (re *Regexp) Replace(input, replacement string, startAt, count int) (string, error) { - data, err := syntax.NewReplacerData(replacement, re.caps, re.capsize, re.capnames, syntax.RegexOptions(re.options)) - if err != nil { - return "", err - } - //TODO: cache ReplacerData - - return replace(re, data, nil, input, startAt, count) -} - -// ReplaceFunc searches the input string and replaces each match found using the string from the evaluator -// Count will limit the number of matches attempted and startAt will allow -// us to skip past possible matches at the start of the input (left or right depending on RightToLeft option). -// Set startAt and count to -1 to go through the whole string. -func (re *Regexp) ReplaceFunc(input string, evaluator MatchEvaluator, startAt, count int) (string, error) { - return replace(re, nil, evaluator, input, startAt, count) -} - -// FindStringMatch searches the input string for a Regexp match -func (re *Regexp) FindStringMatch(s string) (*Match, error) { - // convert string to runes - return re.run(false, -1, getRunes(s)) -} - -// FindRunesMatch searches the input rune slice for a Regexp match -func (re *Regexp) FindRunesMatch(r []rune) (*Match, error) { - return re.run(false, -1, r) -} - -// FindStringMatchStartingAt searches the input string for a Regexp match starting at the startAt index -func (re *Regexp) FindStringMatchStartingAt(s string, startAt int) (*Match, error) { - if startAt > len(s) { - return nil, errors.New("startAt must be less than the length of the input string") - } - r, startAt := re.getRunesAndStart(s, startAt) - if startAt == -1 { - // we didn't find our start index in the string -- that's a problem - return nil, errors.New("startAt must align to the start of a valid rune in the input string") - } - - return re.run(false, startAt, r) -} - -// FindRunesMatchStartingAt searches the input rune slice for a Regexp match starting at the startAt index -func (re *Regexp) FindRunesMatchStartingAt(r []rune, startAt int) (*Match, error) { - return re.run(false, startAt, r) -} - -// FindNextMatch returns the next match in the same input string as the match parameter. -// Will return nil if there is no next match or if given a nil match. -func (re *Regexp) FindNextMatch(m *Match) (*Match, error) { - if m == nil { - return nil, nil - } - - // If previous match was empty, advance by one before matching to prevent - // infinite loop - startAt := m.textpos - if m.Length == 0 { - if m.textpos == len(m.text) { - return nil, nil - } - - if re.RightToLeft() { - startAt-- - } else { - startAt++ - } - } - return re.run(false, startAt, m.text) -} - -// MatchString return true if the string matches the regex -// error will be set if a timeout occurs -func (re *Regexp) MatchString(s string) (bool, error) { - m, err := re.run(true, -1, getRunes(s)) - if err != nil { - return false, err - } - return m != nil, nil -} - -func (re *Regexp) getRunesAndStart(s string, startAt int) ([]rune, int) { - if startAt < 0 { - if re.RightToLeft() { - r := getRunes(s) - return r, len(r) - } - return getRunes(s), 0 - } - ret := make([]rune, len(s)) - i := 0 - runeIdx := -1 - for strIdx, r := range s { - if strIdx == startAt { - runeIdx = i - } - ret[i] = r - i++ - } - if startAt == len(s) { - runeIdx = i - } - return ret[:i], runeIdx -} - -func getRunes(s string) []rune { - return []rune(s) -} - -// MatchRunes return true if the runes matches the regex -// error will be set if a timeout occurs -func (re *Regexp) MatchRunes(r []rune) (bool, error) { - m, err := re.run(true, -1, r) - if err != nil { - return false, err - } - return m != nil, nil -} - -// GetGroupNames Returns the set of strings used to name capturing groups in the expression. -func (re *Regexp) GetGroupNames() []string { - var result []string - - if re.capslist == nil { - result = make([]string, re.capsize) - - for i := 0; i < len(result); i++ { - result[i] = strconv.Itoa(i) - } - } else { - result = make([]string, len(re.capslist)) - copy(result, re.capslist) - } - - return result -} - -// GetGroupNumbers returns the integer group numbers corresponding to a group name. -func (re *Regexp) GetGroupNumbers() []int { - var result []int - - if re.caps == nil { - result = make([]int, re.capsize) - - for i := 0; i < len(result); i++ { - result[i] = i - } - } else { - result = make([]int, len(re.caps)) - - for k, v := range re.caps { - result[v] = k - } - } - - return result -} - -// GroupNameFromNumber retrieves a group name that corresponds to a group number. -// It will return "" for and unknown group number. Unnamed groups automatically -// receive a name that is the decimal string equivalent of its number. -func (re *Regexp) GroupNameFromNumber(i int) string { - if re.capslist == nil { - if i >= 0 && i < re.capsize { - return strconv.Itoa(i) - } - - return "" - } - - if re.caps != nil { - var ok bool - if i, ok = re.caps[i]; !ok { - return "" - } - } - - if i >= 0 && i < len(re.capslist) { - return re.capslist[i] - } - - return "" -} - -// GroupNumberFromName returns a group number that corresponds to a group name. -// Returns -1 if the name is not a recognized group name. Numbered groups -// automatically get a group name that is the decimal string equivalent of its number. -func (re *Regexp) GroupNumberFromName(name string) int { - // look up name if we have a hashtable of names - if re.capnames != nil { - if k, ok := re.capnames[name]; ok { - return k - } - - return -1 - } - - // convert to an int if it looks like a number - result := 0 - for i := 0; i < len(name); i++ { - ch := name[i] - - if ch > '9' || ch < '0' { - return -1 - } - - result *= 10 - result += int(ch - '0') - } - - // return int if it's in range - if result >= 0 && result < re.capsize { - return result - } - - return -1 -} - -// MarshalText implements [encoding.TextMarshaler]. The output -// matches that of calling the [Regexp.String] method. -func (re *Regexp) MarshalText() ([]byte, error) { - return []byte(re.String()), nil -} - -// UnmarshalText implements [encoding.TextUnmarshaler] by calling -// [Compile] on the encoded value. -func (re *Regexp) UnmarshalText(text []byte) error { - newRE, err := Compile(string(text), DefaultUnmarshalOptions) - if err != nil { - return err - } - *re = *newRE - return nil -} diff --git a/third_party/regexp2/replace.go b/third_party/regexp2/replace.go deleted file mode 100644 index 0376bd9d3..000000000 --- a/third_party/regexp2/replace.go +++ /dev/null @@ -1,177 +0,0 @@ -package regexp2 - -import ( - "bytes" - "errors" - - "github.com/dlclark/regexp2/syntax" -) - -const ( - replaceSpecials = 4 - replaceLeftPortion = -1 - replaceRightPortion = -2 - replaceLastGroup = -3 - replaceWholeString = -4 -) - -// MatchEvaluator is a function that takes a match and returns a replacement string to be used -type MatchEvaluator func(Match) string - -// Three very similar algorithms appear below: replace (pattern), -// replace (evaluator), and split. - -// Replace Replaces all occurrences of the regex in the string with the -// replacement pattern. -// -// Note that the special case of no matches is handled on its own: -// with no matches, the input string is returned unchanged. -// The right-to-left case is split out because StringBuilder -// doesn't handle right-to-left string building directly very well. -func replace(regex *Regexp, data *syntax.ReplacerData, evaluator MatchEvaluator, input string, startAt, count int) (string, error) { - if count < -1 { - return "", errors.New("Count too small") - } - if count == 0 { - return "", nil - } - - m, err := regex.FindStringMatchStartingAt(input, startAt) - - if err != nil { - return "", err - } - if m == nil { - return input, nil - } - - buf := &bytes.Buffer{} - text := m.text - - if !regex.RightToLeft() { - prevat := 0 - for m != nil { - if m.Index != prevat { - buf.WriteString(string(text[prevat:m.Index])) - } - prevat = m.Index + m.Length - if evaluator == nil { - replacementImpl(data, buf, m) - } else { - buf.WriteString(evaluator(*m)) - } - - count-- - if count == 0 { - break - } - m, err = regex.FindNextMatch(m) - if err != nil { - return "", nil - } - } - - if prevat < len(text) { - buf.WriteString(string(text[prevat:])) - } - } else { - prevat := len(text) - var al []string - - for m != nil { - if m.Index+m.Length != prevat { - al = append(al, string(text[m.Index+m.Length:prevat])) - } - prevat = m.Index - if evaluator == nil { - replacementImplRTL(data, &al, m) - } else { - al = append(al, evaluator(*m)) - } - - count-- - if count == 0 { - break - } - m, err = regex.FindNextMatch(m) - if err != nil { - return "", nil - } - } - - if prevat > 0 { - buf.WriteString(string(text[:prevat])) - } - - for i := len(al) - 1; i >= 0; i-- { - buf.WriteString(al[i]) - } - } - - return buf.String(), nil -} - -// Given a Match, emits into the StringBuilder the evaluated -// substitution pattern. -func replacementImpl(data *syntax.ReplacerData, buf *bytes.Buffer, m *Match) { - for _, r := range data.Rules { - - if r >= 0 { // string lookup - buf.WriteString(data.Strings[r]) - } else if r < -replaceSpecials { // group lookup - m.groupValueAppendToBuf(-replaceSpecials-1-r, buf) - } else { - switch -replaceSpecials - 1 - r { // special insertion patterns - case replaceLeftPortion: - for i := 0; i < m.Index; i++ { - buf.WriteRune(m.text[i]) - } - case replaceRightPortion: - for i := m.Index + m.Length; i < len(m.text); i++ { - buf.WriteRune(m.text[i]) - } - case replaceLastGroup: - m.groupValueAppendToBuf(m.GroupCount()-1, buf) - case replaceWholeString: - for i := 0; i < len(m.text); i++ { - buf.WriteRune(m.text[i]) - } - } - } - } -} - -func replacementImplRTL(data *syntax.ReplacerData, al *[]string, m *Match) { - l := *al - buf := &bytes.Buffer{} - - for _, r := range data.Rules { - buf.Reset() - if r >= 0 { // string lookup - l = append(l, data.Strings[r]) - } else if r < -replaceSpecials { // group lookup - m.groupValueAppendToBuf(-replaceSpecials-1-r, buf) - l = append(l, buf.String()) - } else { - switch -replaceSpecials - 1 - r { // special insertion patterns - case replaceLeftPortion: - for i := 0; i < m.Index; i++ { - buf.WriteRune(m.text[i]) - } - case replaceRightPortion: - for i := m.Index + m.Length; i < len(m.text); i++ { - buf.WriteRune(m.text[i]) - } - case replaceLastGroup: - m.groupValueAppendToBuf(m.GroupCount()-1, buf) - case replaceWholeString: - for i := 0; i < len(m.text); i++ { - buf.WriteRune(m.text[i]) - } - } - l = append(l, buf.String()) - } - } - - *al = l -} diff --git a/third_party/regexp2/runner.go b/third_party/regexp2/runner.go deleted file mode 100644 index 4bb0dfa1a..000000000 --- a/third_party/regexp2/runner.go +++ /dev/null @@ -1,1614 +0,0 @@ -package regexp2 - -import ( - "bytes" - "errors" - "fmt" - "math" - "strconv" - "strings" - "time" - "unicode" - - "github.com/dlclark/regexp2/syntax" -) - -type runner struct { - re *Regexp - code *syntax.Code - - runtextstart int // starting point for search - - runtext []rune // text to search - runtextpos int // current position in text - runtextend int - - // The backtracking stack. Opcodes use this to store data regarding - // what they have matched and where to backtrack to. Each "frame" on - // the stack takes the form of [CodePosition Data1 Data2...], where - // CodePosition is the position of the current opcode and - // the data values are all optional. The CodePosition can be negative, and - // these values (also called "back2") are used by the BranchMark family of opcodes - // to indicate whether they are backtracking after a successful or failed - // match. - // When we backtrack, we pop the CodePosition off the stack, set the current - // instruction pointer to that code position, and mark the opcode - // with a backtracking flag ("Back"). Each opcode then knows how to - // handle its own data. - runtrack []int - runtrackpos int - - // This stack is used to track text positions across different opcodes. - // For example, in /(a*b)+/, the parentheses result in a SetMark/CaptureMark - // pair. SetMark records the text position before we match a*b. Then - // CaptureMark uses that position to figure out where the capture starts. - // Opcodes which push onto this stack are always paired with other opcodes - // which will pop the value from it later. A successful match should mean - // that this stack is empty. - runstack []int - runstackpos int - - // The crawl stack is used to keep track of captures. Every time a group - // has a capture, we push its group number onto the runcrawl stack. In - // the case of a balanced match, we push BOTH groups onto the stack. - runcrawl []int - runcrawlpos int - - runtrackcount int // count of states that may do backtracking - - runmatch *Match // result object - - ignoreTimeout bool - timeout time.Duration // timeout in milliseconds (needed for actual) - deadline fasttime - - operator syntax.InstOp - codepos int - rightToLeft bool - caseInsensitive bool -} - -// run searches for matches and can continue from the previous match -// -// quick is usually false, but can be true to not return matches, just put it in caches -// textstart is -1 to start at the "beginning" (depending on Right-To-Left), otherwise an index in input -// input is the string to search for our regex pattern -func (re *Regexp) run(quick bool, textstart int, input []rune) (*Match, error) { - - // get a cached runner - runner := re.getRunner() - defer re.putRunner(runner) - - if textstart < 0 { - if re.RightToLeft() { - textstart = len(input) - } else { - textstart = 0 - } - } - - return runner.scan(input, textstart, quick, re.MatchTimeout) -} - -// Scans the string to find the first match. Uses the Match object -// both to feed text in and as a place to store matches that come out. -// -// All the action is in the Go() method. Our -// responsibility is to load up the class members before -// calling Go. -// -// The optimizer can compute a set of candidate starting characters, -// and we could use a separate method Skip() that will quickly scan past -// any characters that we know can't match. -func (r *runner) scan(rt []rune, textstart int, quick bool, timeout time.Duration) (*Match, error) { - r.timeout = timeout - r.ignoreTimeout = (time.Duration(math.MaxInt64) == timeout) - r.runtextstart = textstart - r.runtext = rt - r.runtextend = len(rt) - - stoppos := r.runtextend - bump := 1 - - if r.re.RightToLeft() { - bump = -1 - stoppos = 0 - } - - r.runtextpos = textstart - initted := false - - r.startTimeoutWatch() - for { - if r.re.Debug() { - //fmt.Printf("\nSearch content: %v\n", string(r.runtext)) - fmt.Printf("\nSearch range: from 0 to %v\n", r.runtextend) - fmt.Printf("Firstchar search starting at %v stopping at %v\n", r.runtextpos, stoppos) - } - - if r.findFirstChar() { - if err := r.checkTimeout(); err != nil { - return nil, err - } - - if !initted { - r.initMatch() - initted = true - } - - if r.re.Debug() { - fmt.Printf("Executing engine starting at %v\n\n", r.runtextpos) - } - - if err := r.execute(); err != nil { - return nil, err - } - - if r.runmatch.matchcount[0] > 0 { - // We'll return a match even if it touches a previous empty match - return r.tidyMatch(quick), nil - } - - // reset state for another go - r.runtrackpos = len(r.runtrack) - r.runstackpos = len(r.runstack) - r.runcrawlpos = len(r.runcrawl) - } - - // failure! - - if r.runtextpos == stoppos { - r.tidyMatch(true) - return nil, nil - } - - // Recognize leading []* and various anchors, and bump on failure accordingly - - // r.bump by one and start again - - r.runtextpos += bump - } - // We never get here -} - -func (r *runner) execute() error { - - r.goTo(0) - - for { - - if r.re.Debug() { - r.dumpState() - } - - if err := r.checkTimeout(); err != nil { - return err - } - - switch r.operator { - case syntax.Stop: - return nil - - case syntax.Nothing: - break - - case syntax.Goto: - r.goTo(r.operand(0)) - continue - - case syntax.Testref: - if !r.runmatch.isMatched(r.operand(0)) { - break - } - r.advance(1) - continue - - case syntax.Lazybranch: - r.trackPush1(r.textPos()) - r.advance(1) - continue - - case syntax.Lazybranch | syntax.Back: - r.trackPop() - r.textto(r.trackPeek()) - r.goTo(r.operand(0)) - continue - - case syntax.Setmark: - r.stackPush(r.textPos()) - r.trackPush() - r.advance(0) - continue - - case syntax.Nullmark: - r.stackPush(-1) - r.trackPush() - r.advance(0) - continue - - case syntax.Setmark | syntax.Back, syntax.Nullmark | syntax.Back: - r.stackPop() - break - - case syntax.Getmark: - r.stackPop() - r.trackPush1(r.stackPeek()) - r.textto(r.stackPeek()) - r.advance(0) - continue - - case syntax.Getmark | syntax.Back: - r.trackPop() - r.stackPush(r.trackPeek()) - break - - case syntax.Capturemark: - if r.operand(1) != -1 && !r.runmatch.isMatched(r.operand(1)) { - break - } - r.stackPop() - if r.operand(1) != -1 { - r.transferCapture(r.operand(0), r.operand(1), r.stackPeek(), r.textPos()) - } else { - r.capture(r.operand(0), r.stackPeek(), r.textPos()) - } - r.trackPush1(r.stackPeek()) - - r.advance(2) - - continue - - case syntax.Capturemark | syntax.Back: - r.trackPop() - r.stackPush(r.trackPeek()) - r.uncapture() - if r.operand(0) != -1 && r.operand(1) != -1 { - r.uncapture() - } - - break - - case syntax.Branchmark: - r.stackPop() - - matched := r.textPos() - r.stackPeek() - - if matched != 0 { // Nonempty match -> loop now - r.trackPush2(r.stackPeek(), r.textPos()) // Save old mark, textpos - r.stackPush(r.textPos()) // Make new mark - r.goTo(r.operand(0)) // Loop - } else { // Empty match -> straight now - r.trackPushNeg1(r.stackPeek()) // Save old mark - r.advance(1) // Straight - } - continue - - case syntax.Branchmark | syntax.Back: - r.trackPopN(2) - r.stackPop() - r.textto(r.trackPeekN(1)) // Recall position - r.trackPushNeg1(r.trackPeek()) // Save old mark - r.advance(1) // Straight - continue - - case syntax.Branchmark | syntax.Back2: - r.trackPop() - r.stackPush(r.trackPeek()) // Recall old mark - break // Backtrack - - case syntax.Lazybranchmark: - { - // We hit this the first time through a lazy loop and after each - // successful match of the inner expression. It simply continues - // on and doesn't loop. - r.stackPop() - - oldMarkPos := r.stackPeek() - - if r.textPos() != oldMarkPos { // Nonempty match -> try to loop again by going to 'back' state - if oldMarkPos != -1 { - r.trackPush2(oldMarkPos, r.textPos()) // Save old mark, textpos - } else { - r.trackPush2(r.textPos(), r.textPos()) - } - } else { - // The inner expression found an empty match, so we'll go directly to 'back2' if we - // backtrack. Don't touch the grouping stack here; instead, record the old mark and - // a flag indicating that backtracking doesn't need to pop a grouping stack frame. - r.trackPushNeg2(oldMarkPos, 0) - } - r.advance(1) - continue - } - - case syntax.Lazybranchmark | syntax.Back: - - // After the first time, Lazybranchmark | syntax.Back occurs - // with each iteration of the loop, and therefore with every attempted - // match of the inner expression. We'll try to match the inner expression, - // then go back to Lazybranchmark if successful. If the inner expression - // fails, we go to Lazybranchmark | syntax.Back2 - - r.trackPopN(2) - pos := r.trackPeekN(1) - r.trackPushNeg2(r.trackPeek(), 1) // Save old mark, note that we pushed a new mark - r.stackPush(pos) // Make new mark - r.textto(pos) // Recall position - r.goTo(r.operand(0)) // Loop - continue - - case syntax.Lazybranchmark | syntax.Back2: - // The lazy loop has failed. We'll do a true backtrack and - // start over before the lazy loop. - r.trackPopN(2) - oldMark := r.trackPeek() - needsPop := r.trackPeekN(1) - if needsPop != 0 { - r.stackPop() - } - r.stackPush(oldMark) // Recall old mark - break - - case syntax.Setcount: - r.stackPush2(r.textPos(), r.operand(0)) - r.trackPush() - r.advance(1) - continue - - case syntax.Nullcount: - r.stackPush2(-1, r.operand(0)) - r.trackPush() - r.advance(1) - continue - - case syntax.Setcount | syntax.Back: - r.stackPopN(2) - break - - case syntax.Nullcount | syntax.Back: - r.stackPopN(2) - break - - case syntax.Branchcount: - // r.stackPush: - // 0: Mark - // 1: Count - - r.stackPopN(2) - mark := r.stackPeek() - count := r.stackPeekN(1) - matched := r.textPos() - mark - - if count >= r.operand(1) || (matched == 0 && count >= 0) { // Max loops or empty match -> straight now - r.trackPushNeg2(mark, count) // Save old mark, count - r.advance(2) // Straight - } else { // Nonempty match -> count+loop now - r.trackPush1(mark) // remember mark - r.stackPush2(r.textPos(), count+1) // Make new mark, incr count - r.goTo(r.operand(0)) // Loop - } - continue - - case syntax.Branchcount | syntax.Back: - // r.trackPush: - // 0: Previous mark - // r.stackPush: - // 0: Mark (= current pos, discarded) - // 1: Count - r.trackPop() - r.stackPopN(2) - if r.stackPeekN(1) > 0 { // Positive -> can go straight - r.textto(r.stackPeek()) // Zap to mark - r.trackPushNeg2(r.trackPeek(), r.stackPeekN(1)-1) // Save old mark, old count - r.advance(2) // Straight - continue - } - r.stackPush2(r.trackPeek(), r.stackPeekN(1)-1) // recall old mark, old count - break - - case syntax.Branchcount | syntax.Back2: - // r.trackPush: - // 0: Previous mark - // 1: Previous count - r.trackPopN(2) - r.stackPush2(r.trackPeek(), r.trackPeekN(1)) // Recall old mark, old count - break // Backtrack - - case syntax.Lazybranchcount: - // r.stackPush: - // 0: Mark - // 1: Count - - r.stackPopN(2) - mark := r.stackPeek() - count := r.stackPeekN(1) - - if count < 0 { // Negative count -> loop now - r.trackPushNeg1(mark) // Save old mark - r.stackPush2(r.textPos(), count+1) // Make new mark, incr count - r.goTo(r.operand(0)) // Loop - } else { // Nonneg count -> straight now - r.trackPush3(mark, count, r.textPos()) // Save mark, count, position - r.advance(2) // Straight - } - continue - - case syntax.Lazybranchcount | syntax.Back: - // r.trackPush: - // 0: Mark - // 1: Count - // 2: r.textPos - - r.trackPopN(3) - mark := r.trackPeek() - textpos := r.trackPeekN(2) - - if r.trackPeekN(1) < r.operand(1) && textpos != mark { // Under limit and not empty match -> loop - r.textto(textpos) // Recall position - r.stackPush2(textpos, r.trackPeekN(1)+1) // Make new mark, incr count - r.trackPushNeg1(mark) // Save old mark - r.goTo(r.operand(0)) // Loop - continue - } else { // Max loops or empty match -> backtrack - r.stackPush2(r.trackPeek(), r.trackPeekN(1)) // Recall old mark, count - break // backtrack - } - - case syntax.Lazybranchcount | syntax.Back2: - // r.trackPush: - // 0: Previous mark - // r.stackPush: - // 0: Mark (== current pos, discarded) - // 1: Count - r.trackPop() - r.stackPopN(2) - r.stackPush2(r.trackPeek(), r.stackPeekN(1)-1) // Recall old mark, count - break // Backtrack - - case syntax.Setjump: - r.stackPush2(r.trackpos(), r.crawlpos()) - r.trackPush() - r.advance(0) - continue - - case syntax.Setjump | syntax.Back: - r.stackPopN(2) - break - - case syntax.Backjump: - // r.stackPush: - // 0: Saved trackpos - // 1: r.crawlpos - r.stackPopN(2) - r.trackto(r.stackPeek()) - - for r.crawlpos() != r.stackPeekN(1) { - r.uncapture() - } - - break - - case syntax.Forejump: - // r.stackPush: - // 0: Saved trackpos - // 1: r.crawlpos - r.stackPopN(2) - r.trackto(r.stackPeek()) - r.trackPush1(r.stackPeekN(1)) - r.advance(0) - continue - - case syntax.Forejump | syntax.Back: - // r.trackPush: - // 0: r.crawlpos - r.trackPop() - - for r.crawlpos() != r.trackPeek() { - r.uncapture() - } - - break - - case syntax.Bol: - if r.leftchars() > 0 && r.charAt(r.textPos()-1) != '\n' { - break - } - r.advance(0) - continue - - case syntax.Eol: - if r.rightchars() > 0 && r.charAt(r.textPos()) != '\n' { - break - } - r.advance(0) - continue - - case syntax.Boundary: - if !r.isBoundary(r.textPos(), 0, r.runtextend) { - break - } - r.advance(0) - continue - - case syntax.Nonboundary: - if r.isBoundary(r.textPos(), 0, r.runtextend) { - break - } - r.advance(0) - continue - - case syntax.ECMABoundary: - if !r.isECMABoundary(r.textPos(), 0, r.runtextend) { - break - } - r.advance(0) - continue - - case syntax.NonECMABoundary: - if r.isECMABoundary(r.textPos(), 0, r.runtextend) { - break - } - r.advance(0) - continue - - case syntax.Beginning: - if r.leftchars() > 0 { - break - } - r.advance(0) - continue - - case syntax.Start: - if r.textPos() != r.textstart() { - break - } - r.advance(0) - continue - - case syntax.EndZ: - rchars := r.rightchars() - if rchars > 1 { - break - } - // RE2 and EcmaScript define $ as "asserts position at the end of the string" - // PCRE/.NET adds "or before the line terminator right at the end of the string (if any)" - if (r.re.options & (RE2 | ECMAScript)) != 0 { - // RE2/Ecmascript mode - if rchars > 0 { - break - } - } else if rchars == 1 && r.charAt(r.textPos()) != '\n' { - // "regular" mode - break - } - - r.advance(0) - continue - - case syntax.End: - if r.rightchars() > 0 { - break - } - r.advance(0) - continue - - case syntax.One: - if r.forwardchars() < 1 || r.forwardcharnext() != rune(r.operand(0)) { - break - } - - r.advance(1) - continue - - case syntax.Notone: - if r.forwardchars() < 1 || r.forwardcharnext() == rune(r.operand(0)) { - break - } - - r.advance(1) - continue - - case syntax.Set: - - if r.forwardchars() < 1 || !r.code.Sets[r.operand(0)].CharIn(r.forwardcharnext()) { - break - } - - r.advance(1) - continue - - case syntax.Multi: - if !r.runematch(r.code.Strings[r.operand(0)]) { - break - } - - r.advance(1) - continue - - case syntax.Ref: - - capnum := r.operand(0) - - if r.runmatch.isMatched(capnum) { - if !r.refmatch(r.runmatch.matchIndex(capnum), r.runmatch.matchLength(capnum)) { - break - } - } else { - if (r.re.options & ECMAScript) == 0 { - break - } - } - - r.advance(1) - continue - - case syntax.Onerep: - - c := r.operand(1) - - if r.forwardchars() < c { - break - } - - ch := rune(r.operand(0)) - - for c > 0 { - if r.forwardcharnext() != ch { - goto BreakBackward - } - c-- - } - - r.advance(2) - continue - - case syntax.Notonerep: - - c := r.operand(1) - - if r.forwardchars() < c { - break - } - ch := rune(r.operand(0)) - - for c > 0 { - if r.forwardcharnext() == ch { - goto BreakBackward - } - c-- - } - - r.advance(2) - continue - - case syntax.Setrep: - - c := r.operand(1) - - if r.forwardchars() < c { - break - } - - set := r.code.Sets[r.operand(0)] - - for c > 0 { - if !set.CharIn(r.forwardcharnext()) { - goto BreakBackward - } - c-- - } - - r.advance(2) - continue - - case syntax.Oneloop: - - c := r.operand(1) - - if c > r.forwardchars() { - c = r.forwardchars() - } - - ch := rune(r.operand(0)) - i := c - - for ; i > 0; i-- { - if r.forwardcharnext() != ch { - r.backwardnext() - break - } - } - - if c > i { - r.trackPush2(c-i-1, r.textPos()-r.bump()) - } - - r.advance(2) - continue - - case syntax.Notoneloop: - - c := r.operand(1) - - if c > r.forwardchars() { - c = r.forwardchars() - } - - ch := rune(r.operand(0)) - i := c - - for ; i > 0; i-- { - if r.forwardcharnext() == ch { - r.backwardnext() - break - } - } - - if c > i { - r.trackPush2(c-i-1, r.textPos()-r.bump()) - } - - r.advance(2) - continue - - case syntax.Setloop: - - c := r.operand(1) - - if c > r.forwardchars() { - c = r.forwardchars() - } - - set := r.code.Sets[r.operand(0)] - i := c - - for ; i > 0; i-- { - if !set.CharIn(r.forwardcharnext()) { - r.backwardnext() - break - } - } - - if c > i { - r.trackPush2(c-i-1, r.textPos()-r.bump()) - } - - r.advance(2) - continue - - case syntax.Oneloop | syntax.Back, syntax.Notoneloop | syntax.Back: - - r.trackPopN(2) - i := r.trackPeek() - pos := r.trackPeekN(1) - - r.textto(pos) - - if i > 0 { - r.trackPush2(i-1, pos-r.bump()) - } - - r.advance(2) - continue - - case syntax.Setloop | syntax.Back: - - r.trackPopN(2) - i := r.trackPeek() - pos := r.trackPeekN(1) - - r.textto(pos) - - if i > 0 { - r.trackPush2(i-1, pos-r.bump()) - } - - r.advance(2) - continue - - case syntax.Onelazy, syntax.Notonelazy: - - c := r.operand(1) - - if c > r.forwardchars() { - c = r.forwardchars() - } - - if c > 0 { - r.trackPush2(c-1, r.textPos()) - } - - r.advance(2) - continue - - case syntax.Setlazy: - - c := r.operand(1) - - if c > r.forwardchars() { - c = r.forwardchars() - } - - if c > 0 { - r.trackPush2(c-1, r.textPos()) - } - - r.advance(2) - continue - - case syntax.Onelazy | syntax.Back: - - r.trackPopN(2) - pos := r.trackPeekN(1) - r.textto(pos) - - if r.forwardcharnext() != rune(r.operand(0)) { - break - } - - i := r.trackPeek() - - if i > 0 { - r.trackPush2(i-1, pos+r.bump()) - } - - r.advance(2) - continue - - case syntax.Notonelazy | syntax.Back: - - r.trackPopN(2) - pos := r.trackPeekN(1) - r.textto(pos) - - if r.forwardcharnext() == rune(r.operand(0)) { - break - } - - i := r.trackPeek() - - if i > 0 { - r.trackPush2(i-1, pos+r.bump()) - } - - r.advance(2) - continue - - case syntax.Setlazy | syntax.Back: - - r.trackPopN(2) - pos := r.trackPeekN(1) - r.textto(pos) - - if !r.code.Sets[r.operand(0)].CharIn(r.forwardcharnext()) { - break - } - - i := r.trackPeek() - - if i > 0 { - r.trackPush2(i-1, pos+r.bump()) - } - - r.advance(2) - continue - - default: - return errors.New("unknown state in regex runner") - } - - BreakBackward: - ; - - // "break Backward" comes here: - r.backtrack() - } -} - -// increase the size of stack and track storage -func (r *runner) ensureStorage() { - if r.runstackpos < r.runtrackcount*4 { - doubleIntSlice(&r.runstack, &r.runstackpos) - } - if r.runtrackpos < r.runtrackcount*4 { - doubleIntSlice(&r.runtrack, &r.runtrackpos) - } -} - -func doubleIntSlice(s *[]int, pos *int) { - oldLen := len(*s) - newS := make([]int, oldLen*2) - - copy(newS[oldLen:], *s) - *pos += oldLen - *s = newS -} - -// Save a number on the longjump unrolling stack -func (r *runner) crawl(i int) { - if r.runcrawlpos == 0 { - doubleIntSlice(&r.runcrawl, &r.runcrawlpos) - } - r.runcrawlpos-- - r.runcrawl[r.runcrawlpos] = i -} - -// Remove a number from the longjump unrolling stack -func (r *runner) popcrawl() int { - val := r.runcrawl[r.runcrawlpos] - r.runcrawlpos++ - return val -} - -// Get the height of the stack -func (r *runner) crawlpos() int { - return len(r.runcrawl) - r.runcrawlpos -} - -func (r *runner) advance(i int) { - r.codepos += (i + 1) - r.setOperator(r.code.Codes[r.codepos]) -} - -func (r *runner) goTo(newpos int) { - // when branching backward or in place, ensure storage - if newpos <= r.codepos { - r.ensureStorage() - } - - r.setOperator(r.code.Codes[newpos]) - r.codepos = newpos -} - -func (r *runner) textto(newpos int) { - r.runtextpos = newpos -} - -func (r *runner) trackto(newpos int) { - r.runtrackpos = len(r.runtrack) - newpos -} - -func (r *runner) textstart() int { - return r.runtextstart -} - -func (r *runner) textPos() int { - return r.runtextpos -} - -// push onto the backtracking stack -func (r *runner) trackpos() int { - return len(r.runtrack) - r.runtrackpos -} - -func (r *runner) trackPush() { - r.runtrackpos-- - r.runtrack[r.runtrackpos] = r.codepos -} - -func (r *runner) trackPush1(I1 int) { - r.runtrackpos-- - r.runtrack[r.runtrackpos] = I1 - r.runtrackpos-- - r.runtrack[r.runtrackpos] = r.codepos -} - -func (r *runner) trackPush2(I1, I2 int) { - r.runtrackpos-- - r.runtrack[r.runtrackpos] = I1 - r.runtrackpos-- - r.runtrack[r.runtrackpos] = I2 - r.runtrackpos-- - r.runtrack[r.runtrackpos] = r.codepos -} - -func (r *runner) trackPush3(I1, I2, I3 int) { - r.runtrackpos-- - r.runtrack[r.runtrackpos] = I1 - r.runtrackpos-- - r.runtrack[r.runtrackpos] = I2 - r.runtrackpos-- - r.runtrack[r.runtrackpos] = I3 - r.runtrackpos-- - r.runtrack[r.runtrackpos] = r.codepos -} - -func (r *runner) trackPushNeg1(I1 int) { - r.runtrackpos-- - r.runtrack[r.runtrackpos] = I1 - r.runtrackpos-- - r.runtrack[r.runtrackpos] = -r.codepos -} - -func (r *runner) trackPushNeg2(I1, I2 int) { - r.runtrackpos-- - r.runtrack[r.runtrackpos] = I1 - r.runtrackpos-- - r.runtrack[r.runtrackpos] = I2 - r.runtrackpos-- - r.runtrack[r.runtrackpos] = -r.codepos -} - -func (r *runner) backtrack() { - newpos := r.runtrack[r.runtrackpos] - r.runtrackpos++ - - if r.re.Debug() { - if newpos < 0 { - fmt.Printf(" Backtracking (back2) to code position %v\n", -newpos) - } else { - fmt.Printf(" Backtracking to code position %v\n", newpos) - } - } - - if newpos < 0 { - newpos = -newpos - r.setOperator(r.code.Codes[newpos] | syntax.Back2) - } else { - r.setOperator(r.code.Codes[newpos] | syntax.Back) - } - - // When branching backward, ensure storage - if newpos < r.codepos { - r.ensureStorage() - } - - r.codepos = newpos -} - -func (r *runner) setOperator(op int) { - r.caseInsensitive = (0 != (op & syntax.Ci)) - r.rightToLeft = (0 != (op & syntax.Rtl)) - r.operator = syntax.InstOp(op & ^(syntax.Rtl | syntax.Ci)) -} - -func (r *runner) trackPop() { - r.runtrackpos++ -} - -// pop framesize items from the backtracking stack -func (r *runner) trackPopN(framesize int) { - r.runtrackpos += framesize -} - -// Technically we are actually peeking at items already popped. So if you want to -// get and pop the top item from the stack, you do -// r.trackPop(); -// r.trackPeek(); -func (r *runner) trackPeek() int { - return r.runtrack[r.runtrackpos-1] -} - -// get the ith element down on the backtracking stack -func (r *runner) trackPeekN(i int) int { - return r.runtrack[r.runtrackpos-i-1] -} - -// Push onto the grouping stack -func (r *runner) stackPush(I1 int) { - r.runstackpos-- - r.runstack[r.runstackpos] = I1 -} - -func (r *runner) stackPush2(I1, I2 int) { - r.runstackpos-- - r.runstack[r.runstackpos] = I1 - r.runstackpos-- - r.runstack[r.runstackpos] = I2 -} - -func (r *runner) stackPop() { - r.runstackpos++ -} - -// pop framesize items from the grouping stack -func (r *runner) stackPopN(framesize int) { - r.runstackpos += framesize -} - -// Technically we are actually peeking at items already popped. So if you want to -// get and pop the top item from the stack, you do -// r.stackPop(); -// r.stackPeek(); -func (r *runner) stackPeek() int { - return r.runstack[r.runstackpos-1] -} - -// get the ith element down on the grouping stack -func (r *runner) stackPeekN(i int) int { - return r.runstack[r.runstackpos-i-1] -} - -func (r *runner) operand(i int) int { - return r.code.Codes[r.codepos+i+1] -} - -func (r *runner) leftchars() int { - return r.runtextpos -} - -func (r *runner) rightchars() int { - return r.runtextend - r.runtextpos -} - -func (r *runner) bump() int { - if r.rightToLeft { - return -1 - } - return 1 -} - -func (r *runner) forwardchars() int { - if r.rightToLeft { - return r.runtextpos - } - return r.runtextend - r.runtextpos -} - -func (r *runner) forwardcharnext() rune { - var ch rune - if r.rightToLeft { - r.runtextpos-- - ch = r.runtext[r.runtextpos] - } else { - ch = r.runtext[r.runtextpos] - r.runtextpos++ - } - - if r.caseInsensitive { - return unicode.ToLower(ch) - } - return ch -} - -func (r *runner) runematch(str []rune) bool { - var pos int - - c := len(str) - if !r.rightToLeft { - if r.runtextend-r.runtextpos < c { - return false - } - - pos = r.runtextpos + c - } else { - if r.runtextpos-0 < c { - return false - } - - pos = r.runtextpos - } - - if !r.caseInsensitive { - for c != 0 { - c-- - pos-- - if str[c] != r.runtext[pos] { - return false - } - } - } else { - for c != 0 { - c-- - pos-- - if str[c] != unicode.ToLower(r.runtext[pos]) { - return false - } - } - } - - if !r.rightToLeft { - pos += len(str) - } - - r.runtextpos = pos - - return true -} - -func (r *runner) refmatch(index, len int) bool { - var c, pos, cmpos int - - if !r.rightToLeft { - if r.runtextend-r.runtextpos < len { - return false - } - - pos = r.runtextpos + len - } else { - if r.runtextpos-0 < len { - return false - } - - pos = r.runtextpos - } - cmpos = index + len - - c = len - - if !r.caseInsensitive { - for c != 0 { - c-- - cmpos-- - pos-- - if r.runtext[cmpos] != r.runtext[pos] { - return false - } - - } - } else { - for c != 0 { - c-- - cmpos-- - pos-- - - if unicode.ToLower(r.runtext[cmpos]) != unicode.ToLower(r.runtext[pos]) { - return false - } - } - } - - if !r.rightToLeft { - pos += len - } - - r.runtextpos = pos - - return true -} - -func (r *runner) backwardnext() { - if r.rightToLeft { - r.runtextpos++ - } else { - r.runtextpos-- - } -} - -func (r *runner) charAt(j int) rune { - return r.runtext[j] -} - -func (r *runner) findFirstChar() bool { - - if 0 != (r.code.Anchors & (syntax.AnchorBeginning | syntax.AnchorStart | syntax.AnchorEndZ | syntax.AnchorEnd)) { - if !r.code.RightToLeft { - if (0 != (r.code.Anchors&syntax.AnchorBeginning) && r.runtextpos > 0) || - (0 != (r.code.Anchors&syntax.AnchorStart) && r.runtextpos > r.runtextstart) { - r.runtextpos = r.runtextend - return false - } - if 0 != (r.code.Anchors&syntax.AnchorEndZ) && r.runtextpos < r.runtextend-1 { - r.runtextpos = r.runtextend - 1 - } else if 0 != (r.code.Anchors&syntax.AnchorEnd) && r.runtextpos < r.runtextend { - r.runtextpos = r.runtextend - } - } else { - if (0 != (r.code.Anchors&syntax.AnchorEnd) && r.runtextpos < r.runtextend) || - (0 != (r.code.Anchors&syntax.AnchorEndZ) && (r.runtextpos < r.runtextend-1 || - (r.runtextpos == r.runtextend-1 && r.charAt(r.runtextpos) != '\n'))) || - (0 != (r.code.Anchors&syntax.AnchorStart) && r.runtextpos < r.runtextstart) { - r.runtextpos = 0 - return false - } - if 0 != (r.code.Anchors&syntax.AnchorBeginning) && r.runtextpos > 0 { - r.runtextpos = 0 - } - } - - if r.code.BmPrefix != nil { - return r.code.BmPrefix.IsMatch(r.runtext, r.runtextpos, 0, r.runtextend) - } - - return true // found a valid start or end anchor - } else if r.code.BmPrefix != nil { - r.runtextpos = r.code.BmPrefix.Scan(r.runtext, r.runtextpos, 0, r.runtextend) - - if r.runtextpos == -1 { - if r.code.RightToLeft { - r.runtextpos = 0 - } else { - r.runtextpos = r.runtextend - } - return false - } - - return true - } else if r.code.FcPrefix == nil { - return true - } - - r.rightToLeft = r.code.RightToLeft - r.caseInsensitive = r.code.FcPrefix.CaseInsensitive - - set := r.code.FcPrefix.PrefixSet - if set.IsSingleton() { - ch := set.SingletonChar() - for i := r.forwardchars(); i > 0; i-- { - if ch == r.forwardcharnext() { - r.backwardnext() - return true - } - } - } else { - for i := r.forwardchars(); i > 0; i-- { - n := r.forwardcharnext() - //fmt.Printf("%v in %v: %v\n", string(n), set.String(), set.CharIn(n)) - if set.CharIn(n) { - r.backwardnext() - return true - } - } - } - - return false -} - -func (r *runner) initMatch() { - // Use a hashtable'ed Match object if the capture numbers are sparse - - if r.runmatch == nil { - if r.re.caps != nil { - r.runmatch = newMatchSparse(r.re, r.re.caps, r.re.capsize, r.runtext, r.runtextstart) - } else { - r.runmatch = newMatch(r.re, r.re.capsize, r.runtext, r.runtextstart) - } - } else { - r.runmatch.reset(r.runtext, r.runtextstart) - } - - // note we test runcrawl, because it is the last one to be allocated - // If there is an alloc failure in the middle of the three allocations, - // we may still return to reuse this instance, and we want to behave - // as if the allocations didn't occur. (we used to test _trackcount != 0) - - if r.runcrawl != nil { - r.runtrackpos = len(r.runtrack) - r.runstackpos = len(r.runstack) - r.runcrawlpos = len(r.runcrawl) - return - } - - r.initTrackCount() - - tracksize := r.runtrackcount * 8 - stacksize := r.runtrackcount * 8 - - if tracksize < 32 { - tracksize = 32 - } - if stacksize < 16 { - stacksize = 16 - } - - r.runtrack = make([]int, tracksize) - r.runtrackpos = tracksize - - r.runstack = make([]int, stacksize) - r.runstackpos = stacksize - - r.runcrawl = make([]int, 32) - r.runcrawlpos = 32 -} - -func (r *runner) tidyMatch(quick bool) *Match { - if !quick { - match := r.runmatch - - r.runmatch = nil - - match.tidy(r.runtextpos) - return match - } else { - // send back our match -- it's not leaving the package, so it's safe to not clean it up - // this reduces allocs for frequent calls to the "IsMatch" bool-only functions - return r.runmatch - } -} - -// capture captures a subexpression. Note that the -// capnum used here has already been mapped to a non-sparse -// index (by the code generator RegexWriter). -func (r *runner) capture(capnum, start, end int) { - if end < start { - T := end - end = start - start = T - } - - r.crawl(capnum) - r.runmatch.addMatch(capnum, start, end-start) -} - -// transferCapture captures a subexpression. Note that the -// capnum used here has already been mapped to a non-sparse -// index (by the code generator RegexWriter). -func (r *runner) transferCapture(capnum, uncapnum, start, end int) { - var start2, end2 int - - // these are the two intervals that are cancelling each other - - if end < start { - T := end - end = start - start = T - } - - start2 = r.runmatch.matchIndex(uncapnum) - end2 = start2 + r.runmatch.matchLength(uncapnum) - - // The new capture gets the innermost defined interval - - if start >= end2 { - end = start - start = end2 - } else if end <= start2 { - start = start2 - } else { - if end > end2 { - end = end2 - } - if start2 > start { - start = start2 - } - } - - r.crawl(uncapnum) - r.runmatch.balanceMatch(uncapnum) - - if capnum != -1 { - r.crawl(capnum) - r.runmatch.addMatch(capnum, start, end-start) - } -} - -// revert the last capture -func (r *runner) uncapture() { - capnum := r.popcrawl() - r.runmatch.removeMatch(capnum) -} - -//debug - -func (r *runner) dumpState() { - back := "" - if r.operator&syntax.Back != 0 { - back = " Back" - } - if r.operator&syntax.Back2 != 0 { - back += " Back2" - } - fmt.Printf("Text: %v\nTrack: %v\nStack: %v\n %s%s\n\n", - r.textposDescription(), - r.stackDescription(r.runtrack, r.runtrackpos), - r.stackDescription(r.runstack, r.runstackpos), - r.code.OpcodeDescription(r.codepos), - back) -} - -func (r *runner) stackDescription(a []int, index int) string { - buf := &bytes.Buffer{} - - fmt.Fprintf(buf, "%v/%v", len(a)-index, len(a)) - if buf.Len() < 8 { - buf.WriteString(strings.Repeat(" ", 8-buf.Len())) - } - - buf.WriteRune('(') - for i := index; i < len(a); i++ { - if i > index { - buf.WriteRune(' ') - } - - buf.WriteString(strconv.Itoa(a[i])) - } - - buf.WriteRune(')') - - return buf.String() -} - -func (r *runner) textposDescription() string { - buf := &bytes.Buffer{} - - buf.WriteString(strconv.Itoa(r.runtextpos)) - - if buf.Len() < 8 { - buf.WriteString(strings.Repeat(" ", 8-buf.Len())) - } - - if r.runtextpos > 0 { - buf.WriteString(syntax.CharDescription(r.runtext[r.runtextpos-1])) - } else { - buf.WriteRune('^') - } - - buf.WriteRune('>') - - for i := r.runtextpos; i < r.runtextend; i++ { - buf.WriteString(syntax.CharDescription(r.runtext[i])) - } - if buf.Len() >= 64 { - buf.Truncate(61) - buf.WriteString("...") - } else { - buf.WriteRune('$') - } - - return buf.String() -} - -// decide whether the pos -// at the specified index is a boundary or not. It's just not worth -// emitting inline code for this logic. -func (r *runner) isBoundary(index, startpos, endpos int) bool { - return (index > startpos && syntax.IsWordChar(r.runtext[index-1])) != - (index < endpos && syntax.IsWordChar(r.runtext[index])) -} - -func (r *runner) isECMABoundary(index, startpos, endpos int) bool { - return (index > startpos && syntax.IsECMAWordChar(r.runtext[index-1])) != - (index < endpos && syntax.IsECMAWordChar(r.runtext[index])) -} - -func (r *runner) startTimeoutWatch() { - if r.ignoreTimeout { - return - } - r.deadline = makeDeadline(r.timeout) -} - -func (r *runner) checkTimeout() error { - if r.ignoreTimeout || !r.deadline.reached() { - return nil - } - - if r.re.Debug() { - //Debug.WriteLine("") - //Debug.WriteLine("RegEx match timeout occurred!") - //Debug.WriteLine("Specified timeout: " + TimeSpan.FromMilliseconds(_timeout).ToString()) - //Debug.WriteLine("Timeout check frequency: " + TimeoutCheckFrequency) - //Debug.WriteLine("Search pattern: " + _runregex._pattern) - //Debug.WriteLine("Input: " + r.runtext) - //Debug.WriteLine("About to throw RegexMatchTimeoutException.") - } - - return fmt.Errorf("match timeout after %v on input `%v`", r.timeout, string(r.runtext)) -} - -func (r *runner) initTrackCount() { - r.runtrackcount = r.code.TrackCount -} - -// getRunner returns a run to use for matching re. -// It uses the re's runner cache if possible, to avoid -// unnecessary allocation. -func (re *Regexp) getRunner() *runner { - re.muRun.Lock() - if n := len(re.runner); n > 0 { - z := re.runner[n-1] - re.runner = re.runner[:n-1] - re.muRun.Unlock() - return z - } - re.muRun.Unlock() - z := &runner{ - re: re, - code: re.code, - } - return z -} - -// putRunner returns a runner to the re's cache. -// There is no attempt to limit the size of the cache, so it will -// grow to the maximum number of simultaneous matches -// run using re. (The cache empties when re gets garbage collected.) -func (re *Regexp) putRunner(r *runner) { - re.muRun.Lock() - r.runtext = nil - if r.runmatch != nil { - r.runmatch.text = nil - } - re.runner = append(re.runner, r) - re.muRun.Unlock() -} diff --git a/third_party/regexp2/syntax/charclass.go b/third_party/regexp2/syntax/charclass.go deleted file mode 100644 index 6881a0e29..000000000 --- a/third_party/regexp2/syntax/charclass.go +++ /dev/null @@ -1,865 +0,0 @@ -package syntax - -import ( - "bytes" - "encoding/binary" - "fmt" - "sort" - "unicode" - "unicode/utf8" -) - -// CharSet combines start-end rune ranges and unicode categories representing a set of characters -type CharSet struct { - ranges []singleRange - categories []category - sub *CharSet //optional subtractor - negate bool - anything bool -} - -type category struct { - negate bool - cat string -} - -type singleRange struct { - first rune - last rune -} - -const ( - spaceCategoryText = " " - wordCategoryText = "W" -) - -var ( - ecmaSpace = []rune{0x0009, 0x000e, 0x0020, 0x0021, 0x00a0, 0x00a1, 0x1680, 0x1681, 0x2000, 0x200b, 0x2028, 0x202a, 0x202f, 0x2030, 0x205f, 0x2060, 0x3000, 0x3001, 0xfeff, 0xff00} - ecmaWord = []rune{0x0030, 0x003a, 0x0041, 0x005b, 0x005f, 0x0060, 0x0061, 0x007b} - ecmaDigit = []rune{0x0030, 0x003a} - - re2Space = []rune{0x0009, 0x000b, 0x000c, 0x000e, 0x0020, 0x0021} -) - -var ( - AnyClass = getCharSetFromOldString([]rune{0}, false) - ECMAAnyClass = getCharSetFromOldString([]rune{0, 0x000a, 0x000b, 0x000d, 0x000e}, false) - NoneClass = getCharSetFromOldString(nil, false) - ECMAWordClass = getCharSetFromOldString(ecmaWord, false) - NotECMAWordClass = getCharSetFromOldString(ecmaWord, true) - ECMASpaceClass = getCharSetFromOldString(ecmaSpace, false) - NotECMASpaceClass = getCharSetFromOldString(ecmaSpace, true) - ECMADigitClass = getCharSetFromOldString(ecmaDigit, false) - NotECMADigitClass = getCharSetFromOldString(ecmaDigit, true) - - WordClass = getCharSetFromCategoryString(false, false, wordCategoryText) - NotWordClass = getCharSetFromCategoryString(true, false, wordCategoryText) - SpaceClass = getCharSetFromCategoryString(false, false, spaceCategoryText) - NotSpaceClass = getCharSetFromCategoryString(true, false, spaceCategoryText) - DigitClass = getCharSetFromCategoryString(false, false, "Nd") - NotDigitClass = getCharSetFromCategoryString(false, true, "Nd") - - RE2SpaceClass = getCharSetFromOldString(re2Space, false) - NotRE2SpaceClass = getCharSetFromOldString(re2Space, true) -) - -var unicodeCategories = func() map[string]*unicode.RangeTable { - retVal := make(map[string]*unicode.RangeTable) - for k, v := range unicode.Scripts { - retVal[k] = v - } - for k, v := range unicode.Categories { - retVal[k] = v - } - for k, v := range unicode.Properties { - retVal[k] = v - } - return retVal -}() - -func getCharSetFromCategoryString(negateSet bool, negateCat bool, cats ...string) func() *CharSet { - if negateCat && negateSet { - panic("BUG! You should only negate the set OR the category in a constant setup, but not both") - } - - c := CharSet{negate: negateSet} - - c.categories = make([]category, len(cats)) - for i, cat := range cats { - c.categories[i] = category{cat: cat, negate: negateCat} - } - return func() *CharSet { - //make a copy each time - local := c - //return that address - return &local - } -} - -func getCharSetFromOldString(setText []rune, negate bool) func() *CharSet { - c := CharSet{} - if len(setText) > 0 { - fillFirst := false - l := len(setText) - if negate { - if setText[0] == 0 { - setText = setText[1:] - } else { - l++ - fillFirst = true - } - } - - if l%2 == 0 { - c.ranges = make([]singleRange, l/2) - } else { - c.ranges = make([]singleRange, l/2+1) - } - - first := true - if fillFirst { - c.ranges[0] = singleRange{first: 0} - first = false - } - - i := 0 - for _, r := range setText { - if first { - // lower bound in a new range - c.ranges[i] = singleRange{first: r} - first = false - } else { - c.ranges[i].last = r - 1 - i++ - first = true - } - } - if !first { - c.ranges[i].last = utf8.MaxRune - } - } - - return func() *CharSet { - local := c - return &local - } -} - -// Copy makes a deep copy to prevent accidental mutation of a set -func (c CharSet) Copy() CharSet { - ret := CharSet{ - anything: c.anything, - negate: c.negate, - } - - ret.ranges = append(ret.ranges, c.ranges...) - ret.categories = append(ret.categories, c.categories...) - - if c.sub != nil { - sub := c.sub.Copy() - ret.sub = &sub - } - - return ret -} - -// gets a human-readable description for a set string -func (c CharSet) String() string { - buf := &bytes.Buffer{} - buf.WriteRune('[') - - if c.IsNegated() { - buf.WriteRune('^') - } - - for _, r := range c.ranges { - - buf.WriteString(CharDescription(r.first)) - if r.first != r.last { - if r.last-r.first != 1 { - //groups that are 1 char apart skip the dash - buf.WriteRune('-') - } - buf.WriteString(CharDescription(r.last)) - } - } - - for _, c := range c.categories { - buf.WriteString(c.String()) - } - - if c.sub != nil { - buf.WriteRune('-') - buf.WriteString(c.sub.String()) - } - - buf.WriteRune(']') - - return buf.String() -} - -// mapHashFill converts a charset into a buffer for use in maps -func (c CharSet) mapHashFill(buf *bytes.Buffer) { - if c.negate { - buf.WriteByte(0) - } else { - buf.WriteByte(1) - } - - binary.Write(buf, binary.LittleEndian, len(c.ranges)) - binary.Write(buf, binary.LittleEndian, len(c.categories)) - for _, r := range c.ranges { - buf.WriteRune(r.first) - buf.WriteRune(r.last) - } - for _, ct := range c.categories { - buf.WriteString(ct.cat) - if ct.negate { - buf.WriteByte(1) - } else { - buf.WriteByte(0) - } - } - - if c.sub != nil { - c.sub.mapHashFill(buf) - } -} - -// CharIn returns true if the rune is in our character set (either ranges or categories). -// It handles negations and subtracted sub-charsets. -func (c CharSet) CharIn(ch rune) bool { - val := false - // in s && !s.subtracted - - //check ranges - for _, r := range c.ranges { - if ch < r.first { - continue - } - if ch <= r.last { - val = true - break - } - } - - //check categories if we haven't already found a range - if !val && len(c.categories) > 0 { - for _, ct := range c.categories { - // special categories...then unicode - if ct.cat == spaceCategoryText { - if unicode.IsSpace(ch) { - // we found a space so we're done - // negate means this is a "bad" thing - val = !ct.negate - break - } else if ct.negate { - val = true - break - } - } else if ct.cat == wordCategoryText { - if IsWordChar(ch) { - val = !ct.negate - break - } else if ct.negate { - val = true - break - } - } else if unicode.Is(unicodeCategories[ct.cat], ch) { - // if we're in this unicode category then we're done - // if negate=true on this category then we "failed" our test - // otherwise we're good that we found it - val = !ct.negate - break - } else if ct.negate { - val = true - break - } - } - } - - // negate the whole char set - if c.negate { - val = !val - } - - // get subtracted recurse - if val && c.sub != nil { - val = !c.sub.CharIn(ch) - } - - //log.Printf("Char '%v' in %v == %v", string(ch), c.String(), val) - return val -} - -func (c category) String() string { - switch c.cat { - case spaceCategoryText: - if c.negate { - return "\\S" - } - return "\\s" - case wordCategoryText: - if c.negate { - return "\\W" - } - return "\\w" - } - if _, ok := unicodeCategories[c.cat]; ok { - - if c.negate { - return "\\P{" + c.cat + "}" - } - return "\\p{" + c.cat + "}" - } - return "Unknown category: " + c.cat -} - -// CharDescription Produces a human-readable description for a single character. -func CharDescription(ch rune) string { - /*if ch == '\\' { - return "\\\\" - } - - if ch > ' ' && ch <= '~' { - return string(ch) - } else if ch == '\n' { - return "\\n" - } else if ch == ' ' { - return "\\ " - }*/ - - b := &bytes.Buffer{} - escape(b, ch, false) //fmt.Sprintf("%U", ch) - return b.String() -} - -// According to UTS#18 Unicode Regular Expressions (http://www.unicode.org/reports/tr18/) -// RL 1.4 Simple Word Boundaries The class of includes all Alphabetic -// values from the Unicode character database, from UnicodeData.txt [UData], plus the U+200C -// ZERO WIDTH NON-JOINER and U+200D ZERO WIDTH JOINER. -func IsWordChar(r rune) bool { - //"L", "Mn", "Nd", "Pc" - return unicode.In(r, - unicode.Categories["L"], unicode.Categories["Mn"], - unicode.Categories["Nd"], unicode.Categories["Pc"]) || r == '\u200D' || r == '\u200C' - //return 'A' <= r && r <= 'Z' || 'a' <= r && r <= 'z' || '0' <= r && r <= '9' || r == '_' -} - -func IsECMAWordChar(r rune) bool { - return unicode.In(r, - unicode.Categories["L"], unicode.Categories["Mn"], - unicode.Categories["Nd"], unicode.Categories["Pc"]) - - //return 'A' <= r && r <= 'Z' || 'a' <= r && r <= 'z' || '0' <= r && r <= '9' || r == '_' -} - -// SingletonChar will return the char from the first range without validation. -// It assumes you have checked for IsSingleton or IsSingletonInverse and will panic given bad input -func (c CharSet) SingletonChar() rune { - return c.ranges[0].first -} - -func (c CharSet) IsSingleton() bool { - return !c.negate && //negated is multiple chars - len(c.categories) == 0 && len(c.ranges) == 1 && // multiple ranges and unicode classes represent multiple chars - c.sub == nil && // subtraction means we've got multiple chars - c.ranges[0].first == c.ranges[0].last // first and last equal means we're just 1 char -} - -func (c CharSet) IsSingletonInverse() bool { - return c.negate && //same as above, but requires negated - len(c.categories) == 0 && len(c.ranges) == 1 && // multiple ranges and unicode classes represent multiple chars - c.sub == nil && // subtraction means we've got multiple chars - c.ranges[0].first == c.ranges[0].last // first and last equal means we're just 1 char -} - -func (c CharSet) IsMergeable() bool { - return !c.IsNegated() && !c.HasSubtraction() -} - -func (c CharSet) IsNegated() bool { - return c.negate -} - -func (c CharSet) HasSubtraction() bool { - return c.sub != nil -} - -func (c CharSet) IsEmpty() bool { - return len(c.ranges) == 0 && len(c.categories) == 0 && c.sub == nil -} - -func (c *CharSet) addDigit(ecma, negate bool, pattern string) { - if ecma { - if negate { - c.addRanges(NotECMADigitClass().ranges) - } else { - c.addRanges(ECMADigitClass().ranges) - } - } else { - c.addCategories(category{cat: "Nd", negate: negate}) - } -} - -func (c *CharSet) addChar(ch rune) { - c.addRange(ch, ch) -} - -func (c *CharSet) addSpace(ecma, re2, negate bool) { - if ecma { - if negate { - c.addRanges(NotECMASpaceClass().ranges) - } else { - c.addRanges(ECMASpaceClass().ranges) - } - } else if re2 { - if negate { - c.addRanges(NotRE2SpaceClass().ranges) - } else { - c.addRanges(RE2SpaceClass().ranges) - } - } else { - c.addCategories(category{cat: spaceCategoryText, negate: negate}) - } -} - -func (c *CharSet) addWord(ecma, negate bool) { - if ecma { - if negate { - c.addRanges(NotECMAWordClass().ranges) - } else { - c.addRanges(ECMAWordClass().ranges) - } - } else { - c.addCategories(category{cat: wordCategoryText, negate: negate}) - } -} - -// Add set ranges and categories into ours -- no deduping or anything -func (c *CharSet) addSet(set CharSet) { - if c.anything { - return - } - if set.anything { - c.makeAnything() - return - } - // just append here to prevent double-canon - c.ranges = append(c.ranges, set.ranges...) - c.addCategories(set.categories...) - c.canonicalize() -} - -func (c *CharSet) makeAnything() { - c.anything = true - c.categories = []category{} - c.ranges = AnyClass().ranges -} - -func (c *CharSet) addCategories(cats ...category) { - // don't add dupes and remove positive+negative - if c.anything { - // if we've had a previous positive+negative group then - // just return, we're as broad as we can get - return - } - - for _, ct := range cats { - found := false - for _, ct2 := range c.categories { - if ct.cat == ct2.cat { - if ct.negate != ct2.negate { - // oposite negations...this mean we just - // take us as anything and move on - c.makeAnything() - return - } - found = true - break - } - } - - if !found { - c.categories = append(c.categories, ct) - } - } -} - -// Merges new ranges to our own -func (c *CharSet) addRanges(ranges []singleRange) { - if c.anything { - return - } - c.ranges = append(c.ranges, ranges...) - c.canonicalize() -} - -// Merges everything but the new ranges into our own -func (c *CharSet) addNegativeRanges(ranges []singleRange) { - if c.anything { - return - } - - var hi rune - - // convert incoming ranges into opposites, assume they are in order - for _, r := range ranges { - if hi < r.first { - c.ranges = append(c.ranges, singleRange{hi, r.first - 1}) - } - hi = r.last + 1 - } - - if hi < utf8.MaxRune { - c.ranges = append(c.ranges, singleRange{hi, utf8.MaxRune}) - } - - c.canonicalize() -} - -func isValidUnicodeCat(catName string) bool { - _, ok := unicodeCategories[catName] - return ok -} - -func (c *CharSet) addCategory(categoryName string, negate, caseInsensitive bool, pattern string) { - if !isValidUnicodeCat(categoryName) { - // unknown unicode category, script, or property "blah" - panic(fmt.Errorf("Unknown unicode category, script, or property '%v'", categoryName)) - - } - - if caseInsensitive && (categoryName == "Ll" || categoryName == "Lu" || categoryName == "Lt") { - // when RegexOptions.IgnoreCase is specified then {Ll} {Lu} and {Lt} cases should all match - c.addCategories( - category{cat: "Ll", negate: negate}, - category{cat: "Lu", negate: negate}, - category{cat: "Lt", negate: negate}) - } - c.addCategories(category{cat: categoryName, negate: negate}) -} - -func (c *CharSet) addSubtraction(sub *CharSet) { - c.sub = sub -} - -func (c *CharSet) addRange(chMin, chMax rune) { - c.ranges = append(c.ranges, singleRange{first: chMin, last: chMax}) - c.canonicalize() -} - -func (c *CharSet) addNamedASCII(name string, negate bool) bool { - var rs []singleRange - - switch name { - case "alnum": - rs = []singleRange{singleRange{'0', '9'}, singleRange{'A', 'Z'}, singleRange{'a', 'z'}} - case "alpha": - rs = []singleRange{singleRange{'A', 'Z'}, singleRange{'a', 'z'}} - case "ascii": - rs = []singleRange{singleRange{0, 0x7f}} - case "blank": - rs = []singleRange{singleRange{'\t', '\t'}, singleRange{' ', ' '}} - case "cntrl": - rs = []singleRange{singleRange{0, 0x1f}, singleRange{0x7f, 0x7f}} - case "digit": - c.addDigit(false, negate, "") - case "graph": - rs = []singleRange{singleRange{'!', '~'}} - case "lower": - rs = []singleRange{singleRange{'a', 'z'}} - case "print": - rs = []singleRange{singleRange{' ', '~'}} - case "punct": //[!-/:-@[-`{-~] - rs = []singleRange{singleRange{'!', '/'}, singleRange{':', '@'}, singleRange{'[', '`'}, singleRange{'{', '~'}} - case "space": - c.addSpace(true, false, negate) - case "upper": - rs = []singleRange{singleRange{'A', 'Z'}} - case "word": - c.addWord(true, negate) - case "xdigit": - rs = []singleRange{singleRange{'0', '9'}, singleRange{'A', 'F'}, singleRange{'a', 'f'}} - default: - return false - } - - if len(rs) > 0 { - if negate { - c.addNegativeRanges(rs) - } else { - c.addRanges(rs) - } - } - - return true -} - -type singleRangeSorter []singleRange - -func (p singleRangeSorter) Len() int { return len(p) } -func (p singleRangeSorter) Less(i, j int) bool { return p[i].first < p[j].first } -func (p singleRangeSorter) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// Logic to reduce a character class to a unique, sorted form. -func (c *CharSet) canonicalize() { - var i, j int - var last rune - - // - // Find and eliminate overlapping or abutting ranges - // - - if len(c.ranges) > 1 { - sort.Sort(singleRangeSorter(c.ranges)) - - done := false - - for i, j = 1, 0; ; i++ { - for last = c.ranges[j].last; ; i++ { - if i == len(c.ranges) || last == utf8.MaxRune { - done = true - break - } - - CurrentRange := c.ranges[i] - if CurrentRange.first > last+1 { - break - } - - if last < CurrentRange.last { - last = CurrentRange.last - } - } - - c.ranges[j] = singleRange{first: c.ranges[j].first, last: last} - - j++ - - if done { - break - } - - if j < i { - c.ranges[j] = c.ranges[i] - } - } - - c.ranges = append(c.ranges[:j], c.ranges[len(c.ranges):]...) - } -} - -// Adds to the class any lowercase versions of characters already -// in the class. Used for case-insensitivity. -func (c *CharSet) addLowercase() { - if c.anything { - return - } - toAdd := []singleRange{} - for i := 0; i < len(c.ranges); i++ { - r := c.ranges[i] - if r.first == r.last { - lower := unicode.ToLower(r.first) - c.ranges[i] = singleRange{first: lower, last: lower} - } else { - toAdd = append(toAdd, r) - } - } - - for _, r := range toAdd { - c.addLowercaseRange(r.first, r.last) - } - c.canonicalize() -} - -/************************************************************************** - Let U be the set of Unicode character values and let L be the lowercase - function, mapping from U to U. To perform case insensitive matching of - character sets, we need to be able to map an interval I in U, say - - I = [chMin, chMax] = { ch : chMin <= ch <= chMax } - - to a set A such that A contains L(I) and A is contained in the union of - I and L(I). - - The table below partitions U into intervals on which L is non-decreasing. - Thus, for any interval J = [a, b] contained in one of these intervals, - L(J) is contained in [L(a), L(b)]. - - It is also true that for any such J, [L(a), L(b)] is contained in the - union of J and L(J). This does not follow from L being non-decreasing on - these intervals. It follows from the nature of the L on each interval. - On each interval, L has one of the following forms: - - (1) L(ch) = constant (LowercaseSet) - (2) L(ch) = ch + offset (LowercaseAdd) - (3) L(ch) = ch | 1 (LowercaseBor) - (4) L(ch) = ch + (ch & 1) (LowercaseBad) - - It is easy to verify that for any of these forms [L(a), L(b)] is - contained in the union of [a, b] and L([a, b]). -***************************************************************************/ - -const ( - LowercaseSet = 0 // Set to arg. - LowercaseAdd = 1 // Add arg. - LowercaseBor = 2 // Bitwise or with 1. - LowercaseBad = 3 // Bitwise and with 1 and add original. -) - -type lcMap struct { - chMin, chMax rune - op, data int32 -} - -var lcTable = []lcMap{ - lcMap{'\u0041', '\u005A', LowercaseAdd, 32}, - lcMap{'\u00C0', '\u00DE', LowercaseAdd, 32}, - lcMap{'\u0100', '\u012E', LowercaseBor, 0}, - lcMap{'\u0130', '\u0130', LowercaseSet, 0x0069}, - lcMap{'\u0132', '\u0136', LowercaseBor, 0}, - lcMap{'\u0139', '\u0147', LowercaseBad, 0}, - lcMap{'\u014A', '\u0176', LowercaseBor, 0}, - lcMap{'\u0178', '\u0178', LowercaseSet, 0x00FF}, - lcMap{'\u0179', '\u017D', LowercaseBad, 0}, - lcMap{'\u0181', '\u0181', LowercaseSet, 0x0253}, - lcMap{'\u0182', '\u0184', LowercaseBor, 0}, - lcMap{'\u0186', '\u0186', LowercaseSet, 0x0254}, - lcMap{'\u0187', '\u0187', LowercaseSet, 0x0188}, - lcMap{'\u0189', '\u018A', LowercaseAdd, 205}, - lcMap{'\u018B', '\u018B', LowercaseSet, 0x018C}, - lcMap{'\u018E', '\u018E', LowercaseSet, 0x01DD}, - lcMap{'\u018F', '\u018F', LowercaseSet, 0x0259}, - lcMap{'\u0190', '\u0190', LowercaseSet, 0x025B}, - lcMap{'\u0191', '\u0191', LowercaseSet, 0x0192}, - lcMap{'\u0193', '\u0193', LowercaseSet, 0x0260}, - lcMap{'\u0194', '\u0194', LowercaseSet, 0x0263}, - lcMap{'\u0196', '\u0196', LowercaseSet, 0x0269}, - lcMap{'\u0197', '\u0197', LowercaseSet, 0x0268}, - lcMap{'\u0198', '\u0198', LowercaseSet, 0x0199}, - lcMap{'\u019C', '\u019C', LowercaseSet, 0x026F}, - lcMap{'\u019D', '\u019D', LowercaseSet, 0x0272}, - lcMap{'\u019F', '\u019F', LowercaseSet, 0x0275}, - lcMap{'\u01A0', '\u01A4', LowercaseBor, 0}, - lcMap{'\u01A7', '\u01A7', LowercaseSet, 0x01A8}, - lcMap{'\u01A9', '\u01A9', LowercaseSet, 0x0283}, - lcMap{'\u01AC', '\u01AC', LowercaseSet, 0x01AD}, - lcMap{'\u01AE', '\u01AE', LowercaseSet, 0x0288}, - lcMap{'\u01AF', '\u01AF', LowercaseSet, 0x01B0}, - lcMap{'\u01B1', '\u01B2', LowercaseAdd, 217}, - lcMap{'\u01B3', '\u01B5', LowercaseBad, 0}, - lcMap{'\u01B7', '\u01B7', LowercaseSet, 0x0292}, - lcMap{'\u01B8', '\u01B8', LowercaseSet, 0x01B9}, - lcMap{'\u01BC', '\u01BC', LowercaseSet, 0x01BD}, - lcMap{'\u01C4', '\u01C5', LowercaseSet, 0x01C6}, - lcMap{'\u01C7', '\u01C8', LowercaseSet, 0x01C9}, - lcMap{'\u01CA', '\u01CB', LowercaseSet, 0x01CC}, - lcMap{'\u01CD', '\u01DB', LowercaseBad, 0}, - lcMap{'\u01DE', '\u01EE', LowercaseBor, 0}, - lcMap{'\u01F1', '\u01F2', LowercaseSet, 0x01F3}, - lcMap{'\u01F4', '\u01F4', LowercaseSet, 0x01F5}, - lcMap{'\u01FA', '\u0216', LowercaseBor, 0}, - lcMap{'\u0386', '\u0386', LowercaseSet, 0x03AC}, - lcMap{'\u0388', '\u038A', LowercaseAdd, 37}, - lcMap{'\u038C', '\u038C', LowercaseSet, 0x03CC}, - lcMap{'\u038E', '\u038F', LowercaseAdd, 63}, - lcMap{'\u0391', '\u03AB', LowercaseAdd, 32}, - lcMap{'\u03E2', '\u03EE', LowercaseBor, 0}, - lcMap{'\u0401', '\u040F', LowercaseAdd, 80}, - lcMap{'\u0410', '\u042F', LowercaseAdd, 32}, - lcMap{'\u0460', '\u0480', LowercaseBor, 0}, - lcMap{'\u0490', '\u04BE', LowercaseBor, 0}, - lcMap{'\u04C1', '\u04C3', LowercaseBad, 0}, - lcMap{'\u04C7', '\u04C7', LowercaseSet, 0x04C8}, - lcMap{'\u04CB', '\u04CB', LowercaseSet, 0x04CC}, - lcMap{'\u04D0', '\u04EA', LowercaseBor, 0}, - lcMap{'\u04EE', '\u04F4', LowercaseBor, 0}, - lcMap{'\u04F8', '\u04F8', LowercaseSet, 0x04F9}, - lcMap{'\u0531', '\u0556', LowercaseAdd, 48}, - lcMap{'\u10A0', '\u10C5', LowercaseAdd, 48}, - lcMap{'\u1E00', '\u1EF8', LowercaseBor, 0}, - lcMap{'\u1F08', '\u1F0F', LowercaseAdd, -8}, - lcMap{'\u1F18', '\u1F1F', LowercaseAdd, -8}, - lcMap{'\u1F28', '\u1F2F', LowercaseAdd, -8}, - lcMap{'\u1F38', '\u1F3F', LowercaseAdd, -8}, - lcMap{'\u1F48', '\u1F4D', LowercaseAdd, -8}, - lcMap{'\u1F59', '\u1F59', LowercaseSet, 0x1F51}, - lcMap{'\u1F5B', '\u1F5B', LowercaseSet, 0x1F53}, - lcMap{'\u1F5D', '\u1F5D', LowercaseSet, 0x1F55}, - lcMap{'\u1F5F', '\u1F5F', LowercaseSet, 0x1F57}, - lcMap{'\u1F68', '\u1F6F', LowercaseAdd, -8}, - lcMap{'\u1F88', '\u1F8F', LowercaseAdd, -8}, - lcMap{'\u1F98', '\u1F9F', LowercaseAdd, -8}, - lcMap{'\u1FA8', '\u1FAF', LowercaseAdd, -8}, - lcMap{'\u1FB8', '\u1FB9', LowercaseAdd, -8}, - lcMap{'\u1FBA', '\u1FBB', LowercaseAdd, -74}, - lcMap{'\u1FBC', '\u1FBC', LowercaseSet, 0x1FB3}, - lcMap{'\u1FC8', '\u1FCB', LowercaseAdd, -86}, - lcMap{'\u1FCC', '\u1FCC', LowercaseSet, 0x1FC3}, - lcMap{'\u1FD8', '\u1FD9', LowercaseAdd, -8}, - lcMap{'\u1FDA', '\u1FDB', LowercaseAdd, -100}, - lcMap{'\u1FE8', '\u1FE9', LowercaseAdd, -8}, - lcMap{'\u1FEA', '\u1FEB', LowercaseAdd, -112}, - lcMap{'\u1FEC', '\u1FEC', LowercaseSet, 0x1FE5}, - lcMap{'\u1FF8', '\u1FF9', LowercaseAdd, -128}, - lcMap{'\u1FFA', '\u1FFB', LowercaseAdd, -126}, - lcMap{'\u1FFC', '\u1FFC', LowercaseSet, 0x1FF3}, - lcMap{'\u2160', '\u216F', LowercaseAdd, 16}, - lcMap{'\u24B6', '\u24D0', LowercaseAdd, 26}, - lcMap{'\uFF21', '\uFF3A', LowercaseAdd, 32}, -} - -func (c *CharSet) addLowercaseRange(chMin, chMax rune) { - var i, iMax, iMid int - var chMinT, chMaxT rune - var lc lcMap - - for i, iMax = 0, len(lcTable); i < iMax; { - iMid = (i + iMax) / 2 - if lcTable[iMid].chMax < chMin { - i = iMid + 1 - } else { - iMax = iMid - } - } - - for ; i < len(lcTable); i++ { - lc = lcTable[i] - if lc.chMin > chMax { - return - } - chMinT = lc.chMin - if chMinT < chMin { - chMinT = chMin - } - - chMaxT = lc.chMax - if chMaxT > chMax { - chMaxT = chMax - } - - switch lc.op { - case LowercaseSet: - chMinT = rune(lc.data) - chMaxT = rune(lc.data) - break - case LowercaseAdd: - chMinT += lc.data - chMaxT += lc.data - break - case LowercaseBor: - chMinT |= 1 - chMaxT |= 1 - break - case LowercaseBad: - chMinT += (chMinT & 1) - chMaxT += (chMaxT & 1) - break - } - - if chMinT < chMin || chMaxT > chMax { - c.addRange(chMinT, chMaxT) - } - } -} diff --git a/third_party/regexp2/syntax/code.go b/third_party/regexp2/syntax/code.go deleted file mode 100644 index 686e822af..000000000 --- a/third_party/regexp2/syntax/code.go +++ /dev/null @@ -1,274 +0,0 @@ -package syntax - -import ( - "bytes" - "fmt" - "math" -) - -// similar to prog.go in the go regex package...also with comment 'may not belong in this package' - -// File provides operator constants for use by the Builder and the Machine. - -// Implementation notes: -// -// Regexps are built into RegexCodes, which contain an operation array, -// a string table, and some constants. -// -// Each operation is one of the codes below, followed by the integer -// operands specified for each op. -// -// Strings and sets are indices into a string table. - -type InstOp int - -const ( - // lef/back operands description - - Onerep InstOp = 0 // lef,back char,min,max a {n} - Notonerep = 1 // lef,back char,min,max .{n} - Setrep = 2 // lef,back set,min,max [\d]{n} - - Oneloop = 3 // lef,back char,min,max a {,n} - Notoneloop = 4 // lef,back char,min,max .{,n} - Setloop = 5 // lef,back set,min,max [\d]{,n} - - Onelazy = 6 // lef,back char,min,max a {,n}? - Notonelazy = 7 // lef,back char,min,max .{,n}? - Setlazy = 8 // lef,back set,min,max [\d]{,n}? - - One = 9 // lef char a - Notone = 10 // lef char [^a] - Set = 11 // lef set [a-z\s] \w \s \d - - Multi = 12 // lef string abcd - Ref = 13 // lef group \# - - Bol = 14 // ^ - Eol = 15 // $ - Boundary = 16 // \b - Nonboundary = 17 // \B - Beginning = 18 // \A - Start = 19 // \G - EndZ = 20 // \Z - End = 21 // \Z - - Nothing = 22 // Reject! - - // Primitive control structures - - Lazybranch = 23 // back jump straight first - Branchmark = 24 // back jump branch first for loop - Lazybranchmark = 25 // back jump straight first for loop - Nullcount = 26 // back val set counter, null mark - Setcount = 27 // back val set counter, make mark - Branchcount = 28 // back jump,limit branch++ if zero<=c impl group slots - Capsize int // number of impl group slots - FcPrefix *Prefix // the set of candidate first characters (may be null) - BmPrefix *BmPrefix // the fixed prefix string as a Boyer-Moore machine (may be null) - Anchors AnchorLoc // the set of zero-length start anchors (RegexFCD.Bol, etc) - RightToLeft bool // true if right to left -} - -func opcodeBacktracks(op InstOp) bool { - op &= Mask - - switch op { - case Oneloop, Notoneloop, Setloop, Onelazy, Notonelazy, Setlazy, Lazybranch, Branchmark, Lazybranchmark, - Nullcount, Setcount, Branchcount, Lazybranchcount, Setmark, Capturemark, Getmark, Setjump, Backjump, - Forejump, Goto: - return true - - default: - return false - } -} - -func opcodeSize(op InstOp) int { - op &= Mask - - switch op { - case Nothing, Bol, Eol, Boundary, Nonboundary, ECMABoundary, NonECMABoundary, Beginning, Start, EndZ, - End, Nullmark, Setmark, Getmark, Setjump, Backjump, Forejump, Stop: - return 1 - - case One, Notone, Multi, Ref, Testref, Goto, Nullcount, Setcount, Lazybranch, Branchmark, Lazybranchmark, - Prune, Set: - return 2 - - case Capturemark, Branchcount, Lazybranchcount, Onerep, Notonerep, Oneloop, Notoneloop, Onelazy, Notonelazy, - Setlazy, Setrep, Setloop: - return 3 - - default: - panic(fmt.Errorf("Unexpected op code: %v", op)) - } -} - -var codeStr = []string{ - "Onerep", "Notonerep", "Setrep", - "Oneloop", "Notoneloop", "Setloop", - "Onelazy", "Notonelazy", "Setlazy", - "One", "Notone", "Set", - "Multi", "Ref", - "Bol", "Eol", "Boundary", "Nonboundary", "Beginning", "Start", "EndZ", "End", - "Nothing", - "Lazybranch", "Branchmark", "Lazybranchmark", - "Nullcount", "Setcount", "Branchcount", "Lazybranchcount", - "Nullmark", "Setmark", "Capturemark", "Getmark", - "Setjump", "Backjump", "Forejump", "Testref", "Goto", - "Prune", "Stop", - "ECMABoundary", "NonECMABoundary", -} - -func operatorDescription(op InstOp) string { - desc := codeStr[op&Mask] - if (op & Ci) != 0 { - desc += "-Ci" - } - if (op & Rtl) != 0 { - desc += "-Rtl" - } - if (op & Back) != 0 { - desc += "-Back" - } - if (op & Back2) != 0 { - desc += "-Back2" - } - - return desc -} - -// OpcodeDescription is a humman readable string of the specific offset -func (c *Code) OpcodeDescription(offset int) string { - buf := &bytes.Buffer{} - - op := InstOp(c.Codes[offset]) - fmt.Fprintf(buf, "%06d ", offset) - - if opcodeBacktracks(op & Mask) { - buf.WriteString("*") - } else { - buf.WriteString(" ") - } - buf.WriteString(operatorDescription(op)) - buf.WriteString("(") - op &= Mask - - switch op { - case One, Notone, Onerep, Notonerep, Oneloop, Notoneloop, Onelazy, Notonelazy: - buf.WriteString("Ch = ") - buf.WriteString(CharDescription(rune(c.Codes[offset+1]))) - - case Set, Setrep, Setloop, Setlazy: - buf.WriteString("Set = ") - buf.WriteString(c.Sets[c.Codes[offset+1]].String()) - - case Multi: - fmt.Fprintf(buf, "String = %s", string(c.Strings[c.Codes[offset+1]])) - - case Ref, Testref: - fmt.Fprintf(buf, "Index = %d", c.Codes[offset+1]) - - case Capturemark: - fmt.Fprintf(buf, "Index = %d", c.Codes[offset+1]) - if c.Codes[offset+2] != -1 { - fmt.Fprintf(buf, ", Unindex = %d", c.Codes[offset+2]) - } - - case Nullcount, Setcount: - fmt.Fprintf(buf, "Value = %d", c.Codes[offset+1]) - - case Goto, Lazybranch, Branchmark, Lazybranchmark, Branchcount, Lazybranchcount: - fmt.Fprintf(buf, "Addr = %d", c.Codes[offset+1]) - } - - switch op { - case Onerep, Notonerep, Oneloop, Notoneloop, Onelazy, Notonelazy, Setrep, Setloop, Setlazy: - buf.WriteString(", Rep = ") - if c.Codes[offset+2] == math.MaxInt32 { - buf.WriteString("inf") - } else { - fmt.Fprintf(buf, "%d", c.Codes[offset+2]) - } - - case Branchcount, Lazybranchcount: - buf.WriteString(", Limit = ") - if c.Codes[offset+2] == math.MaxInt32 { - buf.WriteString("inf") - } else { - fmt.Fprintf(buf, "%d", c.Codes[offset+2]) - } - - } - - buf.WriteString(")") - - return buf.String() -} - -func (c *Code) Dump() string { - buf := &bytes.Buffer{} - - if c.RightToLeft { - fmt.Fprintln(buf, "Direction: right-to-left") - } else { - fmt.Fprintln(buf, "Direction: left-to-right") - } - if c.FcPrefix == nil { - fmt.Fprintln(buf, "Firstchars: n/a") - } else { - fmt.Fprintf(buf, "Firstchars: %v\n", c.FcPrefix.PrefixSet.String()) - } - - if c.BmPrefix == nil { - fmt.Fprintln(buf, "Prefix: n/a") - } else { - fmt.Fprintf(buf, "Prefix: %v\n", Escape(c.BmPrefix.String())) - } - - fmt.Fprintf(buf, "Anchors: %v\n", c.Anchors) - fmt.Fprintln(buf) - - if c.BmPrefix != nil { - fmt.Fprintln(buf, "BoyerMoore:") - fmt.Fprintln(buf, c.BmPrefix.Dump(" ")) - } - for i := 0; i < len(c.Codes); i += opcodeSize(InstOp(c.Codes[i])) { - fmt.Fprintln(buf, c.OpcodeDescription(i)) - } - - return buf.String() -} diff --git a/third_party/regexp2/syntax/escape.go b/third_party/regexp2/syntax/escape.go deleted file mode 100644 index 609df1073..000000000 --- a/third_party/regexp2/syntax/escape.go +++ /dev/null @@ -1,94 +0,0 @@ -package syntax - -import ( - "bytes" - "strconv" - "strings" - "unicode" -) - -func Escape(input string) string { - b := &bytes.Buffer{} - for _, r := range input { - escape(b, r, false) - } - return b.String() -} - -const meta = `\.+*?()|[]{}^$# ` - -func escape(b *bytes.Buffer, r rune, force bool) { - if unicode.IsPrint(r) { - if strings.IndexRune(meta, r) >= 0 || force { - b.WriteRune('\\') - } - b.WriteRune(r) - return - } - - switch r { - case '\a': - b.WriteString(`\a`) - case '\f': - b.WriteString(`\f`) - case '\n': - b.WriteString(`\n`) - case '\r': - b.WriteString(`\r`) - case '\t': - b.WriteString(`\t`) - case '\v': - b.WriteString(`\v`) - default: - if r < 0x100 { - b.WriteString(`\x`) - s := strconv.FormatInt(int64(r), 16) - if len(s) == 1 { - b.WriteRune('0') - } - b.WriteString(s) - break - } - b.WriteString(`\u`) - b.WriteString(strconv.FormatInt(int64(r), 16)) - } -} - -func Unescape(input string) (string, error) { - idx := strings.IndexRune(input, '\\') - // no slashes means no unescape needed - if idx == -1 { - return input, nil - } - - buf := bytes.NewBufferString(input[:idx]) - // get the runes for the rest of the string -- we're going full parser scan on this - - p := parser{} - p.setPattern(input[idx+1:]) - for { - if p.rightMost() { - return "", p.getErr(ErrIllegalEndEscape) - } - r, err := p.scanCharEscape() - if err != nil { - return "", err - } - buf.WriteRune(r) - // are we done? - if p.rightMost() { - return buf.String(), nil - } - - r = p.moveRightGetChar() - for r != '\\' { - buf.WriteRune(r) - if p.rightMost() { - // we're done, no more slashes - return buf.String(), nil - } - // keep scanning until we get another slash - r = p.moveRightGetChar() - } - } -} diff --git a/third_party/regexp2/syntax/fuzz.go b/third_party/regexp2/syntax/fuzz.go deleted file mode 100644 index ee863866d..000000000 --- a/third_party/regexp2/syntax/fuzz.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build gofuzz - -package syntax - -// Fuzz is the input point for go-fuzz -func Fuzz(data []byte) int { - sdata := string(data) - tree, err := Parse(sdata, RegexOptions(0)) - if err != nil { - return 0 - } - - // translate it to code - _, err = Write(tree) - if err != nil { - panic(err) - } - - return 1 -} diff --git a/third_party/regexp2/syntax/parser.go b/third_party/regexp2/syntax/parser.go deleted file mode 100644 index 4ff0aaa83..000000000 --- a/third_party/regexp2/syntax/parser.go +++ /dev/null @@ -1,2262 +0,0 @@ -package syntax - -import ( - "fmt" - "math" - "os" - "sort" - "strconv" - "unicode" -) - -type RegexOptions int32 - -const ( - IgnoreCase RegexOptions = 0x0001 // "i" - Multiline = 0x0002 // "m" - ExplicitCapture = 0x0004 // "n" - Compiled = 0x0008 // "c" - Singleline = 0x0010 // "s" - IgnorePatternWhitespace = 0x0020 // "x" - RightToLeft = 0x0040 // "r" - Debug = 0x0080 // "d" - ECMAScript = 0x0100 // "e" - RE2 = 0x0200 // RE2 compat mode - Unicode = 0x0400 // "u" -) - -func optionFromCode(ch rune) RegexOptions { - // case-insensitive - switch ch { - case 'i', 'I': - return IgnoreCase - case 'r', 'R': - return RightToLeft - case 'm', 'M': - return Multiline - case 'n', 'N': - return ExplicitCapture - case 's', 'S': - return Singleline - case 'x', 'X': - return IgnorePatternWhitespace - case 'd', 'D': - return Debug - case 'e', 'E': - return ECMAScript - case 'u', 'U': - return Unicode - default: - return 0 - } -} - -// An Error describes a failure to parse a regular expression -// and gives the offending expression. -type Error struct { - Code ErrorCode - Expr string - Args []interface{} -} - -func (e *Error) Error() string { - if len(e.Args) == 0 { - return "error parsing regexp: " + e.Code.String() + " in `" + e.Expr + "`" - } - return "error parsing regexp: " + fmt.Sprintf(e.Code.String(), e.Args...) + " in `" + e.Expr + "`" -} - -// An ErrorCode describes a failure to parse a regular expression. -type ErrorCode string - -const ( - // internal issue - ErrInternalError ErrorCode = "regexp/syntax: internal error" - // Parser errors - ErrUnterminatedComment = "unterminated comment" - ErrInvalidCharRange = "invalid character class range" - ErrInvalidRepeatSize = "invalid repeat count" - ErrInvalidUTF8 = "invalid UTF-8" - ErrCaptureGroupOutOfRange = "capture group number out of range" - ErrUnexpectedParen = "unexpected )" - ErrMissingParen = "missing closing )" - ErrMissingBrace = "missing closing }" - ErrInvalidRepeatOp = "invalid nested repetition operator" - ErrMissingRepeatArgument = "missing argument to repetition operator" - ErrConditionalExpression = "illegal conditional (?(...)) expression" - ErrTooManyAlternates = "too many | in (?()|)" - ErrUnrecognizedGrouping = "unrecognized grouping construct: (%v" - ErrInvalidGroupName = "invalid group name: group names must begin with a word character and have a matching terminator" - ErrCapNumNotZero = "capture number cannot be zero" - ErrUndefinedBackRef = "reference to undefined group number %v" - ErrUndefinedNameRef = "reference to undefined group name %v" - ErrAlternationCantCapture = "alternation conditions do not capture and cannot be named" - ErrAlternationCantHaveComment = "alternation conditions cannot be comments" - ErrMalformedReference = "(?(%v) ) malformed" - ErrUndefinedReference = "(?(%v) ) reference to undefined group" - ErrIllegalEndEscape = "illegal \\ at end of pattern" - ErrMalformedSlashP = "malformed \\p{X} character escape" - ErrIncompleteSlashP = "incomplete \\p{X} character escape" - ErrUnknownSlashP = "unknown unicode category, script, or property '%v'" - ErrUnrecognizedEscape = "unrecognized escape sequence \\%v" - ErrMissingControl = "missing control character" - ErrUnrecognizedControl = "unrecognized control character" - ErrTooFewHex = "insufficient hexadecimal digits" - ErrInvalidHex = "hex values may not be larger than 0x10FFFF" - ErrMalformedNameRef = "malformed \\k<...> named back reference" - ErrBadClassInCharRange = "cannot include class \\%v in character range" - ErrUnterminatedBracket = "unterminated [] set" - ErrSubtractionMustBeLast = "a subtraction must be the last element in a character class" - ErrReversedCharRange = "[%c-%c] range in reverse order" -) - -func (e ErrorCode) String() string { - return string(e) -} - -type parser struct { - stack *regexNode - group *regexNode - alternation *regexNode - concatenation *regexNode - unit *regexNode - - patternRaw string - pattern []rune - - currentPos int - specialCase *unicode.SpecialCase - - autocap int - capcount int - captop int - capsize int - - caps map[int]int - capnames map[string]int - - capnumlist []int - capnamelist []string - - options RegexOptions - optionsStack []RegexOptions - ignoreNextParen bool -} - -const ( - maxValueDiv10 int = math.MaxInt32 / 10 - maxValueMod10 = math.MaxInt32 % 10 -) - -// Parse converts a regex string into a parse tree -func Parse(re string, op RegexOptions) (*RegexTree, error) { - p := parser{ - options: op, - caps: make(map[int]int), - } - p.setPattern(re) - - if err := p.countCaptures(); err != nil { - return nil, err - } - - p.reset(op) - root, err := p.scanRegex() - - if err != nil { - return nil, err - } - tree := &RegexTree{ - root: root, - caps: p.caps, - capnumlist: p.capnumlist, - captop: p.captop, - Capnames: p.capnames, - Caplist: p.capnamelist, - options: op, - } - - if tree.options&Debug > 0 { - os.Stdout.WriteString(tree.Dump()) - } - - return tree, nil -} - -func (p *parser) setPattern(pattern string) { - p.patternRaw = pattern - p.pattern = make([]rune, 0, len(pattern)) - - //populate our rune array to handle utf8 encoding - for _, r := range pattern { - p.pattern = append(p.pattern, r) - } -} -func (p *parser) getErr(code ErrorCode, args ...interface{}) error { - return &Error{Code: code, Expr: p.patternRaw, Args: args} -} - -func (p *parser) noteCaptureSlot(i, pos int) { - if _, ok := p.caps[i]; !ok { - // the rhs of the hashtable isn't used in the parser - p.caps[i] = pos - p.capcount++ - - if p.captop <= i { - if i == math.MaxInt32 { - p.captop = i - } else { - p.captop = i + 1 - } - } - } -} - -func (p *parser) noteCaptureName(name string, pos int) { - if p.capnames == nil { - p.capnames = make(map[string]int) - } - - if _, ok := p.capnames[name]; !ok { - p.capnames[name] = pos - p.capnamelist = append(p.capnamelist, name) - } -} - -func (p *parser) assignNameSlots() { - if p.capnames != nil { - for _, name := range p.capnamelist { - for p.isCaptureSlot(p.autocap) { - p.autocap++ - } - pos := p.capnames[name] - p.capnames[name] = p.autocap - p.noteCaptureSlot(p.autocap, pos) - - p.autocap++ - } - } - - // if the caps array has at least one gap, construct the list of used slots - if p.capcount < p.captop { - p.capnumlist = make([]int, p.capcount) - i := 0 - - for k := range p.caps { - p.capnumlist[i] = k - i++ - } - - sort.Ints(p.capnumlist) - } - - // merge capsnumlist into capnamelist - if p.capnames != nil || p.capnumlist != nil { - var oldcapnamelist []string - var next int - var k int - - if p.capnames == nil { - oldcapnamelist = nil - p.capnames = make(map[string]int) - p.capnamelist = []string{} - next = -1 - } else { - oldcapnamelist = p.capnamelist - p.capnamelist = []string{} - next = p.capnames[oldcapnamelist[0]] - } - - for i := 0; i < p.capcount; i++ { - j := i - if p.capnumlist != nil { - j = p.capnumlist[i] - } - - if next == j { - p.capnamelist = append(p.capnamelist, oldcapnamelist[k]) - k++ - - if k == len(oldcapnamelist) { - next = -1 - } else { - next = p.capnames[oldcapnamelist[k]] - } - - } else { - //feature: culture? - str := strconv.Itoa(j) - p.capnamelist = append(p.capnamelist, str) - p.capnames[str] = j - } - } - } -} - -func (p *parser) consumeAutocap() int { - r := p.autocap - p.autocap++ - return r -} - -// CountCaptures is a prescanner for deducing the slots used for -// captures by doing a partial tokenization of the pattern. -func (p *parser) countCaptures() error { - var ch rune - - p.noteCaptureSlot(0, 0) - - p.autocap = 1 - - for p.charsRight() > 0 { - pos := p.textpos() - ch = p.moveRightGetChar() - switch ch { - case '\\': - if p.charsRight() > 0 { - p.scanBackslash(true) - } - - case '#': - if p.useOptionX() { - p.moveLeft() - p.scanBlank() - } - - case '[': - p.scanCharSet(false, true) - - case ')': - if !p.emptyOptionsStack() { - p.popOptions() - } - - case '(': - if p.charsRight() >= 2 && p.rightChar(1) == '#' && p.rightChar(0) == '?' { - p.moveLeft() - p.scanBlank() - } else { - p.pushOptions() - if p.charsRight() > 0 && p.rightChar(0) == '?' { - // we have (?... - p.moveRight(1) - - if p.charsRight() > 1 && (p.rightChar(0) == '<' || p.rightChar(0) == '\'') { - // named group: (?<... or (?'... - - p.moveRight(1) - ch = p.rightChar(0) - - if ch != '0' && IsWordChar(ch) { - if ch >= '1' && ch <= '9' { - dec, err := p.scanDecimal() - if err != nil { - return err - } - p.noteCaptureSlot(dec, pos) - } else { - p.noteCaptureName(p.scanCapname(), pos) - } - } - } else if p.useRE2() && p.charsRight() > 2 && (p.rightChar(0) == 'P' && p.rightChar(1) == '<') { - // RE2-compat (?P<) - p.moveRight(2) - ch = p.rightChar(0) - if IsWordChar(ch) { - p.noteCaptureName(p.scanCapname(), pos) - } - - } else { - // (?... - - // get the options if it's an option construct (?cimsx-cimsx...) - p.scanOptions() - - if p.charsRight() > 0 { - if p.rightChar(0) == ')' { - // (?cimsx-cimsx) - p.moveRight(1) - p.popKeepOptions() - } else if p.rightChar(0) == '(' { - // alternation construct: (?(foo)yes|no) - // ignore the next paren so we don't capture the condition - p.ignoreNextParen = true - - // break from here so we don't reset ignoreNextParen - continue - } - } - } - } else { - if !p.useOptionN() && !p.ignoreNextParen { - p.noteCaptureSlot(p.consumeAutocap(), pos) - } - } - } - - p.ignoreNextParen = false - - } - } - - p.assignNameSlots() - return nil -} - -func (p *parser) reset(topopts RegexOptions) { - p.currentPos = 0 - p.autocap = 1 - p.ignoreNextParen = false - - if len(p.optionsStack) > 0 { - p.optionsStack = p.optionsStack[:0] - } - - p.options = topopts - p.stack = nil -} - -func (p *parser) scanRegex() (*regexNode, error) { - ch := '@' // nonspecial ch, means at beginning - isQuant := false - - p.startGroup(newRegexNodeMN(ntCapture, p.options, 0, -1)) - - for p.charsRight() > 0 { - wasPrevQuantifier := isQuant - isQuant = false - - if err := p.scanBlank(); err != nil { - return nil, err - } - - startpos := p.textpos() - - // move past all of the normal characters. We'll stop when we hit some kind of control character, - // or if IgnorePatternWhiteSpace is on, we'll stop when we see some whitespace. - if p.useOptionX() { - for p.charsRight() > 0 { - ch = p.rightChar(0) - //UGLY: clean up, this is ugly - if !(!isStopperX(ch) || (ch == '{' && !p.isTrueQuantifier())) { - break - } - p.moveRight(1) - } - } else { - for p.charsRight() > 0 { - ch = p.rightChar(0) - if !(!isSpecial(ch) || ch == '{' && !p.isTrueQuantifier()) { - break - } - p.moveRight(1) - } - } - - endpos := p.textpos() - - p.scanBlank() - - if p.charsRight() == 0 { - ch = '!' // nonspecial, means at end - } else if ch = p.rightChar(0); isSpecial(ch) { - isQuant = isQuantifier(ch) - p.moveRight(1) - } else { - ch = ' ' // nonspecial, means at ordinary char - } - - if startpos < endpos { - cchUnquantified := endpos - startpos - if isQuant { - cchUnquantified-- - } - wasPrevQuantifier = false - - if cchUnquantified > 0 { - p.addToConcatenate(startpos, cchUnquantified, false) - } - - if isQuant { - p.addUnitOne(p.charAt(endpos - 1)) - } - } - - switch ch { - case '!': - goto BreakOuterScan - - case ' ': - goto ContinueOuterScan - - case '[': - cc, err := p.scanCharSet(p.useOptionI(), false) - if err != nil { - return nil, err - } - p.addUnitSet(cc) - - case '(': - p.pushOptions() - - if grouper, err := p.scanGroupOpen(); err != nil { - return nil, err - } else if grouper == nil { - p.popKeepOptions() - } else { - p.pushGroup() - p.startGroup(grouper) - } - - continue - - case '|': - p.addAlternate() - goto ContinueOuterScan - - case ')': - if p.emptyStack() { - return nil, p.getErr(ErrUnexpectedParen) - } - - if err := p.addGroup(); err != nil { - return nil, err - } - if err := p.popGroup(); err != nil { - return nil, err - } - p.popOptions() - - if p.unit == nil { - goto ContinueOuterScan - } - - case '\\': - n, err := p.scanBackslash(false) - if err != nil { - return nil, err - } - p.addUnitNode(n) - - case '^': - if p.useOptionM() { - p.addUnitType(ntBol) - } else { - p.addUnitType(ntBeginning) - } - - case '$': - if p.useOptionM() { - p.addUnitType(ntEol) - } else { - p.addUnitType(ntEndZ) - } - - case '.': - if p.useOptionS() { - p.addUnitSet(AnyClass()) - } else if p.useOptionE() { - p.addUnitSet(ECMAAnyClass()) - } else { - p.addUnitNotone('\n') - } - - case '{', '*', '+', '?': - if p.unit == nil { - if wasPrevQuantifier { - return nil, p.getErr(ErrInvalidRepeatOp) - } else { - return nil, p.getErr(ErrMissingRepeatArgument) - } - } - p.moveLeft() - - default: - return nil, p.getErr(ErrInternalError) - } - - if err := p.scanBlank(); err != nil { - return nil, err - } - - if p.charsRight() > 0 { - isQuant = p.isTrueQuantifier() - } - if p.charsRight() == 0 || !isQuant { - //maintain odd C# assignment order -- not sure if required, could clean up? - p.addConcatenate() - goto ContinueOuterScan - } - - ch = p.moveRightGetChar() - - // Handle quantifiers - for p.unit != nil { - var min, max int - var lazy bool - - switch ch { - case '*': - min = 0 - max = math.MaxInt32 - - case '?': - min = 0 - max = 1 - - case '+': - min = 1 - max = math.MaxInt32 - - case '{': - { - var err error - startpos = p.textpos() - if min, err = p.scanDecimal(); err != nil { - return nil, err - } - max = min - if startpos < p.textpos() { - if p.charsRight() > 0 && p.rightChar(0) == ',' { - p.moveRight(1) - if p.charsRight() == 0 || p.rightChar(0) == '}' { - max = math.MaxInt32 - } else { - if max, err = p.scanDecimal(); err != nil { - return nil, err - } - } - } - } - - if startpos == p.textpos() || p.charsRight() == 0 || p.moveRightGetChar() != '}' { - p.addConcatenate() - p.textto(startpos - 1) - goto ContinueOuterScan - } - } - - default: - return nil, p.getErr(ErrInternalError) - } - - if err := p.scanBlank(); err != nil { - return nil, err - } - - if p.charsRight() == 0 || p.rightChar(0) != '?' { - lazy = false - } else { - p.moveRight(1) - lazy = true - } - - if min > max { - return nil, p.getErr(ErrInvalidRepeatSize) - } - - p.addConcatenate3(lazy, min, max) - } - - ContinueOuterScan: - } - -BreakOuterScan: - ; - - if !p.emptyStack() { - return nil, p.getErr(ErrMissingParen) - } - - if err := p.addGroup(); err != nil { - return nil, err - } - - return p.unit, nil - -} - -/* - * Simple parsing for replacement patterns - */ -func (p *parser) scanReplacement() (*regexNode, error) { - var c, startpos int - - p.concatenation = newRegexNode(ntConcatenate, p.options) - - for { - c = p.charsRight() - if c == 0 { - break - } - - startpos = p.textpos() - - for c > 0 && p.rightChar(0) != '$' { - p.moveRight(1) - c-- - } - - p.addToConcatenate(startpos, p.textpos()-startpos, true) - - if c > 0 { - if p.moveRightGetChar() == '$' { - n, err := p.scanDollar() - if err != nil { - return nil, err - } - p.addUnitNode(n) - } - p.addConcatenate() - } - } - - return p.concatenation, nil -} - -/* - * Scans $ patterns recognized within replacement patterns - */ -func (p *parser) scanDollar() (*regexNode, error) { - if p.charsRight() == 0 { - return newRegexNodeCh(ntOne, p.options, '$'), nil - } - - ch := p.rightChar(0) - angled := false - backpos := p.textpos() - lastEndPos := backpos - - // Note angle - - if ch == '{' && p.charsRight() > 1 { - angled = true - p.moveRight(1) - ch = p.rightChar(0) - } - - // Try to parse backreference: \1 or \{1} or \{cap} - - if ch >= '0' && ch <= '9' { - if !angled && p.useOptionE() { - capnum := -1 - newcapnum := int(ch - '0') - p.moveRight(1) - if p.isCaptureSlot(newcapnum) { - capnum = newcapnum - lastEndPos = p.textpos() - } - - for p.charsRight() > 0 { - ch = p.rightChar(0) - if ch < '0' || ch > '9' { - break - } - digit := int(ch - '0') - if newcapnum > maxValueDiv10 || (newcapnum == maxValueDiv10 && digit > maxValueMod10) { - return nil, p.getErr(ErrCaptureGroupOutOfRange) - } - - newcapnum = newcapnum*10 + digit - - p.moveRight(1) - if p.isCaptureSlot(newcapnum) { - capnum = newcapnum - lastEndPos = p.textpos() - } - } - p.textto(lastEndPos) - if capnum >= 0 { - return newRegexNodeM(ntRef, p.options, capnum), nil - } - } else { - capnum, err := p.scanDecimal() - if err != nil { - return nil, err - } - if !angled || p.charsRight() > 0 && p.moveRightGetChar() == '}' { - if p.isCaptureSlot(capnum) { - return newRegexNodeM(ntRef, p.options, capnum), nil - } - } - } - } else if angled && IsWordChar(ch) { - capname := p.scanCapname() - - if p.charsRight() > 0 && p.moveRightGetChar() == '}' { - if p.isCaptureName(capname) { - return newRegexNodeM(ntRef, p.options, p.captureSlotFromName(capname)), nil - } - } - } else if !angled { - capnum := 1 - - switch ch { - case '$': - p.moveRight(1) - return newRegexNodeCh(ntOne, p.options, '$'), nil - case '&': - capnum = 0 - case '`': - capnum = replaceLeftPortion - case '\'': - capnum = replaceRightPortion - case '+': - capnum = replaceLastGroup - case '_': - capnum = replaceWholeString - } - - if capnum != 1 { - p.moveRight(1) - return newRegexNodeM(ntRef, p.options, capnum), nil - } - } - - // unrecognized $: literalize - - p.textto(backpos) - return newRegexNodeCh(ntOne, p.options, '$'), nil -} - -// scanGroupOpen scans chars following a '(' (not counting the '('), and returns -// a RegexNode for the type of group scanned, or nil if the group -// simply changed options (?cimsx-cimsx) or was a comment (#...). -func (p *parser) scanGroupOpen() (*regexNode, error) { - var ch rune - var nt nodeType - var err error - close := '>' - start := p.textpos() - - // just return a RegexNode if we have: - // 1. "(" followed by nothing - // 2. "(x" where x != ? - // 3. "(?)" - if p.charsRight() == 0 || p.rightChar(0) != '?' || (p.rightChar(0) == '?' && (p.charsRight() > 1 && p.rightChar(1) == ')')) { - if p.useOptionN() || p.ignoreNextParen { - p.ignoreNextParen = false - return newRegexNode(ntGroup, p.options), nil - } - return newRegexNodeMN(ntCapture, p.options, p.consumeAutocap(), -1), nil - } - - p.moveRight(1) - - for { - if p.charsRight() == 0 { - break - } - - switch ch = p.moveRightGetChar(); ch { - case ':': - nt = ntGroup - - case '=': - p.options &= ^RightToLeft - nt = ntRequire - - case '!': - p.options &= ^RightToLeft - nt = ntPrevent - - case '>': - nt = ntGreedy - - case '\'': - close = '\'' - fallthrough - - case '<': - if p.charsRight() == 0 { - goto BreakRecognize - } - - switch ch = p.moveRightGetChar(); ch { - case '=': - if close == '\'' { - goto BreakRecognize - } - - p.options |= RightToLeft - nt = ntRequire - - case '!': - if close == '\'' { - goto BreakRecognize - } - - p.options |= RightToLeft - nt = ntPrevent - - default: - p.moveLeft() - capnum := -1 - uncapnum := -1 - proceed := false - - // grab part before - - - if ch >= '0' && ch <= '9' { - if capnum, err = p.scanDecimal(); err != nil { - return nil, err - } - - if !p.isCaptureSlot(capnum) { - capnum = -1 - } - - // check if we have bogus characters after the number - if p.charsRight() > 0 && !(p.rightChar(0) == close || p.rightChar(0) == '-') { - return nil, p.getErr(ErrInvalidGroupName) - } - if capnum == 0 { - return nil, p.getErr(ErrCapNumNotZero) - } - } else if IsWordChar(ch) { - capname := p.scanCapname() - - if p.isCaptureName(capname) { - capnum = p.captureSlotFromName(capname) - } - - // check if we have bogus character after the name - if p.charsRight() > 0 && !(p.rightChar(0) == close || p.rightChar(0) == '-') { - return nil, p.getErr(ErrInvalidGroupName) - } - } else if ch == '-' { - proceed = true - } else { - // bad group name - starts with something other than a word character and isn't a number - return nil, p.getErr(ErrInvalidGroupName) - } - - // grab part after - if any - - if (capnum != -1 || proceed == true) && p.charsRight() > 0 && p.rightChar(0) == '-' { - p.moveRight(1) - - //no more chars left, no closing char, etc - if p.charsRight() == 0 { - return nil, p.getErr(ErrInvalidGroupName) - } - - ch = p.rightChar(0) - if ch >= '0' && ch <= '9' { - if uncapnum, err = p.scanDecimal(); err != nil { - return nil, err - } - - if !p.isCaptureSlot(uncapnum) { - return nil, p.getErr(ErrUndefinedBackRef, uncapnum) - } - - // check if we have bogus characters after the number - if p.charsRight() > 0 && p.rightChar(0) != close { - return nil, p.getErr(ErrInvalidGroupName) - } - } else if IsWordChar(ch) { - uncapname := p.scanCapname() - - if !p.isCaptureName(uncapname) { - return nil, p.getErr(ErrUndefinedNameRef, uncapname) - } - uncapnum = p.captureSlotFromName(uncapname) - - // check if we have bogus character after the name - if p.charsRight() > 0 && p.rightChar(0) != close { - return nil, p.getErr(ErrInvalidGroupName) - } - } else { - // bad group name - starts with something other than a word character and isn't a number - return nil, p.getErr(ErrInvalidGroupName) - } - } - - // actually make the node - - if (capnum != -1 || uncapnum != -1) && p.charsRight() > 0 && p.moveRightGetChar() == close { - return newRegexNodeMN(ntCapture, p.options, capnum, uncapnum), nil - } - goto BreakRecognize - } - - case '(': - // alternation construct (?(...) | ) - - parenPos := p.textpos() - if p.charsRight() > 0 { - ch = p.rightChar(0) - - // check if the alternation condition is a backref - if ch >= '0' && ch <= '9' { - var capnum int - if capnum, err = p.scanDecimal(); err != nil { - return nil, err - } - if p.charsRight() > 0 && p.moveRightGetChar() == ')' { - if p.isCaptureSlot(capnum) { - return newRegexNodeM(ntTestref, p.options, capnum), nil - } - return nil, p.getErr(ErrUndefinedReference, capnum) - } - - return nil, p.getErr(ErrMalformedReference, capnum) - - } else if IsWordChar(ch) { - capname := p.scanCapname() - - if p.isCaptureName(capname) && p.charsRight() > 0 && p.moveRightGetChar() == ')' { - return newRegexNodeM(ntTestref, p.options, p.captureSlotFromName(capname)), nil - } - } - } - // not a backref - nt = ntTestgroup - p.textto(parenPos - 1) // jump to the start of the parentheses - p.ignoreNextParen = true // but make sure we don't try to capture the insides - - charsRight := p.charsRight() - if charsRight >= 3 && p.rightChar(1) == '?' { - rightchar2 := p.rightChar(2) - // disallow comments in the condition - if rightchar2 == '#' { - return nil, p.getErr(ErrAlternationCantHaveComment) - } - - // disallow named capture group (?<..>..) in the condition - if rightchar2 == '\'' { - return nil, p.getErr(ErrAlternationCantCapture) - } - - if charsRight >= 4 && (rightchar2 == '<' && p.rightChar(3) != '!' && p.rightChar(3) != '=') { - return nil, p.getErr(ErrAlternationCantCapture) - } - } - - case 'P': - if p.useRE2() { - // support for P syntax - if p.charsRight() < 3 { - goto BreakRecognize - } - - ch = p.moveRightGetChar() - if ch != '<' { - goto BreakRecognize - } - - ch = p.moveRightGetChar() - p.moveLeft() - - if IsWordChar(ch) { - capnum := -1 - capname := p.scanCapname() - - if p.isCaptureName(capname) { - capnum = p.captureSlotFromName(capname) - } - - // check if we have bogus character after the name - if p.charsRight() > 0 && p.rightChar(0) != '>' { - return nil, p.getErr(ErrInvalidGroupName) - } - - // actually make the node - - if capnum != -1 && p.charsRight() > 0 && p.moveRightGetChar() == '>' { - return newRegexNodeMN(ntCapture, p.options, capnum, -1), nil - } - goto BreakRecognize - - } else { - // bad group name - starts with something other than a word character and isn't a number - return nil, p.getErr(ErrInvalidGroupName) - } - } - // if we're not using RE2 compat mode then - // we just behave like normal - fallthrough - - default: - p.moveLeft() - - nt = ntGroup - // disallow options in the children of a testgroup node - if p.group.t != ntTestgroup { - p.scanOptions() - } - if p.charsRight() == 0 { - goto BreakRecognize - } - - if ch = p.moveRightGetChar(); ch == ')' { - return nil, nil - } - - if ch != ':' { - goto BreakRecognize - } - - } - - return newRegexNode(nt, p.options), nil - } - -BreakRecognize: - - // break Recognize comes here - - return nil, p.getErr(ErrUnrecognizedGrouping, string(p.pattern[start:p.textpos()])) -} - -// scans backslash specials and basics -func (p *parser) scanBackslash(scanOnly bool) (*regexNode, error) { - - if p.charsRight() == 0 { - return nil, p.getErr(ErrIllegalEndEscape) - } - - switch ch := p.rightChar(0); ch { - case 'b', 'B', 'A', 'G', 'Z', 'z': - p.moveRight(1) - return newRegexNode(p.typeFromCode(ch), p.options), nil - - case 'w': - p.moveRight(1) - if p.useOptionE() || p.useRE2() { - return newRegexNodeSet(ntSet, p.options, ECMAWordClass()), nil - } - return newRegexNodeSet(ntSet, p.options, WordClass()), nil - - case 'W': - p.moveRight(1) - if p.useOptionE() || p.useRE2() { - return newRegexNodeSet(ntSet, p.options, NotECMAWordClass()), nil - } - return newRegexNodeSet(ntSet, p.options, NotWordClass()), nil - - case 's': - p.moveRight(1) - if p.useOptionE() { - return newRegexNodeSet(ntSet, p.options, ECMASpaceClass()), nil - } else if p.useRE2() { - return newRegexNodeSet(ntSet, p.options, RE2SpaceClass()), nil - } - return newRegexNodeSet(ntSet, p.options, SpaceClass()), nil - - case 'S': - p.moveRight(1) - if p.useOptionE() { - return newRegexNodeSet(ntSet, p.options, NotECMASpaceClass()), nil - } else if p.useRE2() { - return newRegexNodeSet(ntSet, p.options, NotRE2SpaceClass()), nil - } - return newRegexNodeSet(ntSet, p.options, NotSpaceClass()), nil - - case 'd': - p.moveRight(1) - if p.useOptionE() || p.useRE2() { - return newRegexNodeSet(ntSet, p.options, ECMADigitClass()), nil - } - return newRegexNodeSet(ntSet, p.options, DigitClass()), nil - - case 'D': - p.moveRight(1) - if p.useOptionE() || p.useRE2() { - return newRegexNodeSet(ntSet, p.options, NotECMADigitClass()), nil - } - return newRegexNodeSet(ntSet, p.options, NotDigitClass()), nil - - case 'p', 'P': - p.moveRight(1) - prop, err := p.parseProperty() - if err != nil { - return nil, err - } - cc := &CharSet{} - cc.addCategory(prop, (ch != 'p'), p.useOptionI(), p.patternRaw) - if p.useOptionI() { - cc.addLowercase() - } - - return newRegexNodeSet(ntSet, p.options, cc), nil - - default: - return p.scanBasicBackslash(scanOnly) - } -} - -// Scans \-style backreferences and character escapes -func (p *parser) scanBasicBackslash(scanOnly bool) (*regexNode, error) { - if p.charsRight() == 0 { - return nil, p.getErr(ErrIllegalEndEscape) - } - angled := false - k := false - close := '\x00' - - backpos := p.textpos() - ch := p.rightChar(0) - - // Allow \k instead of \, which is now deprecated. - - // According to ECMAScript specification, \k is only parsed as a named group reference if - // there is at least one group name in the regexp. - // See https://www.ecma-international.org/ecma-262/#sec-isvalidregularexpressionliteral, step 7. - // Note, during the first (scanOnly) run we may not have all group names scanned, but that's ok. - if ch == 'k' && (!p.useOptionE() || len(p.capnames) > 0) { - if p.charsRight() >= 2 { - p.moveRight(1) - ch = p.moveRightGetChar() - - if ch == '<' || (!p.useOptionE() && ch == '\'') { // No support for \k'name' in ECMAScript - angled = true - if ch == '\'' { - close = '\'' - } else { - close = '>' - } - } - } - - if !angled || p.charsRight() <= 0 { - return nil, p.getErr(ErrMalformedNameRef) - } - - ch = p.rightChar(0) - k = true - - } else if !p.useOptionE() && (ch == '<' || ch == '\'') && p.charsRight() > 1 { // Note angle without \g - angled = true - if ch == '\'' { - close = '\'' - } else { - close = '>' - } - - p.moveRight(1) - ch = p.rightChar(0) - } - - // Try to parse backreference: \<1> or \ - - if angled && ch >= '0' && ch <= '9' { - capnum, err := p.scanDecimal() - if err != nil { - return nil, err - } - - if p.charsRight() > 0 && p.moveRightGetChar() == close { - if p.isCaptureSlot(capnum) { - return newRegexNodeM(ntRef, p.options, capnum), nil - } - return nil, p.getErr(ErrUndefinedBackRef, capnum) - } - } else if !angled && ch >= '1' && ch <= '9' { // Try to parse backreference or octal: \1 - capnum, err := p.scanDecimal() - if err != nil { - return nil, err - } - - if scanOnly { - return nil, nil - } - - if p.isCaptureSlot(capnum) { - return newRegexNodeM(ntRef, p.options, capnum), nil - } - if capnum <= 9 && !p.useOptionE() { - return nil, p.getErr(ErrUndefinedBackRef, capnum) - } - - } else if angled { - capname := p.scanCapname() - - if capname != "" && p.charsRight() > 0 && p.moveRightGetChar() == close { - - if scanOnly { - return nil, nil - } - - if p.isCaptureName(capname) { - return newRegexNodeM(ntRef, p.options, p.captureSlotFromName(capname)), nil - } - return nil, p.getErr(ErrUndefinedNameRef, capname) - } else { - if k { - return nil, p.getErr(ErrMalformedNameRef) - } - } - } - - // Not backreference: must be char code - - p.textto(backpos) - ch, err := p.scanCharEscape() - if err != nil { - return nil, err - } - - if scanOnly { - return nil, nil - } - - if p.useOptionI() { - ch = unicode.ToLower(ch) - } - - return newRegexNodeCh(ntOne, p.options, ch), nil -} - -// Scans X for \p{X} or \P{X} -func (p *parser) parseProperty() (string, error) { - // RE2 and PCRE supports \pX syntax (no {} and only 1 letter unicode cats supported) - // since this is purely additive syntax it's not behind a flag - if p.charsRight() >= 1 && p.rightChar(0) != '{' { - ch := string(p.moveRightGetChar()) - // check if it's a valid cat - if !isValidUnicodeCat(ch) { - return "", p.getErr(ErrUnknownSlashP, ch) - } - return ch, nil - } - - if p.charsRight() < 3 { - return "", p.getErr(ErrIncompleteSlashP) - } - ch := p.moveRightGetChar() - if ch != '{' { - return "", p.getErr(ErrMalformedSlashP) - } - - startpos := p.textpos() - for p.charsRight() > 0 { - ch = p.moveRightGetChar() - if !(IsWordChar(ch) || ch == '-') { - p.moveLeft() - break - } - } - capname := string(p.pattern[startpos:p.textpos()]) - - if p.charsRight() == 0 || p.moveRightGetChar() != '}' { - return "", p.getErr(ErrIncompleteSlashP) - } - - if !isValidUnicodeCat(capname) { - return "", p.getErr(ErrUnknownSlashP, capname) - } - - return capname, nil -} - -// Returns ReNode type for zero-length assertions with a \ code. -func (p *parser) typeFromCode(ch rune) nodeType { - switch ch { - case 'b': - if p.useOptionE() { - return ntECMABoundary - } - return ntBoundary - case 'B': - if p.useOptionE() { - return ntNonECMABoundary - } - return ntNonboundary - case 'A': - return ntBeginning - case 'G': - return ntStart - case 'Z': - return ntEndZ - case 'z': - return ntEnd - default: - return ntNothing - } -} - -// Scans whitespace or x-mode comments. -func (p *parser) scanBlank() error { - if p.useOptionX() { - for { - for p.charsRight() > 0 && isSpace(p.rightChar(0)) { - p.moveRight(1) - } - - if p.charsRight() == 0 { - break - } - - if p.rightChar(0) == '#' { - for p.charsRight() > 0 && p.rightChar(0) != '\n' { - p.moveRight(1) - } - } else if p.charsRight() >= 3 && p.rightChar(2) == '#' && - p.rightChar(1) == '?' && p.rightChar(0) == '(' { - for p.charsRight() > 0 && p.rightChar(0) != ')' { - p.moveRight(1) - } - if p.charsRight() == 0 { - return p.getErr(ErrUnterminatedComment) - } - p.moveRight(1) - } else { - break - } - } - } else { - for { - if p.charsRight() < 3 || p.rightChar(2) != '#' || - p.rightChar(1) != '?' || p.rightChar(0) != '(' { - return nil - } - - for p.charsRight() > 0 && p.rightChar(0) != ')' { - p.moveRight(1) - } - if p.charsRight() == 0 { - return p.getErr(ErrUnterminatedComment) - } - p.moveRight(1) - } - } - return nil -} - -func (p *parser) scanCapname() string { - startpos := p.textpos() - - for p.charsRight() > 0 { - if !IsWordChar(p.moveRightGetChar()) { - p.moveLeft() - break - } - } - - return string(p.pattern[startpos:p.textpos()]) -} - -// Scans contents of [] (not including []'s), and converts to a set. -func (p *parser) scanCharSet(caseInsensitive, scanOnly bool) (*CharSet, error) { - ch := '\x00' - chPrev := '\x00' - inRange := false - firstChar := true - closed := false - - var cc *CharSet - if !scanOnly { - cc = &CharSet{} - } - - if p.charsRight() > 0 && p.rightChar(0) == '^' { - p.moveRight(1) - if !scanOnly { - cc.negate = true - } - } - - for ; p.charsRight() > 0; firstChar = false { - fTranslatedChar := false - ch = p.moveRightGetChar() - if ch == ']' { - if !firstChar { - closed = true - break - } else if p.useOptionE() { - if !scanOnly { - cc.addRanges(NoneClass().ranges) - } - closed = true - break - } - - } else if ch == '\\' && p.charsRight() > 0 { - switch ch = p.moveRightGetChar(); ch { - case 'D', 'd': - if !scanOnly { - if inRange { - return nil, p.getErr(ErrBadClassInCharRange, ch) - } - cc.addDigit(p.useOptionE() || p.useRE2(), ch == 'D', p.patternRaw) - } - continue - - case 'S', 's': - if !scanOnly { - if inRange { - return nil, p.getErr(ErrBadClassInCharRange, ch) - } - cc.addSpace(p.useOptionE(), p.useRE2(), ch == 'S') - } - continue - - case 'W', 'w': - if !scanOnly { - if inRange { - return nil, p.getErr(ErrBadClassInCharRange, ch) - } - - cc.addWord(p.useOptionE() || p.useRE2(), ch == 'W') - } - continue - - case 'p', 'P': - if !scanOnly { - if inRange { - return nil, p.getErr(ErrBadClassInCharRange, ch) - } - prop, err := p.parseProperty() - if err != nil { - return nil, err - } - cc.addCategory(prop, (ch != 'p'), caseInsensitive, p.patternRaw) - } else { - p.parseProperty() - } - - continue - - case '-': - if !scanOnly { - cc.addRange(ch, ch) - } - continue - - default: - p.moveLeft() - var err error - ch, err = p.scanCharEscape() // non-literal character - if err != nil { - return nil, err - } - fTranslatedChar = true - break // this break will only break out of the switch - } - } else if ch == '[' { - // This is code for Posix style properties - [:Ll:] or [:IsTibetan:]. - // It currently doesn't do anything other than skip the whole thing! - if p.charsRight() > 0 && p.rightChar(0) == ':' && !inRange { - savePos := p.textpos() - - p.moveRight(1) - negate := false - if p.charsRight() > 1 && p.rightChar(0) == '^' { - negate = true - p.moveRight(1) - } - - nm := p.scanCapname() // snag the name - if !scanOnly && p.useRE2() { - // look up the name since these are valid for RE2 - // add the group based on the name - if ok := cc.addNamedASCII(nm, negate); !ok { - return nil, p.getErr(ErrInvalidCharRange) - } - } - if p.charsRight() < 2 || p.moveRightGetChar() != ':' || p.moveRightGetChar() != ']' { - p.textto(savePos) - } else if p.useRE2() { - // move on - continue - } - } - } - - if inRange { - inRange = false - if !scanOnly { - if ch == '[' && !fTranslatedChar && !firstChar { - // We thought we were in a range, but we're actually starting a subtraction. - // In that case, we'll add chPrev to our char class, skip the opening [, and - // scan the new character class recursively. - cc.addChar(chPrev) - sub, err := p.scanCharSet(caseInsensitive, false) - if err != nil { - return nil, err - } - cc.addSubtraction(sub) - - if p.charsRight() > 0 && p.rightChar(0) != ']' { - return nil, p.getErr(ErrSubtractionMustBeLast) - } - } else { - // a regular range, like a-z - if chPrev > ch { - return nil, p.getErr(ErrReversedCharRange, chPrev, ch) - } - cc.addRange(chPrev, ch) - } - } - } else if p.charsRight() >= 2 && p.rightChar(0) == '-' && p.rightChar(1) != ']' { - // this could be the start of a range - chPrev = ch - inRange = true - p.moveRight(1) - } else if p.charsRight() >= 1 && ch == '-' && !fTranslatedChar && p.rightChar(0) == '[' && !firstChar { - // we aren't in a range, and now there is a subtraction. Usually this happens - // only when a subtraction follows a range, like [a-z-[b]] - if !scanOnly { - p.moveRight(1) - sub, err := p.scanCharSet(caseInsensitive, false) - if err != nil { - return nil, err - } - cc.addSubtraction(sub) - - if p.charsRight() > 0 && p.rightChar(0) != ']' { - return nil, p.getErr(ErrSubtractionMustBeLast) - } - } else { - p.moveRight(1) - p.scanCharSet(caseInsensitive, true) - } - } else { - if !scanOnly { - cc.addRange(ch, ch) - } - } - } - - if !closed { - return nil, p.getErr(ErrUnterminatedBracket) - } - - if !scanOnly && caseInsensitive { - cc.addLowercase() - } - - return cc, nil -} - -// Scans any number of decimal digits (pegs value at 2^31-1 if too large) -func (p *parser) scanDecimal() (int, error) { - i := 0 - var d int - - for p.charsRight() > 0 { - d = int(p.rightChar(0) - '0') - if d < 0 || d > 9 { - break - } - p.moveRight(1) - - if i > maxValueDiv10 || (i == maxValueDiv10 && d > maxValueMod10) { - return 0, p.getErr(ErrCaptureGroupOutOfRange) - } - - i *= 10 - i += d - } - - return int(i), nil -} - -// Returns true for options allowed only at the top level -func isOnlyTopOption(option RegexOptions) bool { - return option == RightToLeft || option == ECMAScript || option == RE2 -} - -// Scans cimsx-cimsx option string, stops at the first unrecognized char. -func (p *parser) scanOptions() { - - for off := false; p.charsRight() > 0; p.moveRight(1) { - ch := p.rightChar(0) - - if ch == '-' { - off = true - } else if ch == '+' { - off = false - } else { - option := optionFromCode(ch) - if option == 0 || isOnlyTopOption(option) { - return - } - - if off { - p.options &= ^option - } else { - p.options |= option - } - } - } -} - -// Scans \ code for escape codes that map to single unicode chars. -func (p *parser) scanCharEscape() (r rune, err error) { - - ch := p.moveRightGetChar() - - if ch >= '0' && ch <= '7' { - p.moveLeft() - return p.scanOctal(), nil - } - - pos := p.textpos() - - switch ch { - case 'x': - // support for \x{HEX} syntax from Perl and PCRE - if p.charsRight() > 0 && p.rightChar(0) == '{' { - if p.useOptionE() { - return ch, nil - } - p.moveRight(1) - return p.scanHexUntilBrace() - } else { - r, err = p.scanHex(2) - } - case 'u': - // ECMAscript suppot \u{HEX} only if `u` is also set - if p.useOptionE() && p.useOptionU() && p.charsRight() > 0 && p.rightChar(0) == '{' { - p.moveRight(1) - return p.scanHexUntilBrace() - } else { - r, err = p.scanHex(4) - } - case 'a': - return '\u0007', nil - case 'b': - return '\b', nil - case 'e': - return '\u001B', nil - case 'f': - return '\f', nil - case 'n': - return '\n', nil - case 'r': - return '\r', nil - case 't': - return '\t', nil - case 'v': - return '\u000B', nil - case 'c': - r, err = p.scanControl() - default: - if !p.useOptionE() && !p.useRE2() && IsWordChar(ch) { - return 0, p.getErr(ErrUnrecognizedEscape, string(ch)) - } - return ch, nil - } - if err != nil && p.useOptionE() { - p.textto(pos) - return ch, nil - } - return -} - -// Grabs and converts an ascii control character -func (p *parser) scanControl() (rune, error) { - if p.charsRight() <= 0 { - return 0, p.getErr(ErrMissingControl) - } - - ch := p.moveRightGetChar() - - // \ca interpreted as \cA - - if ch >= 'a' && ch <= 'z' { - ch = (ch - ('a' - 'A')) - } - ch = (ch - '@') - if ch >= 0 && ch < ' ' { - return ch, nil - } - - return 0, p.getErr(ErrUnrecognizedControl) - -} - -// Scan hex digits until we hit a closing brace. -// Non-hex digits, hex value too large for UTF-8, or running out of chars are errors -func (p *parser) scanHexUntilBrace() (rune, error) { - // PCRE spec reads like unlimited hex digits are allowed, but unicode has a limit - // so we can enforce that - i := 0 - hasContent := false - - for p.charsRight() > 0 { - ch := p.moveRightGetChar() - if ch == '}' { - // hit our close brace, we're done here - // prevent \x{} - if !hasContent { - return 0, p.getErr(ErrTooFewHex) - } - return rune(i), nil - } - hasContent = true - // no brace needs to be hex digit - d := hexDigit(ch) - if d < 0 { - return 0, p.getErr(ErrMissingBrace) - } - - i *= 0x10 - i += d - - if i > unicode.MaxRune { - return 0, p.getErr(ErrInvalidHex) - } - } - - // we only make it here if we run out of digits without finding the brace - return 0, p.getErr(ErrMissingBrace) -} - -// Scans exactly c hex digits (c=2 for \xFF, c=4 for \uFFFF) -func (p *parser) scanHex(c int) (rune, error) { - - i := 0 - - if p.charsRight() >= c { - for c > 0 { - d := hexDigit(p.moveRightGetChar()) - if d < 0 { - break - } - i *= 0x10 - i += d - c-- - } - } - - if c > 0 { - return 0, p.getErr(ErrTooFewHex) - } - - return rune(i), nil -} - -// Returns n <= 0xF for a hex digit. -func hexDigit(ch rune) int { - - if d := uint(ch - '0'); d <= 9 { - return int(d) - } - - if d := uint(ch - 'a'); d <= 5 { - return int(d + 0xa) - } - - if d := uint(ch - 'A'); d <= 5 { - return int(d + 0xa) - } - - return -1 -} - -// Scans up to three octal digits (stops before exceeding 0377). -func (p *parser) scanOctal() rune { - // Consume octal chars only up to 3 digits and value 0377 - - c := 3 - - if c > p.charsRight() { - c = p.charsRight() - } - - //we know the first char is good because the caller had to check - i := 0 - d := int(p.rightChar(0) - '0') - for c > 0 && d <= 7 && d >= 0 { - if i >= 0x20 && p.useOptionE() { - break - } - i *= 8 - i += d - c-- - - p.moveRight(1) - if !p.rightMost() { - d = int(p.rightChar(0) - '0') - } - } - - // Octal codes only go up to 255. Any larger and the behavior that Perl follows - // is simply to truncate the high bits. - i &= 0xFF - - return rune(i) -} - -// Returns the current parsing position. -func (p *parser) textpos() int { - return p.currentPos -} - -// Zaps to a specific parsing position. -func (p *parser) textto(pos int) { - p.currentPos = pos -} - -// Returns the char at the right of the current parsing position and advances to the right. -func (p *parser) moveRightGetChar() rune { - ch := p.pattern[p.currentPos] - p.currentPos++ - return ch -} - -// Moves the current position to the right. -func (p *parser) moveRight(i int) { - // default would be 1 - p.currentPos += i -} - -// Moves the current parsing position one to the left. -func (p *parser) moveLeft() { - p.currentPos-- -} - -// Returns the char left of the current parsing position. -func (p *parser) charAt(i int) rune { - return p.pattern[i] -} - -// Returns the char i chars right of the current parsing position. -func (p *parser) rightChar(i int) rune { - // default would be 0 - return p.pattern[p.currentPos+i] -} - -// Number of characters to the right of the current parsing position. -func (p *parser) charsRight() int { - return len(p.pattern) - p.currentPos -} - -func (p *parser) rightMost() bool { - return p.currentPos == len(p.pattern) -} - -// Looks up the slot number for a given name -func (p *parser) captureSlotFromName(capname string) int { - return p.capnames[capname] -} - -// True if the capture slot was noted -func (p *parser) isCaptureSlot(i int) bool { - if p.caps != nil { - _, ok := p.caps[i] - return ok - } - - return (i >= 0 && i < p.capsize) -} - -// Looks up the slot number for a given name -func (p *parser) isCaptureName(capname string) bool { - if p.capnames == nil { - return false - } - - _, ok := p.capnames[capname] - return ok -} - -// option shortcuts - -// True if N option disabling '(' autocapture is on. -func (p *parser) useOptionN() bool { - return (p.options & ExplicitCapture) != 0 -} - -// True if I option enabling case-insensitivity is on. -func (p *parser) useOptionI() bool { - return (p.options & IgnoreCase) != 0 -} - -// True if M option altering meaning of $ and ^ is on. -func (p *parser) useOptionM() bool { - return (p.options & Multiline) != 0 -} - -// True if S option altering meaning of . is on. -func (p *parser) useOptionS() bool { - return (p.options & Singleline) != 0 -} - -// True if X option enabling whitespace/comment mode is on. -func (p *parser) useOptionX() bool { - return (p.options & IgnorePatternWhitespace) != 0 -} - -// True if E option enabling ECMAScript behavior on. -func (p *parser) useOptionE() bool { - return (p.options & ECMAScript) != 0 -} - -// true to use RE2 compatibility parsing behavior. -func (p *parser) useRE2() bool { - return (p.options & RE2) != 0 -} - -// True if U option enabling ECMAScript's Unicode behavior on. -func (p *parser) useOptionU() bool { - return (p.options & Unicode) != 0 -} - -// True if options stack is empty. -func (p *parser) emptyOptionsStack() bool { - return len(p.optionsStack) == 0 -} - -// Finish the current quantifiable (when a quantifier is not found or is not possible) -func (p *parser) addConcatenate() { - // The first (| inside a Testgroup group goes directly to the group - p.concatenation.addChild(p.unit) - p.unit = nil -} - -// Finish the current quantifiable (when a quantifier is found) -func (p *parser) addConcatenate3(lazy bool, min, max int) { - p.concatenation.addChild(p.unit.makeQuantifier(lazy, min, max)) - p.unit = nil -} - -// Sets the current unit to a single char node -func (p *parser) addUnitOne(ch rune) { - if p.useOptionI() { - ch = unicode.ToLower(ch) - } - - p.unit = newRegexNodeCh(ntOne, p.options, ch) -} - -// Sets the current unit to a single inverse-char node -func (p *parser) addUnitNotone(ch rune) { - if p.useOptionI() { - ch = unicode.ToLower(ch) - } - - p.unit = newRegexNodeCh(ntNotone, p.options, ch) -} - -// Sets the current unit to a single set node -func (p *parser) addUnitSet(set *CharSet) { - p.unit = newRegexNodeSet(ntSet, p.options, set) -} - -// Sets the current unit to a subtree -func (p *parser) addUnitNode(node *regexNode) { - p.unit = node -} - -// Sets the current unit to an assertion of the specified type -func (p *parser) addUnitType(t nodeType) { - p.unit = newRegexNode(t, p.options) -} - -// Finish the current group (in response to a ')' or end) -func (p *parser) addGroup() error { - if p.group.t == ntTestgroup || p.group.t == ntTestref { - p.group.addChild(p.concatenation.reverseLeft()) - if (p.group.t == ntTestref && len(p.group.children) > 2) || len(p.group.children) > 3 { - return p.getErr(ErrTooManyAlternates) - } - } else { - p.alternation.addChild(p.concatenation.reverseLeft()) - p.group.addChild(p.alternation) - } - - p.unit = p.group - return nil -} - -// Pops the option stack, but keeps the current options unchanged. -func (p *parser) popKeepOptions() { - lastIdx := len(p.optionsStack) - 1 - p.optionsStack = p.optionsStack[:lastIdx] -} - -// Recalls options from the stack. -func (p *parser) popOptions() { - lastIdx := len(p.optionsStack) - 1 - // get the last item on the stack and then remove it by reslicing - p.options = p.optionsStack[lastIdx] - p.optionsStack = p.optionsStack[:lastIdx] -} - -// Saves options on a stack. -func (p *parser) pushOptions() { - p.optionsStack = append(p.optionsStack, p.options) -} - -// Add a string to the last concatenate. -func (p *parser) addToConcatenate(pos, cch int, isReplacement bool) { - var node *regexNode - - if cch == 0 { - return - } - - if cch > 1 { - str := make([]rune, cch) - copy(str, p.pattern[pos:pos+cch]) - - if p.useOptionI() && !isReplacement { - // We do the ToLower character by character for consistency. With surrogate chars, doing - // a ToLower on the entire string could actually change the surrogate pair. This is more correct - // linguistically, but since Regex doesn't support surrogates, it's more important to be - // consistent. - for i := 0; i < len(str); i++ { - str[i] = unicode.ToLower(str[i]) - } - } - - node = newRegexNodeStr(ntMulti, p.options, str) - } else { - ch := p.charAt(pos) - - if p.useOptionI() && !isReplacement { - ch = unicode.ToLower(ch) - } - - node = newRegexNodeCh(ntOne, p.options, ch) - } - - p.concatenation.addChild(node) -} - -// Push the parser state (in response to an open paren) -func (p *parser) pushGroup() { - p.group.next = p.stack - p.alternation.next = p.group - p.concatenation.next = p.alternation - p.stack = p.concatenation -} - -// Remember the pushed state (in response to a ')') -func (p *parser) popGroup() error { - p.concatenation = p.stack - p.alternation = p.concatenation.next - p.group = p.alternation.next - p.stack = p.group.next - - // The first () inside a Testgroup group goes directly to the group - if p.group.t == ntTestgroup && len(p.group.children) == 0 { - if p.unit == nil { - return p.getErr(ErrConditionalExpression) - } - - p.group.addChild(p.unit) - p.unit = nil - } - return nil -} - -// True if the group stack is empty. -func (p *parser) emptyStack() bool { - return p.stack == nil -} - -// Start a new round for the parser state (in response to an open paren or string start) -func (p *parser) startGroup(openGroup *regexNode) { - p.group = openGroup - p.alternation = newRegexNode(ntAlternate, p.options) - p.concatenation = newRegexNode(ntConcatenate, p.options) -} - -// Finish the current concatenation (in response to a |) -func (p *parser) addAlternate() { - // The | parts inside a Testgroup group go directly to the group - - if p.group.t == ntTestgroup || p.group.t == ntTestref { - p.group.addChild(p.concatenation.reverseLeft()) - } else { - p.alternation.addChild(p.concatenation.reverseLeft()) - } - - p.concatenation = newRegexNode(ntConcatenate, p.options) -} - -// For categorizing ascii characters. - -const ( - Q byte = 5 // quantifier - S = 4 // ordinary stopper - Z = 3 // ScanBlank stopper - X = 2 // whitespace - E = 1 // should be escaped -) - -var _category = []byte{ - //01 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F - 0, 0, 0, 0, 0, 0, 0, 0, 0, X, X, X, X, X, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - // ! " # $ % & ' ( ) * + , - . / 0 1 2 3 4 5 6 7 8 9 : ; < = > ? - X, 0, 0, Z, S, 0, 0, 0, S, S, Q, Q, 0, 0, S, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Q, - //@A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, S, S, 0, S, 0, - //'a b c d e f g h i j k l m n o p q r s t u v w x y z { | } ~ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Q, S, 0, 0, 0, -} - -func isSpace(ch rune) bool { - return (ch <= ' ' && _category[ch] == X) -} - -// Returns true for those characters that terminate a string of ordinary chars. -func isSpecial(ch rune) bool { - return (ch <= '|' && _category[ch] >= S) -} - -// Returns true for those characters that terminate a string of ordinary chars. -func isStopperX(ch rune) bool { - return (ch <= '|' && _category[ch] >= X) -} - -// Returns true for those characters that begin a quantifier. -func isQuantifier(ch rune) bool { - return (ch <= '{' && _category[ch] >= Q) -} - -func (p *parser) isTrueQuantifier() bool { - nChars := p.charsRight() - if nChars == 0 { - return false - } - - startpos := p.textpos() - ch := p.charAt(startpos) - if ch != '{' { - return ch <= '{' && _category[ch] >= Q - } - - //UGLY: this is ugly -- the original code was ugly too - pos := startpos - for { - nChars-- - if nChars <= 0 { - break - } - pos++ - ch = p.charAt(pos) - if ch < '0' || ch > '9' { - break - } - } - - if nChars == 0 || pos-startpos == 1 { - return false - } - if ch == '}' { - return true - } - if ch != ',' { - return false - } - for { - nChars-- - if nChars <= 0 { - break - } - pos++ - ch = p.charAt(pos) - if ch < '0' || ch > '9' { - break - } - } - - return nChars > 0 && ch == '}' -} diff --git a/third_party/regexp2/syntax/prefix.go b/third_party/regexp2/syntax/prefix.go deleted file mode 100644 index f67168862..000000000 --- a/third_party/regexp2/syntax/prefix.go +++ /dev/null @@ -1,896 +0,0 @@ -package syntax - -import ( - "bytes" - "fmt" - "strconv" - "unicode" - "unicode/utf8" -) - -type Prefix struct { - PrefixStr []rune - PrefixSet CharSet - CaseInsensitive bool -} - -// It takes a RegexTree and computes the set of chars that can start it. -func getFirstCharsPrefix(tree *RegexTree) *Prefix { - s := regexFcd{ - fcStack: make([]regexFc, 32), - intStack: make([]int, 32), - } - fc := s.regexFCFromRegexTree(tree) - - if fc == nil || fc.nullable || fc.cc.IsEmpty() { - return nil - } - fcSet := fc.getFirstChars() - return &Prefix{PrefixSet: fcSet, CaseInsensitive: fc.caseInsensitive} -} - -type regexFcd struct { - intStack []int - intDepth int - fcStack []regexFc - fcDepth int - skipAllChildren bool // don't process any more children at the current level - skipchild bool // don't process the current child. - failed bool -} - -/* - * The main FC computation. It does a shortcutted depth-first walk - * through the tree and calls CalculateFC to emits code before - * and after each child of an interior node, and at each leaf. - */ -func (s *regexFcd) regexFCFromRegexTree(tree *RegexTree) *regexFc { - curNode := tree.root - curChild := 0 - - for { - if len(curNode.children) == 0 { - // This is a leaf node - s.calculateFC(curNode.t, curNode, 0) - } else if curChild < len(curNode.children) && !s.skipAllChildren { - // This is an interior node, and we have more children to analyze - s.calculateFC(curNode.t|beforeChild, curNode, curChild) - - if !s.skipchild { - curNode = curNode.children[curChild] - // this stack is how we get a depth first walk of the tree. - s.pushInt(curChild) - curChild = 0 - } else { - curChild++ - s.skipchild = false - } - continue - } - - // This is an interior node where we've finished analyzing all the children, or - // the end of a leaf node. - s.skipAllChildren = false - - if s.intIsEmpty() { - break - } - - curChild = s.popInt() - curNode = curNode.next - - s.calculateFC(curNode.t|afterChild, curNode, curChild) - if s.failed { - return nil - } - - curChild++ - } - - if s.fcIsEmpty() { - return nil - } - - return s.popFC() -} - -// To avoid recursion, we use a simple integer stack. -// This is the push. -func (s *regexFcd) pushInt(I int) { - if s.intDepth >= len(s.intStack) { - expanded := make([]int, s.intDepth*2) - copy(expanded, s.intStack) - s.intStack = expanded - } - - s.intStack[s.intDepth] = I - s.intDepth++ -} - -// True if the stack is empty. -func (s *regexFcd) intIsEmpty() bool { - return s.intDepth == 0 -} - -// This is the pop. -func (s *regexFcd) popInt() int { - s.intDepth-- - return s.intStack[s.intDepth] -} - -// We also use a stack of RegexFC objects. -// This is the push. -func (s *regexFcd) pushFC(fc regexFc) { - if s.fcDepth >= len(s.fcStack) { - expanded := make([]regexFc, s.fcDepth*2) - copy(expanded, s.fcStack) - s.fcStack = expanded - } - - s.fcStack[s.fcDepth] = fc - s.fcDepth++ -} - -// True if the stack is empty. -func (s *regexFcd) fcIsEmpty() bool { - return s.fcDepth == 0 -} - -// This is the pop. -func (s *regexFcd) popFC() *regexFc { - s.fcDepth-- - return &s.fcStack[s.fcDepth] -} - -// This is the top. -func (s *regexFcd) topFC() *regexFc { - return &s.fcStack[s.fcDepth-1] -} - -// Called in Beforechild to prevent further processing of the current child -func (s *regexFcd) skipChild() { - s.skipchild = true -} - -// FC computation and shortcut cases for each node type -func (s *regexFcd) calculateFC(nt nodeType, node *regexNode, CurIndex int) { - //fmt.Printf("NodeType: %v, CurIndex: %v, Desc: %v\n", nt, CurIndex, node.description()) - ci := false - rtl := false - - if nt <= ntRef { - if (node.options & IgnoreCase) != 0 { - ci = true - } - if (node.options & RightToLeft) != 0 { - rtl = true - } - } - - switch nt { - case ntConcatenate | beforeChild, ntAlternate | beforeChild, ntTestref | beforeChild, ntLoop | beforeChild, ntLazyloop | beforeChild: - break - - case ntTestgroup | beforeChild: - if CurIndex == 0 { - s.skipChild() - } - break - - case ntEmpty: - s.pushFC(regexFc{nullable: true}) - break - - case ntConcatenate | afterChild: - if CurIndex != 0 { - child := s.popFC() - cumul := s.topFC() - - s.failed = !cumul.addFC(*child, true) - } - - fc := s.topFC() - if !fc.nullable { - s.skipAllChildren = true - } - break - - case ntTestgroup | afterChild: - if CurIndex > 1 { - child := s.popFC() - cumul := s.topFC() - - s.failed = !cumul.addFC(*child, false) - } - break - - case ntAlternate | afterChild, ntTestref | afterChild: - if CurIndex != 0 { - child := s.popFC() - cumul := s.topFC() - - s.failed = !cumul.addFC(*child, false) - } - break - - case ntLoop | afterChild, ntLazyloop | afterChild: - if node.m == 0 { - fc := s.topFC() - fc.nullable = true - } - break - - case ntGroup | beforeChild, ntGroup | afterChild, ntCapture | beforeChild, ntCapture | afterChild, ntGreedy | beforeChild, ntGreedy | afterChild: - break - - case ntRequire | beforeChild, ntPrevent | beforeChild: - s.skipChild() - s.pushFC(regexFc{nullable: true}) - break - - case ntRequire | afterChild, ntPrevent | afterChild: - break - - case ntOne, ntNotone: - s.pushFC(newRegexFc(node.ch, nt == ntNotone, false, ci)) - break - - case ntOneloop, ntOnelazy: - s.pushFC(newRegexFc(node.ch, false, node.m == 0, ci)) - break - - case ntNotoneloop, ntNotonelazy: - s.pushFC(newRegexFc(node.ch, true, node.m == 0, ci)) - break - - case ntMulti: - if len(node.str) == 0 { - s.pushFC(regexFc{nullable: true}) - } else if !rtl { - s.pushFC(newRegexFc(node.str[0], false, false, ci)) - } else { - s.pushFC(newRegexFc(node.str[len(node.str)-1], false, false, ci)) - } - break - - case ntSet: - s.pushFC(regexFc{cc: node.set.Copy(), nullable: false, caseInsensitive: ci}) - break - - case ntSetloop, ntSetlazy: - s.pushFC(regexFc{cc: node.set.Copy(), nullable: node.m == 0, caseInsensitive: ci}) - break - - case ntRef: - s.pushFC(regexFc{cc: *AnyClass(), nullable: true, caseInsensitive: false}) - break - - case ntNothing, ntBol, ntEol, ntBoundary, ntNonboundary, ntECMABoundary, ntNonECMABoundary, ntBeginning, ntStart, ntEndZ, ntEnd: - s.pushFC(regexFc{nullable: true}) - break - - default: - panic(fmt.Sprintf("unexpected op code: %v", nt)) - } -} - -type regexFc struct { - cc CharSet - nullable bool - caseInsensitive bool -} - -func newRegexFc(ch rune, not, nullable, caseInsensitive bool) regexFc { - r := regexFc{ - caseInsensitive: caseInsensitive, - nullable: nullable, - } - if not { - if ch > 0 { - r.cc.addRange('\x00', ch-1) - } - if ch < 0xFFFF { - r.cc.addRange(ch+1, utf8.MaxRune) - } - } else { - r.cc.addRange(ch, ch) - } - return r -} - -func (r *regexFc) getFirstChars() CharSet { - if r.caseInsensitive { - r.cc.addLowercase() - } - - return r.cc -} - -func (r *regexFc) addFC(fc regexFc, concatenate bool) bool { - if !r.cc.IsMergeable() || !fc.cc.IsMergeable() { - return false - } - - if concatenate { - if !r.nullable { - return true - } - - if !fc.nullable { - r.nullable = false - } - } else { - if fc.nullable { - r.nullable = true - } - } - - r.caseInsensitive = r.caseInsensitive || fc.caseInsensitive - r.cc.addSet(fc.cc) - - return true -} - -// This is a related computation: it takes a RegexTree and computes the -// leading substring if it sees one. It's quite trivial and gives up easily. -func getPrefix(tree *RegexTree) *Prefix { - var concatNode *regexNode - nextChild := 0 - - curNode := tree.root - - for { - switch curNode.t { - case ntConcatenate: - if len(curNode.children) > 0 { - concatNode = curNode - nextChild = 0 - } - - case ntGreedy, ntCapture: - curNode = curNode.children[0] - concatNode = nil - continue - - case ntOneloop, ntOnelazy: - if curNode.m > 0 { - return &Prefix{ - PrefixStr: repeat(curNode.ch, curNode.m), - CaseInsensitive: (curNode.options & IgnoreCase) != 0, - } - } - return nil - - case ntOne: - return &Prefix{ - PrefixStr: []rune{curNode.ch}, - CaseInsensitive: (curNode.options & IgnoreCase) != 0, - } - - case ntMulti: - return &Prefix{ - PrefixStr: curNode.str, - CaseInsensitive: (curNode.options & IgnoreCase) != 0, - } - - case ntBol, ntEol, ntBoundary, ntECMABoundary, ntBeginning, ntStart, - ntEndZ, ntEnd, ntEmpty, ntRequire, ntPrevent: - - default: - return nil - } - - if concatNode == nil || nextChild >= len(concatNode.children) { - return nil - } - - curNode = concatNode.children[nextChild] - nextChild++ - } -} - -// repeat the rune r, c times... up to the max of MaxPrefixSize -func repeat(r rune, c int) []rune { - if c > MaxPrefixSize { - c = MaxPrefixSize - } - - ret := make([]rune, c) - - // binary growth using copy for speed - ret[0] = r - bp := 1 - for bp < len(ret) { - copy(ret[bp:], ret[:bp]) - bp *= 2 - } - - return ret -} - -// BmPrefix precomputes the Boyer-Moore -// tables for fast string scanning. These tables allow -// you to scan for the first occurrence of a string within -// a large body of text without examining every character. -// The performance of the heuristic depends on the actual -// string and the text being searched, but usually, the longer -// the string that is being searched for, the fewer characters -// need to be examined. -type BmPrefix struct { - positive []int - negativeASCII []int - negativeUnicode [][]int - pattern []rune - lowASCII rune - highASCII rune - rightToLeft bool - caseInsensitive bool -} - -func newBmPrefix(pattern []rune, caseInsensitive, rightToLeft bool) *BmPrefix { - - b := &BmPrefix{ - rightToLeft: rightToLeft, - caseInsensitive: caseInsensitive, - pattern: pattern, - } - - if caseInsensitive { - for i := 0; i < len(b.pattern); i++ { - // We do the ToLower character by character for consistency. With surrogate chars, doing - // a ToLower on the entire string could actually change the surrogate pair. This is more correct - // linguistically, but since Regex doesn't support surrogates, it's more important to be - // consistent. - - b.pattern[i] = unicode.ToLower(b.pattern[i]) - } - } - - var beforefirst, last, bump int - var scan, match int - - if !rightToLeft { - beforefirst = -1 - last = len(b.pattern) - 1 - bump = 1 - } else { - beforefirst = len(b.pattern) - last = 0 - bump = -1 - } - - // PART I - the good-suffix shift table - // - // compute the positive requirement: - // if char "i" is the first one from the right that doesn't match, - // then we know the matcher can advance by _positive[i]. - // - // This algorithm is a simplified variant of the standard - // Boyer-Moore good suffix calculation. - - b.positive = make([]int, len(b.pattern)) - - examine := last - ch := b.pattern[examine] - b.positive[examine] = bump - examine -= bump - -Outerloop: - for { - // find an internal char (examine) that matches the tail - - for { - if examine == beforefirst { - break Outerloop - } - if b.pattern[examine] == ch { - break - } - examine -= bump - } - - match = last - scan = examine - - // find the length of the match - for { - if scan == beforefirst || b.pattern[match] != b.pattern[scan] { - // at the end of the match, note the difference in _positive - // this is not the length of the match, but the distance from the internal match - // to the tail suffix. - if b.positive[match] == 0 { - b.positive[match] = match - scan - } - - // System.Diagnostics.Debug.WriteLine("Set positive[" + match + "] to " + (match - scan)); - - break - } - - scan -= bump - match -= bump - } - - examine -= bump - } - - match = last - bump - - // scan for the chars for which there are no shifts that yield a different candidate - - // The inside of the if statement used to say - // "_positive[match] = last - beforefirst;" - // This is slightly less aggressive in how much we skip, but at worst it - // should mean a little more work rather than skipping a potential match. - for match != beforefirst { - if b.positive[match] == 0 { - b.positive[match] = bump - } - - match -= bump - } - - // PART II - the bad-character shift table - // - // compute the negative requirement: - // if char "ch" is the reject character when testing position "i", - // we can slide up by _negative[ch]; - // (_negative[ch] = str.Length - 1 - str.LastIndexOf(ch)) - // - // the lookup table is divided into ASCII and Unicode portions; - // only those parts of the Unicode 16-bit code set that actually - // appear in the string are in the table. (Maximum size with - // Unicode is 65K; ASCII only case is 512 bytes.) - - b.negativeASCII = make([]int, 128) - - for i := 0; i < len(b.negativeASCII); i++ { - b.negativeASCII[i] = last - beforefirst - } - - b.lowASCII = 127 - b.highASCII = 0 - - for examine = last; examine != beforefirst; examine -= bump { - ch = b.pattern[examine] - - switch { - case ch < 128: - if b.lowASCII > ch { - b.lowASCII = ch - } - - if b.highASCII < ch { - b.highASCII = ch - } - - if b.negativeASCII[ch] == last-beforefirst { - b.negativeASCII[ch] = last - examine - } - case ch <= 0xffff: - i, j := ch>>8, ch&0xFF - - if b.negativeUnicode == nil { - b.negativeUnicode = make([][]int, 256) - } - - if b.negativeUnicode[i] == nil { - newarray := make([]int, 256) - - for k := 0; k < len(newarray); k++ { - newarray[k] = last - beforefirst - } - - if i == 0 { - copy(newarray, b.negativeASCII) - //TODO: this line needed? - b.negativeASCII = newarray - } - - b.negativeUnicode[i] = newarray - } - - if b.negativeUnicode[i][j] == last-beforefirst { - b.negativeUnicode[i][j] = last - examine - } - default: - // we can't do the filter because this algo doesn't support - // unicode chars >0xffff - return nil - } - } - - return b -} - -func (b *BmPrefix) String() string { - return string(b.pattern) -} - -// Dump returns the contents of the filter as a human readable string -func (b *BmPrefix) Dump(indent string) string { - buf := &bytes.Buffer{} - - fmt.Fprintf(buf, "%sBM Pattern: %s\n%sPositive: ", indent, string(b.pattern), indent) - for i := 0; i < len(b.positive); i++ { - buf.WriteString(strconv.Itoa(b.positive[i])) - buf.WriteRune(' ') - } - buf.WriteRune('\n') - - if b.negativeASCII != nil { - buf.WriteString(indent) - buf.WriteString("Negative table\n") - for i := 0; i < len(b.negativeASCII); i++ { - if b.negativeASCII[i] != len(b.pattern) { - fmt.Fprintf(buf, "%s %s %s\n", indent, Escape(string(rune(i))), strconv.Itoa(b.negativeASCII[i])) - } - } - } - - return buf.String() -} - -// Scan uses the Boyer-Moore algorithm to find the first occurrence -// of the specified string within text, beginning at index, and -// constrained within beglimit and endlimit. -// -// The direction and case-sensitivity of the match is determined -// by the arguments to the RegexBoyerMoore constructor. -func (b *BmPrefix) Scan(text []rune, index, beglimit, endlimit int) int { - var ( - defadv, test, test2 int - match, startmatch, endmatch int - bump, advance int - chTest rune - unicodeLookup []int - ) - - if !b.rightToLeft { - defadv = len(b.pattern) - startmatch = len(b.pattern) - 1 - endmatch = 0 - test = index + defadv - 1 - bump = 1 - } else { - defadv = -len(b.pattern) - startmatch = 0 - endmatch = -defadv - 1 - test = index + defadv - bump = -1 - } - - chMatch := b.pattern[startmatch] - - for { - if test >= endlimit || test < beglimit { - return -1 - } - - chTest = text[test] - - if b.caseInsensitive { - chTest = unicode.ToLower(chTest) - } - - if chTest != chMatch { - if chTest < 128 { - advance = b.negativeASCII[chTest] - } else if chTest < 0xffff && len(b.negativeUnicode) > 0 { - unicodeLookup = b.negativeUnicode[chTest>>8] - if len(unicodeLookup) > 0 { - advance = unicodeLookup[chTest&0xFF] - } else { - advance = defadv - } - } else { - advance = defadv - } - - test += advance - } else { // if (chTest == chMatch) - test2 = test - match = startmatch - - for { - if match == endmatch { - if b.rightToLeft { - return test2 + 1 - } else { - return test2 - } - } - - match -= bump - test2 -= bump - - chTest = text[test2] - - if b.caseInsensitive { - chTest = unicode.ToLower(chTest) - } - - if chTest != b.pattern[match] { - advance = b.positive[match] - if chTest < 128 { - test2 = (match - startmatch) + b.negativeASCII[chTest] - } else if chTest < 0xffff && len(b.negativeUnicode) > 0 { - unicodeLookup = b.negativeUnicode[chTest>>8] - if len(unicodeLookup) > 0 { - test2 = (match - startmatch) + unicodeLookup[chTest&0xFF] - } else { - test += advance - break - } - } else { - test += advance - break - } - - if b.rightToLeft { - if test2 < advance { - advance = test2 - } - } else if test2 > advance { - advance = test2 - } - - test += advance - break - } - } - } - } -} - -// When a regex is anchored, we can do a quick IsMatch test instead of a Scan -func (b *BmPrefix) IsMatch(text []rune, index, beglimit, endlimit int) bool { - if !b.rightToLeft { - if index < beglimit || endlimit-index < len(b.pattern) { - return false - } - - return b.matchPattern(text, index) - } else { - if index > endlimit || index-beglimit < len(b.pattern) { - return false - } - - return b.matchPattern(text, index-len(b.pattern)) - } -} - -func (b *BmPrefix) matchPattern(text []rune, index int) bool { - if len(text)-index < len(b.pattern) { - return false - } - - if b.caseInsensitive { - for i := 0; i < len(b.pattern); i++ { - //Debug.Assert(textinfo.ToLower(_pattern[i]) == _pattern[i], "pattern should be converted to lower case in constructor!"); - if unicode.ToLower(text[index+i]) != b.pattern[i] { - return false - } - } - return true - } else { - for i := 0; i < len(b.pattern); i++ { - if text[index+i] != b.pattern[i] { - return false - } - } - return true - } -} - -type AnchorLoc int16 - -// where the regex can be pegged -const ( - AnchorBeginning AnchorLoc = 0x0001 - AnchorBol = 0x0002 - AnchorStart = 0x0004 - AnchorEol = 0x0008 - AnchorEndZ = 0x0010 - AnchorEnd = 0x0020 - AnchorBoundary = 0x0040 - AnchorECMABoundary = 0x0080 -) - -func getAnchors(tree *RegexTree) AnchorLoc { - - var concatNode *regexNode - nextChild, result := 0, AnchorLoc(0) - - curNode := tree.root - - for { - switch curNode.t { - case ntConcatenate: - if len(curNode.children) > 0 { - concatNode = curNode - nextChild = 0 - } - - case ntGreedy, ntCapture: - curNode = curNode.children[0] - concatNode = nil - continue - - case ntBol, ntEol, ntBoundary, ntECMABoundary, ntBeginning, - ntStart, ntEndZ, ntEnd: - return result | anchorFromType(curNode.t) - - case ntEmpty, ntRequire, ntPrevent: - - default: - return result - } - - if concatNode == nil || nextChild >= len(concatNode.children) { - return result - } - - curNode = concatNode.children[nextChild] - nextChild++ - } -} - -func anchorFromType(t nodeType) AnchorLoc { - switch t { - case ntBol: - return AnchorBol - case ntEol: - return AnchorEol - case ntBoundary: - return AnchorBoundary - case ntECMABoundary: - return AnchorECMABoundary - case ntBeginning: - return AnchorBeginning - case ntStart: - return AnchorStart - case ntEndZ: - return AnchorEndZ - case ntEnd: - return AnchorEnd - default: - return 0 - } -} - -// anchorDescription returns a human-readable description of the anchors -func (anchors AnchorLoc) String() string { - buf := &bytes.Buffer{} - - if 0 != (anchors & AnchorBeginning) { - buf.WriteString(", Beginning") - } - if 0 != (anchors & AnchorStart) { - buf.WriteString(", Start") - } - if 0 != (anchors & AnchorBol) { - buf.WriteString(", Bol") - } - if 0 != (anchors & AnchorBoundary) { - buf.WriteString(", Boundary") - } - if 0 != (anchors & AnchorECMABoundary) { - buf.WriteString(", ECMABoundary") - } - if 0 != (anchors & AnchorEol) { - buf.WriteString(", Eol") - } - if 0 != (anchors & AnchorEnd) { - buf.WriteString(", End") - } - if 0 != (anchors & AnchorEndZ) { - buf.WriteString(", EndZ") - } - - // trim off comma - if buf.Len() >= 2 { - return buf.String()[2:] - } - return "None" -} diff --git a/third_party/regexp2/syntax/replacerdata.go b/third_party/regexp2/syntax/replacerdata.go deleted file mode 100644 index bcf4d3f25..000000000 --- a/third_party/regexp2/syntax/replacerdata.go +++ /dev/null @@ -1,87 +0,0 @@ -package syntax - -import ( - "bytes" - "errors" -) - -type ReplacerData struct { - Rep string - Strings []string - Rules []int -} - -const ( - replaceSpecials = 4 - replaceLeftPortion = -1 - replaceRightPortion = -2 - replaceLastGroup = -3 - replaceWholeString = -4 -) - -//ErrReplacementError is a general error during parsing the replacement text -var ErrReplacementError = errors.New("Replacement pattern error.") - -// NewReplacerData will populate a reusable replacer data struct based on the given replacement string -// and the capture group data from a regexp -func NewReplacerData(rep string, caps map[int]int, capsize int, capnames map[string]int, op RegexOptions) (*ReplacerData, error) { - p := parser{ - options: op, - caps: caps, - capsize: capsize, - capnames: capnames, - } - p.setPattern(rep) - concat, err := p.scanReplacement() - if err != nil { - return nil, err - } - - if concat.t != ntConcatenate { - panic(ErrReplacementError) - } - - sb := &bytes.Buffer{} - var ( - strings []string - rules []int - ) - - for _, child := range concat.children { - switch child.t { - case ntMulti: - child.writeStrToBuf(sb) - - case ntOne: - sb.WriteRune(child.ch) - - case ntRef: - if sb.Len() > 0 { - rules = append(rules, len(strings)) - strings = append(strings, sb.String()) - sb.Reset() - } - slot := child.m - - if len(caps) > 0 && slot >= 0 { - slot = caps[slot] - } - - rules = append(rules, -replaceSpecials-1-slot) - - default: - panic(ErrReplacementError) - } - } - - if sb.Len() > 0 { - rules = append(rules, len(strings)) - strings = append(strings, sb.String()) - } - - return &ReplacerData{ - Rep: rep, - Strings: strings, - Rules: rules, - }, nil -} diff --git a/third_party/regexp2/syntax/tree.go b/third_party/regexp2/syntax/tree.go deleted file mode 100644 index ea2882931..000000000 --- a/third_party/regexp2/syntax/tree.go +++ /dev/null @@ -1,654 +0,0 @@ -package syntax - -import ( - "bytes" - "fmt" - "math" - "strconv" -) - -type RegexTree struct { - root *regexNode - caps map[int]int - capnumlist []int - captop int - Capnames map[string]int - Caplist []string - options RegexOptions -} - -// It is built into a parsed tree for a regular expression. - -// Implementation notes: -// -// Since the node tree is a temporary data structure only used -// during compilation of the regexp to integer codes, it's -// designed for clarity and convenience rather than -// space efficiency. -// -// RegexNodes are built into a tree, linked by the n.children list. -// Each node also has a n.parent and n.ichild member indicating -// its parent and which child # it is in its parent's list. -// -// RegexNodes come in as many types as there are constructs in -// a regular expression, for example, "concatenate", "alternate", -// "one", "rept", "group". There are also node types for basic -// peephole optimizations, e.g., "onerep", "notsetrep", etc. -// -// Because perl 5 allows "lookback" groups that scan backwards, -// each node also gets a "direction". Normally the value of -// boolean n.backward = false. -// -// During parsing, top-level nodes are also stacked onto a parse -// stack (a stack of trees). For this purpose we have a n.next -// pointer. [Note that to save a few bytes, we could overload the -// n.parent pointer instead.] -// -// On the parse stack, each tree has a "role" - basically, the -// nonterminal in the grammar that the parser has currently -// assigned to the tree. That code is stored in n.role. -// -// Finally, some of the different kinds of nodes have data. -// Two integers (for the looping constructs) are stored in -// n.operands, an an object (either a string or a set) -// is stored in n.data -type regexNode struct { - t nodeType - children []*regexNode - str []rune - set *CharSet - ch rune - m int - n int - options RegexOptions - next *regexNode -} - -type nodeType int32 - -const ( - // The following are leaves, and correspond to primitive operations - - ntOnerep nodeType = 0 // lef,back char,min,max a {n} - ntNotonerep = 1 // lef,back char,min,max .{n} - ntSetrep = 2 // lef,back set,min,max [\d]{n} - ntOneloop = 3 // lef,back char,min,max a {,n} - ntNotoneloop = 4 // lef,back char,min,max .{,n} - ntSetloop = 5 // lef,back set,min,max [\d]{,n} - ntOnelazy = 6 // lef,back char,min,max a {,n}? - ntNotonelazy = 7 // lef,back char,min,max .{,n}? - ntSetlazy = 8 // lef,back set,min,max [\d]{,n}? - ntOne = 9 // lef char a - ntNotone = 10 // lef char [^a] - ntSet = 11 // lef set [a-z\s] \w \s \d - ntMulti = 12 // lef string abcd - ntRef = 13 // lef group \# - ntBol = 14 // ^ - ntEol = 15 // $ - ntBoundary = 16 // \b - ntNonboundary = 17 // \B - ntBeginning = 18 // \A - ntStart = 19 // \G - ntEndZ = 20 // \Z - ntEnd = 21 // \Z - - // Interior nodes do not correspond to primitive operations, but - // control structures compositing other operations - - // Concat and alternate take n children, and can run forward or backwards - - ntNothing = 22 // [] - ntEmpty = 23 // () - ntAlternate = 24 // a|b - ntConcatenate = 25 // ab - ntLoop = 26 // m,x * + ? {,} - ntLazyloop = 27 // m,x *? +? ?? {,}? - ntCapture = 28 // n () - ntGroup = 29 // (?:) - ntRequire = 30 // (?=) (?<=) - ntPrevent = 31 // (?!) (?) (?<) - ntTestref = 33 // (?(n) | ) - ntTestgroup = 34 // (?(...) | ) - - ntECMABoundary = 41 // \b - ntNonECMABoundary = 42 // \B -) - -func newRegexNode(t nodeType, opt RegexOptions) *regexNode { - return ®exNode{ - t: t, - options: opt, - } -} - -func newRegexNodeCh(t nodeType, opt RegexOptions, ch rune) *regexNode { - return ®exNode{ - t: t, - options: opt, - ch: ch, - } -} - -func newRegexNodeStr(t nodeType, opt RegexOptions, str []rune) *regexNode { - return ®exNode{ - t: t, - options: opt, - str: str, - } -} - -func newRegexNodeSet(t nodeType, opt RegexOptions, set *CharSet) *regexNode { - return ®exNode{ - t: t, - options: opt, - set: set, - } -} - -func newRegexNodeM(t nodeType, opt RegexOptions, m int) *regexNode { - return ®exNode{ - t: t, - options: opt, - m: m, - } -} -func newRegexNodeMN(t nodeType, opt RegexOptions, m, n int) *regexNode { - return ®exNode{ - t: t, - options: opt, - m: m, - n: n, - } -} - -func (n *regexNode) writeStrToBuf(buf *bytes.Buffer) { - for i := 0; i < len(n.str); i++ { - buf.WriteRune(n.str[i]) - } -} - -func (n *regexNode) addChild(child *regexNode) { - reduced := child.reduce() - n.children = append(n.children, reduced) - reduced.next = n -} - -func (n *regexNode) insertChildren(afterIndex int, nodes []*regexNode) { - newChildren := make([]*regexNode, 0, len(n.children)+len(nodes)) - n.children = append(append(append(newChildren, n.children[:afterIndex]...), nodes...), n.children[afterIndex:]...) -} - -// removes children including the start but not the end index -func (n *regexNode) removeChildren(startIndex, endIndex int) { - n.children = append(n.children[:startIndex], n.children[endIndex:]...) -} - -// Pass type as OneLazy or OneLoop -func (n *regexNode) makeRep(t nodeType, min, max int) { - n.t += (t - ntOne) - n.m = min - n.n = max -} - -func (n *regexNode) reduce() *regexNode { - switch n.t { - case ntAlternate: - return n.reduceAlternation() - - case ntConcatenate: - return n.reduceConcatenation() - - case ntLoop, ntLazyloop: - return n.reduceRep() - - case ntGroup: - return n.reduceGroup() - - case ntSet, ntSetloop: - return n.reduceSet() - - default: - return n - } -} - -// Basic optimization. Single-letter alternations can be replaced -// by faster set specifications, and nested alternations with no -// intervening operators can be flattened: -// -// a|b|c|def|g|h -> [a-c]|def|[gh] -// apple|(?:orange|pear)|grape -> apple|orange|pear|grape -func (n *regexNode) reduceAlternation() *regexNode { - if len(n.children) == 0 { - return newRegexNode(ntNothing, n.options) - } - - wasLastSet := false - lastNodeCannotMerge := false - var optionsLast RegexOptions - var i, j int - - for i, j = 0, 0; i < len(n.children); i, j = i+1, j+1 { - at := n.children[i] - - if j < i { - n.children[j] = at - } - - for { - if at.t == ntAlternate { - for k := 0; k < len(at.children); k++ { - at.children[k].next = n - } - n.insertChildren(i+1, at.children) - - j-- - } else if at.t == ntSet || at.t == ntOne { - // Cannot merge sets if L or I options differ, or if either are negated. - optionsAt := at.options & (RightToLeft | IgnoreCase) - - if at.t == ntSet { - if !wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge || !at.set.IsMergeable() { - wasLastSet = true - lastNodeCannotMerge = !at.set.IsMergeable() - optionsLast = optionsAt - break - } - } else if !wasLastSet || optionsLast != optionsAt || lastNodeCannotMerge { - wasLastSet = true - lastNodeCannotMerge = false - optionsLast = optionsAt - break - } - - // The last node was a Set or a One, we're a Set or One and our options are the same. - // Merge the two nodes. - j-- - prev := n.children[j] - - var prevCharClass *CharSet - if prev.t == ntOne { - prevCharClass = &CharSet{} - prevCharClass.addChar(prev.ch) - } else { - prevCharClass = prev.set - } - - if at.t == ntOne { - prevCharClass.addChar(at.ch) - } else { - prevCharClass.addSet(*at.set) - } - - prev.t = ntSet - prev.set = prevCharClass - } else if at.t == ntNothing { - j-- - } else { - wasLastSet = false - lastNodeCannotMerge = false - } - break - } - } - - if j < i { - n.removeChildren(j, i) - } - - return n.stripEnation(ntNothing) -} - -// Basic optimization. Adjacent strings can be concatenated. -// -// (?:abc)(?:def) -> abcdef -func (n *regexNode) reduceConcatenation() *regexNode { - // Eliminate empties and concat adjacent strings/chars - - var optionsLast RegexOptions - var optionsAt RegexOptions - var i, j int - - if len(n.children) == 0 { - return newRegexNode(ntEmpty, n.options) - } - - wasLastString := false - - for i, j = 0, 0; i < len(n.children); i, j = i+1, j+1 { - var at, prev *regexNode - - at = n.children[i] - - if j < i { - n.children[j] = at - } - - if at.t == ntConcatenate && - ((at.options & RightToLeft) == (n.options & RightToLeft)) { - for k := 0; k < len(at.children); k++ { - at.children[k].next = n - } - - //insert at.children at i+1 index in n.children - n.insertChildren(i+1, at.children) - - j-- - } else if at.t == ntMulti || at.t == ntOne { - // Cannot merge strings if L or I options differ - optionsAt = at.options & (RightToLeft | IgnoreCase) - - if !wasLastString || optionsLast != optionsAt { - wasLastString = true - optionsLast = optionsAt - continue - } - - j-- - prev = n.children[j] - - if prev.t == ntOne { - prev.t = ntMulti - prev.str = []rune{prev.ch} - } - - if (optionsAt & RightToLeft) == 0 { - if at.t == ntOne { - prev.str = append(prev.str, at.ch) - } else { - prev.str = append(prev.str, at.str...) - } - } else { - if at.t == ntOne { - // insert at the front by expanding our slice, copying the data over, and then setting the value - prev.str = append(prev.str, 0) - copy(prev.str[1:], prev.str) - prev.str[0] = at.ch - } else { - //insert at the front...this one we'll make a new slice and copy both into it - merge := make([]rune, len(prev.str)+len(at.str)) - copy(merge, at.str) - copy(merge[len(at.str):], prev.str) - prev.str = merge - } - } - } else if at.t == ntEmpty { - j-- - } else { - wasLastString = false - } - } - - if j < i { - // remove indices j through i from the children - n.removeChildren(j, i) - } - - return n.stripEnation(ntEmpty) -} - -// Nested repeaters just get multiplied with each other if they're not -// too lumpy -func (n *regexNode) reduceRep() *regexNode { - - u := n - t := n.t - min := n.m - max := n.n - - for { - if len(u.children) == 0 { - break - } - - child := u.children[0] - - // multiply reps of the same type only - if child.t != t { - childType := child.t - - if !(childType >= ntOneloop && childType <= ntSetloop && t == ntLoop || - childType >= ntOnelazy && childType <= ntSetlazy && t == ntLazyloop) { - break - } - } - - // child can be too lumpy to blur, e.g., (a {100,105}) {3} or (a {2,})? - // [but things like (a {2,})+ are not too lumpy...] - if u.m == 0 && child.m > 1 || child.n < child.m*2 { - break - } - - u = child - if u.m > 0 { - if (math.MaxInt32-1)/u.m < min { - u.m = math.MaxInt32 - } else { - u.m = u.m * min - } - } - if u.n > 0 { - if (math.MaxInt32-1)/u.n < max { - u.n = math.MaxInt32 - } else { - u.n = u.n * max - } - } - } - - if math.MaxInt32 == min { - return newRegexNode(ntNothing, n.options) - } - return u - -} - -// Simple optimization. If a concatenation or alternation has only -// one child strip out the intermediate node. If it has zero children, -// turn it into an empty. -func (n *regexNode) stripEnation(emptyType nodeType) *regexNode { - switch len(n.children) { - case 0: - return newRegexNode(emptyType, n.options) - case 1: - return n.children[0] - default: - return n - } -} - -func (n *regexNode) reduceGroup() *regexNode { - u := n - - for u.t == ntGroup { - u = u.children[0] - } - - return u -} - -// Simple optimization. If a set is a singleton, an inverse singleton, -// or empty, it's transformed accordingly. -func (n *regexNode) reduceSet() *regexNode { - // Extract empty-set, one and not-one case as special - - if n.set == nil { - n.t = ntNothing - } else if n.set.IsSingleton() { - n.ch = n.set.SingletonChar() - n.set = nil - n.t += (ntOne - ntSet) - } else if n.set.IsSingletonInverse() { - n.ch = n.set.SingletonChar() - n.set = nil - n.t += (ntNotone - ntSet) - } - - return n -} - -func (n *regexNode) reverseLeft() *regexNode { - if n.options&RightToLeft != 0 && n.t == ntConcatenate && len(n.children) > 0 { - //reverse children order - for left, right := 0, len(n.children)-1; left < right; left, right = left+1, right-1 { - n.children[left], n.children[right] = n.children[right], n.children[left] - } - } - - return n -} - -func (n *regexNode) makeQuantifier(lazy bool, min, max int) *regexNode { - if min == 0 && max == 0 { - return newRegexNode(ntEmpty, n.options) - } - - if min == 1 && max == 1 { - return n - } - - switch n.t { - case ntOne, ntNotone, ntSet: - if lazy { - n.makeRep(Onelazy, min, max) - } else { - n.makeRep(Oneloop, min, max) - } - return n - - default: - var t nodeType - if lazy { - t = ntLazyloop - } else { - t = ntLoop - } - result := newRegexNodeMN(t, n.options, min, max) - result.addChild(n) - return result - } -} - -// debug functions - -var typeStr = []string{ - "Onerep", "Notonerep", "Setrep", - "Oneloop", "Notoneloop", "Setloop", - "Onelazy", "Notonelazy", "Setlazy", - "One", "Notone", "Set", - "Multi", "Ref", - "Bol", "Eol", "Boundary", "Nonboundary", - "Beginning", "Start", "EndZ", "End", - "Nothing", "Empty", - "Alternate", "Concatenate", - "Loop", "Lazyloop", - "Capture", "Group", "Require", "Prevent", "Greedy", - "Testref", "Testgroup", - "Unknown", "Unknown", "Unknown", - "Unknown", "Unknown", "Unknown", - "ECMABoundary", "NonECMABoundary", -} - -func (n *regexNode) description() string { - buf := &bytes.Buffer{} - - buf.WriteString(typeStr[n.t]) - - if (n.options & ExplicitCapture) != 0 { - buf.WriteString("-C") - } - if (n.options & IgnoreCase) != 0 { - buf.WriteString("-I") - } - if (n.options & RightToLeft) != 0 { - buf.WriteString("-L") - } - if (n.options & Multiline) != 0 { - buf.WriteString("-M") - } - if (n.options & Singleline) != 0 { - buf.WriteString("-S") - } - if (n.options & IgnorePatternWhitespace) != 0 { - buf.WriteString("-X") - } - if (n.options & ECMAScript) != 0 { - buf.WriteString("-E") - } - - switch n.t { - case ntOneloop, ntNotoneloop, ntOnelazy, ntNotonelazy, ntOne, ntNotone: - buf.WriteString("(Ch = " + CharDescription(n.ch) + ")") - break - case ntCapture: - buf.WriteString("(index = " + strconv.Itoa(n.m) + ", unindex = " + strconv.Itoa(n.n) + ")") - break - case ntRef, ntTestref: - buf.WriteString("(index = " + strconv.Itoa(n.m) + ")") - break - case ntMulti: - fmt.Fprintf(buf, "(String = %s)", string(n.str)) - break - case ntSet, ntSetloop, ntSetlazy: - buf.WriteString("(Set = " + n.set.String() + ")") - break - } - - switch n.t { - case ntOneloop, ntNotoneloop, ntOnelazy, ntNotonelazy, ntSetloop, ntSetlazy, ntLoop, ntLazyloop: - buf.WriteString("(Min = ") - buf.WriteString(strconv.Itoa(n.m)) - buf.WriteString(", Max = ") - if n.n == math.MaxInt32 { - buf.WriteString("inf") - } else { - buf.WriteString(strconv.Itoa(n.n)) - } - buf.WriteString(")") - - break - } - - return buf.String() -} - -var padSpace = []byte(" ") - -func (t *RegexTree) Dump() string { - return t.root.dump() -} - -func (n *regexNode) dump() string { - var stack []int - CurNode := n - CurChild := 0 - - buf := bytes.NewBufferString(CurNode.description()) - buf.WriteRune('\n') - - for { - if CurNode.children != nil && CurChild < len(CurNode.children) { - stack = append(stack, CurChild+1) - CurNode = CurNode.children[CurChild] - CurChild = 0 - - Depth := len(stack) - if Depth > 32 { - Depth = 32 - } - buf.Write(padSpace[:Depth]) - buf.WriteString(CurNode.description()) - buf.WriteRune('\n') - } else { - if len(stack) == 0 { - break - } - - CurChild = stack[len(stack)-1] - stack = stack[:len(stack)-1] - CurNode = CurNode.next - } - } - return buf.String() -} diff --git a/third_party/regexp2/syntax/writer.go b/third_party/regexp2/syntax/writer.go deleted file mode 100644 index a5aa11ca0..000000000 --- a/third_party/regexp2/syntax/writer.go +++ /dev/null @@ -1,500 +0,0 @@ -package syntax - -import ( - "bytes" - "fmt" - "math" - "os" -) - -func Write(tree *RegexTree) (*Code, error) { - w := writer{ - intStack: make([]int, 0, 32), - emitted: make([]int, 2), - stringhash: make(map[string]int), - sethash: make(map[string]int), - } - - code, err := w.codeFromTree(tree) - - if tree.options&Debug > 0 && code != nil { - os.Stdout.WriteString(code.Dump()) - os.Stdout.WriteString("\n") - } - - return code, err -} - -type writer struct { - emitted []int - - intStack []int - curpos int - stringhash map[string]int - stringtable [][]rune - sethash map[string]int - settable []*CharSet - counting bool - count int - trackcount int - caps map[int]int -} - -const ( - beforeChild nodeType = 64 - afterChild = 128 - //MaxPrefixSize is the largest number of runes we'll use for a BoyerMoyer prefix - MaxPrefixSize = 50 -) - -// The top level RegexCode generator. It does a depth-first walk -// through the tree and calls EmitFragment to emits code before -// and after each child of an interior node, and at each leaf. -// -// It runs two passes, first to count the size of the generated -// code, and second to generate the code. -// -// We should time it against the alternative, which is -// to just generate the code and grow the array as we go. -func (w *writer) codeFromTree(tree *RegexTree) (*Code, error) { - var ( - curNode *regexNode - curChild int - capsize int - ) - // construct sparse capnum mapping if some numbers are unused - - if tree.capnumlist == nil || tree.captop == len(tree.capnumlist) { - capsize = tree.captop - w.caps = nil - } else { - capsize = len(tree.capnumlist) - w.caps = tree.caps - for i := 0; i < len(tree.capnumlist); i++ { - w.caps[tree.capnumlist[i]] = i - } - } - - w.counting = true - - for { - if !w.counting { - w.emitted = make([]int, w.count) - } - - curNode = tree.root - curChild = 0 - - w.emit1(Lazybranch, 0) - - for { - if len(curNode.children) == 0 { - w.emitFragment(curNode.t, curNode, 0) - } else if curChild < len(curNode.children) { - w.emitFragment(curNode.t|beforeChild, curNode, curChild) - - curNode = curNode.children[curChild] - - w.pushInt(curChild) - curChild = 0 - continue - } - - if w.emptyStack() { - break - } - - curChild = w.popInt() - curNode = curNode.next - - w.emitFragment(curNode.t|afterChild, curNode, curChild) - curChild++ - } - - w.patchJump(0, w.curPos()) - w.emit(Stop) - - if !w.counting { - break - } - - w.counting = false - } - - fcPrefix := getFirstCharsPrefix(tree) - prefix := getPrefix(tree) - rtl := (tree.options & RightToLeft) != 0 - - var bmPrefix *BmPrefix - //TODO: benchmark string prefixes - if prefix != nil && len(prefix.PrefixStr) > 0 && MaxPrefixSize > 0 { - if len(prefix.PrefixStr) > MaxPrefixSize { - // limit prefix changes to 10k - prefix.PrefixStr = prefix.PrefixStr[:MaxPrefixSize] - } - bmPrefix = newBmPrefix(prefix.PrefixStr, prefix.CaseInsensitive, rtl) - } else { - bmPrefix = nil - } - - return &Code{ - Codes: w.emitted, - Strings: w.stringtable, - Sets: w.settable, - TrackCount: w.trackcount, - Caps: w.caps, - Capsize: capsize, - FcPrefix: fcPrefix, - BmPrefix: bmPrefix, - Anchors: getAnchors(tree), - RightToLeft: rtl, - }, nil -} - -// The main RegexCode generator. It does a depth-first walk -// through the tree and calls EmitFragment to emits code before -// and after each child of an interior node, and at each leaf. -func (w *writer) emitFragment(nodetype nodeType, node *regexNode, curIndex int) error { - bits := InstOp(0) - - if nodetype <= ntRef { - if (node.options & RightToLeft) != 0 { - bits |= Rtl - } - if (node.options & IgnoreCase) != 0 { - bits |= Ci - } - } - ntBits := nodeType(bits) - - switch nodetype { - case ntConcatenate | beforeChild, ntConcatenate | afterChild, ntEmpty: - break - - case ntAlternate | beforeChild: - if curIndex < len(node.children)-1 { - w.pushInt(w.curPos()) - w.emit1(Lazybranch, 0) - } - - case ntAlternate | afterChild: - if curIndex < len(node.children)-1 { - lbPos := w.popInt() - w.pushInt(w.curPos()) - w.emit1(Goto, 0) - w.patchJump(lbPos, w.curPos()) - } else { - for i := 0; i < curIndex; i++ { - w.patchJump(w.popInt(), w.curPos()) - } - } - break - - case ntTestref | beforeChild: - if curIndex == 0 { - w.emit(Setjump) - w.pushInt(w.curPos()) - w.emit1(Lazybranch, 0) - w.emit1(Testref, w.mapCapnum(node.m)) - w.emit(Forejump) - } - - case ntTestref | afterChild: - if curIndex == 0 { - branchpos := w.popInt() - w.pushInt(w.curPos()) - w.emit1(Goto, 0) - w.patchJump(branchpos, w.curPos()) - w.emit(Forejump) - if len(node.children) <= 1 { - w.patchJump(w.popInt(), w.curPos()) - } - } else if curIndex == 1 { - w.patchJump(w.popInt(), w.curPos()) - } - - case ntTestgroup | beforeChild: - if curIndex == 0 { - w.emit(Setjump) - w.emit(Setmark) - w.pushInt(w.curPos()) - w.emit1(Lazybranch, 0) - } - - case ntTestgroup | afterChild: - if curIndex == 0 { - w.emit(Getmark) - w.emit(Forejump) - } else if curIndex == 1 { - Branchpos := w.popInt() - w.pushInt(w.curPos()) - w.emit1(Goto, 0) - w.patchJump(Branchpos, w.curPos()) - w.emit(Getmark) - w.emit(Forejump) - if len(node.children) <= 2 { - w.patchJump(w.popInt(), w.curPos()) - } - } else if curIndex == 2 { - w.patchJump(w.popInt(), w.curPos()) - } - - case ntLoop | beforeChild, ntLazyloop | beforeChild: - - if node.n < math.MaxInt32 || node.m > 1 { - if node.m == 0 { - w.emit1(Nullcount, 0) - } else { - w.emit1(Setcount, 1-node.m) - } - } else if node.m == 0 { - w.emit(Nullmark) - } else { - w.emit(Setmark) - } - - if node.m == 0 { - w.pushInt(w.curPos()) - w.emit1(Goto, 0) - } - w.pushInt(w.curPos()) - - case ntLoop | afterChild, ntLazyloop | afterChild: - - startJumpPos := w.curPos() - lazy := (nodetype - (ntLoop | afterChild)) - - if node.n < math.MaxInt32 || node.m > 1 { - if node.n == math.MaxInt32 { - w.emit2(InstOp(Branchcount+lazy), w.popInt(), math.MaxInt32) - } else { - w.emit2(InstOp(Branchcount+lazy), w.popInt(), node.n-node.m) - } - } else { - w.emit1(InstOp(Branchmark+lazy), w.popInt()) - } - - if node.m == 0 { - w.patchJump(w.popInt(), startJumpPos) - } - - case ntGroup | beforeChild, ntGroup | afterChild: - - case ntCapture | beforeChild: - w.emit(Setmark) - - case ntCapture | afterChild: - w.emit2(Capturemark, w.mapCapnum(node.m), w.mapCapnum(node.n)) - - case ntRequire | beforeChild: - // NOTE: the following line causes lookahead/lookbehind to be - // NON-BACKTRACKING. It can be commented out with (*) - w.emit(Setjump) - - w.emit(Setmark) - - case ntRequire | afterChild: - w.emit(Getmark) - - // NOTE: the following line causes lookahead/lookbehind to be - // NON-BACKTRACKING. It can be commented out with (*) - w.emit(Forejump) - - case ntPrevent | beforeChild: - w.emit(Setjump) - w.pushInt(w.curPos()) - w.emit1(Lazybranch, 0) - - case ntPrevent | afterChild: - w.emit(Backjump) - w.patchJump(w.popInt(), w.curPos()) - w.emit(Forejump) - - case ntGreedy | beforeChild: - w.emit(Setjump) - - case ntGreedy | afterChild: - w.emit(Forejump) - - case ntOne, ntNotone: - w.emit1(InstOp(node.t|ntBits), int(node.ch)) - - case ntNotoneloop, ntNotonelazy, ntOneloop, ntOnelazy: - if node.m > 0 { - if node.t == ntOneloop || node.t == ntOnelazy { - w.emit2(Onerep|bits, int(node.ch), node.m) - } else { - w.emit2(Notonerep|bits, int(node.ch), node.m) - } - } - if node.n > node.m { - if node.n == math.MaxInt32 { - w.emit2(InstOp(node.t|ntBits), int(node.ch), math.MaxInt32) - } else { - w.emit2(InstOp(node.t|ntBits), int(node.ch), node.n-node.m) - } - } - - case ntSetloop, ntSetlazy: - if node.m > 0 { - w.emit2(Setrep|bits, w.setCode(node.set), node.m) - } - if node.n > node.m { - if node.n == math.MaxInt32 { - w.emit2(InstOp(node.t|ntBits), w.setCode(node.set), math.MaxInt32) - } else { - w.emit2(InstOp(node.t|ntBits), w.setCode(node.set), node.n-node.m) - } - } - - case ntMulti: - w.emit1(InstOp(node.t|ntBits), w.stringCode(node.str)) - - case ntSet: - w.emit1(InstOp(node.t|ntBits), w.setCode(node.set)) - - case ntRef: - w.emit1(InstOp(node.t|ntBits), w.mapCapnum(node.m)) - - case ntNothing, ntBol, ntEol, ntBoundary, ntNonboundary, ntECMABoundary, ntNonECMABoundary, ntBeginning, ntStart, ntEndZ, ntEnd: - w.emit(InstOp(node.t)) - - default: - return fmt.Errorf("unexpected opcode in regular expression generation: %v", nodetype) - } - - return nil -} - -// To avoid recursion, we use a simple integer stack. -// This is the push. -func (w *writer) pushInt(i int) { - w.intStack = append(w.intStack, i) -} - -// Returns true if the stack is empty. -func (w *writer) emptyStack() bool { - return len(w.intStack) == 0 -} - -// This is the pop. -func (w *writer) popInt() int { - //get our item - idx := len(w.intStack) - 1 - i := w.intStack[idx] - //trim our slice - w.intStack = w.intStack[:idx] - return i -} - -// Returns the current position in the emitted code. -func (w *writer) curPos() int { - return w.curpos -} - -// Fixes up a jump instruction at the specified offset -// so that it jumps to the specified jumpDest. -func (w *writer) patchJump(offset, jumpDest int) { - w.emitted[offset+1] = jumpDest -} - -// Returns an index in the set table for a charset -// uses a map to eliminate duplicates. -func (w *writer) setCode(set *CharSet) int { - if w.counting { - return 0 - } - - buf := &bytes.Buffer{} - - set.mapHashFill(buf) - hash := buf.String() - i, ok := w.sethash[hash] - if !ok { - i = len(w.sethash) - w.sethash[hash] = i - w.settable = append(w.settable, set) - } - return i -} - -// Returns an index in the string table for a string. -// uses a map to eliminate duplicates. -func (w *writer) stringCode(str []rune) int { - if w.counting { - return 0 - } - - hash := string(str) - i, ok := w.stringhash[hash] - if !ok { - i = len(w.stringhash) - w.stringhash[hash] = i - w.stringtable = append(w.stringtable, str) - } - - return i -} - -// When generating code on a regex that uses a sparse set -// of capture slots, we hash them to a dense set of indices -// for an array of capture slots. Instead of doing the hash -// at match time, it's done at compile time, here. -func (w *writer) mapCapnum(capnum int) int { - if capnum == -1 { - return -1 - } - - if w.caps != nil { - return w.caps[capnum] - } - - return capnum -} - -// Emits a zero-argument operation. Note that the emit -// functions all run in two modes: they can emit code, or -// they can just count the size of the code. -func (w *writer) emit(op InstOp) { - if w.counting { - w.count++ - if opcodeBacktracks(op) { - w.trackcount++ - } - return - } - w.emitted[w.curpos] = int(op) - w.curpos++ -} - -// Emits a one-argument operation. -func (w *writer) emit1(op InstOp, opd1 int) { - if w.counting { - w.count += 2 - if opcodeBacktracks(op) { - w.trackcount++ - } - return - } - w.emitted[w.curpos] = int(op) - w.curpos++ - w.emitted[w.curpos] = opd1 - w.curpos++ -} - -// Emits a two-argument operation. -func (w *writer) emit2(op InstOp, opd1, opd2 int) { - if w.counting { - w.count += 3 - if opcodeBacktracks(op) { - w.trackcount++ - } - return - } - w.emitted[w.curpos] = int(op) - w.curpos++ - w.emitted[w.curpos] = opd1 - w.curpos++ - w.emitted[w.curpos] = opd2 - w.curpos++ -} diff --git a/web/src/gen/mistgate/admin/v1/subscription_pb.ts b/web/src/gen/mistgate/admin/v1/subscription_pb.ts index 76b7b2cb5..2c0959ef8 100644 --- a/web/src/gen/mistgate/admin/v1/subscription_pb.ts +++ b/web/src/gen/mistgate/admin/v1/subscription_pb.ts @@ -371,9 +371,9 @@ export const RoutingInfoSchema: GenMessage = /*@__PURE__*/ /** * One Mihomo YAML profile of the owner. The panel puts the servers of the person at the start of its `proxies` and, while * link_auto_select is on and the template has no group of that name, adds a url-test group `Auto` over them at the end of its - * `proxy-groups`; groups take the servers with `include-all-proxies` or `filter`. `dns` is added (resolvers of the person's preset, - * respect-rules on) only when the template has none. Everything else is left as written, comments included. The panel never - * fetches a URL of a template. + * `proxy-groups`. Groups can opt in to panel order with `mistgate-ordered-proxies: true`, or let Mihomo include and sort + * servers with `include-all-proxies` or `include-all`. `dns` is added (preset resolvers, respect-rules on) only when the + * template has none. The panel never fetches a URL of a template. * * A save is refused (INVALID_ARGUMENT, the text names the line) unless the text is one valid YAML document that parses in full (no * alias bomb, no repeated key), has a mapping at its root, `proxies` and `proxy-groups` that are lists (or absent) with named @@ -1095,9 +1095,9 @@ export const PreviewMihomoTemplateRequestSchema: GenMessage