1+ import fs from 'fs' ;
2+
3+ const dec = new TextDecoder ( "utf-8" ) ;
4+
5+ if ( process . argv . length != 3 ) {
6+ console . log ( "Usage: node verify.mjs <wasm-file>" ) ;
7+ process . exit ( 0 ) ;
8+ }
9+
10+ const wasmfile = process . argv [ 2 ] ;
11+ if ( ! fs . existsSync ( wasmfile ) ) {
12+ console . log ( "Error: File not found:" , wasmfile ) ;
13+ process . exit ( 1 ) ;
14+ }
15+
16+ const wasmBuffer = fs . readFileSync ( wasmfile ) ;
17+
18+ async function main ( ) {
19+
20+ let memory = new ArrayBuffer ( 0 ) // will be changed after instantiate
21+
22+ const captured_output = [ ] ;
23+
24+ const imports = {
25+ env : {
26+ __log_utf8 : ( ptr , size ) => {
27+ const str = dec . decode ( new DataView ( memory , ptr , size ) ) ;
28+ captured_output . push ( str ) ;
29+ console . log ( str ) ;
30+ }
31+ }
32+ } ;
33+
34+ const wasmModule = await WebAssembly . instantiate ( wasmBuffer , imports ) ;
35+ memory = wasmModule . instance . exports . memory . buffer ;
36+
37+ const start = wasmModule . instance . exports . start ;
38+ const return_code = start ( ) ;
39+
40+ console . log ( "Return-Code:" , return_code ) ;
41+
42+ if ( return_code !== 0 ) {
43+ console . error ( "Expected return code 0" ) ;
44+ process . exit ( return_code ) ;
45+ }
46+
47+ const expected_output = [
48+ '`r#try` called with ptr 0x1234' ,
49+ 'Dropped' ,
50+ 'Caught something!' ,
51+ ' data : 0x1234' ,
52+ ' exception: "index out of bounds: the len is 1 but the index is 4"' ,
53+ 'This program terminates correctly.' ,
54+ ] ;
55+
56+ assert_equal ( captured_output , expected_output ) ;
57+ }
58+
59+ function assert_equal ( captured_output , expected_output ) {
60+ if ( captured_output . length != expected_output . length ) {
61+ console . error ( "Unexpected number of output lines. Got" , captured_output . length , "but expected" , expected_output . length ) ;
62+ process . exit ( 1 ) ; // exit with error
63+ }
64+
65+ for ( let idx = 0 ; idx < expected_output . length ; ++ idx ) {
66+ if ( captured_output [ idx ] !== expected_output [ idx ] ) {
67+ console . error ( "Unexpected output" ) ;
68+ console . error ( "[got] " , captured_output [ idx ] ) ;
69+ console . error ( "[expected]" , expected_output [ idx ] ) ;
70+ process . exit ( 2 ) ; // exit with error
71+ }
72+ }
73+ }
74+
75+ await main ( ) ;
0 commit comments