C := Object clone do(
libc := DynLib clone open("libSystem.dylib")
curlyBrackets := method(call argAt(0))
forward := method(
libc performWithArgList("call", list(call message name, call message arguments map(x, self doMessage(x))) flatten)
)
int := Object clone
int updateSlot := method(str, C setSlot(str, call evalArgAt(1)))
int forward := method(
if(call message arguments size > 0,
attached := call message attached
args := call message arguments map(v, v attached name)
body := attached arguments at(0)
call message setAttached(attached attached)
C setSlot(call message name, self getSlot("Block") clone setMessage(body) setArgumentNames(args) setIsActivatable(true))
,
call message arguments foreach(v, call sender setSlot(v attached name, nil))
)
)
)
Now then, just to trim it up, you've seen the libc stuff before, if not, check postings from yesterday; so I'll skip over that (this includes the C forward method).
Now I defined a curlyBrackets method on C, which you might be asking, what's it do? Well Io transforms {} into a message curlyBrackets with whatever arguments you specified between the { and }. All this does is return the message argument since for the basic subset of C we're defining, we only want access to the first element in a { }.
Next I defined an int object. As you can assume, it's C's type "int", but could easily be a "long" or "double". It defines an updateSlot method which is what comes out of the parser when it sees an "=" identifier. In it, we pass setSlot onto the C object and evaluate the argument on the right hand side of = within the body of where it was called. Then I defined a forward method on int, which basically is just used for defining a C function. It doesn't check to make sure that the attached message is a curlyBrackets, which it probably should, but I'm lazy, sue me. =] This forward method sets a slot with the name supplied after the int and before the first parenthesis within the context of the C object. We can later call C thatFunction(args, it, defined) to call it.
And we wrap up our C code in a do message on C because that's where we defined our C DSL.
C do(
int foo(int a, int b) {
return a + b;
}
int x = foo(1, 2);
printf("%d\n", x);
)
Hope you enjoyed this!
[UPDATE: Oh and I should note that this isn't the best way to write a C-like syntax in Io]

No comments:
Post a Comment