Search code examples
compiler-constructioninterpreter

How compiler and interpreter both are used in one language?


I have read enough explanation about the definition of compiler, interpreter and "things" that use both. I didn't find how compiler and interpreter both are used in one language.


Solution

  • In Java the source code is first compiled to bytecode and then it's run by an interpreter (JVM - Java Virtual Machine).

    bytecode is machine code for a virtual machine.

    In Javascript there's a runtime (engine) that does just in time compilation (JIT). Basically, at execution time it's given a source code which it immediately converts to native code and then the code is executed. In Chrome's engine there are two modules that do compilation: one can execute code fast but the code isn't much optimized (ignition interpreter) and the other produces a highly performant code but compilation takes more time (turbofan compiler).

    Why use both:

    • portability - when you use intermediate representation that is compiled AOT you can take this bytecode and run it on any architecture for which a Virtual Machine is provided. You can push the same Java bytecode to clients on Mac, PC or Linux. If they have JVM installed the code will run. For C or C++ you have to ship different program executable for each architecture
    • fast initial start and decent execution performance - compilation takes time (and the more optimized code the more time it needs for compilation generally) but nobody likes to wait. It's better to produce something that is not perfect (ignite phase) and then gradually improve the code by compiling hot paths into highly optimized machine code (turbofan phase). This is especially plausible today where we have CPUs with many cores but we are not able utilize them all because creating programs with many parallel threads is hard (so one core can execute program while the other can optimize code in the meantime)