Improve CLI

This commit is contained in:
MrLetsplay 2024-03-29 15:43:55 +01:00
parent eec2a2c96e
commit 7d38efd106
Signed by: mr
SSH Key Fingerprint: SHA256:92jBH80vpXyaZHjaIl47pjRq+Yt7XGTArqQg1V7hSqg

47
main.go
View File

@ -2,9 +2,12 @@
package main package main
import ( import (
"bytes"
"embed" "embed"
"flag"
"log" "log"
"os" "os"
"os/exec"
"strconv" "strconv"
"strings" "strings"
) )
@ -83,11 +86,16 @@ func readEmbedDir(name string, files map[string]string) {
} }
func main() { func main() {
outputFile := flag.String("o", "a.out", "Output file")
generateWAT := flag.Bool("wat", false, "Generate WAT instead of WASM")
includeStdlib := flag.Bool("stdlib", true, "Include the standard library")
flag.Parse()
if len(os.Args) < 2 { if len(os.Args) < 2 {
log.Fatalln("Usage: " + os.Args[0] + " <files...>") log.Fatalln("Usage: " + os.Args[0] + " <files...>")
} }
files := os.Args[1:] files := flag.Args()
fileSources := make(map[string]string) fileSources := make(map[string]string)
for _, file := range files { for _, file := range files {
@ -99,10 +107,12 @@ func main() {
fileSources[file] = string(content) fileSources[file] = string(content)
} }
stdlibFiles := make(map[string]string) if *includeStdlib {
readEmbedDir("stdlib", stdlibFiles) stdlibFiles := make(map[string]string)
for path, file := range stdlibFiles { readEmbedDir("stdlib", stdlibFiles)
fileSources["[embedded]/"+path] = file for path, file := range stdlibFiles {
fileSources["[embedded]/"+path] = file
}
} }
fileTokens := make(map[string][]LexToken) fileTokens := make(map[string][]LexToken)
@ -136,7 +146,7 @@ func main() {
return return
} }
log.Printf("Parsed:\n%+#v\n\n", parsed) // log.Printf("Parsed:\n%+#v\n\n", parsed)
parsedFiles = append(parsedFiles, parsed) parsedFiles = append(parsedFiles, parsed)
} }
@ -169,6 +179,27 @@ func main() {
return return
} }
log.Println("WAT: " + wat) // log.Println("WAT: " + wat)
os.WriteFile("out.wat", []byte(wat), 0o644)
if *generateWAT {
os.WriteFile(*outputFile, []byte(wat), 0o644)
return
}
cmd := exec.Command("wat2wasm", "-o", *outputFile, "-")
var input bytes.Buffer
input.Write([]byte(wat))
cmd.Stdin = &input
err = cmd.Start()
if err != nil {
log.Fatalln(err)
}
err = cmd.Wait()
if err != nil {
log.Fatalln(err)
}
} }