d8d8bc61be4fe83061e556dc49d61efee28cfc27
[YACASL2.git] / src / assemble.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <ctype.h>
5 #include <assert.h>
6
7 #include "assemble.h"
8 #include "cerr.h"
9
10 /**
11  * アセンブルモード: src, label, onlylabel, asdetail, onlyassemble
12  */
13 ASMODE asmode = {false, false, false, false, false};
14
15 /**
16  * アセンブル時の、現在およびリテラルのアドレスとプログラム入口名: ptr, lptr, prog
17  */
18 ASPTR *asptr;
19
20 /**
21  * アセンブルのエラー定義
22  */
23 static CERR cerr_assemble[] = {
24     { 106, "operand mismatch in assemble command" },
25     { 107, "no label in START" },
26     { 108, "not command of operand \"r\"" },
27     { 109, "not command of operand \"r1,r2\"" },
28     { 110, "not command of operand \"r,adr[,x]\"" },
29     { 111, "not command of operand \"adr[,x]\"" },
30     { 112, "not command of no operand" },
31     { 113, "operand too many in COMET II command" },
32     { 119, "out of COMET II memory" },
33     { 120, "GR0 in operand x" },
34     { 122, "cannot create hash table" },
35     { 124, "more than one character in literal" },
36     { 125, "not GR in operand x" },
37 };
38
39 WORD getadr(const char *prog, const char *str, PASS pass);
40
41 WORD getgr(const char *str, bool is_x);
42
43 WORD getliteral(const char *str, PASS pass);
44
45 bool assemblecmd(const CMDLINE *cmdl, PASS pass);
46
47 bool macrocmd(const CMDLINE *cmdl, PASS pass);
48
49 void writeIN(const char *ibuf, const char *len, PASS pass);
50
51 void writeOUT(const char *obuf, const char *len, PASS pass);
52
53 void writeRPUSH(PASS pass);
54
55 void writeRPOP(PASS pass);
56
57 bool cometcmd(const CMDLINE *cmdl, PASS pass);
58
59 void writememory(WORD word, WORD adr, PASS pass);
60
61 void writestr(const char *str, bool literal, PASS pass);
62
63 void writeDC(const char *str, PASS pass);
64
65 bool assembletok(const CMDLINE *cmdl, PASS pass);
66
67 bool assembleline(const char *line, PASS pass);
68
69 void printline(FILE *stream, const char *filename, int lineno, char *line);
70
71 /**
72  * 汎用レジスタを表す文字列「GR[0-7]」から、レジスタ番号[0-7]をWORD値で返す
73  * 文字列が汎用レジスタを表さない場合は、0xFFFFを返す
74  * is_xがtrueの場合は指標レジスタ。GR0が指定された場合は、COMET IIの仕様によりエラー発生
75  */
76 WORD getgr(const char *str, bool is_x)
77 {
78     assert(str != NULL);
79     WORD r;
80
81     /* 「GR[0-7]」以外の文字列では、0xFFFFを返して終了 */
82     if(!(strlen(str) == 3 && strncmp(str, "GR", 2) == 0 &&
83          (*(str+2) >= '0' && *(str+2) <= '0' + (GRSIZE - 1))))
84     {
85         return 0xFFFF;
86     }
87     r = (WORD)(*(str+2) - '0');
88     /* GR0は指標レジスタとして用いることができない */
89     if(is_x == true && r == 0x0) {
90         setcerr(120, NULL);    /* GR0 in operand x */
91         return 0x0;
92     }
93     return r;
94 }
95
96 /**
97  * 定数の前に等号(=)をつけて記述されるリテラルを返す
98  * リテラルには、10進定数/16進定数/文字定数が含まれる
99  */
100 WORD getliteral(const char *str, PASS pass)
101 {
102     assert(*str == '=');
103     WORD adr = asptr->lptr;
104
105     if(*(++str) == '\'') {    /* 文字定数 */
106         writestr(str, true, pass);
107     } else {
108         writememory(nh2word(str), (asptr->lptr)++, pass);
109     }
110     return adr;
111 }
112
113 /**
114  * アセンブラ命令をメモリに書込
115  * アセンブラ命令の場合はtrue、それ以外の場合はfalseを返す
116  */
117 bool assemblecmd(const CMDLINE *cmdl, PASS pass)
118 {
119     int i = 0;
120     ASCMDID cmdid = 0;
121     ASCMD ascmd[] = {
122         { START, 0, 1, "START" },
123         { END, 0, 0, "END" },
124         { DC, 1, OPDSIZE, "DC" },
125         { DS, 1, 1, "DS" },
126         { 0, 0, 0, NULL }
127     };
128
129     do {
130         if(strcmp(cmdl->cmd, ascmd[i].cmd) == 0) {
131             if(cmdl->opd->opdc < ascmd[i].opdc_min || cmdl->opd->opdc > ascmd[i].opdc_max) {
132                 setcerr(106, NULL);    /* operand count mismatch */
133                 return true;
134             }
135             cmdid = ascmd[i].cmdid;
136             break;
137         }
138     } while(ascmd[++i].cmdid != 0);
139     /* アセンブラ命令 */
140     switch(cmdid)
141     {
142     case START:
143         if(cmdl->label == NULL) {
144             setcerr(107, NULL);    /* no label in START */
145             return true;
146         }
147         /* プログラム名の設定 */
148         asptr->prog = strdup_chk(cmdl->label, "asptr.prog");
149         /* オペランドがある場合、実行開始アドレスを設定 */
150         if(pass == SECOND && cmdl->opd->opdc == 1) {
151             if((execptr->start = getlabel(asptr->prog, cmdl->opd->opdv[0])) == 0xFFFF) {
152                 setcerr(103, cmdl->opd->opdv[0]);    /* label not found */
153             }
154         }
155         break;
156     case END:
157         /* 1回目のアセンブルの場合は、リテラル領域開始アドレスを設定 */
158         if(pass == FIRST) {
159             asptr->lptr = asptr->ptr;
160         }
161         /* 2回目のアセンブルの場合は、リテラル領域終了アドレスを実行終了アドレスとして設定 */
162         else if(pass == SECOND) {
163             execptr->end = asptr->lptr;
164         }
165         FREE(asptr->prog);
166         break;
167     case DS:
168         for(i = 0; i < atoi(cmdl->opd->opdv[0]); i++) {
169             writememory(0x0, (asptr->ptr)++, pass);
170             if(cerr->num > 0) {
171                 break;
172             }
173         }
174         break;
175     case DC:
176         for(i = 0; i < cmdl->opd->opdc; i++) {
177             writeDC(cmdl->opd->opdv[i], pass);
178             if(cerr->num > 0) {
179                 break;
180             }
181         }
182         break;
183     default:
184         return false;
185     }
186     return true;
187 }
188
189 /**
190  *  macrocmd
191  * マクロ命令をメモリに書込
192  * マクロ命令の場合はtrue、それ以外の場合はfalseを返す
193  */
194 bool macrocmd(const CMDLINE *cmdl, PASS pass)
195 {
196     int i = 0;
197     MACROCMDID cmdid = 0;
198     MACROCMD macrocmd[] = {
199         { IN, 2, 2, "IN" },
200         { OUT, 2, 2, "OUT" },
201         { RPUSH, 0, 0, "RPUSH" },
202         { RPOP, 0, 0, "RPOP" },
203         { 0, 0, 0, NULL }
204     };
205
206     do {
207         if(strcmp(cmdl->cmd, macrocmd[i].cmd) == 0) {
208             if(cmdl->opd->opdc < macrocmd[i].opdc_min ||
209                cmdl->opd->opdc > macrocmd[i].opdc_max)
210             {
211                 setcerr(106, NULL);    /* operand count mismatch */
212                 return true;
213             }
214             cmdid = macrocmd[i].cmdid;
215             break;
216         }
217     } while(macrocmd[++i].cmdid != 0);
218     switch(cmdid)
219     {
220     case IN:
221         writeIN(cmdl->opd->opdv[0], cmdl->opd->opdv[1], pass);
222         break;
223     case OUT:
224         writeOUT(cmdl->opd->opdv[0], cmdl->opd->opdv[1], pass);
225         break;
226     case RPUSH:
227         writeRPUSH(pass);
228         break;
229     case RPOP:
230         writeRPOP(pass);
231         break;
232     default:
233         return false;
234     }
235     return true;
236 }
237
238 /**
239  * マクロ命令「IN IBUF,LEN」をメモリに書込
240  *      PUSH 0,GR1
241  *      PUSH 0,GR2
242  *      LAD GR1,IBUF
243  *      LAD GR2,LEN
244  *      SVC 1
245  *      POP GR2
246  *      POP GR1
247  */
248 void writeIN(const char *ibuf, const char *len, PASS pass)
249 {
250     char *line = malloc_chk(LINESIZE + 1, "writeIN.line");
251
252     assembleline("    PUSH 0,GR1", pass);
253     assembleline("    PUSH 0,GR2", pass);
254     sprintf(line, "    LAD GR1,%s", ibuf);
255     assembleline(line, pass);
256     sprintf(line, "    LAD GR2,%s", len);
257     assembleline(line, pass);
258     assembleline("    SVC 1", pass);
259     assembleline("    POP GR2", pass);
260     assembleline("    POP GR1", pass);
261
262     FREE(line);
263 }
264
265 /**
266  *  マクロ命令「OUT OBUF,LEN」をメモリに書込
267  *      PUSH 0,GR1
268  *      PUSH 0,GR2
269  *      LAD GR1,OBUF
270  *      LAD GR2,LEN
271  *      SVC 2
272  *      LAD GR1,=#A
273  *      LAD GR2,=1
274  *      SVC 2
275  *      POP GR2
276  *      POP GR1
277  */
278 void writeOUT(const char *obuf, const char *len, PASS pass)
279 {
280     char *line = malloc_chk(LINESIZE + 1, "writeOUT.line");
281
282     assembleline("    PUSH 0,GR1", pass);
283     assembleline("    PUSH 0,GR2", pass);
284     sprintf(line, "    LAD GR1,%s", obuf);
285     assembleline(line, pass);
286     sprintf(line, "    LAD GR2,%s", len);
287     assembleline(line, pass);
288     assembleline("    SVC 2", pass);
289     assembleline("    LAD GR1,=#A", pass);
290     assembleline("    LAD GR2,=1", pass);
291     assembleline("    SVC 2", pass);
292     assembleline("    POP GR2", pass);
293     assembleline("    POP GR1", pass);
294     FREE(line);
295 }
296
297 /** マクロ命令「RPUSH」をメモリに書き込む
298  *       PUSH 0,GR1
299  *       PUSH 0,GR2
300  *       PUSH 0,GR3
301  *       PUSH 0,GR4
302  *       PUSH 0,GR5
303  *       PUSH 0,GR6
304  *       PUSH 0,GR7
305  */
306 void writeRPUSH(PASS pass)
307 {
308     int i;
309     char *line = malloc_chk(LINESIZE + 1, "writeRPUSH.line");
310
311     for(i = 1; i <= GRSIZE-1; i++) {
312         sprintf(line, "    PUSH 0,GR%d", i);
313         assembleline(line, pass);
314     }
315     FREE(line);
316 }
317
318 /**
319  * マクロ命令「RPOP」をメモリに書き込む
320  *      POP GR7
321  *      POP GR6
322  *      POP GR5
323  *      POP GR4
324  *      POP GR3
325  *      POP GR3
326  *      POP GR2
327  *      POP GR1
328  */
329 void writeRPOP(PASS pass)
330 {
331     int i;
332     char *line = malloc_chk(LINESIZE + 1, "writeRPOP.line");
333
334     for(i = GRSIZE-1; i >= 1; i--) {
335         sprintf(line, "    POP GR%d", i);
336         assembleline(line, pass);
337     }
338     FREE(line);
339 }
340
341 /**
342  * 機械語命令をメモリに書込
343  * 書込に、成功した場合はtrue、失敗した場合はfalse、を返す
344  */
345 bool cometcmd(const CMDLINE *cmdl, PASS pass)
346 {
347     WORD cmd, r_r1, x_r2, adr;
348
349     /* オペランドなし */
350     if(cmdl->opd->opdc == 0) {
351         if((cmd = getcmdcode(cmdl->cmd, NONE)) == 0xFFFF) {
352             setcerr(112, cmdl->cmd);    /* not command of no operand */
353             return false;
354         }
355         writememory(cmd, (asptr->ptr)++, pass);
356     }
357     /* 第1オペランドは汎用レジスタ */
358     else if((r_r1 = getgr(cmdl->opd->opdv[0], false)) != 0xFFFF) {
359         /* オペランド数1 */
360         if(cmdl->opd->opdc == 1) {
361             if((cmd = getcmdcode(cmdl->cmd, R_)) == 0xFFFF) {
362                 setcerr(108, cmdl->cmd);    /* not command of operand "r" */
363                 return false;
364             }
365             cmd |= (r_r1 << 4);
366             writememory(cmd, (asptr->ptr)++, pass);
367         }
368         /* オペランド数2。第2オペランドは汎用レジスタ */
369         else if(cmdl->opd->opdc == 2 && (x_r2 = getgr(cmdl->opd->opdv[1], false)) != 0xFFFF) {
370             if((cmd = getcmdcode(cmdl->cmd, R1_R2)) == 0xFFFF) {
371                 setcerr(109, cmdl->cmd);    /* not command of operand "r1,r2" */
372                 return false;
373             }
374             cmd |= ((r_r1 << 4) | x_r2);               /* 第1オペランド、第2オペランドともに汎用レジスタ */
375             /* メモリへの書き込み */
376             writememory(cmd, (asptr->ptr)++, pass);
377         }
378         /* オペランド数2または3 */
379         else if(cmdl->opd->opdc == 2 || cmdl->opd->opdc == 3) {
380             if((cmd = getcmdcode(cmdl->cmd, R_ADR_X)) == 0xFFFF) {
381                 setcerr(110, cmdl->cmd);    /* not command of operand "r,adr[,x]" */
382                 return false;
383             }
384             cmd |= (r_r1 << 4);                    /* 第1オペランドは汎用レジスタ */
385             /* オペランド数3の場合 */
386             if(cmdl->opd->opdc == 3) {             /* 第3オペランドは指標レジスタとして用いる汎用レジスタ */
387                 if((x_r2 = getgr(cmdl->opd->opdv[2], true)) == 0xFFFF) {
388                     setcerr(125, cmdl->cmd);    /* not GR in operand x */
389                     return false;
390                 }
391                 cmd |= x_r2;
392             }
393             adr = getadr(asptr->prog, cmdl->opd->opdv[1], pass); /* 第2オペランドはアドレス */
394             /* メモリへの書き込み */
395             writememory(cmd, (asptr->ptr)++, pass);
396             writememory(adr, (asptr->ptr)++, pass);
397         } else {
398             setcerr(113, cmdl->cmd);    /* operand too many in COMET II command */
399             return false;
400         }
401     }
402     /* オペランド数1または2。第1オペランドはアドレス */
403     else if(cmdl->opd->opdc == 1 || cmdl->opd->opdc == 2) {
404         if((cmd = getcmdcode(cmdl->cmd, ADR_X)) == 0xFFFF) {
405             setcerr(111, cmdl->cmd);    /* not command of operand "adr[,x]" */
406             return false;
407         }
408         /* オペランド数2の場合 */
409         if(cmdl->opd->opdc == 2) {             /* 第2オペランドは指標レジスタとして用いる汎用レジスタ */
410             x_r2 = getgr(cmdl->opd->opdv[1], true);
411             if(cerr->num > 0) {
412                 return false;
413             }
414             cmd |= x_r2;
415         }
416         /* CALLの場合はプログラムの入口名を表すラベルを取得 */
417         /* CALL以外の命令の場合と、プログラムの入口名を取得できない場合は、 */
418         /* 同一プログラム内のラベルを取得 */
419         if(pass == SECOND && cmd == 0x8000) {        /* CALL命令 */
420             adr = getlabel(NULL, cmdl->opd->opdv[0]);
421         }
422         if(cmd != 0x8000 || (pass == SECOND && adr == 0xFFFF)) {
423             adr = getadr(asptr->prog, cmdl->opd->opdv[0], pass);
424         }
425         /* メモリへの書き込み */
426         writememory(cmd, (asptr->ptr)++, pass);
427         writememory(adr, (asptr->ptr)++, pass);
428     }
429     return (cerr->num == 0) ? true : false;
430 }
431
432 /**
433  * COMET IIのメモリにアドレス値を書き込む
434  */
435 void writememory(WORD word, WORD adr, PASS pass)
436 {
437     /* COMET IIメモリオーバーの場合、エラー発生 */
438     if(adr >= sys->memsize) {
439         setcerr(119, word2n(adr));    /* out of COMET II memory */
440         return;
441     }
442     (sys->memory)[adr] = word;
443     if(pass == SECOND && asmode.asdetail == true) {
444         fprintf(stdout, "\t#%04X\t#%04X\n", adr, word);
445     }
446 }
447
448 /**
449  * 文字をメモリに書き込む
450  */
451 void writestr(const char *str, bool literal, PASS pass)
452 {
453     assert(*str == '\'');
454     const char *p = str + 1;
455     bool lw = false;
456
457     for(; ;) {
458         /* 閉じ「'」がないまま文字列が終了した場合 */
459         if(*p == '\0') {
460             setcerr(123, str);    /* unclosed quote */
461             break;
462         }
463         /* 「'」の場合、次の文字が「'」でない場合は正常終了 */
464         if(*p == '\'' && *(++p) != '\'') {
465             break;
466         } else if(literal == true && lw == true) {
467             setcerr(124, str);    /* more than one character in literal */
468             break;
469         }
470         /*リテラルの場合はリテラル領域に書込 */
471         if(literal == true) {
472             writememory(*(p++), (asptr->lptr)++, pass);
473             lw = true;
474         } else {
475             writememory(*(p++), (asptr->ptr)++, pass);
476         }
477     }
478 }
479
480 /**
481  * DC命令の内容を書き込む
482  */
483 void writeDC(const char *str, PASS pass)
484 {
485     WORD adr = 0x0;
486
487     if(*str == '\'') {
488         writestr(str, false, pass);
489     } else {
490         if(*str == '#' || isdigit(*str) || *str == '-') {
491             adr = nh2word(str);
492         } else {
493             if(pass == SECOND && (adr = getlabel(asptr->prog, str)) == 0xFFFF) {
494                 setcerr(103, str);    /* label not found */
495             }
496         }
497         writememory(adr, (asptr->ptr)++, pass);
498     }
499 }
500
501 /**
502  * トークンをアセンブル
503  */
504 bool assembletok(const CMDLINE *cmdl, PASS pass)
505 {
506     /* 命令がない場合 */
507     if(cmdl->cmd == NULL){
508         return true;
509     }
510     /* アセンブラ命令またはマクロ命令の書込 */
511     if(assemblecmd(cmdl, pass) == false && macrocmd(cmdl, pass) == false) {
512         /* COMET II命令の書込 */
513         if(cometcmd(cmdl, pass) == false && cerr->num == 0) {
514             setcerr(113, cmdl->cmd);    /* operand too many in COMET II command */
515         }
516     }
517     return (cerr->num == 0) ? true : false;
518 }
519
520 /**
521  * ファイルストリームの現在行を番号付きで表示する
522  */
523 void printline(FILE *stream, const char *filename, int lineno, char *line)
524 {
525     fprintf(stream, "%s:%5d:%s", filename, lineno, line);
526 }
527
528 /**
529  * アドレスを返す
530  * アドレスには、リテラル/10進定数/16進定数/アドレス定数が含まれる
531  */
532 WORD getadr(const char *prog, const char *str, PASS pass)
533 {
534     WORD adr = 0x0;
535
536     if(*str == '=') {
537         adr = getliteral(str, pass);
538     } else if(isdigit(*str) || *str == '-' || *str == '#') {
539         adr = nh2word(str);
540     } else {
541         if(pass == SECOND && (adr = getlabel(prog, str)) == 0xFFFF) {
542             if(prog != NULL) {
543                 setcerr(103, str);    /* label not found */
544             }
545         }
546     }
547     return adr;
548 }
549
550
551 /**
552  * 1行をアセンブル
553  * passが1の場合はラベルを登録し、2の場合はラベルからアドレスを読み込む
554  */
555 bool assembleline(const char *line, PASS pass)
556 {
557     CMDLINE *cmdl;
558     bool stat = true;
559     int i;
560
561     cmdl = linetok(line);
562     stat = (cerr->num == 0) ? true : false;
563     if(cmdl != NULL) {
564         if(stat == true) {
565             if(pass == FIRST && cmdl->label != NULL) {
566                 stat = addlabel(asptr->prog, cmdl->label, asptr->ptr);
567             }
568             if(stat == true) {
569                 stat = assembletok(cmdl, pass);
570             }
571             FREE(cmdl->label);
572         }
573         if(cmdl->opd != NULL) {
574             for(i = 0; i < cmdl->opd->opdc; i++) {
575                 FREE(cmdl->opd->opdv[i]);
576             }
577         }
578         FREE(cmdl->opd);
579         FREE(cmdl->cmd);
580     }
581     FREE(cmdl);
582     return stat;
583 }
584
585 /**
586  * アセンブルのエラーをエラーリストに追加
587  */
588 void addcerrlist_assemble()
589 {
590     addcerrlist_tok();
591     addcerrlist_word();
592     addcerrlist_label();
593     addcerrlist(ARRAYSIZE(cerr_assemble), cerr_assemble);
594 }
595
596 /**
597  * 指定された名前のファイルをアセンブル
598  * アセンブル完了時はtrue、エラー発生時はfalseを返す
599  */
600 bool assemblefile(const char *file, PASS pass)
601 {
602     int lineno = 1;
603     char *line;
604     FILE *fp;
605
606     if((fp = fopen(file, "r")) == NULL) {
607         perror(file);
608         return false;
609     }
610     for(line = malloc_chk(LINESIZE + 1, "assemble.line"); fgets(line, LINESIZE, fp); lineno++) {
611         if((pass == FIRST && asmode.src == true) || (pass == SECOND && asmode.asdetail == true)) {
612             printline(stdout, file, lineno, line);
613         }
614         if(assembleline(line, pass) == false) {
615             break;
616         }
617     }
618     if(cerr->num > 0) {
619         fprintf(stderr, "Assemble error - %d: %s\n", cerr->num, cerr->msg);
620         printline(stderr, file, lineno, line);
621     }
622     FREE(line);
623     fclose(fp);
624     return (cerr->num == 0) ? true : false;
625 }
626
627 /**
628  * 引数で指定したファイルにアセンブル結果を書込
629  */
630 void outassemble(const char *file)
631 {
632     FILE *fp;
633
634     if((fp = fopen(file, "w")) == NULL) {
635         perror(file);
636         exit(-1);
637     }
638     fwrite(sys->memory, sizeof(WORD), execptr->end, fp);
639     fclose(fp);
640 }