1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
use crate::emit::{Emit, EmitContext, Section};
use crate::parse::IndicesToIds;
use crate::tombstone_arena::{Id, Tombstone, TombstoneArena};
use crate::{ImportId, InitExpr, Module, Result, ValType};
pub type GlobalId = Id<Global>;
#[derive(Debug)]
pub struct Global {
id: GlobalId,
pub ty: ValType,
pub mutable: bool,
pub kind: GlobalKind,
}
impl Tombstone for Global {}
#[derive(Debug)]
pub enum GlobalKind {
Import(ImportId),
Local(InitExpr),
}
impl Global {
pub fn id(&self) -> GlobalId {
self.id
}
}
impl Emit for Global {
fn emit(&self, cx: &mut EmitContext) {
Emit::emit(&self.ty, cx);
cx.encoder.byte(self.mutable as u8);
}
}
#[derive(Debug, Default)]
pub struct ModuleGlobals {
arena: TombstoneArena<Global>,
}
impl ModuleGlobals {
pub fn add_import(&mut self, ty: ValType, mutable: bool, import_id: ImportId) -> GlobalId {
self.arena.alloc_with_id(|id| Global {
id,
ty,
mutable,
kind: GlobalKind::Import(import_id),
})
}
pub fn add_local(&mut self, ty: ValType, mutable: bool, init: InitExpr) -> GlobalId {
self.arena.alloc_with_id(|id| Global {
id,
ty,
mutable,
kind: GlobalKind::Local(init),
})
}
pub fn get(&self, id: GlobalId) -> &Global {
&self.arena[id]
}
pub fn get_mut(&mut self, id: GlobalId) -> &mut Global {
&mut self.arena[id]
}
pub fn delete(&mut self, id: GlobalId) {
self.arena.delete(id);
}
pub fn iter(&self) -> impl Iterator<Item = &Global> {
self.arena.iter().map(|(_, f)| f)
}
}
impl Module {
pub(crate) fn parse_globals(
&mut self,
section: wasmparser::GlobalSectionReader,
ids: &mut IndicesToIds,
) -> Result<()> {
log::debug!("parse global section");
for g in section {
let g = g?;
let id = self.globals.add_local(
ValType::parse(&g.ty.content_type)?,
g.ty.mutable,
InitExpr::eval(&g.init_expr, ids)?,
);
ids.push_global(id);
}
Ok(())
}
}
impl Emit for ModuleGlobals {
fn emit(&self, cx: &mut EmitContext) {
log::debug!("emit global section");
fn get_local(global: &Global) -> Option<(&Global, &InitExpr)> {
match &global.kind {
GlobalKind::Import(_) => None,
GlobalKind::Local(local) => Some((global, local)),
}
}
let globals = self.iter().filter_map(get_local).count();
if globals == 0 {
return;
}
let mut cx = cx.start_section(Section::Global);
cx.encoder.usize(globals);
for (global, local) in self.iter().filter_map(get_local) {
cx.indices.push_global(global.id());
global.emit(&mut cx);
local.emit(&mut cx);
}
}
}