-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
302 lines (258 loc) · 6 KB
/
main.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package main
import (
"flag"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"log"
"regexp"
"strconv"
"strings"
)
type Cell struct {
Content string
Type CellType
}
type CellType int
//go:generate stringer -type=CellType
const (
Empty CellType = iota
Text
Number
Expression
Clone
)
type Table [][]Cell
type Dir int
const (
Up Dir = iota + 1
Right
Down
Left
)
var charToDir = map[byte]Dir{
'^': Up,
'>': Right,
'v': Down,
'<': Left,
}
var debugFlag = flag.Bool("dbg", false, "enable intermediate representation and other debug infos")
var prettyPrintFlag = flag.Bool("pp", false, "pretty prints the cells with padding in-between")
var alignmentVar = flag.String("algn", "left", "set one of three valid alignments for cells (left, center, right)")
var numberFormatVar = flag.String("fmt", "%.2f", "printf-like formatting for floating point numbers inside cells")
func init() {
flag.Parse()
if *alignmentVar != "left" && *alignmentVar != "center" && *alignmentVar != "right" {
log.Panic("Invalid alignment: ", *alignmentVar)
}
}
func main() {
if len(flag.Args()) < 1 {
log.Panic("Not enough arguments")
}
c, err := ioutil.ReadFile(flag.Arg(0))
if err != nil {
log.Panic(err)
}
// Calculate size
content := strings.TrimSpace(string(c))
table := parseTable(content)
// Resolve cloning
for i, row := range table {
for j, cell := range row {
switch cell.Type {
case Clone:
var targetCell Cell
dir := charToDir[cell.Content[1]]
incNumber := false
var inc int
if dir == Up || dir == Down {
incNumber = true
}
switch dir {
case Up:
targetCell = table[i-1][j]
inc = 1
case Right:
targetCell = table[i][j+1]
inc = -1
case Down:
targetCell = table[i+1][j]
inc = -1
case Left:
targetCell = table[i][j-1]
inc = 1
}
if targetCell.Type == Expression {
r, _ := regexp.Compile(`[A-Z]\d+`)
matches := r.FindAllString(targetCell.Content, -1)
for _, m := range matches {
letter := m[0]
number, err := strconv.Atoi(m[1:])
if err != nil {
log.Panic(err)
}
if incNumber {
number += inc
} else {
if (letter < 'A' && inc < 0) || (letter > 'Z' && inc > 0) {
log.Panic("Out of bounds")
}
letter += byte(inc)
}
targetCell.Content = strings.ReplaceAll(targetCell.Content, m, fmt.Sprintf("%s%d", string(letter), number))
}
}
table[i][j] = targetCell
}
}
}
if *debugFlag {
dumpTable(table)
fmt.Println(strings.Repeat("-", 80))
}
// Final evaluation
for i, row := range table {
for j, cell := range row {
switch cell.Type {
case Expression:
expr, err := parser.ParseExpr(cell.Content[1:])
if err != nil {
log.Panic(err)
}
value := parseExpr(table, expr)
table[i][j] = Cell{
Content: fmt.Sprintf(*numberFormatVar, value),
Type: Number,
}
case Clone:
log.Panic("There should be no Clones after initial evaluation")
}
}
}
dumpTable(table)
}
func parseTable(content string) Table {
size := len(strings.Split(content, "\n"))
if *debugFlag {
fmt.Println("Rows:", size)
}
table := make(Table, size)
for i, row := range strings.Split(content, "\n") {
parts := strings.Split(row, "|")
for _, p := range parts {
part := strings.TrimSpace(p)
// FIXME: Find a way to eliminate empty cell rows or columns
var t CellType
if strings.HasPrefix(part, "=") {
t = Expression
} else if strings.HasPrefix(part, ":") {
t = Clone
} else if value, err := strconv.ParseFloat(part, 64); err == nil {
t = Number
part = fmt.Sprintf(*numberFormatVar, value)
} else if matched, _ := regexp.MatchString(`[A-Z]`, part); matched {
t = Text
}
table[i] = append(table[i], Cell{
Content: part,
Type: t,
})
}
}
return table
}
func parseExpr(table Table, expr ast.Expr) float64 {
if ident, ok := expr.(*ast.Ident); ok {
cell, err := getCell(table, ident)
if err != nil {
log.Panic(err)
}
if cell.Type == Text {
log.Panic("Text cell should not be used inside expressions")
}
return parseNumber(cell.Content)
}
if binaryExpr, ok := expr.(*ast.BinaryExpr); ok {
lhs := parseExpr(table, binaryExpr.X)
rhs := parseExpr(table, binaryExpr.Y)
switch binaryExpr.Op {
case token.ADD:
return lhs + rhs
case token.SUB:
return lhs - rhs
case token.MUL:
return lhs * rhs
case token.QUO:
return lhs / rhs
}
}
if number, ok := expr.(*ast.BasicLit); ok {
return parseNumber(number.Value)
}
log.Panic("couldn't parse expr")
return -1
}
func dumpTable(table Table) {
// Estimate column widths
widths := make([]int, len(table[0]))
for j := 0; j < len(table[0]); j++ {
var max int
for i := 0; i < len(table); i++ {
col := table[i][j]
if len(col.Content) > max {
max = len(col.Content)
}
}
widths[j] = max
}
if *debugFlag {
fmt.Println("Column widths:", widths)
}
// Render table
for _, row := range table {
for j, cell := range row {
fillSpace := widths[j] - len(cell.Content)
if *alignmentVar == "center" {
fmt.Print(strings.Repeat(" ", fillSpace/2))
} else if *alignmentVar == "right" {
fmt.Print(strings.Repeat(" ", fillSpace))
}
fmt.Print(cell.Content)
if j < len(row)-1 {
if *alignmentVar == "left" {
fmt.Print(strings.Repeat(" ", fillSpace))
} else if *alignmentVar == "center" {
fmt.Print(strings.Repeat(" ", fillSpace-fillSpace/2))
}
if *prettyPrintFlag {
fmt.Print(" | ")
} else {
fmt.Print("|")
}
}
}
fmt.Println()
}
}
func getCell(table Table, ident *ast.Ident) (Cell, error) {
letter := ident.Name[0]
number, err := strconv.Atoi(ident.Name[1:])
if err != nil {
return Cell{}, err
}
if (letter-'A') < 0 || number < 0 {
return Cell{}, fmt.Errorf("invalid cell identifier %q", ident.Name)
}
cell := table[number][letter-'A']
return cell, nil
}
func parseNumber(s string) float64 {
value, err := strconv.ParseFloat(s, 64)
if err != nil {
log.Panic(err)
}
return value
}