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
|
// Copyright 2010 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"
"io/ioutil"
"log"
"os"
"runtime"
"time"
)
var (
inline = flag.Bool("inline", false, "parse rule inlining")
_switch = flag.Bool("switch", false, "replace if-else if-else like blocks with switch blocks")
syntax = flag.Bool("syntax", false, "print out the syntax tree")
highlight = flag.Bool("highlight", false, "test the syntax highlighter")
ast = flag.Bool("ast", false, "generate an AST")
test = flag.Bool("test", false, "test the PEG parser performance")
print = flag.Bool("print", false, "directly dump the syntax tree")
)
func main() {
runtime.GOMAXPROCS(2)
flag.Parse()
if flag.NArg() != 1 {
flag.Usage()
log.Fatalf("FILE: the peg file to compile")
}
file := flag.Arg(0)
buffer, err := ioutil.ReadFile(file)
if err != nil {
log.Fatal(err)
}
if *test {
iterations, p := 1000, &Peg{Tree: New(*inline, *_switch), Buffer: string(buffer)}
p.Init()
start := time.Now()
for i := 0; i < iterations; i++ {
p.Parse()
p.Reset()
}
total := float64(time.Since(start).Nanoseconds()) / float64(1000)
fmt.Printf("time: %v us\n", total/float64(iterations))
return
}
p := &Peg{Tree: New(*inline, *_switch), Buffer: string(buffer), Pretty: true}
p.Init()
if err := p.Parse(); err != nil {
log.Fatal(err)
}
p.Execute()
if *ast {
p.AST().Print(p.Buffer)
}
if *print {
p.Print()
}
if *syntax {
p.PrintSyntaxTree()
}
if *highlight {
p.Highlighter()
}
filename := file + ".go"
out, error := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if error != nil {
fmt.Printf("%v: %v\n", filename, error)
return
}
defer out.Close()
p.Compile(filename, out)
}
|