Skip to content

Project Setup

To start writing the compiler, let’s set up the project directory. The reference Gom compiler uses npm as the package manager, but you are free to use others to manage your dependencies. Let’s start by creating a new Node project using npm and setting up the base project structure.

Terminal window
npm init -y

To work with TypeScript, we’ll install the typescript dependency and the tsx package that allows directly executing TypeScript files.

Terminal window
npm install typescript tsx

Directory structure

We’ll place all our source code in the src directory and create one run.ts as an entry point for the compiler. Create the run.ts and src/index.ts files and leave them empty for now.

  • Directorynode_modules/
  • Directorysrc
    • index.ts
  • package-lock.json
  • package.json
  • run.ts

src/index.ts

This is the main entry point that runs various phases of the compiler and passes output from each phase to the next one. The main function is essentially the compiler pipeline.

src/index.ts
export default async function main(filePath: string) {
console.log(`Compiling ${filePath}`);
}

run.ts

This file reads CLI arguments and passes them to src/index.ts to begin the compilation process. The main argument is the source code file path. Add the following code to run.ts.

run.ts
#!/usr/bin/env node
import main from "./src/index";
const filePath = process.argv[2];
(async () => await main(filePath))();

The first line makes the file executable, allowing us to run it as follows:

Terminal window
npx tsx run.ts path/to/source.gom

Using npm run compile

Let’s add a new script to our package.json to compile any Gom source code file.

package.json
{
"scripts": {
"compile": "tsx run.ts"
}
}

Now running the following command should print the file path of the source code file, we are ready to implement our compiler!

Terminal window
npm run compile path/to/source.gom
# Output: Compiling path/to/source.gom