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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
|
#include "asm.h"
#include "util.h"
#include "tpu.h"
#include <ctype.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#define TEXTALPH "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_"
#define NUMALPH "0123456789"
#define PORTALPH "abcdefghijklmnopqrstuvwxyz0123456789"
#define NAMEALPH TEXTALPH NUMALPH
#define WHITESPACE " \t\v\r\n,"
enum asm_tok {
/* Missing */
TOK_NONE = -1,
/* Global */
TOK_IN, TOK_OUT, TOK_TPU, TOK_END,
/* Operands (order like OP_*) */
TOK_ACC, TOK_NIL, TOK_LEFT, TOK_RIGHT, TOK_UP, TOK_DOWN,
TOK_ANY, TOK_LAST, TOK_LIT, TOK_NAME,
/* Instructions (order like INST_*) */
TOK_NOP, TOK_MOV, TOK_SWP, TOK_SAV, TOK_ADD, TOK_SUB,
TOK_NEG, TOK_JMP, TOK_JEZ, TOK_JNZ, TOK_JGZ, TOK_JLZ, TOK_JRO,
/* Misc */
TOK_COMMENT, TOK_LABEL, TOK_XPOS, TOK_YPOS, TOK_NL, TOK_EOF,
};
struct asm_tokenizer {
const char *filepath;
FILE *file;
enum asm_tok next;
char *tokstr;
size_t lineno, off;
char linebuf[256];
};
static const char *tok_strs[] = {
/* Global */
NULL, NULL, "tpu", "end",
/* Operands (order like OP_*) */
"acc", "nil", "left", "right", "up", "down",
"any", "last", NULL, NULL,
/* Instructions (order like INST_*) */
"nop", "mov", "swp", "sav", "add", "sub",
"neg", "jmp", "jez", "jnz", "jgz", "jlz", "jro",
/* Misc */
NULL, NULL, NULL, NULL, NULL, NULL
};
static const char *tok_reprs[] = {
/* Global */
"IN.<C>", "OUT.<C>", "TPU", "END",
/* Operands (order like OP_*) */
"ACC", "NIL", "LEFT", "RIGHT", "UP", "DOWN",
"ANY", "LAST", "<LIT>", "<NAME>",
/* Instructions (order like INST_*) */
"NOP", "MOV", "SWP", "SAV", "ADD", "SUB",
"NEG", "JMP", "JEZ", "JNZ", "JGZ", "JLZ", "JRO",
/* Misc */
"#<COMMENT>", "<LABEL>:", "X<INT>", "Y<INT>", "<NL>", "<EOF>"
};
static bool
is_int(const char *str)
{
char *end;
long v;
v = strtol(str, &end, 10);
if (!end || *end) return false;
if (v < INT32_MIN || v > INT32_MAX) return false;
return true;
}
static int
asm_port_char_to_index(char c)
{
char *p;
p = strchr(PORTALPH, tolower(c));
if (!p) die("invalid io port char '%c'", c);
return (int) (p - PORTALPH);
}
static bool
asm_is_lit(const char *str)
{
const char *c;
c = str;
if (*c == '-') c++;
else if (*c == '+') c++;
for (; *c && isdigit(*c); c++);
return !*c;
}
static int
asm_str_to_lit(const char *str)
{
int m, v, b, i, o;
if (*str == '-') {
m = -1;
o = 1;
} else if (*str == '+') {
m = 1;
o = 1;
} else {
m = 1;
o = 0;
}
for (b = 1, i = o; str[i]; i++)
b *= 10;
if (i >= 4 + o) {
v = 1000;
} else {
for (v = 0, i = o; str[i]; i++) {
b /= 10;
v += b * (str[i] - '0');
}
}
return MIN(MAX(m * v, -999), 999);
}
enum tpu_inst_type
tok_to_inst(enum asm_tok tok)
{
if (tok < TOK_NOP || tok > TOK_JRO) abort();
return tok - TOK_NOP + INST_NOP;
}
enum tpu_inst_op_type
tok_to_optype(enum asm_tok tok)
{
if (tok < TOK_ACC || tok > TOK_NAME) abort();
return tok - TOK_ACC + OP_ACC;
}
struct tpu_inst_op
tok_to_op(struct asm_tokenizer *tokenizer, enum asm_tok tok)
{
struct tpu_inst_op op;
op.type = tok_to_optype(tok);
if (op.type == OP_LIT) {
op.val.lit = asm_str_to_lit(tokenizer->tokstr);
} else if (op.type == OP_LABEL) {
op.val.label = strdup(tokenizer->tokstr);
if (!op.val.label) die("strdup:");
}
return op;
}
static size_t
strlcat_op_name(char *buf, struct tpu_inst_op *op, size_t n)
{
char tmp[5];
if (op->type == OP_LIT) {
snprintf(tmp, 5, "%i", op->val.lit);
return strdcat(buf, tmp, n);
} else if (op->type == OP_LABEL) {
return strdcat(buf, op->val.label, n);
} else {
return strdcat(buf, op_reprs[op->type], n);
}
}
size_t
asm_print_inst(char *buf, size_t n, struct tpu_inst *inst, size_t max)
{
size_t len, op;
len = strdcpy(buf, inst_reprs[inst->type], n);
if (inst->opcnt >= 1) {
len += strdcat(buf, " ", n);
len += strlcat_op_name(buf, &inst->ops[0], n);
}
if (inst->opcnt >= 2) {
op = strdcat(buf, ", ", n);
op += strlcat_op_name(buf, &inst->ops[1], n);
if (len + op > max && len < n) {
buf[len] = '\0';
op = strdcat(buf, ",", n);
op += strlcat_op_name(buf, &inst->ops[1], n);
}
len += op;
}
return len;
}
static enum asm_tok
tok_next(struct asm_tokenizer *tok)
{
enum asm_tok v;
size_t len;
char *s;
int i;
if (tok->next != TOK_NONE) {
v = tok->next;
tok->next = TOK_NONE;
return v;
}
if (!tok->linebuf[tok->off]) {
if (feof(tok->file)) return TOK_EOF;
s = fgets(tok->linebuf, sizeof(tok->linebuf), tok->file);
if (!s && !feof(tok->file)) die("fgets:");
if (!s) return TOK_NL;
len = strlen(s);
if (len && s[len-1] != '\n' && !feof(tok->file))
die("load: line %lu too long", tok->lineno);
if (len && s[len-1] == '\n') s[len-1] = '\0';
tok->lineno += 1;
tok->tokstr = s;
tok->off = 0;
return TOK_NL;
}
s = tok->linebuf + tok->off;
len = strspn(s, WHITESPACE);
tok->off += len;
if (!s[len]) return TOK_NL;
tok->tokstr = (s += len);
len = strcspn(s, WHITESPACE);
tok->off += len;
if (s[len]) {
s[len] = '\0';
tok->off += 1;
}
for (i = 0; i <= TOK_EOF; i++) {
if (tok_strs[i] && !strcasecmp(s, tok_strs[i]))
return (enum asm_tok) i;
}
if (!strncasecmp(s, "in.", 3) && len == 4) {
return TOK_IN;
} else if (!strncasecmp(s, "out.", 4) && len == 5) {
return TOK_OUT;
} else if (asm_is_lit(s)) {
return TOK_LIT;
} else if (*s == '#') {
tok->tokstr = tok->linebuf + tok->off;
tok->off += strlen(tok->linebuf + tok->off);
return TOK_COMMENT;
} else if (len && strchr(TEXTALPH, *s)
&& strspn(s, NAMEALPH) == len-1 && s[len-1] == ':') {
s[len-1] = '\0';
return TOK_LABEL;
} else if (*s == 'X' && is_int(s+1)) {
return TOK_XPOS;
} else if (*s == 'Y' && is_int(s+1)) {
return TOK_YPOS;
} else if (strchr(TEXTALPH, *s)
&& strspn(s, NAMEALPH) == strlen(s)) {
return TOK_NAME;
} else {
die("load: line %lu, invalid token '%s'", tok->lineno, s);
}
}
static enum asm_tok
tok_next_in(struct asm_tokenizer *tokenizer, ...)
{
va_list ap, cpy;
enum asm_tok tok;
bool first;
int arg;
tok = tok_next(tokenizer);
va_copy(cpy, ap);
va_start(cpy, tokenizer);
while ((arg = va_arg(cpy, int)) > 0) {
if (tok == arg) return tok;
}
va_end(cpy);
fprintf(stderr, "tis-as: load: ");
fprintf(stderr, "line %lu, got tok %s, expected one of (",
tokenizer->lineno, tok_reprs[tok]);
first = true;
va_start(ap, tokenizer);
while ((arg = va_arg(ap, int)) > 0) {
if (!first) fputc(',', stderr);
fputs(tok_reprs[arg], stderr);
first = false;
}
va_end(ap);
fputs(")\n", stderr);
exit(1);
}
static void
tpu_validate(struct tpu *tpu)
{
int dst, i;
for (i = 0; i < tpu->inst_cnt; i++) {
if (tpu->insts[i].opcnt >= 1
&& tpu->insts[i].ops[0].type == OP_LABEL) {
dst = label_map_get(&tpu->label_map,
tpu->insts[i].ops[0].val.label);
if (dst < 0)
die("load: tpu X%i Y%i, label '%s' not defined",
tpu->x, tpu->y,
tpu->insts[i].ops[0].val.label);
}
}
}
void
tis_load_asm(struct tis *tis, const char *filepath)
{
struct tpu_io_port *io_port;
struct asm_tokenizer tokenizer;
struct tpu_inst_op op1, op2;
enum tpu_inst_type inst_type;
struct tpu_inst *inst;
struct tpu *tpu = NULL;
struct tpu_map_link *link;
struct tpu_port *port;
enum asm_tok tok, optok;
char rowbuf[TPU_MAX_COLS+1];
size_t colsused;
int io_x, io_y;
ssize_t i, k;
size_t len;
char c;
tis->asm_filepath = strdup(filepath);
tokenizer.filepath = filepath;
tokenizer.file = fopen(filepath, "r");
if (!tokenizer.file) die("load: fopen '%s':", filepath);
tokenizer.next = TOK_NONE;
tokenizer.lineno = 0;
tokenizer.off = 0;
tokenizer.tokstr = NULL;
tokenizer.linebuf[tokenizer.off] = '\0';
colsused = 0;
while ((tok = tok_next(&tokenizer)) != TOK_EOF) {
switch (tok) {
case TOK_IN:
case TOK_OUT:
if (tpu) goto disallowed;
io_port = malloc(sizeof(struct tpu_io_port));
if (!io_port) die("malloc:");
len = strlen(tokenizer.tokstr);
c = tokenizer.tokstr[len-1];
k = asm_port_char_to_index(c);
if (tok == TOK_IN) {
if (tis->in_ports[k])
die("load: line %lu, duplicate in.%c",
tokenizer.lineno, c);
tis->in_ports[k] = io_port;
} else {
if (tis->out_ports[k])
die("load: loute %lu, duplicate out.%c",
tokenizer.lineno, c);
tis->out_ports[k] = io_port;
}
tok_next_in(&tokenizer, TOK_XPOS, -1);
io_x = atoi(tokenizer.tokstr + 1);
tok_next_in(&tokenizer, TOK_YPOS, -1);
io_y = atoi(tokenizer.tokstr + 1);
tok_next_in(&tokenizer, TOK_NL, -1);
if (tok == TOK_IN) {
tpu_io_port_init(io_port, c, DIR_UP,
PORT_IN, io_x, io_y);
} else {
tpu_io_port_init(io_port, c, DIR_DOWN,
PORT_OUT, io_x, io_y);
}
colsused = 0;
break;
case TOK_TPU:
if (tpu) goto disallowed;
tpu = malloc(sizeof(struct tpu));
if (!tpu) die("malloc:");
tpu_init(tpu);
tok_next_in(&tokenizer, TOK_XPOS, -1);
tpu->x = atoi(tokenizer.tokstr + 1);
tok_next_in(&tokenizer, TOK_YPOS, -1);
tpu->y = atoi(tokenizer.tokstr + 1);
tok_next_in(&tokenizer, TOK_NL, -1);
if (!tpu_map_add(&tis->tpu_map, tpu))
die("load: duplicate tpu location X%i Y%i",
tpu->x, tpu->y);
colsused = 0;
break;
case TOK_END:
if (!tpu) goto disallowed;
tpu_validate(tpu);
tpu = NULL;
tok_next_in(&tokenizer, TOK_NL, -1);
colsused = 0;
break;
case TOK_NOP: case TOK_MOV: case TOK_SWP: case TOK_SAV:
case TOK_ADD: case TOK_SUB: case TOK_NEG: case TOK_JMP:
case TOK_JEZ: case TOK_JNZ: case TOK_JGZ: case TOK_JLZ:
case TOK_JRO:
if (!tpu) goto disallowed;
inst_type = tok_to_inst(tok);
optok = tok_next_in(&tokenizer, TOK_ACC,
TOK_NIL, TOK_LEFT, TOK_RIGHT, TOK_UP, TOK_DOWN,
TOK_ANY, TOK_LAST, TOK_LIT, TOK_NAME, TOK_NL, -1);
if (optok == TOK_NL) {
inst = tpu_add_inst(tpu, inst_type, 0, op1, op2);
if (!inst) {
die("load: line %lu, invalid instruction",
tokenizer.lineno-1);
}
goto inst_check;
}
op1 = tok_to_op(&tokenizer, optok);
optok = tok_next_in(&tokenizer, TOK_ACC,
TOK_NIL, TOK_LEFT, TOK_RIGHT, TOK_UP, TOK_DOWN,
TOK_ANY, TOK_LAST, TOK_LIT, TOK_NAME, TOK_NL, -1);
if (optok == TOK_NL) {
inst = tpu_add_inst(tpu, inst_type, 1, op1, op2);
if (!inst) {
die("load: line %lu, invalid instruction",
tokenizer.lineno-1);
}
goto inst_check;
}
op2 = tok_to_op(&tokenizer, optok);
tok_next_in(&tokenizer, TOK_NL, -1);
inst = tpu_add_inst(tpu, inst_type, 2, op1, op2);
if (!inst) die("load: line %lu, invalid instruction",
tokenizer.lineno-1);
inst_check:
tpu->rows += 1;
if (tpu->inst_cnt > TPU_MAX_INST_CNT || tpu->rows > TPU_MAX_ROWS)
die("load: line %lu, tpu has too many rows",
tokenizer.lineno-1);
len = asm_print_inst(rowbuf, sizeof(rowbuf),
inst, TPU_MAX_COLS - colsused);
if (colsused + len > TPU_MAX_COLS)
die("load: line %lu, tpu row is too long (%zu,%zu)",
tokenizer.lineno-1, colsused, len);
colsused = 0;
break;
case TOK_COMMENT:
if (tpu && !strcmp(tokenizer.tokstr, "DISABLED"))
tpu->disabled = true;
tok_next_in(&tokenizer, TOK_NL, -1);
break;
case TOK_LABEL:
len = strlen(tokenizer.tokstr);
strncpy(rowbuf, tokenizer.tokstr, TPU_MAX_COLS);
optok = tok_next(&tokenizer);
if (!label_map_add(&tpu->label_map, rowbuf,
(int) tpu->inst_cnt, optok != TOK_NL))
die("load: line %lu, duplicate label %s (pos)",
tokenizer.lineno, rowbuf);
if (optok == TOK_NL) {
tpu->rows += 1;
if (tpu->rows > TPU_MAX_ROWS)
die("load: line %lu, line does not fit",
tokenizer.lineno);
colsused = 0;
} else {
tokenizer.next = optok;
colsused = len + 1;
}
if (len + 1 > TPU_MAX_COLS)
die("load: line %lu, label too long",
tokenizer.lineno);
break;
case TOK_NL:
colsused = 0;
break;
default:
goto disallowed;
}
}
for (i = 0; i < TPU_MAP_BUCKETS; i++) {
for (link = tis->tpu_map.buckets[i]; link; link = link->next) {
tpu_init_ports(link->tpu, &tis->tpu_map);
for (k = -TIS_MAX_IO_PORTS; k < TIS_MAX_IO_PORTS; k++) {
io_port = k < 0 ? tis->in_ports[-k-1]
: tis->out_ports[k];
if (!io_port || io_port->port.attached) continue;
if (link->tpu->x != io_port->x) continue;
if (link->tpu->y != io_port->y) continue;
port = &link->tpu->ports[io_port->dir];
if (port->attached) {
die("load: io_port X%i Y%i (%s) busy",
io_port->x, io_port->y,
dir_reprs[io_port->dir]);
}
port->attached = true;
port->dst_port = &io_port->port;
port->type = io_port->type;
io_port->port.attached = true;
io_port->port.dst_port = port;
}
}
}
for (i = -TIS_MAX_IO_PORTS; i < TIS_MAX_IO_PORTS; i++) {
io_port = i < 0 ? tis->in_ports[-i-1] : tis->out_ports[i];
if (io_port && !io_port->port.attached) {
die("load: io_port X%i Y%i (%s) not found",
io_port->x, io_port->y,
dir_reprs[io_port->dir]);
}
}
fclose(tokenizer.file);
return;
disallowed:
if (tok == TOK_NAME) {
die("load: line %lu, unexpected token '%s'",
tokenizer.lineno, tokenizer.tokstr);
} else {
die("load: line %lu, token %s not allowed here",
tokenizer.lineno, tok_reprs[tok]);
}
}
void
tis_load(struct tis *tis, const char **argv)
{
const char **arg;
int n, i;
char c;
if (!*argv) die("missing argv[0]");
for (arg = argv + 1; *arg; arg++) {
if (!strcmp(*arg, "-h") || !strcmp(*arg, "--help")) {
fprintf(stderr, "Usage: %s [-h] [-s] "
"[--in.X IN].. [--out.X OUT].. ASM\n", argv[0]);
} else if (!strcmp(*arg, "-s") || !strcmp(*arg, "--stats")) {
tis->show_stats = true;
} else if (sscanf(*arg, "--in.%c%n", &c, &n) == 1 && n == 6) {
/* after tis_load_asm.. */
arg++;
} else if (sscanf(*arg, "--out.%c%n", &c, &n) == 1 && n == 7) {
/* after tis_load_asm.. */
arg++;
} else {
if (tis->asm_filepath)
die("multiple asm files");
tis_load_asm(tis, *arg);
}
}
for (arg = argv + 1; *arg; arg++) {
if (sscanf(*arg, "--in.%c%n", &c, &n) == 1 && n == 6) {
i = asm_port_char_to_index(c);
if (!tis->in_ports[i])
die("in.%c io port not initialized", c);
tis->in_ports[i]->file = fopen(*++arg, "r");
if (!tis->in_ports[i]->file)
die("fopen '%s':", *arg);
setvbuf(tis->in_ports[i]->file, NULL, _IONBF, 0);
} else if (sscanf(*arg, "--out.%c%n", &c, &n) == 1 && n == 7) {
i = asm_port_char_to_index(c);
if (!tis->out_ports[i])
die("out.%c io port not initialized", c);
tis->out_ports[i]->file = fopen(*++arg, "w+");
if (!tis->out_ports[i]->file)
die("fopen '%s':", *arg);
setvbuf(tis->out_ports[i]->file, NULL, _IONBF, 0);
}
}
}
|