@@ -11,7 +11,7 @@ use tinywasm_types::{
1111
1212use crate :: {
1313 runtime:: { self , DefaultRuntime } ,
14- Error , ModuleInstance , RawWasmValue , Result ,
14+ Error , Extern , Imports , ModuleInstance , RawWasmValue , Result ,
1515} ;
1616
1717// global store id counter
@@ -144,36 +144,42 @@ impl Store {
144144 pub ( crate ) fn add_globals (
145145 & mut self ,
146146 globals : Vec < Global > ,
147- imports : & [ Import ] ,
147+ wasm_imports : & [ Import ] ,
148+ user_imports : & Imports ,
148149 idx : ModuleInstanceAddr ,
149- ) -> Vec < Addr > {
150- let global_count = self . data . globals . len ( ) ;
151- let mut global_addrs = Vec :: with_capacity ( global_count) ;
152-
150+ ) -> Result < Vec < Addr > > {
153151 // TODO: initialize imported globals
154- let imported_globals = imports
152+ let imported_globals = wasm_imports
155153 . iter ( )
156154 . filter_map ( |import| match & import. kind {
157- tinywasm_types:: ImportKind :: Global ( t ) => Some ( t ) ,
155+ tinywasm_types:: ImportKind :: Global ( _ ) => Some ( import ) ,
158156 _ => None ,
159157 } )
160- . collect :: < Vec < _ > > ( ) ;
161-
162- for ( i, global) in imported_globals. into_iter ( ) . enumerate ( ) {
163- log:: debug!( "imported global: {:?}" , global) ;
164- self . data . globals . push ( Rc :: new ( RefCell :: new ( GlobalInstance :: new (
165- global. clone ( ) ,
166- global. ty . default_value ( ) . into ( ) ,
167- idx,
168- ) ) ) ) ;
169- global_addrs. push ( ( i + global_count) as Addr ) ;
170- }
158+ . map ( |import| {
159+ let Some ( global) = user_imports. get ( & import. module , & import. name ) else {
160+ return Err ( Error :: Other ( format ! (
161+ "global import not found for {}::{}" ,
162+ import. module, import. name
163+ ) ) ) ;
164+ } ;
165+ match global {
166+ Extern :: Global ( global) => Ok ( global) ,
167+ _ => Err ( Error :: Other ( format ! (
168+ "expected global import for {}::{}" ,
169+ import. module, import. name
170+ ) ) ) ,
171+ }
172+ } )
173+ . collect :: < Result < Vec < _ > > > ( ) ?;
171174
172175 let global_count = self . data . globals . len ( ) ;
176+ let mut global_addrs = Vec :: with_capacity ( global_count) ;
177+
173178 log:: debug!( "globals: {:?}" , globals) ;
174- for ( i , global ) in globals. into_iter ( ) . enumerate ( ) {
175- // TODO: initialize globals
179+ let globals = globals. into_iter ( ) ;
180+ let iterator = imported_globals . into_iter ( ) . chain ( globals. as_ref ( ) ) ;
176181
182+ for ( i, global) in iterator. enumerate ( ) {
177183 use tinywasm_types:: ConstInstruction :: * ;
178184 let val = match global. init {
179185 F32Const ( f) => RawWasmValue :: from ( f) ,
@@ -197,7 +203,7 @@ impl Store {
197203 global_addrs. push ( ( i + global_count) as Addr ) ;
198204 }
199205 log:: debug!( "global_addrs: {:?}" , global_addrs) ;
200- global_addrs
206+ Ok ( global_addrs)
201207 }
202208
203209 /// Add elements to the store, returning their addresses in the store
0 commit comments