Writing native classes for Lox
nouritsu opened this issue · comments
I would like to add a native class to jlox. What would the most efficient and optimal way to do this?
I wanted to add a class that looks something like this -
class Foo {
init(a) {
this.name = a;
}
print_name(){
print this.name;
}
}
Is it possible to add this as a native class, similar to how native functions were added?
Checkout Blade's implementation. The codebase began as lox C implementation but have diverged so much. Still it should show you a lot about what you are trying to do.
@mcfriend99 Unfortunately I have little experience with Java and translating from C to Java for me would be both inaccurate and slow. Is there a java example or an implementation idea that could be provided?
My mistake. I missed the jlox part. I'll look around for an old project where I did this and reference later.
@mcfriend99 That would be great, thank you!
You can take a look into my KtLox implementation for how to define native classes. The code was written in Kotlin, but it should be enough similar to Java.
https://github.com/HallofFamer/KtLox
Basically you need a way to define native methods, and add the native methods to a native class. It’s not very complex, although it gets a bit tricky when it comes to special classes like root object, number/Boolean class.
Note: I have been working on the clox implementation lately and haven’t touched ktlox for a while, after getting used to bytecode interpreter id never want to write a treewalk interpreter again. But it’s still a good idea for beginners to start with the easiest implementation which is the treewalk interpreter.