Saturday, November 21, 2009

Structs and Syntax

I only realized today that it's been a few days since I last posted. Time flies when stuff is going on; hanging out with someone here and there, telling people about my trip, watching TV, etc.

I got structs into the assembler pretty quickly; now I can have something like:

.struct thing_typ
.word name
.word x
.word y
.endstruct

_variable:
.thing_typ

ldr r0, [_variable.name]
ldr r1, [_variable.x]
ldr r2, [_variable.y]
bl _print

or something similar. This just basically allows better representation and access of data for the future.

I then had to deal with a few extra features of structs, namely their size and the offset of each variable within the struct. In C, you get the size of a variable by saying "sizeof (variable)", which is an operation completed at compile-time. In an effort to avoid too much parsing and continuity in syntax, I decided to implement this with the following syntax:

.struct thing_typ
.word name
.word x
.word y
.endstruct

mov r0, .thing_typ.sizeof

The assembler will convert ".thing_typ.sizeof" into an immediate value and pass that back to the instruciton parser. The reason I didn't opt for the C way was more an effort to keep parenthesis only for arithmetic operations, but it is perfectly implementable.

Getting the offset of variables in structs was a bit different. I envisioned a situation where I would loop through an array of them and want to access the variables of each one; with the syntax I first described, I would need a variable for each struct in the array. Therefore, the way I could iterate was to store a pointer in a register and just increment the register. In C, when you have a pointer to a struct, you can access each variable within it like this:

struct thing_typ
{
char* name;
unsigned int x;
unsigned int y;
};

thing_typ t;
thing_typ* ptr = &t;

ptr->name = "Andrew";

In my assembler, I implemented the following syntax:

.struct thing_typ
.word name
.word x
.word y
.endstruct

t:
.thing_typ

ldr r0, =t
ldr r1, [r0, .thing_typ.x]

It's a bit funny to look at and wrap around at first, but I'll get used to it.

I'll probably spend some more time refining syntax (need to add support for static arrays), which will also lend an opportunity for me to practice ARM/THUMB assembly language some more, which will be big.

No comments:

Post a Comment