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