func main() { short := "hp:" long := []string{ "help", "pattern=", } _, optargs, err := getopt.GetOpt(os.Args[1:], short, long) if err != nil { log.Print(os.Stderr, err) Usage(1) } patterns := make([]string, 0, 10) for _, oa := range optargs { switch oa.Opt() { case "-h", "--help": Usage(0) case "-p", "--pattern": patterns = append(patterns, oa.Arg()) } } if len(patterns) <= 0 { log.Print("Must supply some regulars expressions!") Usage(1) } asts := make([]frontend.AST, 0, len(patterns)) for _, p := range patterns { ast, err := frontend.Parse([]byte(p)) if err != nil { log.Fatal(err) } asts = append(asts, ast) } lexast := asts[len(asts)-1] for i := len(asts) - 2; i >= 0; i-- { lexast = frontend.NewAltMatch(asts[i], lexast) } program, err := frontend.Generate(lexast) if err != nil { log.Fatal(err) } for i, inst := range program { fmt.Printf("%3d %s\n", i, inst.Serialize()) } }
// Compiles the supplied patterns. You don't need func (self *Lexer) Compile() error { if len(self.patterns) == 0 { return fmt.Errorf("No patterns added") } asts := make([]frontend.AST, 0, len(self.patterns)) for _, p := range self.patterns { ast, err := frontend.Parse(p.regex) if err != nil { return err } asts = append(asts, ast) } lexast := asts[len(asts)-1] for i := len(asts) - 2; i >= 0; i-- { lexast = frontend.NewAltMatch(asts[i], lexast) } program, err := frontend.Generate(lexast) if err != nil { return err } self.program = program self.matches = make(map[int]int) ast := 0 for i, instruction := range self.program { if instruction.Op == inst.MATCH { self.matches[i] = ast ast += 1 } } if len(asts) != ast { panic("len(asts) != ast") } return nil }