munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.42k stars 1.01k forks source link

Writing native classes for Lox #1125

Closed nouritsu closed 7 months ago

nouritsu commented 1 year ago

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?

mcfriend99 commented 1 year ago

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.

nouritsu commented 1 year ago

@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?

mcfriend99 commented 1 year ago

My mistake. I missed the jlox part. I'll look around for an old project where I did this and reference later.

nouritsu commented 1 year ago

@mcfriend99 That would be great, thank you!

HallofFamer commented 1 year ago

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.

nouritsu commented 7 months ago

Thank you for the resources. Closing this issue.