-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.go
123 lines (110 loc) · 2.3 KB
/
compiler.go
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
111
112
113
114
115
116
117
118
119
120
121
122
123
package compiler
import (
"bufio"
"fmt"
"github.com/steveoc64/republique5/db"
"os"
"path/filepath"
"github.com/gogo/protobuf/jsonpb"
"github.com/sirupsen/logrus"
)
// Error is an error type returned by the compiler suite
type Error struct {
line int
filename string
msg string
}
// Error returns a string
func (e Error) Error() string {
return fmt.Sprintf("ERROR: Line %d: %s - %s", e.line, e.filename, e.msg)
}
// Compiler is a holder struct for a compiler type
type Compiler struct {
log *logrus.Logger
}
// NewCompiler returns a new compiler
func NewCompiler(log *logrus.Logger) *Compiler {
return &Compiler{
log: log,
}
}
// Compile takes a file and calls the appropriate compiler depending on the filename extension
func (c *Compiler) Compile(filename string) error {
ext := filepath.Ext(filename)
shortName := filename[:len(filename)-len(ext)]
switch ext {
case ".oob":
cmd, err := c.CompileOOB(filename)
if err != nil {
println(err.Error())
return err
}
f, err := os.Create(shortName + ".json")
if err != nil {
fmt.Println(err)
return err
}
marshaler := &jsonpb.Marshaler{}
marshaler.Marshal(f, cmd)
err = f.Close()
if err != nil {
fmt.Println(err)
return err
}
case ".scenario":
scn, err := c.CompileScenario(filename)
if err != nil {
println(err.Error())
return err
}
f, err := os.Create(shortName + ".json")
if err != nil {
fmt.Println(err)
return err
}
marshaler := &jsonpb.Marshaler{}
marshaler.Marshal(f, scn)
err = f.Close()
if err != nil {
fmt.Println(err)
return err
}
case ".game":
game, err := c.CompileGame(filename)
if err != nil {
println(err.Error())
return err
}
db := db.NewDB(c.log, filepath.Base(shortName+".db"))
err = db.Save("game", "state", game)
if err != nil {
fmt.Println(err)
return err
}
}
return nil
}
func (c *Compiler) load(filename string) ([]string, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
lines := []string{}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
func countLeadingRune(line string, r rune) int {
i := 0
for _, runeValue := range line {
if runeValue == r {
i++
} else {
break
}
}
return i
}