DEV Community

Cover image for Creating a Compiler with JavaScript: Theory
Jr. Dev 👨🏾‍💻
Jr. Dev 👨🏾‍💻

Posted on

Creating a Compiler with JavaScript: Theory

Overview

As JavaScript developers, we rarely need to think about low-level computing functionality. We do not have to concern ourselves with how the computer executes the code that we write. But have you ever wondered just how this happens?

This multi-part series aims to give you an introduction to just how compilation works, and what better way to learn, than to create our very own programming language along the way!


Follow along on YouTube

Contents

Benefits of learning compiler theory
Definition
Examples
How compilers works
Diagram
Conclusion


Benefits of Learning Compiler Theory

  • It will help you understand how computers execute our programs
  • You will better understand errors, and therefore improve your debugging skills
  • It will make you a better programmer as the techniques used can be transferred to general software design

Definition

Compilers convert human-readable code to machine code, so that a computer can understand and run programs.

In this series, we will technically be creating a transpiler, so let us give that a definition too:

A transpiler converts code from one language, to another language, that has a similar level of abstraction.


Examples

Babel

https://babel.dev/docs/en/ is a JavaScript transpiler which transpiles newer versions of EcmaScript to older versions for browser compatibility.

TypeScript

https://www.typescriptlang.org/ is a programming language, which is transpiled to JavaScript.

G++

GNU C++ compiler compiles C++ to generate an executable target file.


How Compilers Work

The compilation process is split into multiple stages which each play a crucial part to convert your code into machine instructions.
We will be focusing our attention to arguably the 3 main tasks listed below:

Scanner

The scanner is responsible for reading the source input, one character at a time, and grouping these characters in to tokens.

Parser

Given a formal syntax specification, the parser reads the tokens, outputted by the scanner, and checks the semantics of the source code.

Generator

The generator maps our source input into the target code.


Diagram

Compilation diagram


Conclusion

To conclude, compilation is the process of translating the code you write, into code that a computer understands. It does this by scanning and parsing your source input, and mapping this input to the target output which your computer can understand.


Now that you have a basic understanding of compilation, the next step is to create our very own programming language to compile!

See you then 😊


Header photo by Greg Rakozy on Unsplash

Top comments (1)

Collapse
 
loicboset profile image
Loïc Boset

Very interesting! Thanks!