17 votes

Brainfuck just-in-time compiler with hand-rolled code generation

4 comments

  1. [4]
    isopod
    Link
    Fascinating. If anyone is interested in how a JIT compiler is implemented, the source looks to be in the ballpark of 1500 lines of clean, well-structured Rust. I gave it a read and it cleared a...

    Fascinating. If anyone is interested in how a JIT compiler is implemented, the source looks to be in the ballpark of 1500 lines of clean, well-structured Rust. I gave it a read and it cleared a few things up for me that I'd always wondered about (how do you mark memory as executable and transfer execution in/out of it?)

    It would probably have been much easier for the author to just emit assembly code to disk, but I think the approach they chose is instructive.

    3 votes
    1. [3]
      teaearlgraycold
      Link Parent
      Thanks! Author is me. And you are absolutely right, just generating all of the machine code in one shot would be better. But it’s more fun this way.

      Thanks! Author is me. And you are absolutely right, just generating all of the machine code in one shot would be better. But it’s more fun this way.

      1 vote
      1. [2]
        isopod
        Link Parent
        Oh, that's very cool! I didn't realize. I think my biggest takeaway from reading your code is that if you replaced code_gen with something more powerful and wrote an AST for a slightly more...

        Oh, that's very cool! I didn't realize.

        I think my biggest takeaway from reading your code is that if you replaced code_gen with something more powerful and wrote an AST for a slightly more complex language, you could actually get a JIT for something nontrivial. Like, it might be a few thousand lines, but it would work.

        I've written a bunch of interpreters but I never actually thought it was, idk, in my capacity to do something like that. It always felt like something big teams attacked, not a side project. It's tempting, isn't it?

        2 votes
        1. teaearlgraycold
          Link Parent
          Yeah - either of us could definitely make a JIT for a LISP or something! Wouldn’t be crazy difficult.

          Yeah - either of us could definitely make a JIT for a LISP or something! Wouldn’t be crazy difficult.

          1 vote