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