sqlite
[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.
Brought by drakestapleton
sqlite / ext / wasm / jaccwabyt / jaccwabyt.c-pp.js
| 1 | /** |
| 2 | 2022-06-30 |
| 3 | |
| 4 | The author disclaims copyright to this source code. In place of a |
| 5 | legal notice, here is a blessing: |
| 6 | |
| 7 | * May you do good and not evil. |
| 8 | * May you find forgiveness for yourself and forgive others. |
| 9 | * May you share freely, never taking more than you give. |
| 10 | |
| 11 | *********************************************************************** |
| 12 | |
| 13 | The Jaccwabyt API is documented in detail in an external file, |
| 14 | _possibly_ called jaccwabyt.md in the same directory as this file. |
| 15 | |
| 16 | Project homes: |
| 17 | - https://fossil.wanderinghorse.net/r/jaccwabyt |
| 18 | - https://sqlite.org/src/dir/ext/wasm/jaccwabyt |
| 19 | |
| 20 | This build was generated using: |
| 21 | |
| 22 | //#@ push policy error delimiter "@" "@" |
| 23 | @c-pp::argv@ |
| 24 | |
| 25 | by libcmpp @cmpp::version@ |
| 26 | */ |
| 27 | //#savepoint begin |
| 28 | //#define ? esm 0 |
| 29 | //#define ? no-export 0 |
| 30 | //#define ? lexical-scoped 0 |
| 31 | //#if defined canonical-sqlite3 |
| 32 | //# // The sqlite3 wasm build. |
| 33 | //# define no-export 1 |
| 34 | //# define lexical-scoped 1 |
| 35 | //# if defined target:es6-module |
| 36 | //# define esm 1 |
| 37 | //# /if |
| 38 | //#/if |
| 39 | //#if esm |
| 40 | //# define lexical-scoped 1 |
| 41 | //#/if |
| 42 | const Jaccwabyt = function StructBinderFactory(config){ |
| 43 | //#if not esm |
| 44 | 'use strict'; |
| 45 | //#/if |
| 46 | |
| 47 | const LOGPREFIX = '@__FILE__@:'; |
| 48 | /** Throws a new Error, the message of which is the concatenation of |
| 49 | a file-local prefix and all args with a space between each. */ |
| 50 | const toss = (...args)=>{ |
| 51 | throw new Error(LOGPREFIX+" "+args.join(' ')) |
| 52 | }; |
| 53 | const nu = (...args)=>Object.assign(Object.create(null),...args); |
| 54 | config = nu(config); |
| 55 | for(const k of ['alloc','dealloc']){ |
| 56 | if( !(config[k] instanceof Function) ){ |
| 57 | toss("Config option '"+k+"' must be a function."); |
| 58 | } |
| 59 | } |
| 60 | const error = config.logger?.error |
| 61 | || ((...args)=>console.error(LOGPREFIX,...args)); |
| 62 | { |
| 63 | let h = config.heap; |
| 64 | if( h instanceof WebAssembly.Memory ){ |
| 65 | let u; |
| 66 | config.heap = function(){ |
| 67 | /* Update view when the heap grows. */ |
| 68 | if( u?.length===this.byteLength ) return u; |
| 69 | return u = new Uint8Array(this.buffer); |
| 70 | }.bind(config.heap); |
| 71 | }else if( 1!==h?.()?.BYTES_PER_ELEMENT ){ |
| 72 | error("The bothersome StructBinderFactory config:",config, |
| 73 | "heap =",h?.()); |
| 74 | toss("config.heap must be WebAssembly.Memory instance or", |
| 75 | "a function which returns a Uint8Array/Int8Array view of one."); |
| 76 | } |
| 77 | } |
| 78 | const SBF = StructBinderFactory; |
| 79 | const heap = config.heap, |
| 80 | alloc = config.alloc, |
| 81 | dealloc = config.dealloc, |
| 82 | log = config.log/*deprecated*/ |
| 83 | || config.logger?.debug |
| 84 | || ((...args)=>console.debug(LOGPREFIX,...args)), |
| 85 | warn = config.logger?.warn |
| 86 | || ((...args)=>console.warn(LOGPREFIX,...args)), |
| 87 | memberPrefix = (config.memberPrefix || ""), |
| 88 | memberSuffix = (config.memberSuffix || ""), |
| 89 | BigInt = globalThis['BigInt'], |
| 90 | BigInt64Array = globalThis['BigInt64Array'], |
| 91 | bigIntEnabled = config.bigIntEnabled ?? !!BigInt64Array; |
| 92 | |
| 93 | //warn("config",config); |
| 94 | let ptr; |
| 95 | const ptrSize = config.pointerSize |
| 96 | || config.ptrSize/*deprecated*/ |
| 97 | || ('bigint'===typeof (ptr = alloc(1)) ? 8 : 4); |
| 98 | const ptrIR = config.pointerIR/*deprecated*/ |
| 99 | || config.ptrIR/*deprecated*/ |
| 100 | || (4===ptrSize ? 'i32' : 'i64'); |
| 101 | if( ptr ){ |
| 102 | dealloc(ptr); |
| 103 | ptr = undefined; |
| 104 | } |
| 105 | //warn("ptrIR =",ptrIR,"ptrSize =",ptrSize); |
| 106 | |
| 107 | if(ptrSize!==4 && ptrSize!==8) toss("Invalid pointer size:",ptrSize); |
| 108 | if(ptrIR!=='i32' && ptrIR!=='i64') toss("Invalid pointer representation:",ptrIR); |
| 109 | |
| 110 | /** Either BigInt or, if !bigIntEnabled, a function which |
| 111 | throws complaining that BigInt is not enabled. */ |
| 112 | const __BigInt = (bigIntEnabled && BigInt) |
| 113 | ? (v)=>BigInt(v || 0) |
| 114 | : (v)=>toss("BigInt support is disabled in this build."); |
| 115 | const __asPtrType = ('i32'==ptrIR) ? Number : __BigInt; |
| 116 | const __NullPtr = __asPtrType(0); |
| 117 | const __ptrAdd = (4 === ptrSize) |
| 118 | ? function(a, b){ |
| 119 | if(2 === arguments.length) return (Number(a || 0) + Number(b || 0)) | 0; |
| 120 | let rc = 0; |
| 121 | for(let i = 0; i < arguments.length; ++i) rc += Number(arguments[i] || 0); |
| 122 | return rc | 0; |
| 123 | } |
| 124 | : function(a, b){ |
| 125 | if(2 === arguments.length) return BigInt(a || 0) + BigInt(b || 0); |
| 126 | let rc = 0n; |
| 127 | for(let i = 0; i < arguments.length; ++i) rc += BigInt(arguments[i] || 0); |
| 128 | return rc; |
| 129 | }; |
| 130 | const __ptrAddSelf = function(){ |
| 131 | return __ptrAdd(this.pointer,...arguments); |
| 132 | }; |
| 133 | |
| 134 | if(!SBF.debugFlags){ |
| 135 | SBF.__makeDebugFlags = function(deriveFrom=null){ |
| 136 | /* This is disgustingly overengineered. :/ */ |
| 137 | if(deriveFrom && deriveFrom.__flags) deriveFrom = deriveFrom.__flags; |
| 138 | const f = function f(flags){ |
| 139 | if(0===arguments.length){ |
| 140 | return f.__flags; |
| 141 | } |
| 142 | if(flags<0){ |
| 143 | delete f.__flags.getter; delete f.__flags.setter; |
| 144 | delete f.__flags.alloc; delete f.__flags.dealloc; |
| 145 | }else{ |
| 146 | f.__flags.getter = 0!==(0x01 & flags); |
| 147 | f.__flags.setter = 0!==(0x02 & flags); |
| 148 | f.__flags.alloc = 0!==(0x04 & flags); |
| 149 | f.__flags.dealloc = 0!==(0x08 & flags); |
| 150 | } |
| 151 | return f._flags; |
| 152 | }; |
| 153 | Object.defineProperty(f,'__flags', { |
| 154 | iterable: false, writable: false, |
| 155 | value: Object.create(deriveFrom) |
| 156 | }); |
| 157 | if(!deriveFrom) f(0); |
| 158 | return f; |
| 159 | }; |
| 160 | SBF.debugFlags = SBF.__makeDebugFlags(); |
| 161 | }/*static init*/ |
| 162 | |
| 163 | const isLittleEndian = true || (function() { |
| 164 | const buffer = new ArrayBuffer(2); |
| 165 | new DataView(buffer).setInt16(0, 256, true /* littleEndian */); |
| 166 | // Int16Array uses the platform's endianness. |
| 167 | return new Int16Array(buffer)[0] === 256; |
| 168 | })() /* WASM is, by definition, Little Endian */; |
| 169 | |
| 170 | /** |
| 171 | Some terms used in the internal docs: |
| 172 | |
| 173 | StructType: a struct-wrapping class generated by this |
| 174 | framework. |
| 175 | |
| 176 | DEF: struct descriptor object. |
| 177 | |
| 178 | SIG: struct member signature string. |
| 179 | */ |
| 180 | |
| 181 | /** True if SIG s looks like a function signature, else |
| 182 | false. */ |
| 183 | const isFuncSig = (s)=>'('===s[1]; |
| 184 | /** True if SIG s is-a pointer-type signature. */ |
| 185 | const isPtrSig = (s)=>'p'===s || 'P'===s || 's'===s; |
| 186 | const isAutoPtrSig = (s)=>'P'===s /*EXPERIMENTAL*/; |
| 187 | /** Returns p if SIG s is a function SIG, else returns s[0]. */ |
| 188 | const sigLetter = (s)=>s ? (isFuncSig(s) ? 'p' : s[0]) : undefined; |
| 189 | |
| 190 | /** Returns the WASM IR form of the letter at SIG s[0]. Throws for |
| 191 | an unknown SIG. */ |
| 192 | const sigIR = function(s){ |
| 193 | switch(sigLetter(s)){ |
| 194 | case 'c': case 'C': return 'i8'; |
| 195 | case 'i': return 'i32'; |
| 196 | case 'p': case 'P': case 's': return ptrIR; |
| 197 | case 'j': return 'i64'; |
| 198 | case 'f': return 'float'; |
| 199 | case 'd': return 'double'; |
| 200 | } |
| 201 | toss("Unhandled signature IR:",s); |
| 202 | }; |
| 203 | |
| 204 | /** Returns the WASM sizeof of the letter at SIG s[0]. Throws for an |
| 205 | unknown SIG. */ |
| 206 | const sigSize = function(s){ |
| 207 | switch(sigLetter(s)){ |
| 208 | case 'c': case 'C': return 1; |
| 209 | case 'i': return 4; |
| 210 | case 'p': case 'P': case 's': return ptrSize; |
| 211 | case 'j': return 8; |
| 212 | case 'f': return 4; |
| 213 | case 'd': return 8; |
| 214 | } |
| 215 | toss("Unhandled signature sizeof:",s); |
| 216 | }; |
| 217 | |
| 218 | const affirmBigIntArray = BigInt64Array |
| 219 | ? ()=>true : ()=>toss('BigInt64Array is not available.'); |
| 220 | |
| 221 | /** Returns the name of a DataView getter method corresponding |
| 222 | to the given SIG. */ |
| 223 | const sigDVGetter = function(s){ |
| 224 | switch(sigLetter(s)) { |
| 225 | case 'p': case 'P': case 's': |
| 226 | return 4===ptrSize |
| 227 | ? 'getInt32' |
| 228 | : (affirmBigIntArray() && 'getBigInt64'); |
| 229 | case 'i': return 'getInt32'; |
| 230 | case 'c': return 'getInt8'; |
| 231 | case 'C': return 'getUint8'; |
| 232 | case 'j': return affirmBigIntArray() && 'getBigInt64'; |
| 233 | case 'f': return 'getFloat32'; |
| 234 | case 'd': return 'getFloat64'; |
| 235 | } |
| 236 | toss("Unhandled DataView getter for signature:",s); |
| 237 | }; |
| 238 | |
| 239 | /** Returns the name of a DataView setter method corresponding |
| 240 | to the given SIG. */ |
| 241 | const sigDVSetter = function(s){ |
| 242 | switch(sigLetter(s)){ |
| 243 | case 'p': case 'P': case 's': |
| 244 | return 4===ptrSize |
| 245 | ? 'setInt32' |
| 246 | : (affirmBigIntArray() && 'setBigInt64'); |
| 247 | case 'i': return 'setInt32'; |
| 248 | case 'c': return 'setInt8'; |
| 249 | case 'C': return 'setUint8'; |
| 250 | case 'j': return affirmBigIntArray() && 'setBigInt64'; |
| 251 | case 'f': return 'setFloat32'; |
| 252 | case 'd': return 'setFloat64'; |
| 253 | } |
| 254 | toss("Unhandled DataView setter for signature:",s); |
| 255 | }; |
| 256 | |
| 257 | /** |
| 258 | Returns a factory for either Number or BigInt, depending on the |
| 259 | given SIG. This constructor is used in property setters to coerce |
| 260 | the being-set value to the correct pointer size. |
| 261 | */ |
| 262 | const sigDVSetWrapper = function(s){ |
| 263 | switch(sigLetter(s)) { |
| 264 | case 'i': case 'f': case 'c': case 'C': case 'd': return Number; |
| 265 | case 'j': return __BigInt; |
| 266 | case 'p': case 'P': case 's': |
| 267 | switch(ptrSize){ |
| 268 | case 4: return Number; |
| 269 | case 8: return __BigInt; |
| 270 | } |
| 271 | break; |
| 272 | } |
| 273 | toss("Unhandled DataView set wrapper for signature:",s); |
| 274 | }; |
| 275 | |
| 276 | /** Returns the given struct and member name in a form suitable for |
| 277 | debugging and error output. */ |
| 278 | const sPropName = (s,k)=>s+'::'+k; |
| 279 | |
| 280 | const __propThrowOnSet = function(structName,propName){ |
| 281 | return ()=>toss(sPropName(structName,propName),"is read-only."); |
| 282 | }; |
| 283 | |
| 284 | /** |
| 285 | In order to completely hide StructBinder-bound struct pointers |
| 286 | from JS code, we store them in a scope-local WeakMap which maps |
| 287 | the struct-bound objects to an object with their metadata: |
| 288 | |
| 289 | { |
| 290 | .p = the native pointer, |
| 291 | .o = self (for an eventual reverse-mapping), |
| 292 | .xb = extra bytes allocated for p, |
| 293 | .zod = zeroOnDispose, |
| 294 | .ownsPointer = true if this object owns p |
| 295 | } |
| 296 | |
| 297 | The .p data are accessible via obj.pointer, which is gated behind |
| 298 | a property interceptor, but are not exposed anywhere else in the |
| 299 | public API. |
| 300 | */ |
| 301 | const getInstanceHandle = function f(obj, create=true){ |
| 302 | let ii = f.map.get(obj); |
| 303 | if( !ii && create ){ |
| 304 | f.map.set(obj, (ii=f.create(obj))); |
| 305 | } |
| 306 | return ii; |
| 307 | }; |
| 308 | getInstanceHandle.map = new WeakMap; |
| 309 | getInstanceHandle.create = (forObj)=>{ |
| 310 | return nu({ |
| 311 | o: forObj, |
| 312 | p: undefined/*native ptr*/, |
| 313 | ownsPointer: false, |
| 314 | zod: false/*zeroOnDispose*/, |
| 315 | xb: 0/*extraBytes*/ |
| 316 | }); |
| 317 | }; |
| 318 | |
| 319 | const __objOwnsOwnMemory = (v)=>{ |
| 320 | const ii = getInstanceHandle(v, false); |
| 321 | return !!(ii?.p && ii?.ownsPointer); |
| 322 | }; |
| 323 | |
| 324 | /** |
| 325 | Remove the getInstanceHandle() mapping for obj. |
| 326 | */ |
| 327 | const rmInstanceHandle = (obj)=>getInstanceHandle.map.delete(obj) |
| 328 | /* If/when we have a reverse map of ptr-to-objects, we need to |
| 329 | clean that here. */; |
| 330 | |
| 331 | const __isPtr32 = (ptr)=>('number'===typeof ptr && (ptr===(ptr|0)) && ptr>=0); |
| 332 | const __isPtr64 = (ptr)=>( |
| 333 | ('bigint'===typeof ptr && ptr >= 0) || __isPtr32(ptr) |
| 334 | ); |
| 335 | |
| 336 | /** |
| 337 | isPtr() is an alias for isPtr32() or isPtr64(), depending on |
| 338 | ptrSize. |
| 339 | */ |
| 340 | const __isPtr = (4===ptrSize) ? __isPtr32 : __isPtr64; |
| 341 | |
| 342 | const __isNonNullPtr = (v)=>__isPtr(v) && (v>0); |
| 343 | |
| 344 | /** Frees the obj.pointer memory (a.k.a. m), handles obj.ondispose, |
| 345 | and unmaps obj from its native resources. */ |
| 346 | const __freeStruct = function(ctor, obj, m){ |
| 347 | const ii = getInstanceHandle(obj, false); |
| 348 | if( !ii || ii.isDisposing ) return; |
| 349 | ii.isDisposing = true; |
| 350 | if( !m && !(m = ii.p) ){ |
| 351 | error("Cannot(?) happen: __freeStruct() found no instanceInfo"); |
| 352 | return; |
| 353 | } |
| 354 | if(Array.isArray(obj.ondispose)){ |
| 355 | let x; |
| 356 | while((x = obj.ondispose.pop())){ |
| 357 | try{ |
| 358 | if(x instanceof Function) x.call(obj); |
| 359 | else if(x instanceof StructType) x.dispose(); |
| 360 | else if(__isPtr(x)) dealloc(x); |
| 361 | // else ignore. Strings are permitted to annotate entries |
| 362 | // to assist in debugging. |
| 363 | }catch(e){ |
| 364 | warn("ondispose() for",ctor.structName,'@', |
| 365 | m,'threw. NOT propagating it.',e); |
| 366 | } |
| 367 | } |
| 368 | }else if(obj.ondispose instanceof Function){ |
| 369 | try{obj.ondispose()} |
| 370 | catch(e){ |
| 371 | /*do not rethrow: destructors must not throw*/ |
| 372 | warn("ondispose() for",ctor.structName,'@', |
| 373 | m,'threw. NOT propagating it.',e); |
| 374 | } |
| 375 | } |
| 376 | rmInstanceHandle(obj); |
| 377 | delete obj.ondispose; |
| 378 | if(ctor.debugFlags.__flags.dealloc){ |
| 379 | log("debug.dealloc:"+(ii.ownsPointer?"":" EXTERNAL"), |
| 380 | ctor.structName,"instance:", |
| 381 | ctor.structInfo.sizeof,"bytes @"+m); |
| 382 | } |
| 383 | if(ii.ownsPointer){ |
| 384 | if( ii.zod || ctor.structInfo.zeroOnDispose ){ |
| 385 | heap().fill(0, Number(m), |
| 386 | Number(m) + ctor.structInfo.sizeof + ii.xb); |
| 387 | } |
| 388 | dealloc(m); |
| 389 | } |
| 390 | }; |
| 391 | |
| 392 | /** Returns a skeleton for a read-only, non-iterable property |
| 393 | * descriptor. */ |
| 394 | const rop0 = ()=>{return {configurable: false, writable: false, |
| 395 | iterable: true}}; |
| 396 | |
| 397 | /** Returns a skeleton for a read-only property accessor wrapping |
| 398 | value v. */ |
| 399 | const rop = (v)=>{return {...rop0(), value: v}}; |
| 400 | |
| 401 | /** Allocates obj's memory buffer based on the size defined in |
| 402 | ctor.structInfo.sizeof. */ |
| 403 | const __allocStruct = function f(ctor, obj, xm){ |
| 404 | let opt; |
| 405 | const checkPtr = (ptr)=>{ |
| 406 | __isNonNullPtr(ptr) || |
| 407 | toss("Invalid pointer value",arguments[0],"for",ctor.structName,"constructor."); |
| 408 | }; |
| 409 | if( arguments.length>=3 ){ |
| 410 | if( xm && ('object'===typeof xm) ){ |
| 411 | opt = xm; |
| 412 | xm = opt?.wrap; |
| 413 | }else{ |
| 414 | checkPtr(xm); |
| 415 | opt = nu({wrap: xm}); |
| 416 | } |
| 417 | }else{ |
| 418 | opt = Object.create(null); |
| 419 | } |
| 420 | |
| 421 | const fill = !xm /* true if we need to zero the memory */; |
| 422 | let nAlloc = 0; |
| 423 | let ownsPointer = false; |
| 424 | if(xm){ |
| 425 | /* Externally-allocated memory. */ |
| 426 | checkPtr(xm); |
| 427 | ownsPointer = !!opt?.takeOwnership; |
| 428 | }else{ |
| 429 | const nX = opt?.extraBytes ?? 0; |
| 430 | if( nX<0 || (nX!==(nX|0)) ){ |
| 431 | toss("Invalid extraBytes value:",opt?.extraBytes); |
| 432 | } |
| 433 | nAlloc = ctor.structInfo.sizeof + nX; |
| 434 | xm = alloc(nAlloc) |
| 435 | || toss("Allocation of",ctor.structName,"structure failed."); |
| 436 | ownsPointer = true; |
| 437 | } |
| 438 | try { |
| 439 | if( opt?.debugFlags ){ |
| 440 | /* specifically undocumented */ |
| 441 | obj.debugFlags(opt.debugFlags); |
| 442 | } |
| 443 | if(ctor./*prototype.???*/debugFlags.__flags.alloc){ |
| 444 | log("debug.alloc:",(fill?"":"EXTERNAL"), |
| 445 | ctor.structName,"instance:", |
| 446 | ctor.structInfo.sizeof,"bytes @"+xm); |
| 447 | } |
| 448 | if(fill){ |
| 449 | heap().fill(0, Number(xm), Number(xm) + nAlloc); |
| 450 | } |
| 451 | const ii = getInstanceHandle(obj); |
| 452 | ii.p = xm; |
| 453 | ii.ownsPointer = ownsPointer; |
| 454 | ii.xb = nAlloc ? (nAlloc-ctor.structInfo.sizeof) : 0; |
| 455 | ii.zod = !!opt?.zeroOnDispose; |
| 456 | if( opt?.ondispose && opt.ondispose!==xm ){ |
| 457 | obj.addOnDispose( opt.ondispose ); |
| 458 | } |
| 459 | }catch(e){ |
| 460 | __freeStruct(ctor, obj, xm); |
| 461 | throw e; |
| 462 | } |
| 463 | }; |
| 464 | |
| 465 | /** True if sig looks like an emscripten/jaccwabyt |
| 466 | type signature, else false. */ |
| 467 | const looksLikeASig = function f(sig){ |
| 468 | f.rxSig1 ??= /^[ipPsjfdcC]$/; |
| 469 | f.rxSig2 ??= /^[vipPsjfdcC]\([ipPsjfdcC]*\)$/; |
| 470 | return f.rxSig1.test(sig) || f.rxSig2.test(sig); |
| 471 | }; |
| 472 | |
| 473 | //#define j-proxy-through-ctor 0 |
| 474 | //#if 0 |
| 475 | /* |
| 476 | j-proxy-through-ctor is an attempt to cascade adaptSet(), |
| 477 | adaptGet(), and adaptStruct() through two levels: StructBinder and |
| 478 | the StructCtors which it creates. |
| 479 | |
| 480 | It does not yet work due to missing context pieces in a few spots. |
| 481 | |
| 482 | The problem this is intended to solve is that a struct descriptor |
| 483 | like: |
| 484 | |
| 485 | const Foo = { |
| 486 | adaptor: { |
| 487 | struct: { ProxyInner: someStructDescriptor } |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | does not need to overwrite StructBinder's mapping (if any) of |
| 492 | "ProxyInner". As of this writing, that construct will overwrite |
| 493 | the one in the managing StructBinder. That's not _horrible_, but |
| 494 | having two layers would be nicer. |
| 495 | */ |
| 496 | //#/if |
| 497 | |
| 498 | /** |
| 499 | Returns a pair of adaptor maps (objects) in a length-3 array |
| 500 | specific to the given object. |
| 501 | */ |
| 502 | const __adaptorsFor = function(who, createIfNeeded=true){ |
| 503 | let x = this.get(who); |
| 504 | if( !x && createIfNeeded ){ |
| 505 | x = [ Object.create(null)/*0=getter*/, |
| 506 | Object.create(null)/*1=setter*/, |
| 507 | Object.create(null)/*2=struct*/ ]; |
| 508 | this.set(who, x); |
| 509 | } |
| 510 | return x; |
| 511 | }.bind(new WeakMap); |
| 512 | |
| 513 | /** Code de-duplifier for __adaptGetter(), __adaptSetter(), and |
| 514 | __adaptStruct(): |
| 515 | |
| 516 | If passed 3 args: returns adaptors[key]. |
| 517 | |
| 518 | If proxy is truthy, assigns that to adaptors[key] and returns it. |
| 519 | |
| 520 | Else removes adaptors[key]. i.e. pass a falsy proxy to unset the |
| 521 | proxy. |
| 522 | */ |
| 523 | const __adaptor = function(who, which, key, proxy){ |
| 524 | const a = __adaptorsFor(who)[which]; |
| 525 | if(3===arguments.length) return a[key] /* getter */; |
| 526 | if( proxy ) return a[key] = proxy /* setter */; |
| 527 | return delete a[key] /* remover */; |
| 528 | }; |
| 529 | |
| 530 | const noopAdapter = (x)=>x; |
| 531 | |
| 532 | // StructBinder::adaptGetter() |
| 533 | const __adaptGetter = function(key, ...args){ |
| 534 | return __adaptor(this, 0, key, ...args); |
| 535 | }; |
| 536 | |
| 537 | const __affirmNotASig = function(ctx,key){ |
| 538 | looksLikeASig(key) && |
| 539 | toss(ctx,"(",key,") collides with a data type signature."); |
| 540 | }; |
| 541 | |
| 542 | // StructBinder::adaptSetter() |
| 543 | const __adaptSetter = function(key, ...args){ |
| 544 | __affirmNotASig('Setter adaptor',key); |
| 545 | return __adaptor(this, 1, key, ...args); |
| 546 | }; |
| 547 | |
| 548 | // StructBinder::adaptStruct() |
| 549 | const __adaptStruct = function(key, ...args){ |
| 550 | __affirmNotASig('Struct adaptor',key); |
| 551 | return __adaptor(this, 2, key, ...args); |
| 552 | }; |
| 553 | |
| 554 | /** |
| 555 | An internal counterpart of __adaptStruct(). If key is-a string, |
| 556 | uses __adaptor(who) to fetch the struct-adaptor entry for key, |
| 557 | else key is assumed to be a struct descriptor object. If it |
| 558 | resolves to an object, that's returned, else an exception is |
| 559 | thrown. |
| 560 | */ |
| 561 | const __adaptStruct2 = function(who,key){ |
| 562 | const si = ('string'===typeof key) |
| 563 | ? __adaptor(who, 2, key) : key; |
| 564 | if( 'object'!==typeof si ){ |
| 565 | warn('adaptStruct2(',who,key,')', si); |
| 566 | toss("Invalid struct mapping object. Arg =",key,JSON.stringify(si)); |
| 567 | } |
| 568 | return si; |
| 569 | }; |
| 570 | |
| 571 | const __memberKey = (k)=>memberPrefix + k + memberSuffix; |
| 572 | const __memberKeyProp = rop(__memberKey); |
| 573 | //const __adaptGetterProp = rop(__adaptGetter); |
| 574 | |
| 575 | /** |
| 576 | Looks up a struct member in structInfo.members. Throws if found |
| 577 | if tossIfNotFound is true, else returns undefined if not |
| 578 | found. The given name may be either the name of the |
| 579 | structInfo.members key (faster) or the key as modified by the |
| 580 | memberPrefix and memberSuffix settings. |
| 581 | */ |
| 582 | const __lookupMember = function(structInfo, memberName, tossIfNotFound=true){ |
| 583 | let m = structInfo.members[memberName]; |
| 584 | if(!m && (memberPrefix || memberSuffix)){ |
| 585 | // Check for a match on members[X].key |
| 586 | for(const v of Object.values(structInfo.members)){ |
| 587 | if(v.key===memberName){ m = v; break; } |
| 588 | } |
| 589 | if(!m && tossIfNotFound){ |
| 590 | toss(sPropName(structInfo.name || structInfo.structName, memberName), |
| 591 | 'is not a mapped struct member.'); |
| 592 | } |
| 593 | } |
| 594 | return m; |
| 595 | }; |
| 596 | |
| 597 | /** |
| 598 | Uses __lookupMember(obj.structInfo,memberName) to find a member, |
| 599 | throwing if not found. Returns its signature, either in this |
| 600 | framework's native format or in Emscripten format. |
| 601 | */ |
| 602 | const __memberSignature = (obj,memberName,tossIfNotFNotFound=true)=> |
| 603 | __lookupMember(obj.structInfo, memberName, tossIfNotFNotFound)?.signature; |
| 604 | |
| 605 | /** Impl of X.memberKeys() for StructType and struct ctors. */ |
| 606 | const __structMemberKeys = rop(function(){ |
| 607 | const a = []; |
| 608 | for(const k of Object.keys(this.structInfo.members)){ |
| 609 | a.push(this.memberKey(k)); |
| 610 | } |
| 611 | return a; |
| 612 | }); |
| 613 | |
| 614 | const __utf8Decoder = new TextDecoder(); |
| 615 | const __utf8Encoder = new TextEncoder(); |
| 616 | /** Internal helper to use in operations which need to distinguish |
| 617 | between SharedArrayBuffer heap memory and non-shared heap. */ |
| 618 | const __SAB = ('undefined'===typeof SharedArrayBuffer) |
| 619 | ? function(){} : SharedArrayBuffer; |
| 620 | const __maybeSlice = (typedArray, begin, end)=>{ |
| 621 | if( 8===ptrSize ){ |
| 622 | begin = Number(begin); |
| 623 | end = Number(end); |
| 624 | } |
| 625 | return (typedArray.buffer instanceof __SAB) |
| 626 | ? typedArray.slice(begin, end) |
| 627 | : typedArray.subarray(begin, end); |
| 628 | }; |
| 629 | const __utf8Decode = (typedArray, begin, end)=> |
| 630 | __utf8Decoder.decode(__maybeSlice(typedArray, begin, end)); |
| 631 | |
| 632 | /** |
| 633 | Uses __lookupMember() to find the given obj.structInfo key. |
| 634 | Returns that member if it is a string, else returns false. If the |
| 635 | member is not found, throws if tossIfNotFound is true, else |
| 636 | returns false. |
| 637 | */ |
| 638 | const __memberIsString = function(obj,memberName, tossIfNotFound=false){ |
| 639 | const m = __lookupMember(obj.structInfo, memberName, tossIfNotFound); |
| 640 | return (m && 1===m.signature.length && 's'===m.signature[0]) ? m : false; |
| 641 | }; |
| 642 | |
| 643 | /** |
| 644 | Given a member description object, throws if member.signature is |
| 645 | not valid for assigning to or interpretation as a C-style string. |
| 646 | It optimistically assumes that any signature of (i,p,s) is |
| 647 | C-string compatible. |
| 648 | */ |
| 649 | const __affirmCStringSignature = function(member){ |
| 650 | if('s'===member.signature) return; |
| 651 | toss("Invalid member type signature for C-string value:", |
| 652 | JSON.stringify(member)); |
| 653 | }; |
| 654 | |
| 655 | /** |
| 656 | Looks up the given member in obj.structInfo. If it has a |
| 657 | signature of 's' then it is assumed to be a C-style UTF-8 string |
| 658 | and a decoded copy of the string at its address is returned. If |
| 659 | the signature is of any other type, it throws. If an s-type |
| 660 | member's address is 0, `null` is returned. |
| 661 | */ |
| 662 | const __memberToJsString = function f(obj,memberName){ |
| 663 | const m = __lookupMember(obj.structInfo, memberName, true); |
| 664 | __affirmCStringSignature(m); |
| 665 | const addr = obj[m.key]; |
| 666 | //log("addr =",addr,memberName,"m =",m); |
| 667 | if(!addr) return null; |
| 668 | let pos = addr; |
| 669 | const mem = heap(); |
| 670 | for( ; mem[pos]!==0; ++pos ) { |
| 671 | //log("mem[",pos,"]",mem[pos]); |
| 672 | }; |
| 673 | //log("addr =",addr,"pos =",pos); |
| 674 | return (addr===pos) ? "" : __utf8Decode(mem, addr, pos); |
| 675 | }; |
| 676 | |
| 677 | /** |
| 678 | Adds value v to obj.ondispose, creating ondispose, |
| 679 | or converting it to an array, if needed. |
| 680 | */ |
| 681 | const __addOnDispose = function(obj, ...v){ |
| 682 | if(obj.ondispose){ |
| 683 | if(!Array.isArray(obj.ondispose)){ |
| 684 | obj.ondispose = [obj.ondispose]; |
| 685 | } |
| 686 | }else{ |
| 687 | obj.ondispose = []; |
| 688 | } |
| 689 | obj.ondispose.push(...v); |
| 690 | }; |
| 691 | |
| 692 | /** |
| 693 | Allocates a new UTF-8-encoded, NUL-terminated copy of the given |
| 694 | JS string and returns its address relative to heap(). If |
| 695 | allocation returns 0 this function throws. Ownership of the |
| 696 | memory is transfered to the caller, who must eventually pass it |
| 697 | to the configured dealloc() function. |
| 698 | */ |
| 699 | const __allocCString = function(str){ |
| 700 | const u = __utf8Encoder.encode(str); |
| 701 | const mem = alloc(u.length+1); |
| 702 | if(!mem) toss("Allocation error while duplicating string:",str); |
| 703 | const h = heap(); |
| 704 | //let i = 0; |
| 705 | //for( ; i < u.length; ++i ) h[mem + i] = u[i]; |
| 706 | h.set(u, Number(mem)); |
| 707 | h[__ptrAdd(mem, u.length)] = 0; |
| 708 | //log("allocCString @",mem," =",u); |
| 709 | return mem; |
| 710 | }; |
| 711 | |
| 712 | /** |
| 713 | Sets the given struct member of obj to a dynamically-allocated, |
| 714 | UTF-8-encoded, NUL-terminated copy of str. It is up to the caller |
| 715 | to free any prior memory, if appropriate. The newly-allocated |
| 716 | string is added to obj.ondispose so will be freed when the object |
| 717 | is disposed. |
| 718 | |
| 719 | The given name may be either the name of the structInfo.members |
| 720 | key (faster) or the key as modified by the memberPrefix and |
| 721 | memberSuffix settings. |
| 722 | */ |
| 723 | const __setMemberCString = function(obj, memberName, str){ |
| 724 | const m = __lookupMember(obj.structInfo, memberName, true); |
| 725 | __affirmCStringSignature(m); |
| 726 | /* Potential TODO: if obj.ondispose contains obj[m.key] then |
| 727 | dealloc that value and clear that ondispose entry */ |
| 728 | const mem = __allocCString(str); |
| 729 | obj[m.key] = mem; |
| 730 | __addOnDispose(obj, mem); |
| 731 | return obj; |
| 732 | }; |
| 733 | |
| 734 | /** |
| 735 | Prototype for all StructFactory instances (the constructors |
| 736 | returned from StructBinder). |
| 737 | */ |
| 738 | const StructType = function StructType(structName, structInfo){ |
| 739 | if(arguments[2]!==rop/*internal sentinel value*/){ |
| 740 | toss("Do not call the StructType constructor", |
| 741 | "from client-level code."); |
| 742 | } |
| 743 | Object.defineProperties(this,{ |
| 744 | //isA: rop((v)=>v instanceof StructType), |
| 745 | structName: rop(structName), |
| 746 | structInfo: rop(structInfo) |
| 747 | }); |
| 748 | }; |
| 749 | |
| 750 | /** |
| 751 | Properties inherited by struct-type-specific StructType instances |
| 752 | and (indirectly) concrete struct-type instances. |
| 753 | */ |
| 754 | StructType.prototype = Object.create(null, { |
| 755 | dispose: rop(function(){__freeStruct(this.constructor, this)}), |
| 756 | lookupMember: rop(function(memberName, tossIfNotFound=true){ |
| 757 | return __lookupMember(this.structInfo, memberName, tossIfNotFound); |
| 758 | }), |
| 759 | memberToJsString: rop(function(memberName){ |
| 760 | return __memberToJsString(this, memberName); |
| 761 | }), |
| 762 | memberIsString: rop(function(memberName, tossIfNotFound=true){ |
| 763 | return __memberIsString(this, memberName, tossIfNotFound); |
| 764 | }), |
| 765 | memberKey: __memberKeyProp, |
| 766 | memberKeys: __structMemberKeys, |
| 767 | memberSignature: rop(function(memberName, tossIfNotFNotFound=true){ |
| 768 | return __memberSignature(this, memberName, tossIfNotFNotFound); |
| 769 | }), |
| 770 | memoryDump: rop(function(){ |
| 771 | const ih = getInstanceHandle(this,false); |
| 772 | const p = this.pointer; |
| 773 | return p |
| 774 | ? new Uint8Array( |
| 775 | __maybeSlice(heap(), p, |
| 776 | Number(p) + this.structInfo.sizeof + ih.xb) |
| 777 | ) |
| 778 | : null; |
| 779 | }), |
| 780 | extraBytes: { |
| 781 | configurable: false, enumerable: false, |
| 782 | get: function(){return getInstanceHandle(this, false)?.xb ?? 0;} |
| 783 | }, |
| 784 | zeroOnDispose: { |
| 785 | configurable: false, enumerable: false, |
| 786 | get: function(){ |
| 787 | return getInstanceHandle(this, false)?.zod |
| 788 | ?? !!this.structInfo.zeroOnDispose; |
| 789 | } |
| 790 | }, |
| 791 | pointer: { |
| 792 | configurable: false, enumerable: false, |
| 793 | get: function(){return getInstanceHandle(this, false)?.p}, |
| 794 | set: ()=>toss("Cannot assign the 'pointer' property of a struct.") |
| 795 | // Reminder: leaving `set` undefined makes assignments |
| 796 | // to the property _silently_ do nothing. Current unit tests |
| 797 | // rely on it throwing, though. |
| 798 | }, |
| 799 | setMemberCString: rop(function(memberName, str){ |
| 800 | return __setMemberCString(this, memberName, str); |
| 801 | }) |
| 802 | }); |
| 803 | // Function-type non-Property inherited members |
| 804 | Object.assign(StructType.prototype,{ |
| 805 | addOnDispose: function(...v){ |
| 806 | __addOnDispose(this,...v); |
| 807 | return this; |
| 808 | }, |
| 809 | ownsOwnMemory: function(){ |
| 810 | return __objOwnsOwnMemory(this); |
| 811 | } |
| 812 | }); |
| 813 | |
| 814 | /** |
| 815 | "Static" properties for StructType. |
| 816 | */ |
| 817 | Object.defineProperties(StructType, { |
| 818 | allocCString: rop(__allocCString), |
| 819 | isA: rop((v)=>v instanceof StructType), |
| 820 | memberKey: __memberKeyProp |
| 821 | //ptrAdd = rop(__ptrAdd) no b/c one might think that it adds based on this.pointer. |
| 822 | }); |
| 823 | |
| 824 | /** |
| 825 | If struct descriptor object si has a getter proxy, return it (a |
| 826 | function), else return undefined. |
| 827 | */ |
| 828 | const memberGetterProxy = function(si){ |
| 829 | //#if j-proxy-through-ctor |
| 830 | const g = si.getter; |
| 831 | return (g instanceof Function) |
| 832 | ? g |
| 833 | : (__adaptorsFor(si.constructor, false)?.[0]?.[g] |
| 834 | ?? StructBinder.adaptGetter(g)); |
| 835 | //#else |
| 836 | const g = si.getter; |
| 837 | return g |
| 838 | ? ((g instanceof Function) |
| 839 | ? g |
| 840 | : StructBinder.adaptGetter(g)) |
| 841 | : undefined; |
| 842 | |
| 843 | //#/if |
| 844 | }; |
| 845 | |
| 846 | /** |
| 847 | If struct descriptor object si has a setter proxy, return it (a |
| 848 | function), else return undefined. |
| 849 | */ |
| 850 | const memberSetterProxy = function(si){ |
| 851 | //#if j-proxy-through-ctor |
| 852 | let s = si.setter; |
| 853 | return (s instanceof Function) |
| 854 | ? s |
| 855 | : (__adaptorsFor(si.constructor, false)?.[1]?.[s] |
| 856 | ?? StructBinder.adaptGetter(s)); |
| 857 | //#else |
| 858 | const s = si.setter; |
| 859 | return s |
| 860 | ? ((s instanceof Function) |
| 861 | ? s |
| 862 | : StructBinder.adaptSetter(s)) |
| 863 | : undefined; |
| 864 | //#/if |
| 865 | }; |
| 866 | |
| 867 | /** |
| 868 | To be called by makeMemberWrapper() when si has a 'members' |
| 869 | member, i.e. is an embedded struct. This function sets up that |
| 870 | struct like any other and also sets up property accessor for |
| 871 | ctor.memberKey(name) which returns an instance of that new |
| 872 | StructType when the member is accessed. That instance wraps the |
| 873 | memory of the member's part of the containing C struct instance. |
| 874 | |
| 875 | That is, if struct Foo has member bar which is an inner struct |
| 876 | then: |
| 877 | |
| 878 | const f = new Foo; |
| 879 | const b = f.bar; |
| 880 | assert( b is-a StructType object ); |
| 881 | assert( b.pointer === f.b.pointer ); |
| 882 | |
| 883 | b will be disposed of when f() is. Calling b.dispose() will not |
| 884 | do any permanent harm, as the wrapper object will be recreated |
| 885 | when accessing f.bar, pointing to the same memory in f. |
| 886 | |
| 887 | The si.zeroOnDispose flag has no effect on embedded structs because |
| 888 | they wrap "external" memory, so do not own it, and are thus never |
| 889 | freed, as such. |
| 890 | */ |
| 891 | const makeMemberStructWrapper = function callee(ctor, name, si){ |
| 892 | /** |
| 893 | Where we store inner-struct member proxies. Keys are a |
| 894 | combination of the parent object's pointer address and the |
| 895 | property's name. The values are StructType instances. |
| 896 | */ |
| 897 | const __innerStructs = (callee.innerStructs ??= new Map()); |
| 898 | const key = ctor.memberKey(name); |
| 899 | if( undefined!==si.signature ){ |
| 900 | toss("'signature' cannot be used on an embedded struct (", |
| 901 | ctor.structName,".",key,")."); |
| 902 | } |
| 903 | if( memberSetterProxy(si) ){ |
| 904 | toss("'set' and 'adaptSetter' are not permitted for nested struct members."); |
| 905 | } |
| 906 | //warn("si =",ctor.structName, name, JSON.stringify(si,' ')); |
| 907 | si.structName ??= ctor.structName+'::'+name; |
| 908 | si.key = key; |
| 909 | si.name = name; |
| 910 | si.constructor = this.call(this, si.structName, si); |
| 911 | //warn("si.constructor =",si.constructor); |
| 912 | //warn("si =",si,"ctor=",ctor); |
| 913 | const getterProxy = memberGetterProxy(si); |
| 914 | const prop = nu({ |
| 915 | configurable: false, |
| 916 | enumerable: false, |
| 917 | set: __propThrowOnSet(ctor/*not si.constructor*/.structName, key), |
| 918 | get: function(){ |
| 919 | const dbg = this.debugFlags.__flags; |
| 920 | const p = this.pointer; |
| 921 | const k = p+'.'+key; |
| 922 | let s = __innerStructs.get(k); |
| 923 | if(dbg.getter){ log("debug.getter: k =",k); } |
| 924 | if( !s ){ |
| 925 | /* Create a proxy to access this member and set |
| 926 | it up to be disposed when this object is.*/ |
| 927 | s = new si.constructor(__ptrAdd(p, si.offset)); |
| 928 | __innerStructs.set(k, s); |
| 929 | this.addOnDispose(()=>s.dispose()); |
| 930 | s.addOnDispose( |
| 931 | ()=>__innerStructs.delete(k) |
| 932 | /* Reminder: we need this attached to s, instead of |
| 933 | doing it via this.addOnDispose(), in case |
| 934 | s.dispose() is called. */ |
| 935 | ); |
| 936 | //warn("Created",k,"proxy"); |
| 937 | } |
| 938 | if(getterProxy) s = getterProxy.call(this, name, s); |
| 939 | if(dbg.getter) log("debug.getter: result =",s); |
| 940 | return s; |
| 941 | } |
| 942 | }); |
| 943 | Object.defineProperty(ctor.prototype, key, prop); |
| 944 | }/*makeMemberStructWrapper()*/; |
| 945 | |
| 946 | /** |
| 947 | This is where most of the magic happens. |
| 948 | |
| 949 | Pass this a StructBinderImpl-generated constructor, a member |
| 950 | property name, and the struct member description object. It will |
| 951 | define property accessors for proto[memberKey] which read |
| 952 | from/write to memory in this.pointer. It modifies si to make |
| 953 | certain downstream operations simpler. |
| 954 | */ |
| 955 | const makeMemberWrapper = function f(ctor, name, si){ |
| 956 | si = __adaptStruct2(this, si); |
| 957 | if( si.members ){ |
| 958 | return makeMemberStructWrapper.call(this, ctor, name, si); |
| 959 | } |
| 960 | |
| 961 | if(!f.cache){ |
| 962 | /* Cache all available getters/setters/set-wrappers for |
| 963 | direct reuse in each accessor function. */ |
| 964 | f.cache = nu({getters: nu(), setters: nu(), sw:nu()}); |
| 965 | const a = ['i','c','C','p','P','s','f','d']; |
| 966 | if(bigIntEnabled) a.push('j'); |
| 967 | for(const v of a){ |
| 968 | f.cache.getters[v] = sigDVGetter(v) /* DataView[MethodName] values for GETTERS */; |
| 969 | f.cache.setters[v] = sigDVSetter(v) /* DataView[MethodName] values for SETTERS */; |
| 970 | f.cache.sw[v] = sigDVSetWrapper(v) /* BigInt or Number ctor to wrap around values |
| 971 | for conversion */; |
| 972 | } |
| 973 | f.sigCheck = (obj, name, key,sig)=>{ |
| 974 | if(Object.prototype.hasOwnProperty.call(obj, key)){ |
| 975 | toss(obj.structName,'already has a property named',key+'.'); |
| 976 | } |
| 977 | looksLikeASig(sig) |
| 978 | || toss("Malformed signature for", |
| 979 | sPropName(obj.structName,name)+":",sig); |
| 980 | }; |
| 981 | } |
| 982 | const key = ctor.memberKey(name); |
| 983 | f.sigCheck(ctor.prototype, name, key, si.signature); |
| 984 | si.key = key; |
| 985 | si.name = name; |
| 986 | const sigGlyph = sigLetter(si.signature); |
| 987 | const xPropName = sPropName(ctor.structName,key); |
| 988 | const dbg = ctor.debugFlags.__flags; |
| 989 | /* |
| 990 | TODO?: set prototype of si to an object which can set/fetch |
| 991 | its preferred representation, e.g. conversion to string or mapped |
| 992 | function. Advantage: we can avoid doing that via if/else if/else |
| 993 | in the get/set methods. |
| 994 | */ |
| 995 | const getterProxy = memberGetterProxy(si); |
| 996 | const prop = Object.create(null); |
| 997 | prop.configurable = false; |
| 998 | prop.enumerable = false; |
| 999 | prop.get = function(){ |
| 1000 | /** |
| 1001 | This getter proxy reads its value from the appropriate pointer |
| 1002 | address in the heap. It knows where and how much to read based on |
| 1003 | this.pointer, si.offset, and si.sizeof. |
| 1004 | */ |
| 1005 | if(dbg.getter){ |
| 1006 | log("debug.getter:",f.cache.getters[sigGlyph],"for", sigIR(sigGlyph), |
| 1007 | xPropName,'@', this.pointer,'+',si.offset,'sz',si.sizeof); |
| 1008 | } |
| 1009 | let rc = ( |
| 1010 | new DataView(heap().buffer, Number(this.pointer) + si.offset, si.sizeof) |
| 1011 | )[f.cache.getters[sigGlyph]](0, isLittleEndian); |
| 1012 | |
| 1013 | if(getterProxy){ |
| 1014 | //warn("getterProxy",rc,name,key, xPropName); |
| 1015 | rc = getterProxy.call(this,name/*!key*/,rc); |
| 1016 | } |
| 1017 | if(dbg.getter) log("debug.getter:",xPropName,"result =",rc); |
| 1018 | return rc; |
| 1019 | }; |
| 1020 | if(si.readOnly){ |
| 1021 | prop.set = __propThrowOnSet(ctor.prototype.structName,key); |
| 1022 | }else{ |
| 1023 | const setterProxy = memberSetterProxy(si); |
| 1024 | prop.set = function(v){ |
| 1025 | /** |
| 1026 | The converse of prop.get(), this encodes v into the appropriate |
| 1027 | spot in the WASM heap. |
| 1028 | */ |
| 1029 | if(dbg.setter){ |
| 1030 | log("debug.setter:",f.cache.setters[sigGlyph],"for", sigIR(sigGlyph), |
| 1031 | xPropName,'@', this.pointer,'+',si.offset,'sz',si.sizeof, v); |
| 1032 | } |
| 1033 | if(!this.pointer){ |
| 1034 | toss("Cannot set native property on a disposed", |
| 1035 | this.structName,"instance."); |
| 1036 | } |
| 1037 | if( setterProxy ) v = setterProxy.call(this,name/*!key*/,v); |
| 1038 | if( null===v || undefined===v ) v = __NullPtr; |
| 1039 | else if( isPtrSig(si.signature) && !__isPtr(v) ){ |
| 1040 | if(isAutoPtrSig(si.signature) && (v instanceof StructType)){ |
| 1041 | // It's a struct instance: store its pointer value |
| 1042 | v = v.pointer || __NullPtr; |
| 1043 | if(dbg.setter) log("debug.setter:",xPropName,"resolved to",v); |
| 1044 | }else{ |
| 1045 | toss("Invalid value for pointer-type",xPropName+'.'); |
| 1046 | } |
| 1047 | } |
| 1048 | ( |
| 1049 | new DataView(heap().buffer, Number(this.pointer) + si.offset, |
| 1050 | si.sizeof) |
| 1051 | )[f.cache.setters[sigGlyph]](0, f.cache.sw[sigGlyph](v), isLittleEndian); |
| 1052 | }; |
| 1053 | } |
| 1054 | Object.defineProperty(ctor.prototype, key, prop); |
| 1055 | }/*makeMemberWrapper()*/; |
| 1056 | |
| 1057 | /** |
| 1058 | The main factory function which will be returned to the |
| 1059 | caller. The third argument is structly for internal use. |
| 1060 | |
| 1061 | This level of indirection is to avoid that clients can pass a |
| 1062 | third argument to this, as that's only for internal use. |
| 1063 | |
| 1064 | Usages: |
| 1065 | |
| 1066 | StructBinder(string, obj); |
| 1067 | StructBinder(obj); |
| 1068 | */ |
| 1069 | const StructBinderImpl = function StructBinderImpl(structName, si){ |
| 1070 | /** |
| 1071 | StructCtor is the eventual return value of this function. We |
| 1072 | need to populate this early on so that we can do some trickery |
| 1073 | in feeding it through recursion. |
| 1074 | |
| 1075 | Uses: |
| 1076 | |
| 1077 | // heap-allocated: |
| 1078 | const x = new StructCtor; |
| 1079 | // externally-managed memory: |
| 1080 | const y = new StructCtor( aPtrToACompatibleCStruct ); |
| 1081 | |
| 1082 | or, more recently: |
| 1083 | |
| 1084 | const z = new StructCtor({ |
| 1085 | extraBytes: [int=0] extra bytes to allocate after the struct |
| 1086 | |
| 1087 | wrap: [aPtrToACompatibleCStruct=undefined]. If provided, this |
| 1088 | instance waps, but does not (by default) own the memory, else |
| 1089 | a new instance is allocated from the WASM heap. |
| 1090 | |
| 1091 | ownsPointer: true if this object takes over ownership of |
| 1092 | wrap. |
| 1093 | |
| 1094 | zeroOnDispose: [bool=StructCtor.structInfo.zeroOnDispose] |
| 1095 | |
| 1096 | autoCalcSizeOffset: [bool=false] Automatically calculate |
| 1097 | sizeof and offset. This is fine for pure-JS structs (which |
| 1098 | probably aren't useful beyond testing of Jaccwabyt) but it's |
| 1099 | dangerous to use with actual WASM objects because we cannot |
| 1100 | be guaranteed to have the same memory layout as an ostensibly |
| 1101 | matching C struct. This applies recursively to all children |
| 1102 | of the struct descriptor. |
| 1103 | }); |
| 1104 | */ |
| 1105 | const StructCtor = function StructCtor(arg){ |
| 1106 | //warn("opt",opt,arguments[0]); |
| 1107 | if(!(this instanceof StructCtor)){ |
| 1108 | toss("The",structName,"constructor may only be called via 'new'."); |
| 1109 | } |
| 1110 | __allocStruct(StructCtor, this, ...arguments); |
| 1111 | }; |
| 1112 | const thisBinder = this; |
| 1113 | /** |
| 1114 | "Convert" struct descriptor x to a struct descriptor, if |
| 1115 | needed. This expands adaptStruct() mappings and transforms |
| 1116 | {memberName:signatureString} signature syntax to object form. |
| 1117 | */ |
| 1118 | const ads = (x)=>{ |
| 1119 | //warn("looksLikeASig(",x,") =",looksLikeASig(x)); |
| 1120 | return (('string'===typeof x) && looksLikeASig(x)) |
| 1121 | /* 2026-11-05: why was ^^^ this ^^^ done? */ |
| 1122 | ? nu({signature: x}) : __adaptStruct2(thisBinder,x); |
| 1123 | }; |
| 1124 | if(1===arguments.length){ |
| 1125 | si = ads(structName); |
| 1126 | structName = si.structName || si.name; |
| 1127 | }else if(2===arguments.length){ |
| 1128 | si = ads(si); |
| 1129 | si.name ??= structName; |
| 1130 | }else{ |
| 1131 | si = ads(si); |
| 1132 | } |
| 1133 | structName ??= si.structName; |
| 1134 | //warn("arguments =",JSON.stringify(arguments)); |
| 1135 | if( !structName ){ |
| 1136 | toss("Missing struct name. Pass it as the first argument", |
| 1137 | "or in structDescriptor.structName."); |
| 1138 | } |
| 1139 | if( si.adaptor ){ |
| 1140 | /* Install adaptGetter(), adaptSetter(), and adaptStruct() proxies. */ |
| 1141 | for(const a of [['struct', __adaptStruct], |
| 1142 | ['setter', __adaptSetter], |
| 1143 | ['getter', __adaptGetter]]){ |
| 1144 | const ao = si.adaptor[a[0]]; |
| 1145 | if( !ao ) continue; |
| 1146 | for(const e of Object.entries(ao)){ |
| 1147 | //warn("si.adaptor bits", a, e); |
| 1148 | const [key, proxy] = e; |
| 1149 | if( 'struct'===a[0] ){ |
| 1150 | if( !proxy || ('object'!==typeof proxy ) ){ |
| 1151 | error("Offending struct adaptor", si, ao); |
| 1152 | toss("Expecting an Object for struct adaptor",key); |
| 1153 | } |
| 1154 | }else if( !(proxy instanceof Function) ){ |
| 1155 | toss("Expecting a function for",a[0],"adaptor",key); |
| 1156 | } |
| 1157 | //#if j-proxy-through-ctor |
| 1158 | a[1].call(StructCtor, e[0], e[1]); |
| 1159 | //#else |
| 1160 | if( a[1].call(thisBinder, e[0]) ){ |
| 1161 | warn(structName,"is overriding adaptor", e[0]); |
| 1162 | /* Potential TODO is map any overrides to StructCtor and |
| 1163 | look for those first when fetching. */ |
| 1164 | } |
| 1165 | a[1].call(thisBinder, e[0], e[1]); |
| 1166 | //#/if |
| 1167 | } |
| 1168 | } |
| 1169 | } |
| 1170 | if(!si.members && !si.sizeof){ |
| 1171 | si.sizeof = sigSize(si.signature); |
| 1172 | } |
| 1173 | |
| 1174 | const debugFlags = rop(SBF.__makeDebugFlags(StructBinder.debugFlags)); |
| 1175 | Object.defineProperties(StructCtor,{ |
| 1176 | /* Ctor static properties. */ |
| 1177 | debugFlags: debugFlags, |
| 1178 | isA: rop((v)=>v instanceof StructCtor), |
| 1179 | memberKey: __memberKeyProp, |
| 1180 | memberKeys: __structMemberKeys, |
| 1181 | //methodInfoForKey: rop(function(mKey){/*???*/}), |
| 1182 | structInfo: rop(si), |
| 1183 | structName: rop(structName), |
| 1184 | ptrAdd: rop(__ptrAdd) |
| 1185 | }); |
| 1186 | StructCtor.prototype = new StructType(structName, si, rop); |
| 1187 | Object.defineProperties(StructCtor.prototype,{ |
| 1188 | /* Ctor inherited properties. */ |
| 1189 | debugFlags: debugFlags, |
| 1190 | constructor: rop(StructCtor) |
| 1191 | /*if we assign StructCtor.prototype and don't do |
| 1192 | this then StructCtor!==instance.constructor*/, |
| 1193 | ptrAdd: rop(__ptrAddSelf) |
| 1194 | }); |
| 1195 | let lastMember = false; |
| 1196 | let offset = 0; |
| 1197 | const autoCalc = !!si.autoCalcSizeOffset; |
| 1198 | //warn(structName,"si =",si); |
| 1199 | if( !autoCalc ){ |
| 1200 | if( !si.sizeof ){ |
| 1201 | toss(structName,"description is missing its sizeof property."); |
| 1202 | } |
| 1203 | /*if( undefined===si.offset ){ |
| 1204 | toss(structName,"description is missing its offset property."); |
| 1205 | }*/ |
| 1206 | } |
| 1207 | si.offset ??= 0; |
| 1208 | for( const e of Object.entries(si.members||{}) ){ |
| 1209 | // Sanity checks of sizeof/offset info... |
| 1210 | const [k, v] = e; |
| 1211 | const m = ads(v); |
| 1212 | if(!m.members && !m.sizeof){ |
| 1213 | /* fixme: we need ^^^^^^ to recursively collect all sizeofs |
| 1214 | before updating that. */ |
| 1215 | m.sizeof = sigSize(m.signature); |
| 1216 | if(!m.sizeof){ |
| 1217 | toss(sPropName(structName,k), "is missing a sizeof property.",m); |
| 1218 | } |
| 1219 | } |
| 1220 | if( undefined===m.offset ){ |
| 1221 | if( autoCalc ) m.offset = offset; |
| 1222 | else{ |
| 1223 | toss(sPropName(structName,k),"is missing its offset.", |
| 1224 | JSON.stringify(m)); |
| 1225 | } |
| 1226 | /* A missing offset on the initial child is okay (it's always |
| 1227 | zero), but we don't know for sure that the members are |
| 1228 | their natural order, so we don't know, at this point, which |
| 1229 | one is "first". |
| 1230 | |
| 1231 | 2026-11-05: this is probably gonna break when we start |
| 1232 | supporting proxied instances of structs for sharing across |
| 1233 | disparate outer structs because we modify these objects. |
| 1234 | */ |
| 1235 | } |
| 1236 | si.members[k] = m /* in case ads() resolved it to something else */; |
| 1237 | if(!lastMember || lastMember.offset < m.offset) lastMember = m; |
| 1238 | const oldAutoCalc = !!m.autoCalc; |
| 1239 | if( autoCalc ) m.autoCalcSizeOffset = true; |
| 1240 | makeMemberWrapper.call(thisBinder, StructCtor, k, m); |
| 1241 | if( oldAutoCalc ) m.autoCalcSizeOffset = true; |
| 1242 | else delete m.autoCalcSizeOffset; |
| 1243 | offset += m.sizeof; |
| 1244 | //warn("offset",sPropName(structName,k),offset); |
| 1245 | } |
| 1246 | |
| 1247 | if( !lastMember ) toss("No member property descriptions found."); |
| 1248 | if( !si.sizeof ) si.sizeof = offset; |
| 1249 | if(si.sizeof===1){ |
| 1250 | (si.signature === 'c' || si.signature === 'C') || |
| 1251 | toss("Unexpected sizeof==1 member", |
| 1252 | sPropName(structName,k), |
| 1253 | "with signature",si.signature); |
| 1254 | }else{ |
| 1255 | // sizes and offsets of size-1 members may be odd values, but |
| 1256 | // others may not. |
| 1257 | if(0!==(si.sizeof%4)){ |
| 1258 | warn("Invalid struct member description",si); |
| 1259 | toss(structName,"sizeof is not aligned. sizeof="+si.sizeof); |
| 1260 | } |
| 1261 | if(0!==(si.offset%4)){ |
| 1262 | warn("Invalid struct member description",si); |
| 1263 | toss(structName,"offset is not aligned. offset="+si.offset); |
| 1264 | } |
| 1265 | } |
| 1266 | if( si.sizeof < offset ){ |
| 1267 | warn("Suspect struct descriptor:",si,"offset =",offset); |
| 1268 | toss("Mismatch in the calculated vs. the provided sizeof/offset info.", |
| 1269 | "Expected sizeof",offset,"but got",si.sizeof,"for",si); |
| 1270 | /* It is legal for the native struct to be larger, so long as |
| 1271 | we're pointing to all the right offsets for the members |
| 1272 | exposed here. */ |
| 1273 | } |
| 1274 | delete si.autoCalcSizeOffset; |
| 1275 | return StructCtor; |
| 1276 | }/*StructBinderImpl*/; |
| 1277 | |
| 1278 | const StructBinder = function StructBinder(structName, structInfo){ |
| 1279 | return (1==arguments.length) |
| 1280 | ? StructBinderImpl.call(StructBinder, structName) |
| 1281 | : StructBinderImpl.call(StructBinder, structName, structInfo); |
| 1282 | }; |
| 1283 | StructBinder.StructType = StructType; |
| 1284 | StructBinder.config = config; |
| 1285 | StructBinder.allocCString = __allocCString; |
| 1286 | StructBinder.adaptGetter = __adaptGetter; |
| 1287 | StructBinder.adaptSetter = __adaptSetter; |
| 1288 | StructBinder.adaptStruct = __adaptStruct; |
| 1289 | StructBinder.ptrAdd = __ptrAdd; |
| 1290 | if(!StructBinder.debugFlags){ |
| 1291 | StructBinder.debugFlags = SBF.__makeDebugFlags(SBF.debugFlags); |
| 1292 | } |
| 1293 | return StructBinder; |
| 1294 | }/*StructBinderFactory*/; |
| 1295 | //#if esm |
| 1296 | //# if not no-export |
| 1297 | //# if amalgamation |
| 1298 | export {Jaccwabyt}; |
| 1299 | //# elif not defined no-export-default |
| 1300 | export default Jaccwabyt; |
| 1301 | //# /if |
| 1302 | //# /if |
| 1303 | //#else if not lexical-scoped |
| 1304 | globalThis.Jaccwabyt = Jaccwabyt; |
| 1305 | //# if 0 |
| 1306 | /* ^^^^ it is recommended that clients move that object into wherever |
| 1307 | they'd like to have it and delete the globalThis-held copy. This |
| 1308 | API does not require the global reference - it is simply installed |
| 1309 | as a convenience for connecting these bits to other co-developed |
| 1310 | code before it gets removed from the global namespace. |
| 1311 | */ |
| 1312 | //# /if |
| 1313 | //#/if |
| 1314 | //#savepoint rollback |
| 1315 | //#@ pop policy delimiter |