Debian Codegraph @

third_party/rust/wast/src/core/memory.rs

raw
1 use crate::core::*;
2 use crate::kw;
3 use crate::parser::{Lookahead1, Parse, Parser, Peek, Result};
4 use crate::token::*;
5
6 /// A defined WebAssembly memory instance inside of a module.
7 #[derive(Debug)]
8 pub struct Memory<'a> {
9 /// Where this `memory` was defined
10 pub span: Span,
11 /// An optional name to refer to this memory by.
12 pub id: Option<Id<'a>>,
13 /// An optional name for this function stored in the custom `name` section.
14 pub name: Option<NameAnnotation<'a>>,
15 /// If present, inline export annotations which indicate names this
16 /// definition should be exported under.
17 pub exports: InlineExport<'a>,
18 /// How this memory is defined in the module.
19 pub kind: MemoryKind<'a>,
20 }
21
22 /// Different syntactical ways a memory can be defined in a module.
23 #[derive(Debug)]
24 pub enum MemoryKind<'a> {
25 /// This memory is actually an inlined import definition.
26 #[allow(missing_docs)]
27 Import {
28 import: InlineImport<'a>,
29 ty: MemoryType,
30 },
31
32 /// A typical memory definition which simply says the limits of the memory
33 Normal(MemoryType),
34
35 /// The data of this memory, starting from 0, explicitly listed
36 Inline {
37 /// Whether or not this will be creating a 64-bit memory
38 is64: bool,
39 /// The inline data specified for this memory
40 data: Vec<DataVal<'a>>,
41 },
42 }
43
44 impl<'a> Parse<'a> for Memory<'a> {
45 fn parse(parser: Parser<'a>) -> Result<Self> {
46 let span = parser.parse::<kw::memory>()?.0;
47 let id = parser.parse()?;
48 let name = parser.parse()?;
49 let exports = parser.parse()?;
50
51 // Afterwards figure out which style this is, either:
52 //
53 // * `(import "a" "b") limits`
54 // * `(data ...)`
55 // * `limits`
56 let mut l = parser.lookahead1();
57 let kind = if let Some(import) = parser.parse()? {
58 MemoryKind::Import {
59 import,
60 ty: parser.parse()?,
61 }
62 } else if l.peek::<LParen>()?
63 || ((parser.peek::<kw::i32>()? || parser.peek::<kw::i64>()?)
64 && parser.peek2::<LParen>()?)
65 {
66 let is64 = if parser.parse::<Option<kw::i32>>()?.is_some() {
67 false
68 } else {
69 parser.parse::<Option<kw::i64>>()?.is_some()
70 };
71 let data = parser.parens(|parser| {
72 parser.parse::<kw::data>()?;
73 let mut data = Vec::new();
74 while !parser.is_empty() {
75 data.push(parser.parse()?);
76 }
77 Ok(data)
78 })?;
79 MemoryKind::Inline { data, is64 }
80 } else if l.peek::<u32>()? || l.peek::<kw::i32>()? || l.peek::<kw::i64>()? {
81 MemoryKind::Normal(parser.parse()?)
82 } else {
83 return Err(l.error());
84 };
85 Ok(Memory {
86 span,
87 id,
88 name,
89 exports,
90 kind,
91 })
92 }
93 }
94
95 /// A `data` directive in a WebAssembly module.
96 #[derive(Debug)]
97 pub struct Data<'a> {
98 /// Where this `data` was defined
99 pub span: Span,
100
101 /// The optional name of this data segment
102 pub id: Option<Id<'a>>,
103
104 /// An optional name for this data stored in the custom `name` section.
105 pub name: Option<NameAnnotation<'a>>,
106
107 /// Whether this data segment is passive or active
108 pub kind: DataKind<'a>,
109
110 /// Bytes for this `Data` segment, viewed as the concatenation of all the
111 /// contained slices.
112 pub data: Vec<DataVal<'a>>,
113 }
114
115 /// Different kinds of data segments, either passive or active.
116 #[derive(Debug)]
117 pub enum DataKind<'a> {
118 /// A passive data segment which isn't associated with a memory and is
119 /// referenced from various instructions.
120 Passive,
121
122 /// An active data segment which is associated and loaded into a particular
123 /// memory on module instantiation.
124 Active {
125 /// The memory that this `Data` will be associated with.
126 memory: Index<'a>,
127
128 /// Initial offset to load this data segment at
129 offset: Expression<'a>,
130 },
131 }
132
133 impl<'a> Parse<'a> for Data<'a> {
134 fn parse(parser: Parser<'a>) -> Result<Self> {
135 let span = parser.parse::<kw::data>()?.0;
136 let id = parser.parse()?;
137 let name = parser.parse()?;
138
139 let kind = if parser.peek::<&[u8]>()? || parser.peek::<RParen>()? {
140 DataKind::Passive
141
142 // ... and otherwise we must be attached to a particular memory as well
143 // as having an initialization offset.
144 } else {
145 let memory = if parser.peek::<u32>()? {
146 // FIXME: this is only here to accomodate
147 // proposals/threads/imports.wast at this current moment in
148 // time, this probably should get removed when the threads
149 // proposal is rebased on the current spec.
150 Index::Num(parser.parse()?, span)
151 } else if parser.peek2::<kw::memory>()? {
152 parser.parens(|p| {
153 p.parse::<kw::memory>()?;
154 p.parse()
155 })?
156 } else {
157 Index::Num(0, span)
158 };
159 let offset = parser.parens(|parser| {
160 if parser.peek::<kw::offset>()? {
161 parser.parse::<kw::offset>()?;
162 parser.parse()
163 } else {
164 // This is all that the spec allows, which is that if
165 // `offset` isn't present then this is "sugar" for a
166 // single-instruction expression.
167 let insn = parser.parse()?;
168 if parser.is_empty() {
169 return Ok(Expression::one(insn));
170 }
171
172 // This is support for what is currently invalid syntax
173 // according to the strict specification but is otherwise
174 // present in the spec test suite:
175 //
176 // (data (i32.add (i32.const 0) (i32.const 0)))
177 //
178 // Technically the spec says this should be:
179 //
180 // (data (offset ...))
181 //
182 // but alas
183 let mut expr: Expression = parser.parse()?;
184 let mut instrs = Vec::from(expr.instrs);
185 instrs.push(insn);
186 expr.instrs = instrs.into();
187 Ok(expr)
188 }
189 })?;
190 DataKind::Active { memory, offset }
191 };
192
193 let mut data = Vec::new();
194 while !parser.is_empty() {
195 data.push(parser.parse()?);
196 }
197 Ok(Data {
198 span,
199 id,
200 name,
201 kind,
202 data,
203 })
204 }
205 }
206
207 /// Differnet ways the value of a data segment can be defined.
208 #[derive(Debug)]
209 #[allow(missing_docs)]
210 pub enum DataVal<'a> {
211 String(&'a [u8]),
212 Integral(Vec<u8>),
213 }
214
215 impl DataVal<'_> {
216 /// Returns the length, in bytes, of the memory used to represent this data
217 /// value.
218 pub fn len(&self) -> usize {
219 match self {
220 DataVal::String(s) => s.len(),
221 DataVal::Integral(s) => s.len(),
222 }
223 }
224
225 /// Pushes the value of this data value onto the provided list of bytes.
226 pub fn push_onto(&self, dst: &mut Vec<u8>) {
227 match self {
228 DataVal::String(s) => dst.extend_from_slice(s),
229 DataVal::Integral(s) => dst.extend_from_slice(s),
230 }
231 }
232 }
233
234 impl<'a> Parse<'a> for DataVal<'a> {
235 fn parse(parser: Parser<'a>) -> Result<Self> {
236 if !parser.peek::<LParen>()? {
237 return Ok(DataVal::String(parser.parse()?));
238 }
239
240 return parser.parens(|p| {
241 let mut result = Vec::new();
242 let mut lookahead = p.lookahead1();
243 let l = &mut lookahead;
244 let r = &mut result;
245 if consume::<kw::i8, i8, _>(p, l, r, |u, v| v.push(u as u8))?
246 || consume::<kw::i16, i16, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))?
247 || consume::<kw::i32, i32, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))?
248 || consume::<kw::i64, i64, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))?
249 || consume::<kw::f32, F32, _>(p, l, r, |u, v| v.extend(&u.bits.to_le_bytes()))?
250 || consume::<kw::f64, F64, _>(p, l, r, |u, v| v.extend(&u.bits.to_le_bytes()))?
251 || consume::<kw::v128, V128Const, _>(p, l, r, |u, v| v.extend(&u.to_le_bytes()))?
252 {
253 Ok(DataVal::Integral(result))
254 } else {
255 Err(lookahead.error())
256 }
257 });
258
259 fn consume<'a, T: Peek + Parse<'a>, U: Parse<'a>, F>(
260 parser: Parser<'a>,
261 lookahead: &mut Lookahead1<'a>,
262 dst: &mut Vec<u8>,
263 push: F,
264 ) -> Result<bool>
265 where
266 F: Fn(U, &mut Vec<u8>),
267 {
268 if !lookahead.peek::<T>()? {
269 return Ok(false);
270 }
271 parser.parse::<T>()?;
272 while !parser.is_empty() {
273 let val = parser.parse::<U>()?;
274 push(val, dst);
275 }
276 Ok(true)
277 }
278 }
279 }