Hacker News new | ask | show | jobs
by mg 2429 days ago
Nice. I immediately had to try the same in PHP. To make a working repl with newlines in the output etc, this is what I a came up with:

    while(1) {eval(fgets(STDIN));echo "\n";};
I then tried it on the command line like this:

    php -r 'while(1) {eval(fgets(STDIN));echo "\n";};';
Hurray, it prompted me for input! So I typed:

    for ($i=0;$i<10;$i++) echo $i;
Which got me:

    0123456789
So far so good.

I wondered: Can we now run the repl in the repl? So I typed:

    while(1) {eval(fgets(STDIN));echo "\n";};
It kept prompting me for input. Am I in a REPL in a REPL now? I typed:

    echo "Hello from a REPL in a REPL!";
And the reply was:

    Hello from a REPL in a REPL!
I'm not totally sure if I believe it though.
2 comments

It is that simple! It has practical benefits. For example, if you can call that code from somewhere specific in your program, which is handy for debugging. If your `eval` function takes a lexical environment, you can also implement a debugger easily.

To test whether your logic is working properly, make your repl print out a different character when it prompts for input. For example, the toplevel repl can print out "> " whereas the inner repl prints out "repl> "

For bonus points, your repl should exit if you type Ctrl-D. That way you can go from the inner repl to the outer repl, and from there it should exit your program.

Sounds like a Nine Inch Nails song.

"I am in a REPL in a REPL in a REPL,

Running all my code in nested loops..."

https://youtu.be/pVB_DI4ajKA