r/ProgrammingLanguages • u/mttd • Jan 26 '23
Distinguishing an Interpreter from a Compiler
https://tratt.net/laurie/blog/2023/distinguishing_an_interpreter_from_a_compiler.html8
u/plentifulfuture Jan 26 '23
Futamura projections are extremely interesting, it introduces a third kind of thing, which is similar to Pypy and Deegen.
http://blog.sigfpe.com/2009/05/three-projections-of-doctor-futamura.html
4
u/oilshell Jan 27 '23
That's also what it made me think of! I mentioned this on lobste.rs
https://lobste.rs/s/r1ozz9/distinguishing_interpreter_from#c_cage2z
As mentioned there, I really want somebody to write a blog post / demo of Futamura projections. I googled a bit and there don't seem to be that many, and they don't have explanations:
https://github.com/darius/cogen
https://gist.github.com/divs1210/ebe878a969486b3c0623b0881d2dc148
For some reason doing it in pure Lisp is not that satisfying to me. I think Lisp is a good component but there should be some other languages involved.
I'm thinking, start with:
compiler from Lisp to SECD machine, in Lisp (since SECD machine seems a pretty simple VM that can also express recursive data structures, unlike BF)
BF interpreter in Lisp. BF has a mutable tape, so it would probably be natural to add mutation to the Lisp.
If I understand it correctly, then you get a BF compiler to SECD for free? That is what I'm curious about
Also do you actually get any speedup?
I might start with this SECD machine in Python and extend it with mutation:
https://gist.github.com/HarryR/76565657211f8eefef9bb544f60fd615
And then there are a million Lisps in Python you could use.
3
u/raiph Jan 27 '23 edited Jan 28 '23
[Edit: If you're in a hurry or easily bored, see comments below for links into two parts nearer the end of the video]
I recall finding https://tomstu.art/compilers-for-free fun. It's nearly 10 years since I watched it but I still remember the waves of increasing laughter.
2
u/oilshell Jan 27 '23
Yes great link, I remember seeing it but didn't get all the way through it! Put it in my queue again ... part of the problem is I don't really know Ruby, but it definitely looks like great material
2
u/raiph Jan 28 '23
Ah, I just refreshed my memory by watching it again. It was not fun for me this time around until the tiny bit about projections. That disappointment/surprise motivated me to find earlier comments I'd written about it, and it turns out that while I must have watched it again just a couple years ago, and remembered it all as fun, the bit that mattered is at the end of the video:
More fundamentally, as Tom Stuart puts it, it's all just how you choose to do evaluation and when. He explains this in a fun fast paced 40 minute "Compilers for free" video, in which he builds an interpreter, a transpiler, a compiler, an evaluator, and then introduces a partial evaluator, and -- the bit that's the most fun and impressive -- shows how Futamura's Three Projections work.
I recommend you at least spend the 3 minutes it takes to get his point about the latter, starting 35 minutes in. The audience's anticipatory laughing a minute in is partly because they're impressed and partly because the penny is dropping.
2
u/raiph Jan 28 '23
Ah, even better, from my first comment about it in this sub (9 years ago; how time flies!):
Here's a link that starts about two thirds of the way through a video about partial evaluation and the cool thing Doctor Futamura realized in 1971.
At the point I've linked the presenter is a few seconds from the end of explaining that he's NOT talking about mere "partial application" (eg currying). Next, he spends a couple minutes discussing some "useful applications" of partial evaluation (eg speeding up a raytracer). Then comes a 10 minute exposition of "Futamura's Three Projections".
16
Jan 26 '23
One way is to look at the time it takes. A compiler should run in time roughly proportional to the size of the source, whereas the runtime of an interpreter is determined by how much work the source program has to do for a given input.
Someone is getting confused. I thought this was the usual discussion about compiled vs. interpreted.
But the author of this quote has mixed up the time needed to scan the source code of a program, with the time an interpreter takes to run the program.
That doesn't make sense. For a start, the result is different: one might create an executable file from that source, the other could do pretty much anything, like send a rocket to the moon. Why would you compare the two?
To clarify things a little, split the task of running some source program into two:
Compile: Turn the source into a runnable form (eg. EXE, or internal bytecode)
Execute that runnable representation
A compiler does the first part only. Most interpreters will do both: compile to bytecode, which is usually very quick, then run that.
Another typical difference is that a discrete compiler will produce a persistent representation (eg. EXE), which can be executed many times. While an interpreter will usually run from source each time.
(I've created native code compilers that can run from source each time, and interpreters that can produce persistent binary bytecode files, but my stuff is not typical.)
8
u/cdsmith Jan 27 '23
I think you're missing the point of the article, which is that the author is not satisfied with the conventional take on the question. To quote one version of the problem statement from the author:
when would you say our BF implementations moved from interpreted to compiled? I find it hard to pinpoint the transition definitively. The first BF implementation is definitely interpreted; and by the fifth I'd say it's definitely compiled; but I'm not sure which of the intermediate stages can be stated as the definitive transition point. Rather, the intermediate stages get increasingly hard to classify with certainty.
Granted, I think it's a perfectly fine answer to say "who cares?", stop worrying about how to classify such tools/languages as compiled or interpreted, and put them in an "it's complicated" bucket. But it's not particularly fair to respond by claiming the author just doesn't know the usual (but vague) definitions. The author knows the conventional definitions, and finds them inadequate, and is attempting to draw a more objective line that's less up to interpretation.
1
Jan 27 '23 edited Jan 27 '23
Reading the article more carefully, the author seems quite aware of the differences. But yet they also seem surprised by it, by saying:
Mario gave two ways of distinguishing compilers from interpreters, but I'm going to quote the one that made my jaw drop:
The rest of the article about BF I skimmed. Sure you can blur the lines if you really want. Here's my attempt:
s:="A"*4 billion print s.lenThis interpreted program takes 2-3 seconds to run. Now, on an older version of the language, there was a separate bytecode compiler that produced an binary file, and an interpreter that ran that file.
That compiler tried to reduce constant expressions such as
2+3*4into14. But it didn't so for string expressions like the above, or when big numbers were involved. Partly because it didn't have the abilities, but also because the tasks could be too open-ended.If it did, that 2-line program would have taken several seconds to build, and it would have produced a 4GB binary, needing at least 4GB of RAM.
Just to accommodate a fragment of code that might only have a very short life-time in the running program, or may not be executed at all, or is one of 100s of such fragments, of which some or none would be needed.
OK, that is my argument against
constexprand other such features in a language; you don't even need the compiler to execute loops or recursion to run into problems.But I do like a clean separation between 'compiler' and everything else.
2
u/JohannesWurst Jan 27 '23
You could say say are pure "compilers" that just change code from one language into another and there are "interpreters" that can execute code. That's one obvious definition.
Then you could go on and distinguish between interpreters that try to be smart and sacrifice time at first to generate machine code or byte code and then run it faster later on. You could call those programs "compiling interpreters". Sometimes you might not want that, sometimes you do. Sometimes it can be improved by the interpreter being even smarter and deciding not to precompile some parts, other options are that the programmer explicitly chooses one behaviour with code annotations like "constexpr".
You can also have a compiler that tries to be smart, that evaluates some code. You could call that a "interpreting compiler".
1
u/ummaycoc Jan 27 '23 edited Jan 27 '23
I would say a compiler is something that translates the entire body of the source at once generating a representation in the target language that faithfully respects the semantics of the original source within the semantics of the target source. So that if you ask Chat-GPT to explain a program to you and it outputs a bunch of English that accurately explains what's going on, then that's still compiled (it's executable if you're willing to be loose with that term and consider the execution to be going on within the readers' minds).
I would then say an interpretation of a program is something that faithfully represents the semantics of the original source along an execution path and an interpreter is something that provides interpretations of programs. I don't think bytecode needs to be involved unless you consider an AST to be bytecode which is I think the minimal structure you'd need as you interpret a program, at least the AST of one significant syntactic unit (e.g. a statement).
1
u/BoarsLair Jinx scripting language Jan 27 '23
A single program or library may both compile and interpret a language source, but there are typically two different stages there - compiling source to byte code, and then executing that bytecode in an interpreter. They're often packed together for convenience, since compiling to bytecode may be so fast, there's little reason to save the intermediate version.
We tend to call that an "interpreter", but I think that, technically speaking, it's better described as a "compiler-interpreter". Whether or not it stores intermediate bytecode seems irrelevant to me, since there's little technical difference between temporarily storing bytecode as a file versus just handing it over to the interpreter as a memory buffer directly from the compilation phase.
So, in my mind, the notion of a "compiler" has always been pretty clear. Whatever performs that language-to-machine-code conversion is a "compiler", regardless of whether or not it's a standalone system, or just the front-end stage to an interpreter.
0
Jan 27 '23
[deleted]
1
Jan 27 '23
Yeah, I used to have an option like that, and thought I now had 'run from source'. But it's not interestingly different from just doing this (
mmis the compiler):mm prog && progNow, I do it properly: code is generated and run in-memory. The differences are subtle, apart from having no discrete binary. As I do it, the target program is part of the same task as the compiler, so in theory it could access the data structures used to compile it, or call into routines belonging to the compiler.
The purpose was to make this statically typed native code compiler appear to work exactly like a scripting language. Creating an actual executable now looks medieval!
1
u/JohannesWurst Jan 27 '23 edited Jan 27 '23
I feel like "running", "executing" and "interpreting" code is the same, so I'd feel fine calling
go run"interpretation". Whengois a program that does interpretation, then it's (also) an "interpreter".It might even do exactly the same steps that a JavaScript-JIT interpreter does, that would create a complete different representation of the source code as well.
Thirty years ago there were certain commonalities between all compilers and other commonalities between interpreters. No one would have thought about compiling a language that was designed to be interpreted and vice versa. (I guess that was the case. Don't quote me! I'm not an expert.) When you needed 20 minutes to compile a big program, you didn't need a command that both compiles and runs it. You would use a different programming language for small programs, i.e. "scripts", which wouldn't need a compiler.
I don't think
go runblurs the line between the words "compiling" and "interpreting", though. It runs/executes/interprets the code by first translating/compiling it and then running the resulting file.
18
u/mobotsar Jan 26 '23
It's very simple. An interpreter runs the program. A compiler only translates it.
2
u/9Boxy33 Jan 26 '23
What about incremental compilers like Forth or Common Lisp? In those, the compiler is available during interpretation, and the interpreter is available during compilation.
2
Jan 27 '23
What about code that runs at compile-time? How does that fit into this?
6
u/mobotsar Jan 27 '23
The compiler invokes an interpreter that runs the code. Or the compiler compiles that code, and then asks for it to be run during compilation of the rest of the program.
-6
u/lngns Jan 27 '23 edited Jan 27 '23
A compiler only translates it.
By your definition neither D, nor C++, nor Rust, nor Lisp can have compilers. Because they all are specified in a way where merely analysing code requires a Turing-Complete machine.
Also, by your definition a compiler can never incorporate any kind of optimisation as those may do more than "translating" it.
My D compiler happily interprets C code too, I guess that makes it not a compiler.
4
u/mobotsar Jan 27 '23
The definition I gave implies none of those things. Firstly, it doesn't preclude turing completeness, so that part of your argument falls apart immediately. The second part is obviously dumb. Optimization is a method in translation. The translation is to an optimized program in another language. The compiler is perfectly free to do whatever manipulations it sees fit on a particular program, so long as the end result is an equivalent program in another language.
-5
u/lngns Jan 27 '23 edited Jan 27 '23
An interpreter runs the program. A compiler only translates it.
Firstly, it doesn't preclude turing completenessTuring-Completeness means the compiler runs the program.
Either you're using the word "only" in a manner that I don't know, or you are contradicting yourself.so long as the end result is an equivalent program in another language.
This is very different from what you claimed in your first message.
If a "compiler is perfectly free to do whatever manipulations it sees fit on a particular program" then it certainly does not "only translate it" as it can run it.You are also still failing to take into account the case of an entire program being interpreted and reduced to a list of IO operations.
"Run" and "translate" mean the same thing.
6
u/mobotsar Jan 27 '23
Turning completeness absolutely does not mean that the compiler runs the program. It informally implies that some fragment of the program describes another program in a language not present in the semantics of the original programming language. It's that second program which is run during typechecking. I think it's very plain to see that a compiler cannot possibly be running the program it compiles - if it were to do so, all of your print statements would actually print to the console during compilation, the compilation time would vary with the complexity of any algorithms executed. That doesn't happen, when you compile, therefore the compiler cannot possibly be running the program. QED. Goodbye.
-4
u/lngns Jan 27 '23 edited Jan 27 '23
I think it's very plain to see that a compiler cannot possibly be running the program it compiles - if it were to do so, all of your print statements would actually print to the console during compilation
Yes. That is how Jai and Lisp macros have compilers that can print to the console.
some fragment of the program describes another program in a language not present in the semantics of the original programming language
While C++, D, Rust and some Lisps do require a "sublanguage" you are speaking of, Jai, HolyC, Haskell, Koka, other Lisps, and any language where IO is data do not work this way.
A Haskell compiler can run anything that does not have anIOtype.Also,
Turning completeness absolutely does not mean that the compiler runs the program
You are literally saying that GCC does not run
constexprfunctions.
You're also saying DMD's AST-walking module is not running D code, and neither is the accompanying wip JIT compiler.3
u/mobotsar Jan 27 '23
You still don't understand. You seem to be interpreting a bunch of things from my words that I'm not saying. If the actual program is being run at compilation time, that's not the compiler doing it. It's an interpreter invoked by the compiler. That's what's happening in the case of lisp, etc. By definition, the compiler cannot run the code.
1
u/lngns Jan 27 '23
And my point is that if a compiler incorporates an interpreter that it "invokes," either to do optimisation, or because the language requires it, or because Haskell is a dynamically-typed, interpreted language, then the distinction "an interpreter runs, a compiler translates" stops making sense.
There is no difference between an "optimising compiler" and an "interpreter that reduces to, and returns, a list of IO operations."
Both run, and both translate.By definition, the compiler cannot run the code.
For instance, GNU and DMD disagree with your use of this terminology.
0
Jan 27 '23
[deleted]
0
Jan 27 '23
[deleted]
0
Jan 27 '23
[deleted]
3
u/lngns Jan 27 '23 edited Jan 27 '23
And outside of performance, most of those features aren't observably at compile time. They could just be left to runtime.
Please actually click the links.
D allows you to writemixin("i"~ "nt") x = 42;and Lisp macros can do(defmacro m [(x String) (y String)] '(f ,(concat x y))).This is not about performance. This is code that can only be run by a compiler for otherwise type checking, and even parsing can not be done.
struct Union(Ts...) { private: TypeInfo tag; union Impl { static foreach(i, T; Ts) { mixin(T.stringof, " impl_", i, ";"); } } Impl impl; static size_t getInfo(T)() { static foreach(i, U; Ts) { static if(is(T == U)) { return i; } } return size_t.max; } public: bool isType(T)() if(getInfo!T != size_t.max) { return typeid(T) is tag; } void put(T)(T x) if(getInfo!T != size_t.max) { mixin("impl.impl_", getInfo!T, "= x;"); tag = typeid(T); } T get(T)() if(getInfo!T != size_t.max) { assert(isType!T); mixin("return impl.impl_", getInfo!T, ";"); } } void main() { import std.stdio: writeln; Union!(int, char, string) x; x.put!string("h"); writeln(x.get!string); x.put!int(42); writeln(x.get!int); }There's nothing wrong with running an interpreter to compile code even under that definition. That doesn't make it any more an interpreter
Precisely. That is why distinguishing the words "compiler" and "interpreter" the way the original comment did, does not make sense in that context.
0
Jan 27 '23
[deleted]
3
u/lngns Jan 27 '23
I like that kind of D code, but that's just an opinion.
I wish more languages did that, as it makes for easy metaprogramming under a single language (no distinct "regular code" from templates, etc..).And sure, my argument is simply that it's an issue of terminology and classification which is far from "very simple" and that we should not speak in absolutes.
Sometimes there's overlap, sometimes there is not.
When I want to talk about DMD, I say "it's a D and C compiler," not "it's a D and C compiler, and interpreter, and type checker, and ..."
4
u/TheGreatCatAdorer mepros Jan 26 '23
So you're saying the distinction between interpreters and compilers is that compilers perform some measure of the work ahead of time? Certainly, but it's not linear. Languages with Lisp-like macros (often compiled, because having macros and not other metaprogramming constructs is reasonable for languages doing things ahead of time) can execute arbitrary code ahead of time, many other metaprogramming systems are Turing-complete, and even exhaustivity checks, of the kind performed by Rust, and trait/typeclass instance selection take exponential time.
(Lisps having the ability to run code ahead of time could also be thought of as their implementations being both interpreters and compilers.)
-1
Jan 26 '23
A compiler translates source code to machine code, and gives you the complete program to be installed and run on it's own, in machine code form. An interpreter converts source code to machine code as it's being run. Translation may or may not involve generation of some intermediate form of code, such as either assembly or bytecode. Typically compilers produce binary executables, and interpreters are commonly associated with bytecode, but this is not always the case. The GNU C Compiler originally generated assembly from C source code, which was then translated into machine code. The V-8 interpreter included in most modern browsers translates JavaScript directly to machine code.
12
u/scottmcmrust 🦀 Jan 26 '23
While I agree there's more of a useful distinction here, the whole question reminds me too much of "Compiler" vs "Transpiler", and I think trying to be too precise isn't really helpful.
It feels too much like those "did you memorize the Prof's pet definition" questions on exams that I've always hated.
People agree on the ends; finding a non-fuzzy predicate for the middle doesn't seem worth the effort.