summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/mattermost/rsc/regexp/regmerge/main.go
blob: 672337a04690f431f46f3ddbb25d15361c05bda2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Copyright 2012 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"regexp/syntax"
	"runtime/pprof"
)

var maxState = flag.Int("m", 1e5, "maximum number of states to explore")
var cpuprof = flag.String("cpuprofile", "", "cpu profile file")

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: regmerge [-m maxstate] regexp [regexp2 regexp3....]\n")
		os.Exit(2)
	}
	flag.Parse()

	if len(flag.Args()) < 1 {
		flag.Usage()
	}
	
	os.Exit(run(flag.Args()))
}

func run(args []string) int {
	if *cpuprof != "" {
		f, err := os.Create(*cpuprof)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}
	
	m, err := compile(flag.Args()...)
	if err != nil {
		log.Fatal(err)
	}
	n := 100
	for ;; n *= 2 {
		if n >= *maxState {
			if n >= 2* *maxState {
				fmt.Printf("reached state limit\n")
				return 1
			}
			n = *maxState
		}
		log.Printf("try %d states...\n", n)
		s, err := m.findMatch(n)
		if err == nil {
			fmt.Printf("%q\n", s)
			return 0
		}
		if err != ErrMemory {
			fmt.Printf("failed: %s\n", err)
			return 3
		}
	}
	panic("unreachable")
}

func compile(exprs ...string) (*matcher, error) {
	var progs []*syntax.Prog
	for _, expr := range exprs {
		re, err := syntax.Parse(expr, syntax.Perl)
		if err != nil {
			return nil, err
		}
		sre := re.Simplify()
		prog, err := syntax.Compile(sre)
		if err != nil {
			return nil, err
		}
		if err := toByteProg(prog); err != nil {
			return nil, err
		}
		progs = append(progs, prog)
	}
	m := &matcher{}
	if err := m.init(joinProgs(progs), len(progs)); err != nil {
		return nil, err
	}
	return m, nil
}

func bug() {
	panic("regmerge: internal error")
}