├── LICENSE ├── README.md ├── c4.c └── hello.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 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | c4 - C in four functions 2 | ======================== 3 | 4 | An exercise in minimalism. 5 | 6 | Try the following: 7 | 8 | gcc -o c4 c4.c 9 | ./c4 hello.c 10 | ./c4 -s hello.c 11 | 12 | ./c4 c4.c hello.c 13 | ./c4 c4.c c4.c hello.c 14 | 15 | -------------------------------------------------------------------------------- /c4.c: -------------------------------------------------------------------------------- 1 | // c4.c - C in four functions 2 | 3 | // char, int, and pointer types 4 | // if, while, return, and expression statements 5 | // just enough features to allow self-compilation and a bit more 6 | 7 | // Written by Robert Swierczek 8 | 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #define int long long 15 | 16 | char *p, *lp, // current position in source code 17 | *data; // data/bss pointer 18 | 19 | int *e, *le, // current position in emitted code 20 | *id, // currently parsed identifier 21 | *sym, // symbol table (simple list of identifiers) 22 | tk, // current token 23 | ival, // current token value 24 | ty, // current expression type 25 | loc, // local variable offset 26 | line, // current line number 27 | src, // print source and assembly flag 28 | debug; // print executed instructions 29 | 30 | // tokens and classes (operators last and in precedence order) 31 | enum { 32 | Num = 128, Fun, Sys, Glo, Loc, Id, 33 | Char, Else, Enum, If, Int, Return, Sizeof, While, 34 | Assign, Cond, Lor, Lan, Or, Xor, And, Eq, Ne, Lt, Gt, Le, Ge, Shl, Shr, Add, Sub, Mul, Div, Mod, Inc, Dec, Brak 35 | }; 36 | 37 | // opcodes 38 | enum { LEA ,IMM ,JMP ,JSR ,BZ ,BNZ ,ENT ,ADJ ,LEV ,LI ,LC ,SI ,SC ,PSH , 39 | OR ,XOR ,AND ,EQ ,NE ,LT ,GT ,LE ,GE ,SHL ,SHR ,ADD ,SUB ,MUL ,DIV ,MOD , 40 | OPEN,READ,CLOS,PRTF,MALC,FREE,MSET,MCMP,EXIT }; 41 | 42 | // types 43 | enum { CHAR, INT, PTR }; 44 | 45 | // identifier offsets (since we can't create an ident struct) 46 | enum { Tk, Hash, Name, Class, Type, Val, HClass, HType, HVal, Idsz }; 47 | 48 | void next() 49 | { 50 | char *pp; 51 | 52 | while (tk = *p) { 53 | ++p; 54 | if (tk == '\n') { 55 | if (src) { 56 | printf("%d: %.*s", line, p - lp, lp); 57 | lp = p; 58 | while (le < e) { 59 | printf("%8.4s", &"LEA ,IMM ,JMP ,JSR ,BZ ,BNZ ,ENT ,ADJ ,LEV ,LI ,LC ,SI ,SC ,PSH ," 60 | "OR ,XOR ,AND ,EQ ,NE ,LT ,GT ,LE ,GE ,SHL ,SHR ,ADD ,SUB ,MUL ,DIV ,MOD ," 61 | "OPEN,READ,CLOS,PRTF,MALC,FREE,MSET,MCMP,EXIT,"[*++le * 5]); 62 | if (*le <= ADJ) printf(" %d\n", *++le); else printf("\n"); 63 | } 64 | } 65 | ++line; 66 | } 67 | else if (tk == '#') { 68 | while (*p != 0 && *p != '\n') ++p; 69 | } 70 | else if ((tk >= 'a' && tk <= 'z') || (tk >= 'A' && tk <= 'Z') || tk == '_') { 71 | pp = p - 1; 72 | while ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '_') 73 | tk = tk * 147 + *p++; 74 | tk = (tk << 6) + (p - pp); 75 | id = sym; 76 | while (id[Tk]) { 77 | if (tk == id[Hash] && !memcmp((char *)id[Name], pp, p - pp)) { tk = id[Tk]; return; } 78 | id = id + Idsz; 79 | } 80 | id[Name] = (int)pp; 81 | id[Hash] = tk; 82 | tk = id[Tk] = Id; 83 | return; 84 | } 85 | else if (tk >= '0' && tk <= '9') { 86 | if (ival = tk - '0') { while (*p >= '0' && *p <= '9') ival = ival * 10 + *p++ - '0'; } 87 | else if (*p == 'x' || *p == 'X') { 88 | while ((tk = *++p) && ((tk >= '0' && tk <= '9') || (tk >= 'a' && tk <= 'f') || (tk >= 'A' && tk <= 'F'))) 89 | ival = ival * 16 + (tk & 15) + (tk >= 'A' ? 9 : 0); 90 | } 91 | else { while (*p >= '0' && *p <= '7') ival = ival * 8 + *p++ - '0'; } 92 | tk = Num; 93 | return; 94 | } 95 | else if (tk == '/') { 96 | if (*p == '/') { 97 | ++p; 98 | while (*p != 0 && *p != '\n') ++p; 99 | } 100 | else { 101 | tk = Div; 102 | return; 103 | } 104 | } 105 | else if (tk == '\'' || tk == '"') { 106 | pp = data; 107 | while (*p != 0 && *p != tk) { 108 | if ((ival = *p++) == '\\') { 109 | if ((ival = *p++) == 'n') ival = '\n'; 110 | } 111 | if (tk == '"') *data++ = ival; 112 | } 113 | ++p; 114 | if (tk == '"') ival = (int)pp; else tk = Num; 115 | return; 116 | } 117 | else if (tk == '=') { if (*p == '=') { ++p; tk = Eq; } else tk = Assign; return; } 118 | else if (tk == '+') { if (*p == '+') { ++p; tk = Inc; } else tk = Add; return; } 119 | else if (tk == '-') { if (*p == '-') { ++p; tk = Dec; } else tk = Sub; return; } 120 | else if (tk == '!') { if (*p == '=') { ++p; tk = Ne; } return; } 121 | else if (tk == '<') { if (*p == '=') { ++p; tk = Le; } else if (*p == '<') { ++p; tk = Shl; } else tk = Lt; return; } 122 | else if (tk == '>') { if (*p == '=') { ++p; tk = Ge; } else if (*p == '>') { ++p; tk = Shr; } else tk = Gt; return; } 123 | else if (tk == '|') { if (*p == '|') { ++p; tk = Lor; } else tk = Or; return; } 124 | else if (tk == '&') { if (*p == '&') { ++p; tk = Lan; } else tk = And; return; } 125 | else if (tk == '^') { tk = Xor; return; } 126 | else if (tk == '%') { tk = Mod; return; } 127 | else if (tk == '*') { tk = Mul; return; } 128 | else if (tk == '[') { tk = Brak; return; } 129 | else if (tk == '?') { tk = Cond; return; } 130 | else if (tk == '~' || tk == ';' || tk == '{' || tk == '}' || tk == '(' || tk == ')' || tk == ']' || tk == ',' || tk == ':') return; 131 | } 132 | } 133 | 134 | void expr(int lev) 135 | { 136 | int t, *d; 137 | 138 | if (!tk) { printf("%d: unexpected eof in expression\n", line); exit(-1); } 139 | else if (tk == Num) { *++e = IMM; *++e = ival; next(); ty = INT; } 140 | else if (tk == '"') { 141 | *++e = IMM; *++e = ival; next(); 142 | while (tk == '"') next(); 143 | data = (char *)((int)data + sizeof(int) & -sizeof(int)); ty = PTR; 144 | } 145 | else if (tk == Sizeof) { 146 | next(); if (tk == '(') next(); else { printf("%d: open paren expected in sizeof\n", line); exit(-1); } 147 | ty = INT; if (tk == Int) next(); else if (tk == Char) { next(); ty = CHAR; } 148 | while (tk == Mul) { next(); ty = ty + PTR; } 149 | if (tk == ')') next(); else { printf("%d: close paren expected in sizeof\n", line); exit(-1); } 150 | *++e = IMM; *++e = (ty == CHAR) ? sizeof(char) : sizeof(int); 151 | ty = INT; 152 | } 153 | else if (tk == Id) { 154 | d = id; next(); 155 | if (tk == '(') { 156 | next(); 157 | t = 0; 158 | while (tk != ')') { expr(Assign); *++e = PSH; ++t; if (tk == ',') next(); } 159 | next(); 160 | if (d[Class] == Sys) *++e = d[Val]; 161 | else if (d[Class] == Fun) { *++e = JSR; *++e = d[Val]; } 162 | else { printf("%d: bad function call\n", line); exit(-1); } 163 | if (t) { *++e = ADJ; *++e = t; } 164 | ty = d[Type]; 165 | } 166 | else if (d[Class] == Num) { *++e = IMM; *++e = d[Val]; ty = INT; } 167 | else { 168 | if (d[Class] == Loc) { *++e = LEA; *++e = loc - d[Val]; } 169 | else if (d[Class] == Glo) { *++e = IMM; *++e = d[Val]; } 170 | else { printf("%d: undefined variable\n", line); exit(-1); } 171 | *++e = ((ty = d[Type]) == CHAR) ? LC : LI; 172 | } 173 | } 174 | else if (tk == '(') { 175 | next(); 176 | if (tk == Int || tk == Char) { 177 | t = (tk == Int) ? INT : CHAR; next(); 178 | while (tk == Mul) { next(); t = t + PTR; } 179 | if (tk == ')') next(); else { printf("%d: bad cast\n", line); exit(-1); } 180 | expr(Inc); 181 | ty = t; 182 | } 183 | else { 184 | expr(Assign); 185 | if (tk == ')') next(); else { printf("%d: close paren expected\n", line); exit(-1); } 186 | } 187 | } 188 | else if (tk == Mul) { 189 | next(); expr(Inc); 190 | if (ty > INT) ty = ty - PTR; else { printf("%d: bad dereference\n", line); exit(-1); } 191 | *++e = (ty == CHAR) ? LC : LI; 192 | } 193 | else if (tk == And) { 194 | next(); expr(Inc); 195 | if (*e == LC || *e == LI) --e; else { printf("%d: bad address-of\n", line); exit(-1); } 196 | ty = ty + PTR; 197 | } 198 | else if (tk == '!') { next(); expr(Inc); *++e = PSH; *++e = IMM; *++e = 0; *++e = EQ; ty = INT; } 199 | else if (tk == '~') { next(); expr(Inc); *++e = PSH; *++e = IMM; *++e = -1; *++e = XOR; ty = INT; } 200 | else if (tk == Add) { next(); expr(Inc); ty = INT; } 201 | else if (tk == Sub) { 202 | next(); *++e = IMM; 203 | if (tk == Num) { *++e = -ival; next(); } else { *++e = -1; *++e = PSH; expr(Inc); *++e = MUL; } 204 | ty = INT; 205 | } 206 | else if (tk == Inc || tk == Dec) { 207 | t = tk; next(); expr(Inc); 208 | if (*e == LC) { *e = PSH; *++e = LC; } 209 | else if (*e == LI) { *e = PSH; *++e = LI; } 210 | else { printf("%d: bad lvalue in pre-increment\n", line); exit(-1); } 211 | *++e = PSH; 212 | *++e = IMM; *++e = (ty > PTR) ? sizeof(int) : sizeof(char); 213 | *++e = (t == Inc) ? ADD : SUB; 214 | *++e = (ty == CHAR) ? SC : SI; 215 | } 216 | else { printf("%d: bad expression\n", line); exit(-1); } 217 | 218 | while (tk >= lev) { // "precedence climbing" or "Top Down Operator Precedence" method 219 | t = ty; 220 | if (tk == Assign) { 221 | next(); 222 | if (*e == LC || *e == LI) *e = PSH; else { printf("%d: bad lvalue in assignment\n", line); exit(-1); } 223 | expr(Assign); *++e = ((ty = t) == CHAR) ? SC : SI; 224 | } 225 | else if (tk == Cond) { 226 | next(); 227 | *++e = BZ; d = ++e; 228 | expr(Assign); 229 | if (tk == ':') next(); else { printf("%d: conditional missing colon\n", line); exit(-1); } 230 | *d = (int)(e + 3); *++e = JMP; d = ++e; 231 | expr(Cond); 232 | *d = (int)(e + 1); 233 | } 234 | else if (tk == Lor) { next(); *++e = BNZ; d = ++e; expr(Lan); *d = (int)(e + 1); ty = INT; } 235 | else if (tk == Lan) { next(); *++e = BZ; d = ++e; expr(Or); *d = (int)(e + 1); ty = INT; } 236 | else if (tk == Or) { next(); *++e = PSH; expr(Xor); *++e = OR; ty = INT; } 237 | else if (tk == Xor) { next(); *++e = PSH; expr(And); *++e = XOR; ty = INT; } 238 | else if (tk == And) { next(); *++e = PSH; expr(Eq); *++e = AND; ty = INT; } 239 | else if (tk == Eq) { next(); *++e = PSH; expr(Lt); *++e = EQ; ty = INT; } 240 | else if (tk == Ne) { next(); *++e = PSH; expr(Lt); *++e = NE; ty = INT; } 241 | else if (tk == Lt) { next(); *++e = PSH; expr(Shl); *++e = LT; ty = INT; } 242 | else if (tk == Gt) { next(); *++e = PSH; expr(Shl); *++e = GT; ty = INT; } 243 | else if (tk == Le) { next(); *++e = PSH; expr(Shl); *++e = LE; ty = INT; } 244 | else if (tk == Ge) { next(); *++e = PSH; expr(Shl); *++e = GE; ty = INT; } 245 | else if (tk == Shl) { next(); *++e = PSH; expr(Add); *++e = SHL; ty = INT; } 246 | else if (tk == Shr) { next(); *++e = PSH; expr(Add); *++e = SHR; ty = INT; } 247 | else if (tk == Add) { 248 | next(); *++e = PSH; expr(Mul); 249 | if ((ty = t) > PTR) { *++e = PSH; *++e = IMM; *++e = sizeof(int); *++e = MUL; } 250 | *++e = ADD; 251 | } 252 | else if (tk == Sub) { 253 | next(); *++e = PSH; expr(Mul); 254 | if (t > PTR && t == ty) { *++e = SUB; *++e = PSH; *++e = IMM; *++e = sizeof(int); *++e = DIV; ty = INT; } 255 | else if ((ty = t) > PTR) { *++e = PSH; *++e = IMM; *++e = sizeof(int); *++e = MUL; *++e = SUB; } 256 | else *++e = SUB; 257 | } 258 | else if (tk == Mul) { next(); *++e = PSH; expr(Inc); *++e = MUL; ty = INT; } 259 | else if (tk == Div) { next(); *++e = PSH; expr(Inc); *++e = DIV; ty = INT; } 260 | else if (tk == Mod) { next(); *++e = PSH; expr(Inc); *++e = MOD; ty = INT; } 261 | else if (tk == Inc || tk == Dec) { 262 | if (*e == LC) { *e = PSH; *++e = LC; } 263 | else if (*e == LI) { *e = PSH; *++e = LI; } 264 | else { printf("%d: bad lvalue in post-increment\n", line); exit(-1); } 265 | *++e = PSH; *++e = IMM; *++e = (ty > PTR) ? sizeof(int) : sizeof(char); 266 | *++e = (tk == Inc) ? ADD : SUB; 267 | *++e = (ty == CHAR) ? SC : SI; 268 | *++e = PSH; *++e = IMM; *++e = (ty > PTR) ? sizeof(int) : sizeof(char); 269 | *++e = (tk == Inc) ? SUB : ADD; 270 | next(); 271 | } 272 | else if (tk == Brak) { 273 | next(); *++e = PSH; expr(Assign); 274 | if (tk == ']') next(); else { printf("%d: close bracket expected\n", line); exit(-1); } 275 | if (t > PTR) { *++e = PSH; *++e = IMM; *++e = sizeof(int); *++e = MUL; } 276 | else if (t < PTR) { printf("%d: pointer type expected\n", line); exit(-1); } 277 | *++e = ADD; 278 | *++e = ((ty = t - PTR) == CHAR) ? LC : LI; 279 | } 280 | else { printf("%d: compiler error tk=%d\n", line, tk); exit(-1); } 281 | } 282 | } 283 | 284 | void stmt() 285 | { 286 | int *a, *b; 287 | 288 | if (tk == If) { 289 | next(); 290 | if (tk == '(') next(); else { printf("%d: open paren expected\n", line); exit(-1); } 291 | expr(Assign); 292 | if (tk == ')') next(); else { printf("%d: close paren expected\n", line); exit(-1); } 293 | *++e = BZ; b = ++e; 294 | stmt(); 295 | if (tk == Else) { 296 | *b = (int)(e + 3); *++e = JMP; b = ++e; 297 | next(); 298 | stmt(); 299 | } 300 | *b = (int)(e + 1); 301 | } 302 | else if (tk == While) { 303 | next(); 304 | a = e + 1; 305 | if (tk == '(') next(); else { printf("%d: open paren expected\n", line); exit(-1); } 306 | expr(Assign); 307 | if (tk == ')') next(); else { printf("%d: close paren expected\n", line); exit(-1); } 308 | *++e = BZ; b = ++e; 309 | stmt(); 310 | *++e = JMP; *++e = (int)a; 311 | *b = (int)(e + 1); 312 | } 313 | else if (tk == Return) { 314 | next(); 315 | if (tk != ';') expr(Assign); 316 | *++e = LEV; 317 | if (tk == ';') next(); else { printf("%d: semicolon expected\n", line); exit(-1); } 318 | } 319 | else if (tk == '{') { 320 | next(); 321 | while (tk != '}') stmt(); 322 | next(); 323 | } 324 | else if (tk == ';') { 325 | next(); 326 | } 327 | else { 328 | expr(Assign); 329 | if (tk == ';') next(); else { printf("%d: semicolon expected\n", line); exit(-1); } 330 | } 331 | } 332 | 333 | int main(int argc, char **argv) 334 | { 335 | int fd, bt, ty, poolsz, *idmain; 336 | int *pc, *sp, *bp, a, cycle; // vm registers 337 | int i, *t; // temps 338 | 339 | --argc; ++argv; 340 | if (argc > 0 && **argv == '-' && (*argv)[1] == 's') { src = 1; --argc; ++argv; } 341 | if (argc > 0 && **argv == '-' && (*argv)[1] == 'd') { debug = 1; --argc; ++argv; } 342 | if (argc < 1) { printf("usage: c4 [-s] [-d] file ...\n"); return -1; } 343 | 344 | if ((fd = open(*argv, 0)) < 0) { printf("could not open(%s)\n", *argv); return -1; } 345 | 346 | poolsz = 256*1024; // arbitrary size 347 | if (!(sym = malloc(poolsz))) { printf("could not malloc(%d) symbol area\n", poolsz); return -1; } 348 | if (!(le = e = malloc(poolsz))) { printf("could not malloc(%d) text area\n", poolsz); return -1; } 349 | if (!(data = malloc(poolsz))) { printf("could not malloc(%d) data area\n", poolsz); return -1; } 350 | if (!(sp = malloc(poolsz))) { printf("could not malloc(%d) stack area\n", poolsz); return -1; } 351 | 352 | memset(sym, 0, poolsz); 353 | memset(e, 0, poolsz); 354 | memset(data, 0, poolsz); 355 | 356 | p = "char else enum if int return sizeof while " 357 | "open read close printf malloc free memset memcmp exit void main"; 358 | i = Char; while (i <= While) { next(); id[Tk] = i++; } // add keywords to symbol table 359 | i = OPEN; while (i <= EXIT) { next(); id[Class] = Sys; id[Type] = INT; id[Val] = i++; } // add library to symbol table 360 | next(); id[Tk] = Char; // handle void type 361 | next(); idmain = id; // keep track of main 362 | 363 | if (!(lp = p = malloc(poolsz))) { printf("could not malloc(%d) source area\n", poolsz); return -1; } 364 | if ((i = read(fd, p, poolsz-1)) <= 0) { printf("read() returned %d\n", i); return -1; } 365 | p[i] = 0; 366 | close(fd); 367 | 368 | // parse declarations 369 | line = 1; 370 | next(); 371 | while (tk) { 372 | bt = INT; // basetype 373 | if (tk == Int) next(); 374 | else if (tk == Char) { next(); bt = CHAR; } 375 | else if (tk == Enum) { 376 | next(); 377 | if (tk != '{') next(); 378 | if (tk == '{') { 379 | next(); 380 | i = 0; 381 | while (tk != '}') { 382 | if (tk != Id) { printf("%d: bad enum identifier %d\n", line, tk); return -1; } 383 | next(); 384 | if (tk == Assign) { 385 | next(); 386 | if (tk != Num) { printf("%d: bad enum initializer\n", line); return -1; } 387 | i = ival; 388 | next(); 389 | } 390 | id[Class] = Num; id[Type] = INT; id[Val] = i++; 391 | if (tk == ',') next(); 392 | } 393 | next(); 394 | } 395 | } 396 | while (tk != ';' && tk != '}') { 397 | ty = bt; 398 | while (tk == Mul) { next(); ty = ty + PTR; } 399 | if (tk != Id) { printf("%d: bad global declaration\n", line); return -1; } 400 | if (id[Class]) { printf("%d: duplicate global definition\n", line); return -1; } 401 | next(); 402 | id[Type] = ty; 403 | if (tk == '(') { // function 404 | id[Class] = Fun; 405 | id[Val] = (int)(e + 1); 406 | next(); i = 0; 407 | while (tk != ')') { 408 | ty = INT; 409 | if (tk == Int) next(); 410 | else if (tk == Char) { next(); ty = CHAR; } 411 | while (tk == Mul) { next(); ty = ty + PTR; } 412 | if (tk != Id) { printf("%d: bad parameter declaration\n", line); return -1; } 413 | if (id[Class] == Loc) { printf("%d: duplicate parameter definition\n", line); return -1; } 414 | id[HClass] = id[Class]; id[Class] = Loc; 415 | id[HType] = id[Type]; id[Type] = ty; 416 | id[HVal] = id[Val]; id[Val] = i++; 417 | next(); 418 | if (tk == ',') next(); 419 | } 420 | next(); 421 | if (tk != '{') { printf("%d: bad function definition\n", line); return -1; } 422 | loc = ++i; 423 | next(); 424 | while (tk == Int || tk == Char) { 425 | bt = (tk == Int) ? INT : CHAR; 426 | next(); 427 | while (tk != ';') { 428 | ty = bt; 429 | while (tk == Mul) { next(); ty = ty + PTR; } 430 | if (tk != Id) { printf("%d: bad local declaration\n", line); return -1; } 431 | if (id[Class] == Loc) { printf("%d: duplicate local definition\n", line); return -1; } 432 | id[HClass] = id[Class]; id[Class] = Loc; 433 | id[HType] = id[Type]; id[Type] = ty; 434 | id[HVal] = id[Val]; id[Val] = ++i; 435 | next(); 436 | if (tk == ',') next(); 437 | } 438 | next(); 439 | } 440 | *++e = ENT; *++e = i - loc; 441 | while (tk != '}') stmt(); 442 | *++e = LEV; 443 | id = sym; // unwind symbol table locals 444 | while (id[Tk]) { 445 | if (id[Class] == Loc) { 446 | id[Class] = id[HClass]; 447 | id[Type] = id[HType]; 448 | id[Val] = id[HVal]; 449 | } 450 | id = id + Idsz; 451 | } 452 | } 453 | else { 454 | id[Class] = Glo; 455 | id[Val] = (int)data; 456 | data = data + sizeof(int); 457 | } 458 | if (tk == ',') next(); 459 | } 460 | next(); 461 | } 462 | 463 | if (!(pc = (int *)idmain[Val])) { printf("main() not defined\n"); return -1; } 464 | if (src) return 0; 465 | 466 | // setup stack 467 | bp = sp = (int *)((int)sp + poolsz); 468 | *--sp = EXIT; // call exit if main returns 469 | *--sp = PSH; t = sp; 470 | *--sp = argc; 471 | *--sp = (int)argv; 472 | *--sp = (int)t; 473 | 474 | // run... 475 | cycle = 0; 476 | while (1) { 477 | i = *pc++; ++cycle; 478 | if (debug) { 479 | printf("%d> %.4s", cycle, 480 | &"LEA ,IMM ,JMP ,JSR ,BZ ,BNZ ,ENT ,ADJ ,LEV ,LI ,LC ,SI ,SC ,PSH ," 481 | "OR ,XOR ,AND ,EQ ,NE ,LT ,GT ,LE ,GE ,SHL ,SHR ,ADD ,SUB ,MUL ,DIV ,MOD ," 482 | "OPEN,READ,CLOS,PRTF,MALC,FREE,MSET,MCMP,EXIT,"[i * 5]); 483 | if (i <= ADJ) printf(" %d\n", *pc); else printf("\n"); 484 | } 485 | if (i == LEA) a = (int)(bp + *pc++); // load local address 486 | else if (i == IMM) a = *pc++; // load global address or immediate 487 | else if (i == JMP) pc = (int *)*pc; // jump 488 | else if (i == JSR) { *--sp = (int)(pc + 1); pc = (int *)*pc; } // jump to subroutine 489 | else if (i == BZ) pc = a ? pc + 1 : (int *)*pc; // branch if zero 490 | else if (i == BNZ) pc = a ? (int *)*pc : pc + 1; // branch if not zero 491 | else if (i == ENT) { *--sp = (int)bp; bp = sp; sp = sp - *pc++; } // enter subroutine 492 | else if (i == ADJ) sp = sp + *pc++; // stack adjust 493 | else if (i == LEV) { sp = bp; bp = (int *)*sp++; pc = (int *)*sp++; } // leave subroutine 494 | else if (i == LI) a = *(int *)a; // load int 495 | else if (i == LC) a = *(char *)a; // load char 496 | else if (i == SI) *(int *)*sp++ = a; // store int 497 | else if (i == SC) a = *(char *)*sp++ = a; // store char 498 | else if (i == PSH) *--sp = a; // push 499 | 500 | else if (i == OR) a = *sp++ | a; 501 | else if (i == XOR) a = *sp++ ^ a; 502 | else if (i == AND) a = *sp++ & a; 503 | else if (i == EQ) a = *sp++ == a; 504 | else if (i == NE) a = *sp++ != a; 505 | else if (i == LT) a = *sp++ < a; 506 | else if (i == GT) a = *sp++ > a; 507 | else if (i == LE) a = *sp++ <= a; 508 | else if (i == GE) a = *sp++ >= a; 509 | else if (i == SHL) a = *sp++ << a; 510 | else if (i == SHR) a = *sp++ >> a; 511 | else if (i == ADD) a = *sp++ + a; 512 | else if (i == SUB) a = *sp++ - a; 513 | else if (i == MUL) a = *sp++ * a; 514 | else if (i == DIV) a = *sp++ / a; 515 | else if (i == MOD) a = *sp++ % a; 516 | 517 | else if (i == OPEN) a = open((char *)sp[1], *sp); 518 | else if (i == READ) a = read(sp[2], (char *)sp[1], *sp); 519 | else if (i == CLOS) a = close(*sp); 520 | else if (i == PRTF) { t = sp + pc[1]; a = printf((char *)t[-1], t[-2], t[-3], t[-4], t[-5], t[-6]); } 521 | else if (i == MALC) a = (int)malloc(*sp); 522 | else if (i == FREE) free((void *)*sp); 523 | else if (i == MSET) a = (int)memset((char *)sp[2], sp[1], *sp); 524 | else if (i == MCMP) a = memcmp((char *)sp[2], (char *)sp[1], *sp); 525 | else if (i == EXIT) { printf("exit(%d) cycle = %d\n", *sp, cycle); return *sp; } 526 | else { printf("unknown instruction = %d! cycle = %d\n", i, cycle); return -1; } 527 | } 528 | } 529 | -------------------------------------------------------------------------------- /hello.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("hello, world\n"); 6 | return 0; 7 | } 8 | --------------------------------------------------------------------------------