dekulan

AoC 2021 day 24, writing programs (Perl) that write programs (C Macros) that write programs (C)

Dec 24th, 2021 (edited)
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.62 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5. use v5.10;
  6.  
  7. my $comment = <<'END';
  8. END
  9.  
  10. # compile input down to C code. We'll need a support function for
  11. # implementing 'inp', so, why not actually write everything with
  12. # macros...
  13.  
  14. my $preamble = << '__C';
  15.  
  16. #include <stdio.h>
  17.  
  18. #define INP(a)     a = *(input++)
  19. #define ADD(a,b)   a += b
  20. #define MUL(a,b)   a *= b
  21. #define DIV(a,b)   a /= b
  22. #define MOD(a,b)   a %= b
  23. #define EQL(a,b)   a = (a == b) ? 1 : 0
  24.  
  25. long program(long *input) {
  26.     signed long w = 0;
  27.     signed long x = 0;
  28.     signed long y = 0;
  29.     signed long z = 0;
  30.  
  31. __C
  32.  
  33. my $postamble = << '__C';
  34.  
  35.     return z;
  36. }
  37.  
  38. // increments number, returning false on overflow
  39. int increment(long *num) {
  40.  
  41.     int digit = 9;
  42.     while (digit >= 0) {
  43.         num[digit]++;
  44.         if (num[digit] < 10) {
  45.             return 1;
  46.         }
  47.         // carry to next higher digit
  48.         num[digit] = 1;
  49.         --digit;
  50.     }
  51.     return 0;
  52. }
  53.  
  54. int main(int ac, char** av) {
  55.     long low[14] = { 1, 4, 9, 1, 1, 6, 7, 5, 3, 1, 1, 1, 1, 4 };
  56.     // while(increment(low)) {
  57.     // }
  58.     printf("low x = %d\n", program(low));
  59.     long high[14] = { 6, 9, 9, 1, 4, 9, 9, 9, 9, 7, 5, 3, 6, 9 };
  60.     // while(increment(high)) {
  61.     // }
  62.     printf("high x = %d\n", program(high));
  63.     return 0;
  64. }
  65.  
  66. __C
  67.  
  68. my @clines = ();
  69. foreach ((<>)) {
  70.     chomp;
  71.     if (/^inp (\w)/) {
  72.     push @clines, "INP($1);";
  73.     } elsif (/^(\w+) (\w) ([wxyz]|-?\d+)/) {
  74.     my $instr = uc $1;
  75.     push @clines, "$instr($2,$3);"
  76.     } else {
  77.     die "parse error: $_\n";
  78.     }
  79. }
  80.  
  81. say $preamble;
  82. say join "\n", @clines;
  83. say $postamble;
  84.  
Add Comment
Please, Sign In to add comment