I mentioned a couple days ago that I look forward to writing a compiler 'someday'. Well, in the spirit of Failure Month, let's lower our sights enough that we can s/some/to. Let's just see how much of a class system we can put together. In this post, we'll get method binding working properly, and in a future one we'll look at inheritance.
To avoid muddying the waters with the implementation language's classes, we'll use one that doesn't have any - javascript. We'll avoid the dark corners & just work with functions and hash tables, so if you know any scripting language you should be able to follow this fine.
Let's start without methods, and just get attribute lookups happening. We want to build the backend compilery bits that implement this sort of functionality:
class Foo: # make a class
boop = 3 # instances of this class have an attribute boop, which by default is 3
f = Foo() # make an instance of the class
f2 = Foo() # and another one
f.boop = 7 # set f's attribute boop to 7
print (f.boop) # get f's attribute boop, which is now 7
print (f2.boop) # 3; f2's boop is undefined, so we get the class value, which is not changed
We're not bothering with the frontend compilery bits, so we won't have that nice syntax to work with. Instead, we'll test by calling the backend functions directly in javascript. So the equivalent of the code above will look something like:
var Foo = make_class({boop: 3});
var f = instantiate_class(Foo);
var f2 = instantiate_class(Foo);
set_attr(f, 'boop', 7);
// console.log is the javascript equivalent of print
console.log("This should be 7: ", get_attr(f, 'boop'));
console.log("This should be 3: ", get_attr(f2, 'boop'));
After these functions are defined, then we can get to the good stuff. Excited?
Read more…