/
9.c
165 lines (135 loc) · 2.49 KB
/
9.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_STR_LEN 500
char Look;
void GetChar(){
Look = getchar();
}
//report error
void Error(char *err_msg){
printf("Error : %s.", err_msg);
}
//report error and halt
void Abort(char *err_msg){
Error(err_msg);
exit(EXIT_FAILURE);
}
//report what was expected
void Expected(char *s){
char buf[MAX_STR_LEN];
snprintf(buf, sizeof(buf), "%s Expected", s);
Abort(buf);
}
//match a specific input character
void Match(char c){
if(Look == c) GetChar();
else {
char buf[MAX_STR_LEN];
snprintf(buf, sizeof(buf), "\"%c\"", c);
Expected(buf);
}
}
//get an identifier
char GetName(){
if(!isalpha(Look)) Expected("Name");
char ret = toupper(Look);
GetChar();
return ret;
}
//get a number
char GetNum(){
if(!isdigit(Look)) Expected("Integer");
int ret = Look;
GetChar();
return ret;
}
int isAddop(char c){
return c == '+' || c == '-';
}
int IsWhite(char c){
return c == ' ' || c == '\t';
}
void SkipWhite(){
while(IsWhite(Look)) GetChar();
}
//output a string with tab
void Emit(char *s){
printf("\t%s", s);
}
//output a string with tab and CRLF
void EmitLn(char *s){
printf("\t%s\n", s);
}
void PostLabel(char label){
printf("%c : \n", label);
}
void Statements(){
Match('b');
while(Look != 'e')
GetChar();
Match('e');
}
void Labels(){
Match('l');
}
void Constants(){
Match('c');
}
void Types(){
Match('t');
}
void Variables(){
Match('v');
}
void DoProcedure(){
Match('p');
}
void DoFunction(){
Match('f');
}
void Declarations(){
int other = 0;
while(!other){
switch(Look){
case 'l' : Labels(); break;
case 'c' : Constants(); break;
case 't' : Types(); break;
case 'v' : Variables(); break;
case 'p' : DoProcedure(); break;
case 'f' : DoFunction(); break;
default : other = 1;
}
}
}
void DoBlock(char name){
Declarations();
PostLabel(name);
Statements();
}
void Epilog(char name){
EmitLn("DC WARMST");
char buf[MAX_STR_LEN];
snprintf(buf, sizeof(buf), "END %c", name);
EmitLn(buf);
}
void Prolog(){
EmitLn("WARMST EQU $A01E");
}
void Program(){
Match('p');
char name = GetName();
Prolog(name);
DoBlock(name);
Match('.');
Epilog(name);
}
void Init(){
GetChar();
}
int main(){
Init();
Program();
return 0;
}