├── LICENSE
├── README.md
└── cc500.c
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | cc500
2 | =====
3 |
4 | CC500: a tiny self-hosting C compiler
5 |
6 | http://homepage.ntlworld.com/edmund.grimley-evans/cc500/
7 |
8 |
9 | CC500: a tiny self-hosting C compiler
10 |
11 | Introduction
12 |
13 | I wrote this tiny compiler, which translates a subset of C into x86 machine code, for fun. It has no use, unless it counts as educational. I called it CC500 because I initally guessed it would take about 500 lines. It turned out to be about 600 lines even without the comments and blank lines. With the comments and blank lines it has about 750 lines. It could be made shorter, but I wanted the code to be clear and simple rather than obfuscated.
14 |
15 | Download
16 |
17 | cc500.c - just the code
18 | Compilation:
19 |
20 | gcc cc500.c -o cc500_1
21 | Self-compilation:
22 |
23 | ./cc500_1 < cc500.c > cc500_2
24 | chmod +x cc500_2
25 | How it works
26 |
27 | The compiler reads the whole program in C from stdin and writes an ELF binary for Linux/x86 to stdout. The ELF binary is somewhat non-standard as it consists of a single section that is both writable and executable. It seems to work for me on a real Linux box, but it might cause problems on an emulator.
28 |
29 | No libraries are used. Tiny, machine-code implementations of exit(), getchar(), malloc() and putchar() are included in the binary that is generated. There is no free() as malloc() is just sbrk(), really, implemented with two calls to brk().
30 |
31 | There is almost no error-checking. With some invalid C programs the compiler calls exit(1) instead of generating a binary, but in most cases it generates a binary that crashes when you run it.
32 |
33 | There is no preprocessor. The lexer looks for tokens that match one of the following Perl regular expressions: /[a-z0-9_]+/, /[<=>|&!]+/, /'[^']*'/, /"[^"]*"/, /./. Traditional C-style comments are handled, but not C++-style comments.
34 |
35 | The symbol table is implemented with a single array of char. The type of each symbol is recorded as 'D' (defined global), 'U' (undefined global), 'L' (local variable) or 'A' (argument of a function) - see sym_get_value(). There is also an address recorded for each symbol, but no type, as there is no type-checking and all arrays are assumed to be arrays of char. The address of an 'L' or 'A' is its position on the stack. The address of a 'D' is the position of that function or global variable in the binary. The address of a 'U' is also a pointer into the binary, but a pointer to where the symbol was last used and the head of a linked list of all the forward references to that symbol.
36 |
37 | Scoping rules for local variables are implemented correctly as it is easy to do so: at the end of a compound statement the pointer to the end of the symbol table is restored to what it was at the start of the compound statement - see the assignment to table_pos in statement().
38 |
39 | I started off writing CC500 without local variables, but it felt very unnatural. Nested scopes are an essential part of C and it is not easy to write a recursive-descent parser without automatic variables.
40 |
41 | It is assumed that all variables, arguments and return values are char * or int, though the compiler does not even parse the types, let alone record them in the symbol table. The functions that implement the recursive-descent parser return 1, 2 or 3, corresponding to a "char lval", "int lval" or "other" - see promote().
42 |
43 | Each parsing function is preceded by a comment that documents the syntactic structures recognised, in an obvious notation. In some cases the code accepts additional, incorrect structures in addition to what is documented in the comment. Only a tiny subset of C's operators are accepted: just the ones I needed while writing the compiler. There are no unary operators: instead of the indirection operator * you must use x[y], where it is assumed that x is char * and y is int. The only statements recognised are compound statements, expressions, if, while and return. Local variable declarations, with initialisers, are treated as a kind of statement. (If you write something like if (x) int y; the compiler will not complain, but the binary will crash.)
44 |
45 | There are no arbitary limits on the length of symbols, number of symbols are the like: all three buffers (token, table and code) are supposed to be automatically extended as required by calls to my_realloc().
46 |
47 | Extending it
48 |
49 | Some simple and obvious enhancements would be to print an appropriate message message when an error is detected, check for undefined globals, and allow main() to be anywhere in the file.
50 |
51 | It would be easy to extend the compiler to handle the remaining operators and statement types of C. To implement break and continue you would probably add additional arguments to the parsing functions that record the address and stack height of the current loop. The easiest way to implement switch statements might be to add an argument that records the location of the previous case label in the current switch statement; a case label would then be translated with a comparison and a branch forwards to the next case label. In general, C is quite amenable to direct translation into machine code without going through an IR (intermediate representation).
52 |
53 | Extending the type system would be a bit more challenging. You could correctly implement scalars and pointers, with type checking, by adding a single integer field to the symbol table to record the type. However, if you wanted to implement structs, or function pointers with proper type checking, you would need a recursive data structure to represent the types. It is interesting, but not really surprising, that you start to start to need structs in the implementation language at roughly the same point that you start to implement them. However, C's types get interesting even without structs, unions and typedefs. For example, void (*(*f())(void (*)(void)))(void); declares a function that returns a pointer to a function that takes a pointer to a function as an argument and returns another pointer to a function. I must admit to finding that part of C's syntax rather difficult to parse mentally. I'm glad we have computers to do it for us.
54 |
55 | Links
56 |
57 | bcompiler - Bootstrapping a simple compiler from nothing
58 | OTCC - The smallest self compiling pseudo C compiler
59 | Tiny ELF programs by Brian Raiter
60 | Edmund Grimley Evans
61 |
--------------------------------------------------------------------------------
/cc500.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2006 Edmund GRIMLEY EVANS
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License as published by
6 | * the Free Software Foundation; either version 2 of the License, or
7 | * (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU General Public License
15 | * along with this program; if not, write to the Free Software
16 | * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 | */
18 |
19 | /*
20 | * A self-compiling compiler for a small subset of C.
21 | */
22 |
23 | /* Our library functions. */
24 | void exit(int);
25 | int getchar(void);
26 | void *malloc(int);
27 | int putchar(int);
28 |
29 | /* The first thing defined must be main(). */
30 | int main1();
31 | int main()
32 | {
33 | return main1();
34 | }
35 |
36 | char *my_realloc(char *old, int oldlen, int newlen)
37 | {
38 | char *new = malloc(newlen);
39 | int i = 0;
40 | while (i <= oldlen - 1) {
41 | new[i] = old[i];
42 | i = i + 1;
43 | }
44 | return new;
45 | }
46 |
47 | int nextc;
48 | char *token;
49 | int token_size;
50 |
51 | void error()
52 | {
53 | exit(1);
54 | }
55 |
56 | int i;
57 |
58 | void takechar()
59 | {
60 | if (token_size <= i + 1) {
61 | int x = (i + 10) << 1;
62 | token = my_realloc(token, token_size, x);
63 | token_size = x;
64 | }
65 | token[i] = nextc;
66 | i = i + 1;
67 | nextc = getchar();
68 | }
69 |
70 | void get_token()
71 | {
72 | int w = 1;
73 | while (w) {
74 | w = 0;
75 | while ((nextc == ' ') | (nextc == 9) | (nextc == 10))
76 | nextc = getchar();
77 | i = 0;
78 | while ((('a' <= nextc) & (nextc <= 'z')) |
79 | (('0' <= nextc) & (nextc <= '9')) | (nextc == '_'))
80 | takechar();
81 | if (i == 0)
82 | while ((nextc == '<') | (nextc == '=') | (nextc == '>') |
83 | (nextc == '|') | (nextc == '&') | (nextc == '!'))
84 | takechar();
85 | if (i == 0) {
86 | if (nextc == 39) {
87 | takechar();
88 | while (nextc != 39)
89 | takechar();
90 | takechar();
91 | }
92 | else if (nextc == '"') {
93 | takechar();
94 | while (nextc != '"')
95 | takechar();
96 | takechar();
97 | }
98 | else if (nextc == '/') {
99 | takechar();
100 | if (nextc == '*') {
101 | nextc = getchar();
102 | while (nextc != '/') {
103 | while (nextc != '*')
104 | nextc = getchar();
105 | nextc = getchar();
106 | }
107 | nextc = getchar();
108 | w = 1;
109 | }
110 | }
111 | else if (nextc != 0-1)
112 | takechar();
113 | }
114 | token[i] = 0;
115 | }
116 | }
117 |
118 | int peek(char *s)
119 | {
120 | int i = 0;
121 | while ((s[i] == token[i]) & (s[i] != 0))
122 | i = i + 1;
123 | return s[i] == token[i];
124 | }
125 |
126 | int accept(char *s)
127 | {
128 | if (peek(s)) {
129 | get_token();
130 | return 1;
131 | }
132 | else
133 | return 0;
134 | }
135 |
136 | void expect(char *s)
137 | {
138 | if (accept(s) == 0)
139 | error();
140 | }
141 |
142 | char *code;
143 | int code_size;
144 | int codepos;
145 | int code_offset;
146 |
147 | void save_int(char *p, int n)
148 | {
149 | p[0] = n;
150 | p[1] = n >> 8;
151 | p[2] = n >> 16;
152 | p[3] = n >> 24;
153 | }
154 |
155 | int load_int(char *p)
156 | {
157 | return ((p[0] & 255) + ((p[1] & 255) << 8) +
158 | ((p[2] & 255) << 16) + ((p[3] & 255) << 24));
159 | }
160 |
161 | void emit(int n, char *s)
162 | {
163 | i = 0;
164 | if (code_size <= codepos + n) {
165 | int x = (codepos + n) << 1;
166 | code = my_realloc(code, code_size, x);
167 | code_size = x;
168 | }
169 | while (i <= n - 1) {
170 | code[codepos] = s[i];
171 | codepos = codepos + 1;
172 | i = i + 1;
173 | }
174 | }
175 |
176 | void be_push()
177 | {
178 | emit(1, "\x50"); /* push %eax */
179 | }
180 |
181 | void be_pop(int n)
182 | {
183 | emit(6, "\x81\xc4...."); /* add $(n * 4),%esp */
184 | save_int(code + codepos - 4, n << 2);
185 | }
186 |
187 | char *table;
188 | int table_size;
189 | int table_pos;
190 | int stack_pos;
191 |
192 | int sym_lookup(char *s)
193 | {
194 | int t = 0;
195 | int current_symbol = 0;
196 | while (t <= table_pos - 1) {
197 | i = 0;
198 | while ((s[i] == table[t]) & (s[i] != 0)) {
199 | i = i + 1;
200 | t = t + 1;
201 | }
202 | if (s[i] == table[t])
203 | current_symbol = t;
204 | while (table[t] != 0)
205 | t = t + 1;
206 | t = t + 6;
207 | }
208 | return current_symbol;
209 | }
210 |
211 | void sym_declare(char *s, int type, int value)
212 | {
213 | int t = table_pos;
214 | i = 0;
215 | while (s[i] != 0) {
216 | if (table_size <= t + 10) {
217 | int x = (t + 10) << 1;
218 | table = my_realloc(table, table_size, x);
219 | table_size = x;
220 | }
221 | table[t] = s[i];
222 | i = i + 1;
223 | t = t + 1;
224 | }
225 | table[t] = 0;
226 | table[t + 1] = type;
227 | save_int(table + t + 2, value);
228 | table_pos = t + 6;
229 | }
230 |
231 | int sym_declare_global(char *s)
232 | {
233 | int current_symbol = sym_lookup(s);
234 | if (current_symbol == 0) {
235 | sym_declare(s, 'U', code_offset);
236 | current_symbol = table_pos - 6;
237 | }
238 | return current_symbol;
239 | }
240 |
241 | void sym_define_global(int current_symbol)
242 | {
243 | int i;
244 | int j;
245 | int t = current_symbol;
246 | int v = codepos + code_offset;
247 | if (table[t + 1] != 'U')
248 | error(); /* symbol redefined */
249 | i = load_int(table + t + 2) - code_offset;
250 | while (i) {
251 | j = load_int(code + i) - code_offset;
252 | save_int(code + i, v);
253 | i = j;
254 | }
255 | table[t + 1] = 'D';
256 | save_int(table + t + 2, v);
257 | }
258 |
259 | int number_of_args;
260 |
261 | void sym_get_value(char *s)
262 | {
263 | int t;
264 | if ((t = sym_lookup(s)) == 0)
265 | error();
266 | emit(5, "\xb8...."); /* mov $n,%eax */
267 | save_int(code + codepos - 4, load_int(table + t + 2));
268 | if (table[t + 1] == 'D') { /* defined global */
269 | }
270 | else if (table[t + 1] == 'U') /* undefined global */
271 | save_int(table + t + 2, codepos + code_offset - 4);
272 | else if (table[t + 1] == 'L') { /* local variable */
273 | int k = (stack_pos - table[t + 2] - 1) << 2;
274 | emit(7, "\x8d\x84\x24...."); /* lea (n * 4)(%esp),%eax */
275 | save_int(code + codepos - 4, k);
276 | }
277 | else if (table[t + 1] == 'A') { /* argument */
278 | int k = (stack_pos + number_of_args - table[t + 2] + 1) << 2;
279 | emit(7, "\x8d\x84\x24...."); /* lea (n * 4)(%esp),%eax */
280 | save_int(code + codepos - 4, k);
281 | }
282 | else
283 | error();
284 | }
285 |
286 | void be_start()
287 | {
288 | emit(16, "\x7f\x45\x4c\x46\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00");
289 | emit(16, "\x02\x00\x03\x00\x01\x00\x00\x00\x54\x80\x04\x08\x34\x00\x00\x00");
290 | emit(16, "\x00\x00\x00\x00\x00\x00\x00\x00\x34\x00\x20\x00\x01\x00\x00\x00");
291 | emit(16, "\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x80\x04\x08");
292 | emit(16, "\x00\x80\x04\x08\x10\x4b\x00\x00\x10\x4b\x00\x00\x07\x00\x00\x00");
293 | emit(16, "\x00\x10\x00\x00\xe8\x00\x00\x00\x00\x89\xc3\x31\xc0\x40\xcd\x80");
294 |
295 | sym_define_global(sym_declare_global("exit"));
296 | /* pop %ebx ; pop %ebx ; xor %eax,%eax ; inc %eax ; int $0x80 */
297 | emit(7, "\x5b\x5b\x31\xc0\x40\xcd\x80");
298 |
299 | sym_define_global(sym_declare_global("getchar"));
300 | /* mov $3,%eax ; xor %ebx,%ebx ; push %ebx ; mov %esp,%ecx */
301 | emit(10, "\xb8\x03\x00\x00\x00\x31\xdb\x53\x89\xe1");
302 | /* xor %edx,%edx ; inc %edx ; int $0x80 */
303 | /* test %eax,%eax ; pop %eax ; jne . + 7 */
304 | emit(10, "\x31\xd2\x42\xcd\x80\x85\xc0\x58\x75\x05");
305 | /* mov $-1,%eax ; ret */
306 | emit(6, "\xb8\xff\xff\xff\xff\xc3");
307 |
308 | sym_define_global(sym_declare_global("malloc"));
309 | /* mov 4(%esp),%eax */
310 | emit(4, "\x8b\x44\x24\x04");
311 | /* push %eax ; xor %ebx,%ebx ; mov $45,%eax ; int $0x80 */
312 | emit(10, "\x50\x31\xdb\xb8\x2d\x00\x00\x00\xcd\x80");
313 | /* pop %ebx ; add %eax,%ebx ; push %eax ; push %ebx ; mov $45,%eax */
314 | emit(10, "\x5b\x01\xc3\x50\x53\xb8\x2d\x00\x00\x00");
315 | /* int $0x80 ; pop %ebx ; cmp %eax,%ebx ; pop %eax ; je . + 7 */
316 | emit(8, "\xcd\x80\x5b\x39\xc3\x58\x74\x05");
317 | /* mov $-1,%eax ; ret */
318 | emit(6, "\xb8\xff\xff\xff\xff\xc3");
319 |
320 | sym_define_global(sym_declare_global("putchar"));
321 | /* mov $4,%eax ; xor %ebx,%ebx ; inc %ebx */
322 | emit(8, "\xb8\x04\x00\x00\x00\x31\xdb\x43");
323 | /* lea 4(%esp),%ecx ; mov %ebx,%edx ; int $0x80 ; ret */
324 | emit(9, "\x8d\x4c\x24\x04\x89\xda\xcd\x80\xc3");
325 |
326 | save_int(code + 85, codepos - 89); /* entry set to first thing in file */
327 | }
328 |
329 | void be_finish()
330 | {
331 | save_int(code + 68, codepos);
332 | save_int(code + 72, codepos);
333 | i = 0;
334 | while (i <= codepos - 1) {
335 | putchar(code[i]);
336 | i = i + 1;
337 | }
338 | }
339 |
340 | void promote(int type)
341 | {
342 | /* 1 = char lval, 2 = int lval, 3 = other */
343 | if (type == 1)
344 | emit(3, "\x0f\xbe\x00"); /* movsbl (%eax),%eax */
345 | else if (type == 2)
346 | emit(2, "\x8b\x00"); /* mov (%eax),%eax */
347 | }
348 |
349 | int expression();
350 |
351 | /*
352 | * primary-expr:
353 | * identifier
354 | * constant
355 | * ( expression )
356 | */
357 | int primary_expr()
358 | {
359 | int type;
360 | if (('0' <= token[0]) & (token[0] <= '9')) {
361 | int n = 0;
362 | i = 0;
363 | while (token[i]) {
364 | n = (n << 1) + (n << 3) + token[i] - '0';
365 | i = i + 1;
366 | }
367 | emit(5, "\xb8...."); /* mov $x,%eax */
368 | save_int(code + codepos - 4, n);
369 | type = 3;
370 | }
371 | else if (('a' <= token[0]) & (token[0] <= 'z')) {
372 | sym_get_value(token);
373 | type = 2;
374 | }
375 | else if (accept("(")) {
376 | type = expression();
377 | if (peek(")") == 0)
378 | error();
379 | }
380 | else if ((token[0] == 39) & (token[1] != 0) &
381 | (token[2] == 39) & (token[3] == 0)) {
382 | emit(5, "\xb8...."); /* mov $x,%eax */
383 | save_int(code + codepos - 4, token[1]);
384 | type = 3;
385 | }
386 | else if (token[0] == '"') {
387 | int i = 0;
388 | int j = 1;
389 | int k;
390 | while (token[j] != '"') {
391 | if ((token[j] == 92) & (token[j + 1] == 'x')) {
392 | if (token[j + 2] <= '9')
393 | k = token[j + 2] - '0';
394 | else
395 | k = token[j + 2] - 'a' + 10;
396 | k = k << 4;
397 | if (token[j + 3] <= '9')
398 | k = k + token[j + 3] - '0';
399 | else
400 | k = k + token[j + 3] - 'a' + 10;
401 | token[i] = k;
402 | j = j + 4;
403 | }
404 | else {
405 | token[i] = token[j];
406 | j = j + 1;
407 | }
408 | i = i + 1;
409 | }
410 | token[i] = 0;
411 | /* call ... ; the string ; pop %eax */
412 | emit(5, "\xe8....");
413 | save_int(code + codepos - 4, i + 1);
414 | emit(i + 1, token);
415 | emit(1, "\x58");
416 | type = 3;
417 | }
418 | else
419 | error();
420 | get_token();
421 | return type;
422 | }
423 |
424 | void binary1(int type)
425 | {
426 | promote(type);
427 | be_push();
428 | stack_pos = stack_pos + 1;
429 | }
430 |
431 | int binary2(int type, int n, char *s)
432 | {
433 | promote(type);
434 | emit(n, s);
435 | stack_pos = stack_pos - 1;
436 | return 3;
437 | }
438 |
439 | /*
440 | * postfix-expr:
441 | * primary-expr
442 | * postfix-expr [ expression ]
443 | * postfix-expr ( expression-list-opt )
444 | */
445 | int postfix_expr()
446 | {
447 | int type = primary_expr();
448 | if (accept("[")) {
449 | binary1(type); /* pop %ebx ; add %ebx,%eax */
450 | binary2(expression(), 3, "\x5b\x01\xd8");
451 | expect("]");
452 | type = 1;
453 | }
454 | else if (accept("(")) {
455 | int s = stack_pos;
456 | be_push();
457 | stack_pos = stack_pos + 1;
458 | if (accept(")") == 0) {
459 | promote(expression());
460 | be_push();
461 | stack_pos = stack_pos + 1;
462 | while (accept(",")) {
463 | promote(expression());
464 | be_push();
465 | stack_pos = stack_pos + 1;
466 | }
467 | expect(")");
468 | }
469 | emit(7, "\x8b\x84\x24...."); /* mov (n * 4)(%esp),%eax */
470 | save_int(code + codepos - 4, (stack_pos - s - 1) << 2);
471 | emit(2, "\xff\xd0"); /* call *%eax */
472 | be_pop(stack_pos - s);
473 | stack_pos = s;
474 | type = 3;
475 | }
476 | return type;
477 | }
478 |
479 | /*
480 | * additive-expr:
481 | * postfix-expr
482 | * additive-expr + postfix-expr
483 | * additive-expr - postfix-expr
484 | */
485 | int additive_expr()
486 | {
487 | int type = postfix_expr();
488 | while (1) {
489 | if (accept("+")) {
490 | binary1(type); /* pop %ebx ; add %ebx,%eax */
491 | type = binary2(postfix_expr(), 3, "\x5b\x01\xd8");
492 | }
493 | else if (accept("-")) {
494 | binary1(type); /* pop %ebx ; sub %eax,%ebx ; mov %ebx,%eax */
495 | type = binary2(postfix_expr(), 5, "\x5b\x29\xc3\x89\xd8");
496 | }
497 | else
498 | return type;
499 | }
500 | }
501 |
502 | /*
503 | * shift-expr:
504 | * additive-expr
505 | * shift-expr << additive-expr
506 | * shift-expr >> additive-expr
507 | */
508 | int shift_expr()
509 | {
510 | int type = additive_expr();
511 | while (1) {
512 | if (accept("<<")) {
513 | binary1(type); /* mov %eax,%ecx ; pop %eax ; shl %cl,%eax */
514 | type = binary2(additive_expr(), 5, "\x89\xc1\x58\xd3\xe0");
515 | }
516 | else if (accept(">>")) {
517 | binary1(type); /* mov %eax,%ecx ; pop %eax ; sar %cl,%eax */
518 | type = binary2(additive_expr(), 5, "\x89\xc1\x58\xd3\xf8");
519 | }
520 | else
521 | return type;
522 | }
523 | }
524 |
525 | /*
526 | * relational-expr:
527 | * shift-expr
528 | * relational-expr <= shift-expr
529 | */
530 | int relational_expr()
531 | {
532 | int type = shift_expr();
533 | while (accept("<=")) {
534 | binary1(type);
535 | /* pop %ebx ; cmp %eax,%ebx ; setle %al ; movzbl %al,%eax */
536 | type = binary2(shift_expr(),
537 | 9, "\x5b\x39\xc3\x0f\x9e\xc0\x0f\xb6\xc0");
538 | }
539 | return type;
540 | }
541 |
542 | /*
543 | * equality-expr:
544 | * relational-expr
545 | * equality-expr == relational-expr
546 | * equality-expr != relational-expr
547 | */
548 | int equality_expr()
549 | {
550 | int type = relational_expr();
551 | while (1) {
552 | if (accept("==")) {
553 | binary1(type);
554 | /* pop %ebx ; cmp %eax,%ebx ; sete %al ; movzbl %al,%eax */
555 | type = binary2(relational_expr(),
556 | 9, "\x5b\x39\xc3\x0f\x94\xc0\x0f\xb6\xc0");
557 | }
558 | else if (accept("!=")) {
559 | binary1(type);
560 | /* pop %ebx ; cmp %eax,%ebx ; setne %al ; movzbl %al,%eax */
561 | type = binary2(relational_expr(),
562 | 9, "\x5b\x39\xc3\x0f\x95\xc0\x0f\xb6\xc0");
563 | }
564 | else
565 | return type;
566 | }
567 | }
568 |
569 | /*
570 | * bitwise-and-expr:
571 | * equality-expr
572 | * bitwise-and-expr & equality-expr
573 | */
574 | int bitwise_and_expr()
575 | {
576 | int type = equality_expr();
577 | while (accept("&")) {
578 | binary1(type); /* pop %ebx ; and %ebx,%eax */
579 | type = binary2(equality_expr(), 3, "\x5b\x21\xd8");
580 | }
581 | return type;
582 | }
583 |
584 | /*
585 | * bitwise-or-expr:
586 | * bitwise-and-expr
587 | * bitwise-and-expr | bitwise-or-expr
588 | */
589 | int bitwise_or_expr()
590 | {
591 | int type = bitwise_and_expr();
592 | while (accept("|")) {
593 | binary1(type); /* pop %ebx ; or %ebx,%eax */
594 | type = binary2(bitwise_and_expr(), 3, "\x5b\x09\xd8");
595 | }
596 | return type;
597 | }
598 |
599 | /*
600 | * expression:
601 | * bitwise-or-expr
602 | * bitwise-or-expr = expression
603 | */
604 | int expression()
605 | {
606 | int type = bitwise_or_expr();
607 | if (accept("=")) {
608 | be_push();
609 | stack_pos = stack_pos + 1;
610 | promote(expression());
611 | if (type == 2)
612 | emit(3, "\x5b\x89\x03"); /* pop %ebx ; mov %eax,(%ebx) */
613 | else
614 | emit(3, "\x5b\x88\x03"); /* pop %ebx ; mov %al,(%ebx) */
615 | stack_pos = stack_pos - 1;
616 | type = 3;
617 | }
618 | return type;
619 | }
620 |
621 | /*
622 | * type-name:
623 | * char *
624 | * int
625 | */
626 | void type_name()
627 | {
628 | get_token();
629 | while (accept("*")) {
630 | }
631 | }
632 |
633 | /*
634 | * statement:
635 | * { statement-list-opt }
636 | * type-name identifier ;
637 | * type-name identifier = expression;
638 | * if ( expression ) statement
639 | * if ( expression ) statement else statement
640 | * while ( expression ) statement
641 | * return ;
642 | * expr ;
643 | */
644 | void statement()
645 | {
646 | int p1;
647 | int p2;
648 | if (accept("{")) {
649 | int n = table_pos;
650 | int s = stack_pos;
651 | while (accept("}") == 0)
652 | statement();
653 | table_pos = n;
654 | be_pop(stack_pos - s);
655 | stack_pos = s;
656 | }
657 | else if (peek("char") | peek("int")) {
658 | type_name();
659 | sym_declare(token, 'L', stack_pos);
660 | get_token();
661 | if (accept("="))
662 | promote(expression());
663 | expect(";");
664 | be_push();
665 | stack_pos = stack_pos + 1;
666 | }
667 | else if (accept("if")) {
668 | expect("(");
669 | promote(expression());
670 | emit(8, "\x85\xc0\x0f\x84...."); /* test %eax,%eax ; je ... */
671 | p1 = codepos;
672 | expect(")");
673 | statement();
674 | emit(5, "\xe9...."); /* jmp ... */
675 | p2 = codepos;
676 | save_int(code + p1 - 4, codepos - p1);
677 | if (accept("else"))
678 | statement();
679 | save_int(code + p2 - 4, codepos - p2);
680 | }
681 | else if (accept("while")) {
682 | expect("(");
683 | p1 = codepos;
684 | promote(expression());
685 | emit(8, "\x85\xc0\x0f\x84...."); /* test %eax,%eax ; je ... */
686 | p2 = codepos;
687 | expect(")");
688 | statement();
689 | emit(5, "\xe9...."); /* jmp ... */
690 | save_int(code + codepos - 4, p1 - codepos);
691 | save_int(code + p2 - 4, codepos - p2);
692 | }
693 | else if (accept("return")) {
694 | if (peek(";") == 0)
695 | promote(expression());
696 | expect(";");
697 | be_pop(stack_pos);
698 | emit(1, "\xc3"); /* ret */
699 | }
700 | else {
701 | expression();
702 | expect(";");
703 | }
704 | }
705 |
706 | /*
707 | * program:
708 | * declaration
709 | * declaration program
710 | *
711 | * declaration:
712 | * type-name identifier ;
713 | * type-name identifier ( parameter-list ) ;
714 | * type-name identifier ( parameter-list ) statement
715 | *
716 | * parameter-list:
717 | * parameter-declaration
718 | * parameter-list, parameter-declaration
719 | *
720 | * parameter-declaration:
721 | * type-name identifier-opt
722 | */
723 | void program()
724 | {
725 | int current_symbol;
726 | while (token[0]) {
727 | type_name();
728 | current_symbol = sym_declare_global(token);
729 | get_token();
730 | if (accept(";")) {
731 | sym_define_global(current_symbol);
732 | emit(4, "\x00\x00\x00\x00");
733 | }
734 | else if (accept("(")) {
735 | int n = table_pos;
736 | number_of_args = 0;
737 | while (accept(")") == 0) {
738 | number_of_args = number_of_args + 1;
739 | type_name();
740 | if (peek(")") == 0) {
741 | sym_declare(token, 'A', number_of_args);
742 | get_token();
743 | }
744 | accept(","); /* ignore trailing comma */
745 | }
746 | if (accept(";") == 0) {
747 | sym_define_global(current_symbol);
748 | statement();
749 | emit(1, "\xc3"); /* ret */
750 | }
751 | table_pos = n;
752 | }
753 | else
754 | error();
755 | }
756 | }
757 |
758 | int main1()
759 | {
760 | code_offset = 134512640; /* 0x08048000 */
761 | be_start();
762 | nextc = getchar();
763 | get_token();
764 | program();
765 | be_finish();
766 | return 0;
767 | }
768 |
--------------------------------------------------------------------------------