This is a bootstrap compiler that can be used to compile to compiler written in the target language. You can write a compiler in the target language and compile it with this compiler, and create a brand new language
- Write a compiler in the target language
- Compile it with this compiler
- Run the compiled compiler
You can learn more about this chicken-egg problem in Wikipedia.
To learn more about how to run this code, check this section.
The compiler is pretty basic, yet it is capable to do a lot of the hardwork. It can:
- Add & subtract numbers
- Parse params and arguments of function calls
- Parse nested block statements and outputs the result in a tree structure, called Abstract Syntax Tree.
- Parse
import
andimport from
statements
You can learn more about abstract syntax trees here
There are some steps to extend this compiler if you want to create your language.
- In tokenizer (
tokenize
function, also called the lexer), you need to add the tokens that you want to use in your language. For example, if you want to usenamespace
as a keyword, you need to add it to thetokens
array. - In parser (
parse
function), you need to add the rules for your language. Take thenamespace
example for instance, you can use the switch case statement atparser.ts:181
to add your own rules, keyword etc. - Next up, you need edit the transform function (
transform
function) to transform the base syntax tree to an abstract syntax tree that your code generator will be able to understand. - Finally, you need to edit the code generator (
generate
function) to output the code to your source language, that the computers will be able to parse.
- Clone the repo, I recommend using Github Desktop, it has awesome features.
- Install the dependencies:
yarn install
- Run the compiler. You can
ts-node
for this, or you can just use the build output.
On Darwin-like systems:
yarn compile:darwin && node src/parser
On Windows:
yarn compile:win && node src/parser
I will be working on this repo to make it more powerful and more understandable. This code really does need a refactoring, but I won't be adding any new features, nor accepting extensions via pull requests.
If you want to contribute, you can fork the repo and make a pull request. I will review it and merge it.
See the CONTRIBUTING.md file for more information.
This project is licensed under the Apache License - see the LICENSE file for details