Writing a script compiler?

Started by
0 comments, last by Ashaman73 11 years, 8 months ago
Hey guys. I've recently finished a game engine that has a scripting engine. The script language is just Assembly with custom commands like MOV (move) for a game. Unfortunately writing game logic code in assembly is a bitch. I've written quick utilities that generate code based on numbers. For instance, I made a conversation code generator for the internet. You give it an ID of the other entity and the amount of lines of text to show.
What I now want to write is a custom script compiler. you write a line of script like:
if(x == y){
int d = x;
d = d + 1;
}else{
int d = y;
d = d - 1;
}
That would generate the assembly code:

IFE [0x0001], [0x0002];
SET PC, yes;
SET PC, no;
:yes
SET 0x0003, [0x0001];
ADD 0x0003, 0x0001;
SET PC, end;
:no
SET 0x0003, [0x0002];
SUB 0x0003, 0x0001;
:end

To make a compiler that would compile if statements wouldn't be too hard but having to parse equations like this:
x = y*d+(f/(2*s))/(100*s);
How would you even start on writing a program to parse lines like this?
I guess methods wouldn't be too hard. It would just be:

:method1
//do stuff
SET PC, POP;

Methods that return integers?
Would be annoying.
While loops wouldn't be hard at all.
For loops would be harder.

Does anyone know any tutorials or books on writing compilers (preferably Java).
Advertisement
When writing a compiler you use some kind of syntax grammar and a parser generator to generate code which is able to read your source and transform it into a tree structure. Then you transform the tree into your target format. Expressions like

x = y*d+(f/(2*s))/(100*s);

will be analysed by the parser generator and results in a clean tree and can be easily handled afterwards.

There are lot of parser generators available like bison.

This topic is closed to new replies.

Advertisement