about summary refs log tree commit diff
path: root/cmd/lang/main.go
blob: c5c0fe66d19af3bea08d827754a73d2c744c9222 (plain)
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
85
86
87
package main

import (
	"flag"
	"fmt"
	"jinx/pkg/lang/compiler"
	"jinx/pkg/lang/parser"
	"jinx/pkg/lang/scanner"
	"jinx/pkg/lang/vm"
	"os"
	"os/user"
	"path"
)

func main() {
	compile := flag.String("c", "", "compile to file")
	run := flag.Bool("r", false, "run")

	flag.Parse()

	if *compile == "" && !*run {
		exit("nothing to do, either -c or -r is required")
	}

	filePath := flag.Arg(0)
	if filePath == "" {
		exit("no file specified")
	}

	file, err := os.Open(filePath)
	if err != nil {
		exit("could not open file: %v", err)
	}
	defer file.Close()

	scanner := scanner.New(file)
	tokens, err := scanner.Scan()
	if err != nil {
		exit("error during scanning: %v", err)
	}

	parser := parser.New(tokens)
	program, err := parser.Parse()
	if err != nil {
		exit("error during parsing: %v", err)
	}

	comp := compiler.New(path.Base(filePath), getUsername(), program)
	module, err := comp.Compile()
	if err != nil {
		exit("compilation failed: %v", err)
	}

	if *compile != "" {
		output, err := os.Create(*compile)
		if err != nil {
			exit("could not create file: %v", err)
		}
		defer output.Close()

		if _, err := output.Write(module.Code().Code()); err != nil {
			exit("could not write to file: %v", err)
		}
	}

	if *run {
		vm := vm.New(module, vm.NewConsoleOutput())
		if err := vm.Run(); err != nil {
			exit("execution failed: %v", err)
		}
	}
}

func getUsername() string {
	me, err := user.Current()
	if err != nil {
		return "unknown"
	}

	return me.Username
}

func exit(format string, args ...any) {
	message := fmt.Sprintf(format, args...)
	fmt.Printf("error: %s\n", message)
	os.Exit(1)
}