1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use crate::{
    error::Throwable,
    VM, object::{mem::RefTo, builtins::{Class, Object}, runtime::RuntimeValue},
};

pub mod jdk;
pub mod lang;
pub mod io;

pub type NameAndDescriptor = (String, String);

pub type NativeStaticFunction = fn(
    class: RefTo<Class>,
    args: Vec<RuntimeValue>,
    vm: &mut VM,
) -> Result<Option<RuntimeValue>, Throwable>;

pub type NativeInstanceFunction = fn(
    this: RefTo<Object>,
    args: Vec<RuntimeValue>,
    vm: &mut VM,
) -> Result<Option<RuntimeValue>, Throwable>;

#[derive(Clone, Debug)]
pub enum NativeFunction {
    Static(NativeStaticFunction),
    Instance(NativeInstanceFunction),
}

pub trait NativeModule {
    fn classname() -> &'static str;

    fn methods() -> Vec<(NameAndDescriptor, NativeFunction)> {
        vec![]
    }

    fn static_fields() -> Vec<(NameAndDescriptor, RuntimeValue)> {
        vec![]
    }

    fn register(vm: &mut VM) -> Result<(), Throwable> {
        let class = vm
            .class_loader
            .for_name(Self::classname().to_string())?;

        let class = class.borrow_mut();

        for (name, method) in Self::methods() {
            class.native_methods_mut().insert(name, method);
        }

        Ok(())
    }
}

#[macro_export]
macro_rules! static_method {
    (name: $name: expr, descriptor: $descriptor: expr => $method: expr) => {
        (
            ($name.to_string(), $descriptor.to_string()),
            NativeFunction::Static($method),
        )
    };
}

#[macro_export]
macro_rules! instance_method {
    (name: $name: expr, descriptor: $descriptor: expr => $method: expr) => {
        (
            ($name.to_string(), $descriptor.to_string()),
            NativeFunction::Instance($method),
        )
    };
}

#[macro_export]
macro_rules! field {
    (name: $name: expr, descriptor: $descriptor: expr => $value: expr) => {
        (
            $crate::runtime::object::NameAndDescriptor {
                name: $name.to_string(),
                descriptor: $descriptor.to_string(),
            },
            $value,
        )
    };
}