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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
use crate::ast::{self, kw};
use crate::parser::{Parse, Parser, Result};
#[derive(Debug)]
pub struct Memory<'a> {
pub span: ast::Span,
pub id: Option<ast::Id<'a>>,
pub exports: ast::InlineExport<'a>,
pub kind: MemoryKind<'a>,
}
#[derive(Debug)]
pub enum MemoryKind<'a> {
#[allow(missing_docs)]
Import {
import: ast::InlineImport<'a>,
ty: ast::MemoryType,
},
Normal(ast::MemoryType),
Inline {
is_32: bool,
data: Vec<&'a [u8]>,
},
}
impl<'a> Parse<'a> for Memory<'a> {
fn parse(parser: Parser<'a>) -> Result<Self> {
let span = parser.parse::<kw::memory>()?.0;
let id = parser.parse()?;
let exports = parser.parse()?;
let mut l = parser.lookahead1();
let kind = if let Some(import) = parser.parse()? {
MemoryKind::Import {
import,
ty: parser.parse()?,
}
} else if l.peek::<ast::LParen>() || parser.peek2::<ast::LParen>() {
let is_32 = if parser.parse::<Option<kw::i32>>()?.is_some() {
true
} else if parser.parse::<Option<kw::i64>>()?.is_some() {
false
} else {
true
};
let data = parser.parens(|parser| {
parser.parse::<kw::data>()?;
let mut data = Vec::new();
while !parser.is_empty() {
data.push(parser.parse()?);
}
Ok(data)
})?;
MemoryKind::Inline { data, is_32 }
} else if l.peek::<u32>() || l.peek::<kw::i32>() || l.peek::<kw::i64>() {
MemoryKind::Normal(parser.parse()?)
} else {
return Err(l.error());
};
Ok(Memory {
span,
id,
exports,
kind,
})
}
}
#[derive(Debug)]
pub struct Data<'a> {
pub span: ast::Span,
pub id: Option<ast::Id<'a>>,
pub kind: DataKind<'a>,
pub data: Vec<&'a [u8]>,
}
#[derive(Debug)]
pub enum DataKind<'a> {
Passive,
Active {
memory: ast::Index<'a>,
offset: ast::Expression<'a>,
},
}
impl<'a> Parse<'a> for Data<'a> {
fn parse(parser: Parser<'a>) -> Result<Self> {
let span = parser.parse::<kw::data>()?.0;
let id = parser.parse()?;
let kind = if parser.peek::<kw::passive>() {
parser.parse::<kw::passive>()?;
DataKind::Passive
} else if parser.peek::<&[u8]>() {
DataKind::Passive
} else {
let memory = if parser.peek2::<kw::memory>() {
Some(parser.parens(|p| {
p.parse::<kw::memory>()?;
p.parse()
})?)
} else {
parser.parse()?
};
let offset = parser.parens(|parser| {
if parser.peek::<kw::offset>() {
parser.parse::<kw::offset>()?;
}
parser.parse()
})?;
DataKind::Active {
memory: memory.unwrap_or(ast::Index::Num(0, span)),
offset,
}
};
let mut data = Vec::new();
while !parser.is_empty() {
data.push(parser.parse()?);
}
Ok(Data {
span,
id,
kind,
data,
})
}
}