~rootmos/AoC

fdd2722fddade8b30689a5209ff9ba8dae67b3b1 — Gustav Behm a month ago 68bdb3f
Emit some C for fun
1 files changed, 52 insertions(+), 6 deletions(-)

M 2023/08.hs
M 2023/08.hs => 2023/08.hs +52 -6
@@ 116,25 116,71 @@ emit h (is, map) = do

  let starts = filter isStart ns
      s = length starts
  put $ "int starts[] = {"
  put $ "int ns[] = {"
  flip traverse_ starts $ \n -> do
    put $ printf "n_%s, " n
  putLn $ "};"
  putLn ""

  putLn "#include <stdio.h>"
  putLn $ "int isEnd(enum node n) {"
  putLn $ "    switch(n) {"
  flip traverse_ (filter isEnd ns) $ \n -> do
    putLn $ printf "    case n_%s:" n
  putLn $ "        return 1;"
  putLn $ "    }"
  putLn $ "    return 0;"
  putLn $ "}"
  putLn $ ""

  putLn $        "int endOfTheLine() {"
  putLn $ printf "    for(int i = 0; i < %d; i++) {" s
  putLn $        "        if(!isEnd(ns[i])) return 0;"
  putLn $        "    }"
  putLn $        "    return 1;"
  putLn $        "}"
  putLn $        ""

  putLn $        "void step(const int d[]) {"
  putLn $ printf "    for(int i = 0; i < %d; i++) {" s
  putLn $        "        ns[i] = d[ns[i]];"
  putLn $        "    }"
  putLn $        "}"
  putLn $        ""

  putLn $ "int* instructions[] = {"
  flip traverse_ is $ \case
    'L' -> putLn $ printf "    lefts,"
    'R' -> putLn $ printf "    rights,"
  putLn $ "};"
  putLn $ ""

  putLn          "#include <stdio.h>"
  putLn          "size_t go() {"
  putLn          "    size_t i = 0;"
  putLn          "    for(;;) {"
  putLn $ printf "        for(size_t j = 0; j < %d; j++) {" (length is)
  putLn          "            step(instructions[j]);"
  putLn          "            if(endOfTheLine()) {"
  putLn          "                return i + j;"
  putLn          "            }"
  putLn          "        }"
  putLn $ printf "        i += %d;" (length is)
  putLn          "    }"
  putLn          "}"

  putLn "int main() {"
  putLn "    printf(\"hello\\n\");"
  putLn "    printf(\"%zu\\n\", go()+1);"
  putLn "    return 0;"
  putLn "}"

partB :: Parse -> IO ()
partB p = do
  withSystemTempFile "08.c" $ \fp -> \h -> do
    emit h p 
    emit h p
    hFlush h

    callProcess "cat" [ "-n", fp ]
    --callProcess "cat" [ "-n", fp ]
    --callProcess "cp" [ fp, "08.c" ]
    callProcess "tcc" [ "-run", fp ]

main :: IO ()


@@ 142,4 188,4 @@ main = with parser $ do
  run "08.example" "a example" partA -- 2
  run "08.input" "a input" partA -- 19631
  runIO "08b.example" "b example" partB -- 6
  --run "08.input" "b input" partB
  runIO "08.input" "b input" partB