67 lines
1.3 KiB
Go
67 lines
1.3 KiB
Go
// The compiler
|
|
package main
|
|
|
|
import (
|
|
"log"
|
|
"os"
|
|
)
|
|
|
|
func main() {
|
|
if len(os.Args) != 2 {
|
|
log.Fatalln("Usage: " + os.Args[0] + " <file>")
|
|
}
|
|
|
|
content, err := os.ReadFile(os.Args[1])
|
|
if err != nil {
|
|
log.Fatalln("Cannot open input file.", err)
|
|
}
|
|
|
|
tokens, err := lexer(string(content))
|
|
if err != nil {
|
|
if c, ok := err.(CompilerError); ok {
|
|
log.Fatalln(err, "\nv- here\n"+string([]rune(string(content))[c.Position:]))
|
|
}
|
|
|
|
log.Fatalln(err)
|
|
}
|
|
|
|
log.Printf("Tokens:\n%+#v\n\n", tokens)
|
|
|
|
parser := Parser{Tokens: tokens}
|
|
parsed, err := parser.parseFile()
|
|
if err != nil {
|
|
if c, ok := err.(CompilerError); ok {
|
|
log.Fatalln(err, "\nv- here\n"+string([]rune(string(content))[c.Position:]))
|
|
}
|
|
|
|
log.Fatalln(err)
|
|
}
|
|
|
|
log.Printf("Parsed:\n%+#v\n\n", parsed)
|
|
|
|
errors := validator(parsed)
|
|
if len(errors) != 0 {
|
|
for _, err = range errors {
|
|
if c, ok := err.(CompilerError); ok {
|
|
log.Fatalln(err, "\nv- here\n"+string([]rune(string(content))[c.Position:]))
|
|
}
|
|
|
|
log.Fatalln(err)
|
|
}
|
|
}
|
|
|
|
log.Printf("Validated:\n%+#v\n\n", parsed)
|
|
|
|
wat, err := backendWAT(*parsed)
|
|
if err != nil {
|
|
if c, ok := err.(CompilerError); ok {
|
|
log.Fatalln(err, "\nv- here\n"+string([]rune(string(content))[c.Position:]))
|
|
}
|
|
|
|
log.Fatalln(err)
|
|
}
|
|
|
|
log.Println("WAT: " + wat)
|
|
os.WriteFile("out.wat", []byte(wat), 0o644)
|
|
}
|