29 August 2009

1. Base

Some people wanted to write a compiler in PureBasic, but didn't know how to. So hence I started this tutorial to help people get started. Once you grasp the basics you can expand on your own.

This tutorial is in many ways similar to "Let's write a compiler" by Jack Crenshaw, because that's the tutorial I read to learn this. Now come sue me.

A compiler reads input text (called the source language) and turns that into assembly language (called the target language). Since we need to experiment a lot to understand what's going it would be wise to have a set of common input and output routines. I already made some for you. Unlike a real compiler, which will read from a file and write to another file, these procedures read from the console and write to the console. This makes them suitable for experimenting. Later we will see that retargeting the procedures to read and write files will be simple.

Save this as base.pb. Then see if it compiles and runs (it should do nothing).
Global Look.c
Global Instream.s

Procedure GetLook()
Look = Asc(Instream)
Instream = Mid(Instream, 2)
EndProcedure

Procedure Error(E.s)
PrintN("Error: " + E)
Input()
End
EndProcedure

Procedure Expected(S.s)
Error(S + " expected.")
EndProcedure

Procedure Emit(S.s)
PrintN(#TAB$ + S)
EndProcedure

Procedure Init()
Instream = Input()
GetLook()
EndProcedure

No comments: