-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathc8asm.c
1598 lines (1519 loc) · 47.7 KB
/
c8asm.c
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* CHIP8 assembler
* ==================
*
* ![toc]
*
* ## Overview
*
* The syntax is mostly based on that of [Cowgod's Chip-8 Technical Reference v1.0][cowgod],
* by Thomas P. Greene
*
* Semicolons `;` denote the start of a comment.
*
* Identifiers start with an alphabetic character, and are
* followed by zero or more alphanumeric digits or underscores.
*
* Identifiers are not case sensitive. Identifiers, labels and instruction
* Mnemonics can be written in upper or lower case. For example `sub`, `Sub` and
* `SUB` are all equivalent.
*
* There are a couple of reserved special identifiers:
*
* * `I` for the index register.
* * `DT` for the delay timer register.
* * `ST` for the sound timer register.
* * `K` for the key press register[^fake].
* * `F` for the address of the 8×5 fonts[^fake].
* * `B` for storing BCD values[^fake].
* * `HF` for the address of the larger 8×10 fonts[^fake].
* * `R` for the reserved RPL storage space[^fake][^rpl].
*
* [^fake]: there aren't actual registers `K`, `F`, `B`, `HF` and `R` in the interpreter, in but they're used in special syntax, particularly the `LD` instruction.
*
* These keywords are also reserved:
*
* * `define` to define new symbols
* * `offset` to control where in the ROM output is placed
* * `db` to write bytes to the ROM
* * `dw` to write 16-bit words to the ROM
*
* [cowgod]: http://devernay.free.fr/hacks/chip8/C8TECH10.HTM
*
* ### Notation
*
* In the purposes of this document:
*
* * `Vx`, `Vy` and `Vn` refer to any of the 16 Chip8 registers, `V0` through `VF`
* * `addr` refers to a 12-bit address in the Chip8 interpreter's RAM.
* * `nnn` refers to a 12-bit value.
* * `n` refers to a 4-bit nibble value.
* * `kk` is a byte value.
*
* Decimal literals are a sequence of the characters `0-9`, for example `254`.
*
* Binary literals start with `%` followed by several `0` or `1` symbols,
* for example `%11111110`.
*
* Hexadecimal literals start with a `#` followed by characters from
* `0-9`, `a-f` or `A-F`, for example `#FE` for 254.
*
* ## Summary
*
* | Chip8 Instruction | Mnemonic | Description |
* |--------------------|-------------------|----------------------------------------------------|
* | 0nnn | `sys nnn` | System Call |
* | 00E0 | `cls` | Clear Screen |
* | 00EE | `ret` | Return |
* | 1nnn | `jp addr` | Jump to `addr` |
* | 2nnn | `call addr` | Call routine at `addr` |
* | 3nkk | `se Vn kk` | Skip if `Vn` equals `kk` |
* | 4nkk | `sne Vn kk` | Skip if `Vn` does not equal `kk` |
* | 5xy0 | `se Vx Vy` | Skip if `Vn` equals `Vy` |
* | 6xkk | `ld Vx, kk` | Loads a literal value `kk` into `Vx` |
* | 7nkk | `add Vn, kk` | Add `kk` to register `Vx` |
* | 8xy0 | `ld Vx, Vy` | Loads register `Vy` into `Vx` |
* | 8xy1 | `or Vx, Vy` | Bitwise OR the value in `Vy` with register `Vx` |
* | 8xy2 | `and Vx, Vy` | Bitwise AND the value in `Vy` with register `Vx` |
* | 8xy3 | `xor Vx, Vy` | Bitwise XOR the value in `Vy` with register `Vx` |
* | 8xy4 | `add Vx, Vy` | Add the value in `Vy` to register `Vx` |
* | 8xy5 | `xor Vx, Vy` | Subtract the value in `Vy` from register `Vx` |
* | 8xy6 | `shr Vx [, Vy]` | Shift `Vx` to the right with the value in `Vy` |
* | 8xy7 | `subn Vx, Vy` | Subtract the value in `Vy` from `Vx`, no carry |
* | 8xyE | `shl Vx [, Vy]` | Shift `Vx` to the left with the value in `Vy` |
* | 9xy0 | `sne Vx Vy` | Skip if `Vn` does not equal `Vy` |
* | Annn | `ld I, nnn` | Loads `nnn` into register `I` |
* | Bnnn | `jp v0, addr` | Jump to `v0 + addr` |
* | Cnkk | `rnd Vn, kk` | random number AND `kk` into `Vn` |
* | Dxyn | `drw Vx, Vy, n` | Draw a sprite of `n` rows at `Vx,Vy` |
* | En9E | `skp Vn` | Skip if key in `Vn` pressed |
* | EnA1 | `sknp Vn` | Skip if key in `Vn` not pressed |
* | Fn0A | `ld Vn, K` | loads a key pressed into `Vn` |
* | Fn1E | `add I, Vn` | Add the value in `Vn` to register `I` |
* | Fx07 | `ld Vx, DT` | Loads the delay timer into register `Vx` |
* | Fx15 | `delay Vx` | Loads register `Vx` into the delay timer |
* | Fx18 | `sound Vx` | Loads register `Vx` into the sound timer |
* | Fx29 | `hex Vx` | Loads the 8×5 font sprite of `Vx` into `I` |
* | Fx30[^super] | `hexx Vx` | Loads the 8×10 font sprite of `Vx` into `I` |
* | Fx33 | `bcd Vx` | Load BCD value of `Vx` into `I` to `I+2` |
* | Fx55 | `stor Vx` | Stores `V0` through `Vx` to the address in `I` |
* | Fx65 | `rstr Vx` | Restores `V0` through `Vx` from the address in `I` |
* | Fx75[^super] | `storx Vx` | Stores `V0` through `Vx` to the reserved space |
* | Fx85[^super] | `rstrx Vx` | Restores `V0` through `Vx` from the reserved space |
* | 00Cn[^super] | `scd n` | Scroll down `n` pixels |
* | 00FB[^super] | `scr` | Scroll right |
* | 00FC[^super] | `scl` | Scroll Left |
* | 00FD[^super] | `exit` | Exits the SuperChip48 interpreter |
* | 00FE[^super] | `low` | Low res mode |
* | 00FF[^super] | `high` | Enable 128×64 high-res mode |
*
* [^super]: Denotes a Super Chip48 instruction.
*/
/* CHIP-8 Assembler. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdarg.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
#include "chip8.h"
#define TOK_SIZE 64
#define MAX_DEFS 512
#define MAX_LOOKUP 2048
c8_include_callback_t c8_include_callback = c8_load_txt;
typedef enum {
SYM_END,
SYM_IDENTIFIER,
SYM_INSTRUCTION,
SYM_REGISTER,
SYM_NUMBER,
SYM_STRING,
SYM_I,
SYM_DT,
SYM_ST,
SYM_K,
SYM_F,
SYM_B,
SYM_HF,
SYM_R,
SYM_DEFINE,
SYM_OFFSET,
SYM_DB,
SYM_DW,
SYM_TEXT,
SYM_INCLUDE,
} SYMBOL;
/* List of instruction names.
(NB Keep this list sorted because of `bsearch()`) */
static const char *inst_names[] = {
"add",
"and",
"bcd",
"call",
"cls",
"delay",
"drw",
"exit",
"hex",
"hexx",
"high",
"jp",
"key",
"ld",
"low",
"or",
"ret",
"rnd",
"rstr",
"rstrx",
"scd",
"scl",
"scr",
"se",
"shl",
"shr",
"sknp",
"skp",
"sne",
"sound",
"stor",
"storx",
"sub",
"subn",
"sys",
"xor",
};
/* TIL https://stackoverflow.com/a/15824981/115589 */
static int inst_cmp(const void *s1, const void *s2) {
const char *key = s1;
const char * const *arg = s2;
return strcmp(key, *arg);
}
typedef struct {
const char * in;
const char * last;
SYMBOL sym;
int linenum;
char token[TOK_SIZE];
} Stepper;
#define BITNESS_BITMASK 0b0011
#define EXPRESSION_BITMASK 0b0100
#define EMIT8_BITMASK 0b1000
typedef enum {
CONTINUED=0,
ET_IMM4=0b10000,
ET_IMM8=0b10001,
ET_IMM4_EMIT8=0b11000,
ET_IMM8_EMIT8=0b11001,
ET_IMM12=0b10010,
ET_IMM16=0b10011,
ET_EXP4=0b10100,
ET_EXP8=0b10101,
ET_EXP4_EMIT8=0b11100,
ET_EXP8_EMIT8=0b11101,
ET_EXP12=0b10110,
ET_EXP16=0b10111
} EMITTED_TYPE;
typedef struct {
EMITTED_TYPE type;
uint16_t value;
} Emitted;
/* Generated instructions before binary output */
static struct {
struct {
uint8_t byte;
EMITTED_TYPE type;
int linenum;
char expression[TOK_SIZE];
} bytes[TOTAL_RAM];
uint16_t next_instr; /* Address of next instruction */
uint16_t max_instr; /* Largest instruction address for output */
} program;
/* Lookup table for labels for JP and CALL instructions */
static struct {
char label[TOK_SIZE];
uint16_t addr;
} lookup[MAX_LOOKUP];
static int n_lookup;
/* Lookup table for DEFINE identifier value statements */
static struct {
char name[TOK_SIZE];
SYMBOL type;
char value[TOK_SIZE];
} defs[MAX_DEFS];
static int n_defs;
static void exit_error(const char *msg, ...) {
char buffer[MAX_MESSAGE_TEXT];
if(msg) {
va_list arg;
va_start (arg, msg);
vsnprintf (buffer, MAX_MESSAGE_TEXT - 1, msg, arg);
va_end (arg);
c8_message("%s", buffer);
}
exit(1);
}
static bool is_arith(char c){
switch (c){
case '0' ... '9':
case '(':
case '#':
case '%':
case '+':
case '-':
case '*':
case '/':
case '|':
case '&':
case '^':
case '<':
case '>':
case '~':
return true;
default:
return false;
}
}
static bool is_unary_operator(const char * exp){
if ((*exp=='-'||*exp=='+') && exp[1] == '(')
return true;
else if (*exp=='~')
return true;
else
return false;
}
static int get_precedence(const char * expr){
char c = *expr;
switch (c){
case '<':
case '>':
if(c==expr[1])
return 1;
else
return 0;
case '&':
case '|':
case '^':
return 2;
case '-':
case '+':
return 3;
case '*':
case '/':
case '%':
return 4;
case '(':
return 000;
default:
return 0;
}
}
static int get_base(const char * a){
if (isdigit(*a) )
return 10;
else if ((*a == '-' || *a == '+') && isdigit(a[1]))
return 10;
else if (*a == '#' && isxdigit(a[1]))
return 16;
else if (*a == '%' && (a[1] == '0' || a[1] == '1'))
return 2;
else if (*a == '(')
return -1;
else
return 0;
}
static int parse_int(char **expression, const int linenum){
int base = get_base(*expression);
if(base <= 0)
exit_error("error:%d: Invalid Immediate\n", linenum);
if (base!=10)
(*expression)++;
return (int)strtol(*expression, expression, base);
}
static void copy_arithmetic_expression(char * buffer, const char ** in){
while (**in && **in != ',' && **in !='\n' && **in !=';'){
if (**in == ' ') {
(*in)++;
continue;
}
(*buffer++)=(*(*in)++);
}
*buffer='\0';
}
static int apply_unary_op (const unsigned char op, const int val, const int linenum){
switch (op)
{
case '+' | 0x80:
return val;
case '-' | 0x80 :
return -val;
case '~' | 0x80:
return ~val;
default:
exit_error("error:%d: Invalid Arithmetic Expression\n",linenum);
}
/*unreachable*/
return -1;
}
#define STACK_HEIGHT 64
static int apply_binary_op(const int l_op, const char op, const int r_op, const int linenum){
switch (op)
{
case '+':
return l_op+r_op;
case '-':
return l_op-r_op;
case '*':
return l_op*r_op;
case '/':
return l_op/r_op;
case '|':
return l_op|r_op;
case '&':
return l_op&r_op;
case '^':
return l_op^r_op;
case '<':
return l_op<<r_op;
case '>':
return l_op>>r_op;
default:
exit_error("error:%d: Invalid Arithmetic Expression\n",linenum);
}
/*unreachable*/
return -1;
}
static int evaluate_arithmetic_expression(char *expression, const int linenum){
struct {
unsigned char stack[STACK_HEIGHT];
unsigned char *top;
} operators;
// GCC doesn't like that `operators.top` points to before `operators.stack`
// but upon reviewing it, I decided it is fine.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Warray-bounds"
operators.top = operators.stack - 1;
#pragma GCC diagnostic pop
struct {
int stack[STACK_HEIGHT];
int *top;
} figures;
*figures.stack = 0;
figures.top = figures.stack;
bool is_prev_figure = true;
bool is_first_char_of_clause = true;
while (*expression){
int prec;
int base;
if (strchr(" \t\r", *expression)) {
expression++;
continue;
} else if(*expression == '(') {
//if it's the first char I want to make sure it doesn't try to "bracket" the initial 0
if(is_first_char_of_clause) *(++operators.top)='+';
*(++operators.top)=*expression;
*(++figures.top)=0;
is_prev_figure=true;
expression++;
is_first_char_of_clause=true;
} else if(*expression == ')') {
while((*operators.top) != '(')
{
if (operators.top<operators.stack)
exit_error("error:%d: Unbalanced Brackets\n", linenum);
const int r_op = *(figures.top--);
const int l_op = *(figures.top--);
const unsigned char op = *(operators.top--);
*(++figures.top)=apply_binary_op(l_op, op, r_op,linenum);
}
is_prev_figure=true;
operators.top--;
expression++;
is_first_char_of_clause=false;
} else if (is_unary_operator(expression) && (!is_prev_figure || is_first_char_of_clause)){
if (is_first_char_of_clause) *(++operators.top) = '+';
*(++operators.top)=((unsigned char) *expression)|0x80;
is_prev_figure=false;
expression++;
is_first_char_of_clause=false;
} else if (((prec=get_precedence(expression))>0) | ((base=get_base(expression))>0)){
unsigned char operator_extended[2]={*operators.top,*operators.top};
while(
figures.top>=figures.stack &&
is_prev_figure &&
prec > 0 &&
get_precedence((char *)operator_extended)>prec
){
const int r_op = *(figures.top--);
const int l_op = *(figures.top--);
const unsigned char op = *(operators.top--);
*(++figures.top) = apply_binary_op(l_op, op, r_op,linenum);
memset(operator_extended,*operators.top, 2);
}
if (base>0){
if(is_prev_figure) {
*(++operators.top)='+';
}
*(++figures.top)=parse_int(&expression, linenum);
is_prev_figure=true;
if (*operators.top&0x80){
(*figures.top) = apply_unary_op(*operators.top, *figures.top, linenum);
operators.top--;
}
} else {
if (is_first_char_of_clause)
exit_error("error:%d: Invalid Arithmetic Expression\n", linenum);
*(++operators.top)=*expression;
expression++;
if (*expression=='>' || *expression=='<') expression++;
is_prev_figure=false;
}
is_first_char_of_clause=false;
} else {
bool success = false;
char buffer[64];
char * bufptr=buffer;
while ((*expression) && (!ispunct(*expression) || *expression == '_'))
*bufptr++=*expression++;
*bufptr='\0';
for(int i = 0; i < n_lookup; i++) {
if(!strcmp(lookup[i].label, buffer)) {
if(is_prev_figure) {
*(++operators.top)='+';
}
*(++figures.top)=lookup[i].addr;
if (*operators.top&0x80){
(*figures.top) = apply_unary_op(*operators.top, *figures.top, linenum);
operators.top--;
}
success=true;
is_first_char_of_clause=false;
is_prev_figure=true;
break;
}
}
if(!success) exit_error("error:%d: Invalid Identifier %s in arithmetic expression\n", linenum, buffer);
}
}
while(operators.top>=operators.stack){
if (operators.top<operators.stack)
exit_error("error%d: Unbalanced Brackets\n", linenum);
const int r_op = *(figures.top--);
const int l_op = *(figures.top--);
const unsigned char op = *(operators.top--);
*(++figures.top)=apply_binary_op(l_op, op, r_op,linenum);
}
return *figures.stack;
}
static void emit_b(const Stepper * stepper, uint8_t byte, const EMITTED_TYPE type) {
if(program.next_instr >= TOTAL_RAM)
exit_error("error: program too large\n");
program.bytes[program.next_instr].linenum = stepper->linenum;
program.bytes[program.next_instr].type=type;
if (type & EXPRESSION_BITMASK)
strcpy(program.bytes[program.next_instr].expression, stepper->token);
program.bytes[program.next_instr++].byte = byte;
if(program.next_instr > program.max_instr)
program.max_instr = program.next_instr;
}
static void emit(const Stepper * stepper, const Emitted emitted){
if (emitted.type == CONTINUED)
exit_error("Continued is reserved\n");
else if (emitted.type & EMIT8_BITMASK) {
emit_b(stepper, emitted.value & 0xff, emitted.type);
} else {
emit_b(stepper, emitted.value >> 8, emitted.type);
emit_b(stepper, emitted.value & 0xff, CONTINUED);
}
}
static inline void emit_w(const Stepper * stepper, uint16_t word){
const Emitted e = (Emitted){
.type=ET_IMM16,
.value=word
};
emit(stepper, e);
}
static inline void emit_e(const Stepper * stepper, uint16_t word, size_t nibble_count){
const Emitted e = (Emitted) {
.type=0b10000 | EXPRESSION_BITMASK | (nibble_count-1),
.value=word
};
emit(stepper, e);
}
static void add_label(const char *label, const int linenum) {
if(n_lookup == MAX_LOOKUP)
exit_error("error: too many entries in lookup\n");
for(int i = 0; i < n_lookup; i++)
if(!strcmp(lookup[i].label, label))
exit_error("error:%d: duplicate label '%s'\n", linenum, label);
strcpy(lookup[n_lookup].label, label);
lookup[n_lookup].addr = program.next_instr;
n_lookup++;
}
static void add_definition(const Stepper * stepper, char *name) {
if(n_defs == MAX_DEFS)
exit_error("error:%d: too many definitions\n", stepper->linenum);
strcpy(defs[n_defs].name, name);
defs[n_defs].type = stepper->sym;
strcpy(defs[n_defs].value,stepper->token);
n_defs++;
}
static int nextsym(Stepper * stepper) {
char *tok = stepper->token;
stepper->sym = SYM_END;
*tok = '\0';
scan_start:
while(isspace(*stepper->in)) {
if(*stepper->in == '\n')
stepper->linenum++;
stepper->in++;
}
stepper->last=stepper->in;
if(!*stepper->in)
return SYM_END;
if(*stepper->in == ';') {
while(*stepper->in && *stepper->in != '\n')
stepper->in++;
goto scan_start;
}
if(isalpha(*stepper->in)) {
while(isalnum(*stepper->in) || *stepper->in == '_') {
*tok++ = tolower(*stepper->in++);
if(tok - stepper->token >= TOK_SIZE) {
exit_error("error:%d: token too long (max:%d).\n", stepper->linenum, TOK_SIZE-1);
}
}
*tok = '\0';
if(bsearch(stepper->token, inst_names, (sizeof inst_names)/(sizeof inst_names[0]), sizeof inst_names[0], inst_cmp)) {
stepper->sym = SYM_INSTRUCTION;
} else if(stepper->sym != SYM_INSTRUCTION) {
if(stepper->token[0] == 'v' && isxdigit(stepper->token[1]) && !stepper->token[2])
stepper->sym = SYM_REGISTER;
else if(!strcmp(stepper->token, "i"))
stepper->sym = SYM_I;
else if(!strcmp(stepper->token, "dt"))
stepper->sym = SYM_DT;
else if(!strcmp(stepper->token, "st"))
stepper->sym = SYM_ST;
else if(!strcmp(stepper->token, "k"))
stepper->sym = SYM_K;
else if(!strcmp(stepper->token, "f"))
stepper->sym = SYM_F;
else if(!strcmp(stepper->token, "b"))
stepper->sym = SYM_B;
else if(!strcmp(stepper->token, "hf"))
stepper->sym = SYM_HF;
else if(!strcmp(stepper->token, "r"))
stepper->sym = SYM_R;
else if(!strcmp(stepper->token, "define"))
stepper->sym = SYM_DEFINE;
else if(!strcmp(stepper->token, "offset"))
stepper->sym = SYM_OFFSET;
else if(!strcmp(stepper->token, "db"))
stepper->sym = SYM_DB;
else if(!strcmp(stepper->token, "dw"))
stepper->sym = SYM_DW;
else if(!strcmp(stepper->token, "text"))
stepper->sym = SYM_TEXT;
else if(!strcmp(stepper->token, "include"))
stepper->sym = SYM_INCLUDE;
else {
if (is_arith(*stepper->in)){
char arith_exp[64];
copy_arithmetic_expression(arith_exp, &stepper->in);
strcat (stepper->token,arith_exp);
stepper->sym=SYM_NUMBER;
} else {
stepper->sym = SYM_IDENTIFIER;
for(int i = 0; i < n_defs; i++) {
if(!strcmp(defs[i].name, stepper->token)) {
stepper->sym = defs[i].type;
strcpy(stepper->token, defs[i].value);
break;
}
}
}
}
}
} else if(is_arith(*stepper->in) ) {
copy_arithmetic_expression(stepper->token, &stepper->in);
stepper->sym = SYM_NUMBER;
} else if(*stepper->in == '\"') {
stepper->in++;
for(;;) {
if(!*stepper->in || strchr("\r\n", *stepper->in))
exit_error("error:%d: unterminated string literal\n", stepper->linenum);
if(*stepper->in == '\"') break;
if(*stepper->in == '\\') {
switch(*(++stepper->in)) {
case '\r':
case '\n':
case '\0':
exit_error("error:%d: bad escape in string literal\n", stepper->linenum);
case 'a': *tok++ = '\a'; break;
case 'b': *tok++ = '\b'; break;
case 'e': *tok++ = 0x1B; break;
case 'v': *tok++ = '\v'; break;
case 'f': *tok++ = '\f'; break;
case 'n': *tok++ = '\n'; break;
case 'r': *tok++ = '\r'; break;
case 't': *tok++ = '\t'; break;
case '\\': *tok++ = '\\'; break;
default: *tok++ = *stepper->in; break;
}
stepper->in++;
} else
*tok++ = *(stepper->in++);
if(tok - stepper->token >= TOK_SIZE) {
exit_error("error:%d: string too long (max:%d).\n", stepper->linenum, TOK_SIZE-1);
}
}
*tok = '\0';
stepper->in++;
stepper->sym = SYM_STRING;
} else {
stepper->token[0] = *stepper->in;
stepper->token[1] = '\0';
stepper->sym = *stepper->in++;
}
return stepper->sym;
}
void expect(Stepper * stepper, int what) {
SYMBOL sym = nextsym(stepper);
if(sym != what)
exit_error("error:%d: '%c' expected (got %d)\n", stepper->linenum, what, sym);
nextsym(stepper);
}
static int get_register(const Stepper * stepper) {
int reg = stepper->token[1];
if(stepper->sym != SYM_REGISTER)
exit_error("error:%d: register expected\n", stepper->linenum);
assert(isxdigit(reg));
if(reg >= 'a') {
reg = reg - 'a' + 0xA;
} else {
reg -= '0';
}
assert(reg >= 0 && reg <= 0xF);
return reg;
}
static int get_num(char *token, size_t nibble_count, const int linenum) {
int a = evaluate_arithmetic_expression(token, linenum);
int bound=1<<(4*nibble_count);
if(a < -(bound/2) || a > (bound-1)){
char format[128];
sprintf(format,"error:%%d: number %%d takes more than %zd nibbles (%%0%zdX)\n",nibble_count,nibble_count);
exit_error(format, linenum, a, a);
}
return a&(bound-1);
}
static int c8_assemble_internal(Stepper *stepper);
int c8_assemble(const char *text) {
if(c8_verbose) c8_message("Assembling...\n");
program.max_instr = 0;
static Stepper theStepper;
Stepper *stepper = &theStepper;
stepper->in = text;
stepper->linenum = 1;
stepper->last = NULL;
memset(program.bytes, 0, sizeof program);
program.next_instr = 512;
n_lookup = 0;
n_defs = 0;
int r = c8_assemble_internal(stepper);
if(r)
return r;
if(c8_verbose)
c8_message("Resolving labels...\n");
size_t n = PROG_OFFSET;
bool success=false;
for(int i = PROG_OFFSET; i < program.max_instr; i++) {
uint16_t result=0;
if(program.bytes[i].type & EXPRESSION_BITMASK) {
result = get_num(program.bytes[i].expression, (program.bytes[i].type & BITNESS_BITMASK)+1,program.bytes[i].linenum);
}
if ((program.bytes[i].type != CONTINUED) && (program.bytes[i].type & EMIT8_BITMASK)) {
program.bytes[i].byte |= result &0xff;
} else {
program.bytes[i].byte |= result >> 8;
program.bytes[i+1].byte |= result & 0xff;
}
if(c8_verbose > 1) {
if(!(i & 0x01))
c8_message("%03X: %02X", i, program.bytes[i].byte);
else
c8_message("%02X\n", program.bytes[i].byte);
}
c8_set(n++, program.bytes[i].byte);
}
//Stupid Off by one
if (program.max_instr < TOTAL_RAM && program.bytes[program.max_instr].byte != 0){
c8_set(n++, program.bytes[program.max_instr].byte);
}
if(c8_verbose > 1 && success)
c8_message("\n");
if(c8_verbose) c8_message("Assembled; %d bytes.\n", program.max_instr - PROG_OFFSET);
return 0;
}
int c8_assemble_internal(Stepper *stepper) {
nextsym(stepper);
while(stepper->sym != SYM_END) {
switch(stepper->sym){
/**
* ## Directives
*
* ### define
*
* Syntax: `define ID VALUE`
*
* Associates a value with an identifier.
*
* For example, definitions like these
*
* ```
* ; Sprite X,Y position
* define sprite_x V0
* define sprite_y V1
* ```
*
* will cause the identifiers `sprite_x` and `sprite_y` to be associated with the
* registers `V0` and `V1`
*
*/
case SYM_DEFINE:
{
char name[TOK_SIZE];
nextsym(stepper);
/* "Identifier expected" may also mean that the name has
already been used, eg. if aaa is already defined as 123
then define aaa 456 looks like define 123 456 */
if(stepper->sym != SYM_IDENTIFIER)
exit_error("error:%d: identifier expected, found %s\n", stepper->linenum, stepper->token);
strcpy(name,stepper->token);
nextsym(stepper); /*
if(stepper->sym != SYM_NUMBER && stepper->sym != SYM_REGISTER)
exit_error("error:%d: value expected\n", stepper->linenum);
*/
add_definition(stepper, name);
nextsym(stepper);
}
break;
/**
* ### offset
*
* Syntax: `offset EXPRESSION`
*
* Determines where in the program memory the next instruction will be emitted
*
* For example, the statement
*
* ```
* offset #280
* ```
*
* will cause the next bytes emitted by the assembler to start at 0x280
*
* The initial value is 0x200 (512), which is the default starting address
* for Chip8 programs.
*/
case SYM_OFFSET:
nextsym(stepper);
if(stepper->sym != SYM_NUMBER)
exit_error("error:%d: offset expected\n", stepper->linenum);
program.next_instr = get_num(stepper->token,3,stepper->linenum);
nextsym(stepper);
break;
/**
* ### db
*
* Syntax: `db byte, byte, byte, ...`
*
* Emits a sequence of bytes.
*
* For example, this is how you create a sprite's graphic
* by emitting a sequence of bytes:
*
* ```
* sprite1:
* db %01111110,
* %10000001,
* %10100101,
* %10111101,
* %10111101,
* %10011001,
* %10000001,
* %01111110,
* ```
*
* (the label `sprite1` allows you to find those bytes later
* through a `LD I, sprite1` instruction)
*
*/
case SYM_DB:
do {
nextsym(stepper);
if(stepper->sym == SYM_END)
break;
if(stepper->sym != SYM_NUMBER)
exit_error("error:%d: byte value expected\n", stepper->linenum);
Emitted e={/*
.type=ET_IMM8,
.value.imm8=get_num(stepper,2),
.tlabel=LT_NONE*/
.type=ET_EXP8_EMIT8,
.value=0
};
emit(stepper,e);
nextsym(stepper);
} while(stepper->sym == ',');
break;
/**
* ### `dw`
*
* Syntax: `dw word, word, word, ...`
*
* Like `db`, but emits a sequence of 16-bit words.
*
*/
case SYM_DW:
do {
nextsym(stepper);
if(stepper->sym == SYM_END)
break;
if(stepper->sym != SYM_NUMBER && stepper->sym != SYM_IDENTIFIER)
exit_error("error:%d: byte value expected\n", stepper->linenum);
emit_e(stepper,0, 4);
nextsym(stepper);
} while(stepper->sym == ',');
break;
/**
* ### text
*
* Syntax: `text "A String"`
*
* Writes all the bytes in the string, terminated with a null (`'\0'`) character, to the output.
*
* For example `text "hello"` is equivalent to `db #68, #65, #6C, #6C, #6F, #00`.
*/
case SYM_TEXT: {
nextsym(stepper);
if(stepper->sym != SYM_STRING)
exit_error("error:%d: string value expected\n", stepper->linenum);
Emitted e = { .type=EMIT8_BITMASK };
for(char *c = stepper->token; *c; c++) {
e.value = *c;
emit(stepper, e);
}
e.value = '\0';
emit(stepper, e);
nextsym(stepper);
} break;
/**
* ### include
*
* Syntax: `include "filename"`
*
* Assembles file `filename` and adds the results to the output bytecode.
*
*/
case SYM_INCLUDE: {
nextsym(stepper);
if(stepper->sym != SYM_STRING)
exit_error("error:%d: file name expected\n", stepper->linenum);
if(c8_verbose)
c8_message("including '%s'\n", stepper->token);
if(!c8_include_callback) {
exit_error("error:%d: `include` directive disabled\n", stepper->linenum);