Debian Codegraph @

crates/json-from-wast/src/build.rs

raw
1 use crate::{AnyRef, ContRef, ExnRef, ExternRef, FuncRef, IntString, Opts, WasmFileType};
2 use anyhow::{Context, Result, bail};
3 use std::borrow::Cow;
4 use std::path::Path;
5 use wast::component::WastVal;
6 use wast::core::{
7 AbstractHeapType, EncodeOptions, GenerateDwarf, HeapType, V128Const, V128Pattern, WastArgCore,
8 WastRetCore,
9 };
10 use wast::token::Span;
11 use wast::{
12 QuoteWat, QuoteWatTest, Wast, WastArg, WastDirective, WastExecute, WastInvoke, WastRet,
13 };
14
15 pub fn run<'a>(
16 opts: &Opts,
17 source_filename: &'a str,
18 contents: &'a str,
19 wast: Wast<'a>,
20 ) -> Result<crate::Wast<'a>> {
21 let Wast { directives } = wast;
22
23 let mut builder = JsonBuilder {
24 files: 0,
25 contents,
26 ret: crate::Wast {
27 source_filename: source_filename.into(),
28 commands: Vec::new(),
29 wasms: Vec::new(),
30 },
31 opts,
32 line_end_offsets: Vec::new(),
33 };
34
35 // Build a lookup table from span offset to which line it's in since
36 // `Span::linecol_in` otherwise has to re-count bytes every time which
37 // can be quite slow.
38 let base = contents.as_ptr() as usize;
39 for line in builder.contents.lines() {
40 builder.line_end_offsets.push(line.as_ptr() as usize - base);
41 }
42 builder.line_end_offsets.push(contents.len());
43
44 for directive in directives {
45 let span = directive.span();
46 let command = builder.directive(directive).with_context(|| {
47 format!(
48 "failure processing directive on line {}",
49 builder.lineno(span)
50 )
51 })?;
52 builder.ret.commands.push(command);
53 }
54
55 Ok(builder.ret)
56 }
57
58 struct JsonBuilder<'a, 'b> {
59 files: u32,
60 ret: crate::Wast<'a>,
61 contents: &'a str,
62 line_end_offsets: Vec<usize>,
63 opts: &'b Opts,
64 }
65
66 impl<'a> JsonBuilder<'a, '_> {
67 fn directive(&mut self, directive: WastDirective<'a>) -> Result<crate::Command<'a>> {
68 let line = self.lineno(directive.span());
69 let command = match directive {
70 WastDirective::Module(module) => {
71 let (name, file) = self.emit_file(module, false)?;
72 crate::Command::Module {
73 line,
74 name: name.map(|s| self.module_name(s)),
75 file,
76 }
77 }
78 WastDirective::ModuleDefinition(module) => {
79 let (name, file) = self.emit_file(module, false)?;
80 crate::Command::ModuleDefinition {
81 line,
82 name: name.map(|s| self.module_name(s)),
83 file,
84 }
85 }
86 WastDirective::ModuleInstance {
87 instance, module, ..
88 } => crate::Command::ModuleInstance {
89 line,
90 instance: instance.map(|s| self.module_name(s.name())),
91 module: module.map(|s| self.module_name(s.name())),
92 },
93 WastDirective::AssertMalformed {
94 span: _,
95 module,
96 message,
97 } => {
98 let line = self.lineno(module.span());
99 let (_name, file) = self.emit_file(module, true)?;
100 crate::Command::AssertMalformed {
101 line,
102 text: message.into(),
103 file,
104 }
105 }
106 WastDirective::AssertInvalid {
107 span: _,
108 module,
109 message,
110 } => {
111 let line = self.lineno(module.span());
112 let (_name, file) = self.emit_file(module, false)?;
113 crate::Command::AssertInvalid {
114 line,
115 text: message.into(),
116 file,
117 }
118 }
119 WastDirective::Register {
120 span: _,
121 module,
122 name,
123 } => crate::Command::Register {
124 line,
125 as_: name.into(),
126 name: module.map(|i| self.module_name(i.name())),
127 },
128 WastDirective::Invoke(i) => crate::Command::Action {
129 line,
130 action: self.invoke(i)?,
131 },
132 WastDirective::AssertTrap {
133 span: _,
134 exec: WastExecute::Wat(module),
135 message,
136 } => {
137 let line = self.lineno(module.span());
138 let (_name, file) = self.emit_file(QuoteWat::Wat(module), false)?;
139 crate::Command::AssertUninstantiable {
140 line,
141 text: message.into(),
142 file,
143 }
144 }
145 WastDirective::AssertTrap {
146 span: _,
147 exec,
148 message,
149 } => {
150 let line = self.lineno(exec.span());
151 crate::Command::AssertTrap {
152 line,
153 action: self.action(exec)?,
154 text: message.into(),
155 }
156 }
157 WastDirective::AssertReturn {
158 span: _,
159 exec,
160 results,
161 } => crate::Command::AssertReturn {
162 line: self.lineno(exec.span()),
163 action: self.action(exec)?,
164 expected: self.expected(results)?,
165 },
166 WastDirective::AssertExhaustion {
167 span: _,
168 call,
169 message,
170 } => crate::Command::AssertExhaustion {
171 line,
172 action: self.invoke(call)?,
173 text: message.into(),
174 },
175 WastDirective::AssertUnlinkable {
176 span: _,
177 module,
178 message,
179 } => {
180 let line = self.lineno(module.span());
181 let (_name, file) = self.emit_file(QuoteWat::Wat(module), false)?;
182 crate::Command::AssertUnlinkable {
183 line,
184 text: message.into(),
185 file,
186 }
187 }
188 WastDirective::AssertException { span: _, exec } => crate::Command::AssertException {
189 line,
190 action: self.action(exec)?,
191 },
192 WastDirective::AssertSuspension {
193 span: _,
194 exec,
195 message,
196 } => crate::Command::AssertSuspension {
197 line,
198 text: message.into(),
199 action: self.action(exec)?,
200 },
201 WastDirective::Thread(thread) => crate::Command::Thread {
202 line,
203 name: thread.name.name().into(),
204 shared_module: thread.shared_module.map(|i| i.name().into()),
205 commands: thread
206 .directives
207 .into_iter()
208 .map(|i| self.directive(i))
209 .collect::<Result<_>>()?,
210 },
211 WastDirective::Wait { span: _, thread } => crate::Command::Wait {
212 line,
213 thread: thread.name().into(),
214 },
215 };
216 Ok(command)
217 }
218
219 fn lineno(&self, span: Span) -> u32 {
220 match self.line_end_offsets.binary_search(&span.offset()) {
221 Ok(i) => (i + 1) as u32,
222 Err(i) => i as u32,
223 }
224 }
225
226 fn module_name(&self, s: &str) -> Cow<'a, str> {
227 s.to_string().into()
228 }
229
230 fn emit_file(
231 &mut self,
232 mut module: QuoteWat<'a>,
233 malformed: bool,
234 ) -> Result<(Option<&'a str>, crate::WasmFile<'static>)> {
235 let name = module.name().map(|i| i.name());
236 let (contents, module_type, ext) = match &mut module {
237 QuoteWat::Wat(wat) => {
238 let mut opts = EncodeOptions::new();
239 if self.opts.dwarf {
240 let filename: &str = &self.ret.source_filename;
241 opts.dwarf(filename.as_ref(), self.contents, GenerateDwarf::Lines);
242 }
243 let contents = opts.encode_wat(wat)?;
244 (contents, WasmFileType::Binary, "wasm")
245 }
246 other => match other.to_test()? {
247 QuoteWatTest::Text(s) => (s, WasmFileType::Text, "wat"),
248 QuoteWatTest::Binary(s) => (s, WasmFileType::Binary, "wasm"),
249 },
250 };
251 let filename: &str = &self.ret.source_filename;
252 let stem = Path::new(filename).file_stem().unwrap().to_str().unwrap();
253 let fileno = self.files;
254 self.files += 1;
255 let filename = format!("{stem}.{fileno}.{ext}");
256 let binary_filename = format!("{stem}.{fileno}.wasm");
257 self.ret.wasms.push((filename.clone(), contents));
258 let mut ret = crate::WasmFile {
259 module_type,
260 filename: filename.into(),
261 binary_filename: None,
262 };
263 if module_type == WasmFileType::Text && !malformed {
264 if let Ok(bytes) = module.encode() {
265 self.ret.wasms.push((binary_filename.clone(), bytes));
266 ret.binary_filename = Some(binary_filename.into());
267 }
268 }
269 Ok((name, ret))
270 }
271
272 fn action(&self, exec: WastExecute<'a>) -> Result<crate::Action<'a>> {
273 match exec {
274 WastExecute::Invoke(invoke) => self.invoke(invoke),
275 WastExecute::Wat(_) => {
276 bail!("unsupported `action` found using a module");
277 }
278 WastExecute::Get {
279 span: _,
280 module,
281 global,
282 } => Ok(crate::Action::Get {
283 module: module.map(|m| self.module_name(m.name())),
284 field: global.into(),
285 }),
286 }
287 }
288
289 fn invoke(&self, invoke: WastInvoke<'a>) -> Result<crate::Action<'a>> {
290 let args = self.args(invoke.args)?;
291 Ok(crate::Action::Invoke {
292 module: invoke.module.map(|m| self.module_name(m.name())),
293 field: invoke.name.into(),
294 args,
295 })
296 }
297
298 fn args(&self, args: Vec<WastArg<'a>>) -> Result<Vec<crate::Const<'a>>> {
299 let mut ret = Vec::new();
300 for arg in args {
301 let arg = match arg {
302 WastArg::Core(core) => crate::Const::Core(self.core_arg(core)?),
303 WastArg::Component(arg) => crate::Const::Component(self.component_val(arg)?),
304 _ => bail!("unsupported arg {arg:?}"),
305 };
306 ret.push(arg);
307 }
308 Ok(ret)
309 }
310
311 fn core_arg(&self, arg: WastArgCore<'_>) -> Result<crate::CoreConst> {
312 use WastArgCore::*;
313 Ok(match arg {
314 I32(i) => crate::CoreConst::I32 {
315 value: IntString(i),
316 },
317 I64(i) => crate::CoreConst::I64 {
318 value: IntString(i),
319 },
320 F32(i) => crate::CoreConst::F32 { value: i.into() },
321 F64(i) => crate::CoreConst::F64 { value: i.into() },
322 V128(V128Const::I8x16(vals)) => crate::CoreConst::V128(crate::V128::I8 {
323 value: vals.map(IntString),
324 }),
325 V128(V128Const::I16x8(vals)) => crate::CoreConst::V128(crate::V128::I16 {
326 value: vals.map(IntString),
327 }),
328 V128(V128Const::I32x4(vals)) => crate::CoreConst::V128(crate::V128::I32 {
329 value: vals.map(IntString),
330 }),
331 V128(V128Const::I64x2(vals)) => crate::CoreConst::V128(crate::V128::I64 {
332 value: vals.map(IntString),
333 }),
334 V128(V128Const::F32x4(vals)) => crate::CoreConst::V128(crate::V128::F32 {
335 value: vals.map(|i| i.into()),
336 }),
337 V128(V128Const::F64x2(vals)) => crate::CoreConst::V128(crate::V128::F64 {
338 value: vals.map(|i| i.into()),
339 }),
340 RefNull(ty) => null_heap_ty(ty)?,
341 RefExtern(i) => crate::CoreConst::ExternRef {
342 value: Some(ExternRef::Host(IntString(i))),
343 },
344 RefHost(i) => crate::CoreConst::AnyRef {
345 value: Some(AnyRef::Host(IntString(i))),
346 },
347 })
348 }
349
350 fn component_val(&self, arg: WastVal<'a>) -> Result<crate::ComponentConst<'a>> {
351 Ok(match arg {
352 WastVal::Bool(b) => crate::ComponentConst::Bool(b),
353 WastVal::U8(i) => crate::ComponentConst::U8(IntString(i)),
354 WastVal::S8(i) => crate::ComponentConst::S8(IntString(i)),
355 WastVal::U16(i) => crate::ComponentConst::U16(IntString(i)),
356 WastVal::S16(i) => crate::ComponentConst::S16(IntString(i)),
357 WastVal::U32(i) => crate::ComponentConst::U32(IntString(i)),
358 WastVal::S32(i) => crate::ComponentConst::S32(IntString(i)),
359 WastVal::U64(i) => crate::ComponentConst::U64(IntString(i)),
360 WastVal::S64(i) => crate::ComponentConst::S64(IntString(i)),
361 WastVal::F32(i) => crate::ComponentConst::F32(IntString(i.bits)),
362 WastVal::F64(i) => crate::ComponentConst::F64(IntString(i.bits)),
363 WastVal::Char(c) => crate::ComponentConst::Char(c),
364 WastVal::String(s) => crate::ComponentConst::String(s.into()),
365 WastVal::List(s) => crate::ComponentConst::List(
366 s.into_iter()
367 .map(|i| self.component_val(i))
368 .collect::<Result<_>>()?,
369 ),
370 WastVal::Record(s) => crate::ComponentConst::Record(
371 s.into_iter()
372 .map(|(name, i)| Ok((name.into(), self.component_val(i)?)))
373 .collect::<Result<_>>()?,
374 ),
375 WastVal::Tuple(s) => crate::ComponentConst::Tuple(
376 s.into_iter()
377 .map(|i| self.component_val(i))
378 .collect::<Result<_>>()?,
379 ),
380 WastVal::Variant(case, value) => crate::ComponentConst::Variant {
381 case: case.into(),
382 payload: value
383 .map(|i| self.component_val(*i))
384 .transpose()?
385 .map(Box::new),
386 },
387 WastVal::Enum(case) => crate::ComponentConst::Enum(case.into()),
388 WastVal::Option(val) => crate::ComponentConst::Option(
389 val.map(|i| self.component_val(*i))
390 .transpose()?
391 .map(Box::new),
392 ),
393 WastVal::Result(val) => crate::ComponentConst::Result(match val {
394 Ok(val) => Ok(val
395 .map(|i| self.component_val(*i))
396 .transpose()?
397 .map(Box::new)),
398 Err(val) => Err(val
399 .map(|i| self.component_val(*i))
400 .transpose()?
401 .map(Box::new)),
402 }),
403 WastVal::Flags(vals) => {
404 crate::ComponentConst::Flags(vals.into_iter().map(|v| v.into()).collect())
405 }
406 })
407 }
408
409 fn expected(&self, rets: Vec<WastRet<'a>>) -> Result<Vec<crate::Const<'a>>> {
410 let mut ret = Vec::new();
411 for r in rets {
412 let r = match r {
413 WastRet::Core(core) => crate::Const::Core(self.core_ret(core)?),
414 WastRet::Component(val) => crate::Const::Component(self.component_val(val)?),
415 _ => bail!("encountered unsupported Wast result: {r:?}"),
416 };
417 ret.push(r);
418 }
419 Ok(ret)
420 }
421
422 fn core_ret(&self, ret: WastRetCore<'a>) -> Result<crate::CoreConst> {
423 use wast::core::WastRetCore::*;
424
425 Ok(match ret {
426 I32(i) => crate::CoreConst::I32 {
427 value: IntString(i),
428 },
429 I64(i) => crate::CoreConst::I64 {
430 value: IntString(i),
431 },
432 F32(i) => crate::CoreConst::F32 { value: i.into() },
433 F64(i) => crate::CoreConst::F64 { value: i.into() },
434 V128(V128Pattern::I8x16(vals)) => crate::CoreConst::V128(crate::V128::I8 {
435 value: vals.map(IntString),
436 }),
437 V128(V128Pattern::I16x8(vals)) => crate::CoreConst::V128(crate::V128::I16 {
438 value: vals.map(IntString),
439 }),
440 V128(V128Pattern::I32x4(vals)) => crate::CoreConst::V128(crate::V128::I32 {
441 value: vals.map(IntString),
442 }),
443 V128(V128Pattern::I64x2(vals)) => crate::CoreConst::V128(crate::V128::I64 {
444 value: vals.map(IntString),
445 }),
446 V128(V128Pattern::F32x4(vals)) => crate::CoreConst::V128(crate::V128::F32 {
447 value: vals.map(|i| i.into()),
448 }),
449 V128(V128Pattern::F64x2(vals)) => crate::CoreConst::V128(crate::V128::F64 {
450 value: vals.map(|i| i.into()),
451 }),
452
453 RefNull(Some(ty)) => null_heap_ty(ty)?,
454 RefNull(None) => crate::CoreConst::RefNull,
455 RefExtern(None) => crate::CoreConst::ExternRef { value: None },
456 RefExtern(Some(i)) => crate::CoreConst::ExternRef {
457 value: Some(ExternRef::Host(IntString(i))),
458 },
459 RefHost(i) => crate::CoreConst::AnyRef {
460 value: Some(AnyRef::Host(IntString(i))),
461 },
462 RefFunc(None) => crate::CoreConst::FuncRef { value: None },
463 RefFunc(Some(i)) => crate::CoreConst::FuncRef {
464 value: Some(FuncRef::Index(i.into())),
465 },
466 RefAny => crate::CoreConst::AnyRef { value: None },
467 RefEq => crate::CoreConst::EqRef,
468 RefArray => crate::CoreConst::ArrayRef,
469 RefStruct => crate::CoreConst::StructRef,
470 RefI31 => crate::CoreConst::I31Ref,
471 RefI31Shared => crate::CoreConst::I31RefShared,
472 Either(either) => crate::CoreConst::Either {
473 values: either
474 .into_iter()
475 .map(|i| self.core_ret(i))
476 .collect::<Result<_>>()?,
477 },
478 })
479 }
480 }
481
482 fn null_heap_ty(ty: HeapType<'_>) -> Result<crate::CoreConst> {
483 Ok(match ty {
484 HeapType::Abstract { shared, ty } => {
485 use AbstractHeapType::*;
486 if shared {
487 bail!("shared abstract types are not supported in `ref.null`")
488 }
489 match ty {
490 Func => crate::CoreConst::FuncRef {
491 value: Some(FuncRef::Null),
492 },
493 Extern => crate::CoreConst::ExternRef {
494 value: Some(ExternRef::Null),
495 },
496 Any => crate::CoreConst::AnyRef {
497 value: Some(AnyRef::Null),
498 },
499 None => crate::CoreConst::NullRef,
500 NoFunc => crate::CoreConst::NullFuncRef,
501 NoExtern => crate::CoreConst::NullExternRef,
502 Exn => crate::CoreConst::ExnRef {
503 value: Some(ExnRef::Null),
504 },
505 Eq => crate::CoreConst::EqRef,
506 Struct => crate::CoreConst::StructRef,
507 Array => crate::CoreConst::ArrayRef,
508 I31 => crate::CoreConst::I31Ref,
509 NoExn => crate::CoreConst::NullExnRef,
510 Cont => crate::CoreConst::ContRef {
511 value: Some(ContRef::Null),
512 },
513 NoCont => crate::CoreConst::NullContRef,
514 }
515 }
516 _ => bail!("unsupported heap type found in `ref.null`"),
517 })
518 }