Sign in to follow this  
CryoGenesis

Writing a script compiler?

Recommended Posts

CryoGenesis    528
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).

Share this post


Link to post
Share on other sites
Ashaman73    13715
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
[CODE]
x = y*d+(f/(2*s))/(100*s);
[/CODE]
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 [url="http://en.wikipedia.org/wiki/GNU_bison"]bison.[/url]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this