TDL/TDL.go

77 lines
1.6 KiB
Go
Raw Normal View History

2020-11-04 22:27:06 +01:00
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"strings"
"time"
)
const (
STAMP_FORMAT = "20060102-150405"
)
func checkUsage(debugFlag string, args []string) {
if debugFlag != "" && debugFlag != "lexer" && debugFlag != "parser" && debugFlag != "search" {
fmt.Fprintln(os.Stderr, "invalid value for 'debug'")
os.Exit(1)
}
if len(args) != 1 {
fmt.Fprintln(os.Stderr, "USAGE:", os.Args[0], "FILE")
os.Exit(1)
}
}
func outfile(infile string) io.Writer {
basename := path.Base(infile)
extension := path.Ext(basename)
basename = strings.TrimSuffix(basename, extension)
name := basename + "-" + time.Now().Format(STAMP_FORMAT) + ".txt"
2020-11-04 22:27:06 +01:00
f, err := os.OpenFile(name, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(name)
return f
}
func main() {
var debug string
var stdout bool
flag.StringVar(&debug, "debug", "", "debug output of 'lexer', 'parser' or 'search'")
flag.BoolVar(&stdout, "stdout", false, "use stdout instead of file output")
flag.Parse()
args := flag.Args()
checkUsage(debug, args)
filename := args[0]
bytes, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Fprintln(os.Stderr, err)
} else {
input := []rune(string(bytes))
switch debug {
case "lexer":
DebugLexer(input, os.Stdout)
case "parser":
DebugParser(input, os.Stdout)
case "search":
DebugSearch(input)
default:
parsed := NewParser(input).Parse()
var writer io.Writer
if stdout {
writer = os.Stdout
} else {
writer = outfile(filename)
}
generator := NewStdGenerator(writer)
generator.Generate(parsed)
}
}
}