Attila's Blog

About writing your own programming language in C, Go and Swift

Virtual machine

Jul 12, 2018 Comments

Categories: aspl

In the previous article we chose to generate code for a virtual machine. But what is it exactly?

A virtual machine is an emulator of a computer system. There are two types of virtual machines:

  • system virtual machines, those that emulate a complete computer system, they can be used as a substitute of a real computer. They can execute an entire operating system, and thus they are also called full virtualization VMs.
  • process virtual machines, they are designed to execute computer programs in a platform-independent environment.

Based on this specification it seems obvious that we need to write one of the second kind. What are the pros/cons of writing a process VM?

On the con side it will be slower than compiling our code to native machine code, because every instruction must be simulated at runtime every time the program is executed.

On the pro side we get flexibility and portability. If we choose the implementation language wisely we have to write our VM only once, and the same code will run on every supported platform. Also because it is platform-independent (hides the details of the underlying hardware and operating system), it allows our program to execute and behave exactly the same way on every supported platform. Furthermore, if really needed our bytecode can be translated to native machine code with a technique called just-in-time compilation (JIT). This is exactly what V8 does with Javascript, and it’s utilised by Java and .NET as well.

Sounds like a good compromise to me. Others thought that too, so this kind of VMs are the basis of lots of popular programming languages:

among many others.

We have almost everything now to actually execute our compiled program. The only piece missing is the language runtime. I will talk about it next time.

Stay tuned. I’ll be back.

Tags: virtual machine

← Code Generation Language runtime →

comments powered by Disqus