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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
package main
import (
"flag"
"fmt"
"io"
"jinx/pkg/lang/modules"
"jinx/pkg/lang/vm"
"jinx/pkg/lang/vm/code"
"jinx/pkg/lang/vm/text"
"os"
)
func main() {
// Take the first argument as the path to the file to be parsed.
compile := flag.String("c", "", "compile to file (if not bytecode)")
decompile := flag.String("d", "", "decompile bytecode to file")
generatePCs := flag.Bool("p", false, "if decompiling, generate PC information")
run := flag.Bool("r", false, "run")
bytecode := flag.Bool("b", false, "interpret bytecode, without this flag the program will be interpreted in Lang VM text format.")
flag.Parse()
if *compile != "" && *bytecode {
exit("-c and -b are mutually exclusive")
}
if *compile != "" && *decompile != "" {
exit("-c and -d are mutually exclusive")
}
if *bytecode && !*run {
exit("-b requires -r")
}
if *compile == "" && *decompile == "" && !*run {
exit("nothing to do, either -c, -d or -r is required")
}
if *decompile == "" && *generatePCs {
exit("-p requires -d")
}
path := flag.Arg(0)
if path == "" {
exit("no file specified")
}
file, err := os.Open(path)
if err != nil {
exit("could not open file: %v", err)
}
defer file.Close()
var bc code.Code
if !*bytecode && *decompile == "" {
comp := text.NewCompiler(file)
bc, 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(bc.Code()); err != nil {
exit("could not write to file: %v", err)
}
}
} else {
content, err := io.ReadAll(file)
if err != nil {
exit("could not read file: %v", err)
}
bc = code.New(content, code.NewDebugInfo(path))
if *decompile != "" {
decomp := text.NewDecompiler(bc, *generatePCs)
result := decomp.Decompile()
output, err := os.Create(*decompile)
if err != nil {
exit("could not create file: %v", err)
}
defer output.Close()
if _, err := output.Write([]byte(result)); err != nil {
exit("could not write to file: %v", err)
}
}
}
if *run {
vm := vm.New(modules.NewUnknownModule(&bc), vm.NewConsoleOutput())
if err := vm.Run(); err != nil {
exit("execution failed: %v", err)
}
}
}
func exit(format string, args ...any) {
message := fmt.Sprintf(format, args...)
fmt.Printf("error: %s\n", message)
os.Exit(1)
}
|