Add TS bindings generation, with per-lang strings in their own file
[ldk-java] / typescript_strings.py
1 class Consts:
2     def __init__(self, DEBUG):
3         self.c_file_pfx = """#include <rust_types.h>
4 #include <stdatomic.h>
5 #include <lightning.h>
6
7 // These should be provided...somehow...
8 void *memset(void *s, int c, size_t n);
9 void *memcpy(void *dest, const void *src, size_t n);
10 int memcmp(const void *s1, const void *s2, size_t n);
11
12 void __attribute__((noreturn)) abort(void);
13 void assert(scalar expression);
14 """
15
16         if not DEBUG:
17             self.c_file_pfx = self.c_file_pfx + """
18 void *malloc(size_t size);
19 void free(void *ptr);
20
21 #define MALLOC(a, _) malloc(a)
22 #define FREE(p) if ((long)(p) > 1024) { free(p); }
23 #define DO_ASSERT(a) (void)(a)
24 #define CHECK(a)
25 """
26         else:
27             self.c_file_pfx = self.c_file_pfx + """
28 // Always run a, then assert it is true:
29 #define DO_ASSERT(a) do { bool _assert_val = (a); assert(_assert_val); } while(0)
30 // Assert a is true or do nothing
31 #define CHECK(a) DO_ASSERT(a)
32
33 // Running a leak check across all the allocations and frees of the JDK is a mess,
34 // so instead we implement our own naive leak checker here, relying on the -wrap
35 // linker option to wrap malloc/calloc/realloc/free, tracking everyhing allocated
36 // and free'd in Rust or C across the generated bindings shared library.
37
38 #define BT_MAX 128
39 typedef struct allocation {
40         struct allocation* next;
41         void* ptr;
42         const char* struct_name;
43 } allocation;
44 static allocation* allocation_ll = NULL;
45
46 void* __real_malloc(size_t len);
47 void* __real_calloc(size_t nmemb, size_t len);
48 static void new_allocation(void* res, const char* struct_name) {
49         allocation* new_alloc = __real_malloc(sizeof(allocation));
50         new_alloc->ptr = res;
51         new_alloc->struct_name = struct_name;
52         new_alloc->next = allocation_ll;
53         allocation_ll = new_alloc;
54 }
55 static void* MALLOC(size_t len, const char* struct_name) {
56         void* res = __real_malloc(len);
57         new_allocation(res, struct_name);
58         return res;
59 }
60 void __real_free(void* ptr);
61 static void alloc_freed(void* ptr) {
62         allocation* p = NULL;
63         allocation* it = allocation_ll;
64         while (it->ptr != ptr) {
65                 p = it; it = it->next;
66                 if (it == NULL) {
67                         //XXX: fprintf(stderr, "Tried to free unknown pointer %p\\n", ptr);
68                         return; // addrsan should catch malloc-unknown and print more info than we have
69                 }
70         }
71         if (p) { p->next = it->next; } else { allocation_ll = it->next; }
72         DO_ASSERT(it->ptr == ptr);
73         __real_free(it);
74 }
75 static void FREE(void* ptr) {
76         if ((long)ptr < 1024) return; // Rust loves to create pointers to the NULL page for dummys
77         alloc_freed(ptr);
78         __real_free(ptr);
79 }
80
81 void* __wrap_malloc(size_t len) {
82         void* res = __real_malloc(len);
83         new_allocation(res, "malloc call");
84         return res;
85 }
86 void* __wrap_calloc(size_t nmemb, size_t len) {
87         void* res = __real_calloc(nmemb, len);
88         new_allocation(res, "calloc call");
89         return res;
90 }
91 void __wrap_free(void* ptr) {
92         if (ptr == NULL) return;
93         alloc_freed(ptr);
94         __real_free(ptr);
95 }
96
97 void* __real_realloc(void* ptr, size_t newlen);
98 void* __wrap_realloc(void* ptr, size_t len) {
99         if (ptr != NULL) alloc_freed(ptr);
100         void* res = __real_realloc(ptr, len);
101         new_allocation(res, "realloc call");
102         return res;
103 }
104 void __wrap_reallocarray(void* ptr, size_t new_sz) {
105         // Rust doesn't seem to use reallocarray currently
106         DO_ASSERT(false);
107 }
108
109 void __attribute__((destructor)) check_leaks() {
110         for (allocation* a = allocation_ll; a != NULL; a = a->next) {
111                 //XXX: fprintf(stderr, "%s %p remains\\n", a->struct_name, a->ptr);
112         }
113         DO_ASSERT(allocation_ll == NULL);
114 }
115 """
116         self.c_file_pfx = self.c_file_pfx + """
117 // We assume that CVec_u8Z and u8slice are the same size and layout (and thus pointers to the two can be mixed)
118 _Static_assert(sizeof(LDKCVec_u8Z) == sizeof(LDKu8slice), "Vec<u8> and [u8] need to have been mapped identically");
119 _Static_assert(offsetof(LDKCVec_u8Z, data) == offsetof(LDKu8slice, data), "Vec<u8> and [u8] need to have been mapped identically");
120 _Static_assert(offsetof(LDKCVec_u8Z, datalen) == offsetof(LDKu8slice, datalen), "Vec<u8> and [u8] need to have been mapped identically");
121
122 _Static_assert(sizeof(void*) == 4, "Pointers mut be 32 bits");
123
124 typedef struct int64_tArray {uint32_t len;int64_t *ptr;} int64_tArray;
125 typedef struct uint32_tArray {uint32_t len;int32_t *ptr;} uint32_tArray;
126 typedef struct int8_tArray {uint32_t len;int8_t *ptr;} int8_tArray;
127
128 typedef bool jboolean;
129
130 """
131
132         self.hu_struct_file_prefix = """package org.ldk.structs;
133
134 import org.ldk.impl.bindings;
135 import org.ldk.enums.*;
136 import org.ldk.util.*;
137 import java.util.Arrays;
138
139 @SuppressWarnings("unchecked") // We correctly assign various generic arrays
140 """
141         self.c_fn_ty_pfx = ""
142         self.c_fn_name_pfx = ""
143         self.c_fn_args_pfx = "void* ctx_TODO"
144         self.file_ext = ""
145         self.ptr_c_ty = "uint32_t"
146         self.ptr_native_ty = "uint32_t"
147         self.result_c_ty = "uint32_t"
148         self.ptr_arr = "uint32_tArray"
149         self.get_native_arr_len_call = ("", ".len")
150         self.get_native_arr_ptr_call = ("", ".ptr")
151
152     def release_native_arr_ptr_call(self, arr_var, arr_ptr_var):
153         return None
154     def create_native_arr_call(self, arr_len, ty_info):
155         if ty_info.c_ty == "int8_tArray":
156             return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + ", \"Native " + ty_info.c_ty + " Bytes\") }"
157         elif ty_info.c_ty == "int64_tArray":
158             return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + " * sizeof(int64_t), \"Native " + ty_info.c_ty + " Bytes\") }"
159         elif ty_info.c_ty == "uint32_tArray":
160             return "{ .len = " + arr_len + ", .ptr = MALLOC(" + arr_len + " * sizeof(int32_t), \"Native " + ty_info.c_ty + " Bytes\") }"
161         else:
162             print("Need to create arr!", ty_info.c_ty)
163             return ty_info.c_ty
164     def set_native_arr_contents(self, arr_name, arr_len, ty_info):
165         if ty_info.c_ty == "int8_tArray":
166             return ("memcpy(" + arr_name + ".ptr, ", ", " + arr_len + ")")
167         else:
168             assert False
169     def get_native_arr_contents(self, arr_name, dest_name, arr_len, ty_info, copy):
170         if ty_info.c_ty == "int8_tArray":
171             if copy:
172                 return "memcpy(" + dest_name + ", " + arr_name + ".ptr, " + arr_len + ")"
173             else:
174                 return arr_name + ".ptr"
175         else:
176             return "(" + ty_info.subty.c_ty + "*) " + arr_name + ".ptr"
177     def get_native_arr_elem(self, arr_name, idxc, ty_info):
178         assert False # Only called if above is None
179     def cleanup_native_arr_ref_contents(self, arr_name, dest_name, arr_len, ty_info):
180         if ty_info.c_ty == "int8_tArray":
181             return None
182         else:
183             return None
184
185     def init_str(self, c_array_class_caches):
186         return ""
187
188     def native_c_unitary_enum_map(self, struct_name, variants):
189         out_c = "static inline " + struct_name + " " + struct_name + "_from_js(int32_t ord) {\n"
190         out_c = out_c + "\tswitch (ord) {\n"
191         ord_v = 0
192         for var in variants:
193             out_c = out_c + "\t\tcase %d: return %s;\n" % (ord_v, var)
194             ord_v = ord_v + 1
195         out_c = out_c + "\t}\n"
196         out_c = out_c + "\tabort();\n"
197         out_c = out_c + "}\n"
198
199         out_c = out_c + "static inline int32_t " + struct_name + "_to_js(" + struct_name + " val) {\n"
200         out_c = out_c + "\tswitch (val) {\n"
201         ord_v = 0
202         for var in variants:
203             out_c = out_c + "\t\tcase " + var + ": return %d;\n" % ord_v
204             ord_v = ord_v + 1
205         out_c = out_c + "\t\tdefault: abort();\n"
206         out_c = out_c + "\t}\n"
207         out_c = out_c + "}\n"
208         return (out_c, "", "")
209
210     def c_unitary_enum_to_native_call(self, ty_info):
211         return (ty_info.rust_obj + "_to_js(", ")")
212     def native_unitary_enum_to_c_call(self, ty_info):
213         return (ty_info.rust_obj + "_from_js(", ")")
214
215     def c_complex_enum_pfx(self, struct_name, variants, init_meth_jty_strs):
216         return ""
217
218     def c_complex_enum_pass_ty(self, struct_name):
219         return "uint32_t"
220
221     def c_constr_native_complex_enum(self, struct_name, variant, c_params):
222         ret = "0 /* " + struct_name + " - " + variant + " */"
223         for param in c_params:
224             ret = ret + "; (void) " + param
225         return ret
226
227     def native_c_map_trait(self, struct_name, field_var_convs, field_fn_lines):
228         return ("", "")