# Native Function Loader

Implemented in path `./src/vm_core/native`, the native functions allow C0VM to do many interesting and useful things (like printing to `stdout`!).

This documentation will provide detailed explanation on how we transcribe C Native Functions works into TypeScript. We will also show the native functions we planned to implement and our progress on them.

### Native Functions

Native functions are lower-level functions that is hard to implement using the C0 code itself / is more efficient if implemented using native code.

In C0VM, there are several categories of the native functions, listed as below:

> Status Code:
>
> :green\_circle: Supported
>
> :yellow\_circle: Not Implemented Yet
>
> :red\_circle: No Plan to Implement

| Category Name         |                     Explanation                     | Status           |
| --------------------- | :-------------------------------------------------: | ---------------- |
| Command Line Argument |       Receive CLI argument, Parse CLI argument      | :yellow\_circle: |
| Standard I/O          |    Print content to `STDOUT` and Receives `STDIN`   | :green\_circle:  |
| Cursor                |                Cursor related utility               | :red\_circle:    |
| Double Arithmetic     |         `double` number arithmetic operation        | :red\_circle:    |
| File I/O              |              File read/write operations             | :red\_circle:    |
| Float Arithmetic      |         `float` number arithmetic operation         | :red\_circle:    |
| Image                 |         Image reading, operation and saving         | :red\_circle:    |
| Parse String          | Convert string to data (`int`, `char` or `boolean`) | :green\_circle:  |
| String Operation      |     String-related operation like `concat` etc.     | :green\_circle:  |

### Native Function Implementation

```typescript
type C0Native = {
    numArgs: number;
    readonly functionType: C0NativeFuncType,
    readonly f: (
        hooks: ReactUIHook,
        mem: C0HeapAllocator,
        ...args: C0Value<C0TypeClass>[]
    ) => C0Value<C0TypeClass>;
};
```

The native function object is defined as above.

The `numArgs` represent the number of argument the native function will receive.

The `functionType` stores the name of native function

The `f` stores the actual native function, which receives a `ReactUIHook`, a `HeapAllocator` and several `C0Value`s.

### Native Function Loading

Defined in `./src/vm_core/native/native_interface.ts`, the function `nativeFuncLoader` receives an index and returns the corresponding `C0Native` object.

To call the corresponding native function, use syntax like

```typescript
const native: C0Native = nativeFuncLoader(index);
// to call this native
const retval:C0Value<C0TypeClass> = native.f(hooks, mem, arg1, arg2);
```

