From ad486b790055d1187243cb8faba8eaa69612c7cf Mon Sep 17 00:00:00 2001 From: Robin Date: Tue, 21 Jan 2025 20:48:58 +0100 Subject: [PATCH] continue cmd --- cmd/cmd.go | 55 +++++++++++++++++++++++++++++++++++++++++++++++- parser/parser.go | 4 ++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/cmd/cmd.go b/cmd/cmd.go index f325529..7030a8a 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -3,11 +3,18 @@ package main import ( "flag" "fmt" + "io" "os" + "path/filepath" + "strings" + + "robaertschi.xyz/robaertschi/tt/lexer" + "robaertschi.xyz/robaertschi/tt/parser" + "robaertschi.xyz/robaertschi/tt/token" + "robaertschi.xyz/robaertschi/tt/typechecker" ) func main() { - flag.Usage = func() { fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s [flags] input\nPossible flags:\n", os.Args[0]) flag.PrintDefaults() @@ -23,4 +30,50 @@ func main() { flag.Usage() os.Exit(1) } + + if output == "" { + output = strings.TrimRight(input, filepath.Ext(input)) + } + + file, err := os.Open(input) + if err != nil { + fmt.Printf("Could not open file %q because: %e", input, err) + os.Exit(1) + } + defer file.Close() + + inputText, err := io.ReadAll(file) + if err != nil { + fmt.Printf("Could not read file %q because: %e", input, err) + os.Exit(1) + } + + l, err := lexer.New(string(inputText), input) + if err != nil { + fmt.Printf("Error while creating lexer: %e", err) + os.Exit(1) + } + + l.WithErrorCallback(func(l token.Loc, s string, a ...any) { + fmt.Printf("%s:%d:%d: %s\n", l.File, l.Line, l.Col, fmt.Sprintf(s, a...)) + }) + + p := parser.New(l) + p.WithErrorCallback(func(t token.Token, s string, a ...any) { + loc := t.Loc + fmt.Printf("%s:%d:%d: %s\n", loc.File, loc.Line, loc.Col, fmt.Sprintf(s, a...)) + }) + + program := p.ParseProgram() + + if p.Errors() > 0 { + fmt.Printf("Parser encountered 1 or more errors, quiting...\n") + os.Exit(1) + } + + tprogram, err := typechecker.New().CheckProgram(program) + if err != nil { + fmt.Printf("Typechecker failed with %e\n", err) + os.Exit(1) + } } diff --git a/parser/parser.go b/parser/parser.go index fe3cb2b..437b779 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -51,6 +51,10 @@ func (p *Parser) WithErrorCallback(errorCallback ErrorCallback) { p.errorCallback = errorCallback } +func (p *Parser) Errors() int { + return p.errors +} + func (p *Parser) registerInfixFn(tt token.TokenType, infix infixParseFn) { p.infixParseFns[tt] = infix }