├── .gitignore ├── assets ├── screencast.png └── thumbnail.png ├── hello.c ├── README.md ├── LICENSE └── c.php /.gitignore: -------------------------------------------------------------------------------- 1 | *.py 2 | *.asm 3 | -------------------------------------------------------------------------------- /assets/screencast.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsoding/c.php/HEAD/assets/screencast.png -------------------------------------------------------------------------------- /assets/thumbnail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tsoding/c.php/HEAD/assets/thumbnail.png -------------------------------------------------------------------------------- /hello.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | printf("Hello, World\n"); 6 | printf("important: "); 7 | // printf("Foo, %s, %d\n", "Bar", 69); 8 | return 69; 9 | } 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![thumbnail](./assets/thumbnail.png) 2 | 3 | # Optimizing C to Python compiler in PHP 4 | 5 | This is an April Fools joke. Please don't take it seriously. It only supports a very small subset of C. Literally return and function call. We even made printf an intrinsic. Please don't use it in production. 6 | 7 | ## Quick Start 8 | 9 | ```console 10 | $ php c.php hello.c > hello.py 11 | $ python ./hello.py 12 | ``` 13 | 14 | ## Screencast 15 | 16 | [![screencast](./assets/screencast.png)](https://www.youtube.com/watch?v=Yi6NxMxCFY8) 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright © 2023 Alexey Kutepov 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /c.php: -------------------------------------------------------------------------------- 1 | file_path = $file_path; 28 | $this->row = $row; 29 | $this->col = $col; 30 | } 31 | 32 | public function display() { 33 | return sprintf("%s:%d:%d", $this->file_path, $this->row + 1, $this->col + 1); 34 | } 35 | } 36 | 37 | // #include \nint main(void) {\n... 38 | // ^ ^ 39 | define("TOKEN_NAME", "TOKEN_NAME"); 40 | define("TOKEN_OPAREN", "TOKEN_OPAREN"); 41 | define("TOKEN_CPAREN", "TOKEN_CPAREN"); 42 | define("TOKEN_OCURLY", "TOKEN_OCURLY"); 43 | define("TOKEN_CCURLY", "TOKEN_CCURLY"); 44 | define("TOKEN_COMMA", "TOKEN_COMMA"); 45 | define("TOKEN_SEMICOLON", "TOKEN_SEMICOLON"); 46 | define("TOKEN_NUMBER", "TOKEN_NUMBER"); 47 | define("TOKEN_STRING", "TOKEN_STRING"); 48 | define("TOKEN_RETURN", "TOKEN_RETURN"); 49 | 50 | class Token { 51 | public $type; 52 | public $value; 53 | public $loc; 54 | 55 | public function __construct($loc, $type, $value) { 56 | $this->loc = $loc; 57 | $this->type = $type; 58 | $this->value = $value; 59 | } 60 | } 61 | 62 | class Lexer { 63 | public $file_path; 64 | public $source; 65 | public $cur; 66 | public $bol; 67 | public $row; 68 | 69 | public function __construct($file_path, $source) { 70 | $this->file_path = $file_path; 71 | $this->source = $source; 72 | $this->cur = 0; 73 | $this->bol = 0; 74 | $this->row = 0; 75 | } 76 | 77 | function is_not_empty() { 78 | return $this->cur < strlen($this->source); 79 | } 80 | 81 | function is_empty() { 82 | return !$this->is_not_empty(); 83 | } 84 | 85 | function chop_char() { 86 | if ($this->is_not_empty()) { 87 | $x = $this->source[$this->cur]; 88 | $this->cur += 1; 89 | if ($x === "\n") { 90 | $this->bol = $this->cur; 91 | $this->row += 1; 92 | } 93 | } 94 | } 95 | 96 | function loc() { 97 | return new Loc($this->file_path, $this->row, $this->cur - $this->bol); 98 | } 99 | 100 | function trim_left() { 101 | while ($this->is_not_empty() && ctype_space($this->source[$this->cur])) { 102 | $this->chop_char(); 103 | } 104 | } 105 | 106 | function drop_line() { 107 | while ($this->is_not_empty() && $this->source[$this->cur] !== "\n") { 108 | $this->chop_char(); 109 | } 110 | if ($this->is_not_empty()) { 111 | $this->chop_char(); 112 | } 113 | } 114 | 115 | function next_token() { 116 | $this->trim_left(); 117 | while ($this->is_not_empty()) { 118 | $s = substr($this->source, $this->cur); 119 | if (!php7_str_starts_with($s, "#") && !php7_str_starts_with($s, "//")) break; 120 | $this->drop_line(); 121 | $this->trim_left(); 122 | } 123 | 124 | if ($this->is_empty()) { 125 | return false; 126 | } 127 | 128 | $loc = $this->loc(); 129 | $first = $this->source[$this->cur]; 130 | 131 | if (ctype_alpha($first)) { 132 | $index = $this->cur; 133 | while ($this->is_not_empty() && ctype_alnum($this->source[$this->cur])) { 134 | $this->chop_char(); 135 | } 136 | 137 | $value = substr($this->source, $index, $this->cur - $index); 138 | return new Token($loc, TOKEN_NAME, $value); 139 | } 140 | 141 | $literal_tokens = array( 142 | "(" => TOKEN_OPAREN, 143 | ")" => TOKEN_CPAREN, 144 | "{" => TOKEN_OCURLY, 145 | "}" => TOKEN_CCURLY, 146 | "," => TOKEN_COMMA, 147 | ";" => TOKEN_SEMICOLON, 148 | ); 149 | if (isset($literal_tokens[$first])) { 150 | $this->chop_char(); 151 | return new Token($loc, $literal_tokens[$first], $first); 152 | } 153 | 154 | if ($first === '"') { 155 | $this->chop_char(); 156 | $start = $this->cur; 157 | $literal = ""; 158 | while ($this->is_not_empty()) { 159 | $ch = $this->source[$this->cur]; 160 | switch ($ch) { 161 | case '"': break 2; 162 | case '\\': { 163 | $this->chop_char(); 164 | if ($this->is_empty()) { 165 | print("{$lexer->loc()}: ERROR: unfinished escape sequence\n"); 166 | exit(69); 167 | } 168 | 169 | $escape = $this->source[$this->cur]; 170 | switch ($escape) { 171 | case 'n': 172 | $literal .= "\n"; 173 | $this->chop_char(); 174 | break; 175 | 176 | case '"': 177 | $literal .= "\""; 178 | $this->chop_char(); 179 | break; 180 | 181 | default: 182 | print("{$this->loc()}: ERROR: unknown escape sequence starts with {$escape}\n"); 183 | } 184 | 185 | } break; 186 | 187 | default: 188 | $literal .= $ch; 189 | $this->chop_char(); 190 | } 191 | } 192 | 193 | if ($this->is_not_empty()) { 194 | $this->chop_char(); 195 | return new Token($loc, TOKEN_STRING, $literal); 196 | } 197 | 198 | echo sprintf("%s: ERROR: unclosed string literal\n", $loc->display()); 199 | exit(69); 200 | } 201 | 202 | if (ctype_digit($first)) { 203 | $start = $this->cur; 204 | while ($this->is_not_empty() && ctype_digit($this->source[$this->cur])) { 205 | $this->chop_char(); 206 | } 207 | 208 | $value = (int)substr($this->source, $start, $this->cur - $start); 209 | return new Token($loc, TOKEN_NUMBER, $value); 210 | } 211 | 212 | print("{$loc->display()}: ERROR: unknown token starts with {$first}\n"); 213 | exit(69); 214 | } 215 | } 216 | 217 | define("TYPE_INT", "TYPE_INT"); 218 | 219 | class FuncallStmt { 220 | public $name; 221 | public $args; 222 | 223 | public function __construct($name, $args) { 224 | $this->name = $name; 225 | $this->args = $args; 226 | } 227 | } 228 | 229 | class RetStmt { 230 | public $expr; 231 | 232 | public function __construct($expr) { 233 | $this->expr = $expr; 234 | } 235 | } 236 | 237 | class Func { 238 | public $name; 239 | public $body; 240 | 241 | public function __construct($name, $body) { 242 | $this->name = $name; 243 | $this->body = $body; 244 | } 245 | } 246 | 247 | function expect_token($lexer, ...$types) { 248 | $token = $lexer->next_token(); 249 | if (!$token) { 250 | echo sprintf("%s: ERROR: expected %s but got end of file\n", 251 | $lexer->loc()->display(), join(" or ", $types)); 252 | return false; 253 | } 254 | 255 | foreach($types as &$type) { 256 | if ($token->type === $type) { 257 | return $token; 258 | } 259 | } 260 | 261 | echo sprintf("%s: ERROR: expected %s but got %s\n", 262 | $lexer->loc()->display(), 263 | join(" or ", $types), 264 | $token->type); 265 | return false; 266 | } 267 | 268 | function parse_type($lexer) { 269 | $return_type = expect_token($lexer, TOKEN_NAME); 270 | if ($return_type->value !== "int") { 271 | echo sprintf("%s: ERROR: unexpected type %s", 272 | $return_type->loc->display(), 273 | $return_type->value); 274 | return false; 275 | } 276 | return TYPE_INT; 277 | } 278 | 279 | function parse_arglist($lexer) { 280 | if (!expect_token($lexer, TOKEN_OPAREN)) return false; 281 | $arglist = array(); 282 | 283 | // First argument (optional). 284 | $expr = expect_token($lexer, TOKEN_STRING, TOKEN_NUMBER, TOKEN_CPAREN); 285 | if (!$expr) return false; 286 | if ($expr->type == TOKEN_CPAREN) { 287 | // Call with no arguments. 288 | return $arglist; 289 | } 290 | array_push($arglist, $expr->value); 291 | 292 | // Second, third, etc. arguments (optional). 293 | while (true) { 294 | $expr = expect_token($lexer, TOKEN_CPAREN, TOKEN_COMMA); 295 | if (!$expr) return false; 296 | if ($expr->type == TOKEN_CPAREN) break; 297 | 298 | $expr = expect_token($lexer, TOKEN_STRING, TOKEN_NUMBER); 299 | if (!$expr) return false; 300 | array_push($arglist, $expr->value); 301 | } 302 | 303 | return $arglist; 304 | } 305 | 306 | function parse_block($lexer) { 307 | if (!expect_token($lexer, TOKEN_OCURLY)) return false; 308 | 309 | $block = array(); 310 | 311 | while (true) { 312 | $name = expect_token($lexer, TOKEN_NAME, TOKEN_CCURLY); 313 | if (!$name) return false; 314 | if ($name->type == TOKEN_CCURLY) break; 315 | 316 | if ($name->value == "return") { 317 | $expr = expect_token($lexer, TOKEN_NUMBER, TOKEN_STRING); 318 | if (!$expr) return false; 319 | array_push($block, new RetStmt($expr->value)); 320 | } else { 321 | $arglist = parse_arglist($lexer); 322 | if (!$arglist) return false; 323 | array_push($block, new FuncallStmt($name, $arglist)); 324 | } 325 | 326 | if (!expect_token($lexer, TOKEN_SEMICOLON)) return false; 327 | } 328 | 329 | return $block; 330 | } 331 | 332 | function parse_function($lexer) { 333 | $return_type = parse_type($lexer); 334 | if (!$return_type) return false; 335 | assert($return_type === TYPE_INT); 336 | 337 | $name = expect_token($lexer, TOKEN_NAME); 338 | if (!$name) return false; 339 | 340 | if (!expect_token($lexer, TOKEN_OPAREN)) return false; 341 | if (!expect_token($lexer, TOKEN_CPAREN)) return false; 342 | 343 | $body = parse_block($lexer); 344 | 345 | return new Func($name, $body); 346 | } 347 | 348 | function generate_python3($func) { 349 | function literal_to_py($value) { 350 | if (is_string($value)) { 351 | return "\"" . str_replace("\n", "\\n", $value) . "\""; 352 | } else { 353 | return (string)$value; 354 | } 355 | } 356 | 357 | foreach($func->body as &$stmt) { 358 | if ($stmt instanceof FuncallStmt) { 359 | if ($stmt->name->value === "printf") { 360 | $format = $stmt->args[0]; 361 | if (count($stmt->args) <= 1) { 362 | if (php7_str_ends_with($format, "\\n")) { 363 | // Optimization: print("x") is faster than print("x\n", end=""). 364 | $format_without_newline = substr($format, 0, strlen($format) - 2); 365 | echo sprintf("print(%s)\n", literal_to_py($format_without_newline)); 366 | } else { 367 | // Optimization: Don't invoke Python's % operator if it's unnecessary. 368 | echo sprintf("print(%s, end=\"\")\n", literal_to_py($format)); 369 | } 370 | } else { 371 | $substitutions = " % ("; 372 | foreach ($stmt->args as $i => $arg) { 373 | if ($i === 0) continue; // Skip format string. 374 | $substitutions .= literal_to_py($arg) . ","; 375 | } 376 | $substitutions .= ")"; 377 | echo sprintf("print(%s%s, end=\"\")\n", literal_to_py($format), $substitutions); 378 | } 379 | } else { 380 | echo sprintf("%s: ERROR: unknown function %s\n", 381 | $stmt->name->loc->display(), 382 | $stmt->name->value); 383 | exit(69); 384 | } 385 | } 386 | } 387 | } 388 | 389 | function generate_fasm_x86_64_linux($func) { 390 | print("format ELF64 executable 3\n"); 391 | print("segment readable executable\n"); 392 | print("entry start\n"); 393 | print("start:\n"); 394 | $strings = array(); 395 | foreach($func->body as &$stmt) { 396 | if ($stmt instanceof RetStmt) { 397 | print(" mov rax, 60\n"); 398 | print(" mov rdi, {$stmt->expr}\n"); 399 | print(" syscall\n"); 400 | } else if ($stmt instanceof FuncallStmt) { 401 | if ($stmt->name->value === "printf") { 402 | $arity = count($stmt->args); 403 | if ($arity !== 1) { 404 | print("{$stmt->name->loc->display()}: ERROR: expected 1 argument but got {$arity}\n"); 405 | exit(69); 406 | } 407 | 408 | $format = $stmt->args[0]; 409 | $type = gettype($format); 410 | if ($type !== "string") { 411 | print("{$stmt->name->loc->display()}: ERROR: expected string argument but got {$type}\n"); 412 | exit(69); 413 | } 414 | 415 | $n = count($strings); 416 | $m = strlen($format); 417 | print(" mov rax, 1\n"); 418 | print(" mov rdi, 1\n"); 419 | print(" mov rsi, str_{$n}\n"); 420 | print(" mov rdx, {$m}\n"); 421 | print(" syscall\n"); 422 | 423 | array_push($strings, $format); 424 | } else { 425 | echo sprintf("%s: ERROR: unknown function %s\n", 426 | $stmt->name->loc->display(), 427 | $stmt->name->value); 428 | exit(69); 429 | } 430 | } else { 431 | die("unreachable"); 432 | } 433 | } 434 | 435 | print("segment readable writable\n"); 436 | foreach($strings as $n => $string) { 437 | print("str_{$n} db "); 438 | $m = strlen($string); 439 | for ($i = 0; $i < $m; ++$i) { 440 | $c = ord($string[$i]); 441 | if ($i > 0) print(","); 442 | print("{$c}"); 443 | } 444 | print("\n"); 445 | } 446 | } 447 | 448 | function usage($program) { 449 | print("Usage: php $program [OPTIONS] \n"); 450 | print("OPTIONS:\n"); 451 | print(" -target Compilation target. Provide `list` to get the list of targets. (default: python3)\n"); 452 | print(" -help Print this message\n"); 453 | } 454 | 455 | function main($argv) { 456 | $platforms = array( 457 | "python3", 458 | "fasm-x86_64-linux" 459 | ); 460 | 461 | $program = array_shift($argv); 462 | $input = null; 463 | $platform = $platforms[0]; 464 | 465 | while (sizeof($argv) > 0) { 466 | $flag = array_shift($argv); 467 | switch ($flag) { 468 | case "-help": { 469 | usage($program); 470 | exit(0); 471 | } break; 472 | 473 | case "-target": { 474 | if (sizeof($argv) === 0) { 475 | usage($program); 476 | print("ERROR: no value was provided for flag $flag\n"); 477 | exit(69); 478 | } 479 | 480 | $arg = array_shift($argv); 481 | 482 | if ($arg === "list") { 483 | print("Available targets:\n"); 484 | foreach ($platforms as $p) { 485 | print(" $p\n"); 486 | } 487 | exit(69); 488 | } 489 | 490 | if (in_array($arg, $platforms)) { 491 | $platform = $arg; 492 | } else { 493 | usage($program); 494 | print("ERROR: unknown target $arg\n"); 495 | exit(69); 496 | } 497 | } break; 498 | 499 | default: 500 | $input = $flag; 501 | } 502 | } 503 | 504 | if ($input === null) { 505 | usage($program); 506 | print("ERROR: no input is provided\n"); 507 | exit(69); 508 | } 509 | 510 | $file_path = $input; 511 | $source = file_get_contents($file_path); 512 | if (!$source) exit(69); 513 | $lexer = new Lexer($file_path, $source); 514 | $func = parse_function($lexer); 515 | if (!$func) exit(69); 516 | 517 | switch ($platform) { 518 | case "python3": generate_python3($func); break; 519 | case "fasm-x86_64-linux": generate_fasm_x86_64_linux($func); break; 520 | default: todo("unreachable"); break; 521 | } 522 | } 523 | 524 | main($argv); 525 | --------------------------------------------------------------------------------