wit_bindgen_test/
lib.rs

1use anyhow::{anyhow, bail, Context, Result};
2use clap::Parser;
3use rayon::prelude::*;
4use std::borrow::Cow;
5use std::collections::{HashMap, HashSet};
6use std::fmt;
7use std::fs;
8use std::io::Write;
9use std::path::{Path, PathBuf};
10use std::process::{Command, Stdio};
11use std::sync::Arc;
12use wasm_encoder::{Encode, Section};
13use wit_component::{ComponentEncoder, StringEncoding};
14
15mod c;
16mod config;
17mod cpp;
18mod csharp;
19mod custom;
20mod moonbit;
21mod runner;
22mod rust;
23mod wat;
24
25/// Tool to run tests that exercise the `wit-bindgen` bindings generator.
26///
27/// This tool is used to (a) generate bindings for a target language, (b)
28/// compile the bindings and source code to a wasm component, (c) compose a
29/// "runner" and a "test" component together, and (d) execute this component to
30/// ensure that it passes. This process is guided by filesystem structure which
31/// must adhere to some conventions.
32///
33/// * Tests are located in any directory that contains a `test.wit` description
34///   of the WIT being tested. The `<TEST>` argument to this command is walked
35///   recursively to find `test.wit` files.
36///
37/// * The `test.wit` file must have a `runner` world and a `test` world. The
38///   "runner" should import interfaces that are exported by "test".
39///
40/// * Adjacent to `test.wit` should be a number of `runner*.*` files. There is
41///   one runner per source language, for example `runner.rs` and `runner.c`.
42///   These are source files for the `runner` world. Source files can start with
43///   `//@ ...` comments to deserialize into `config::RuntimeTestConfig`,
44///   currently that supports:
45///
46///   ```text
47///   //@ args = ['--arguments', 'to', '--the', 'bindings', '--generator']
48///   ```
49///
50///   or
51///
52///   ```text
53///   //@ args = '--arguments to --the bindings --generator'
54///   ```
55///
56/// * Adjacent to `test.wit` should also be a number of `test*.*` files. Like
57///   runners there is one per source language. Note that you can have multiple
58///   implementations of tests in the same language too, for example
59///   `test-foo.rs` and `test-bar.rs`. All tests must export the same `test`
60///   world from `test.wit`, however.
61///
62/// This tool will discover `test.wit` files, discover runners/tests, and then
63/// compile everything and run the combinatorial matrix of runners against
64/// tests. It's expected that each `runner.*` and `test.*` perform the same
65/// functionality and only differ in source language.
66#[derive(Default, Debug, Clone, Parser)]
67pub struct Opts {
68    /// Directory containing the test being run or all tests being run.
69    test: Vec<PathBuf>,
70
71    /// Path to where binary artifacts for tests are stored.
72    #[clap(long, value_name = "PATH")]
73    artifacts: PathBuf,
74
75    /// Optional filter to use on test names to only run some tests.
76    ///
77    /// This is a regular expression defined by the `regex` Rust crate.
78    #[clap(short, long, value_name = "REGEX")]
79    filter: Option<regex::Regex>,
80
81    /// The executable or script used to execute a fully composed test case.
82    #[clap(long, default_value = "wasmtime")]
83    runner: std::ffi::OsString,
84
85    #[clap(flatten)]
86    rust: rust::RustOpts,
87
88    #[clap(flatten)]
89    c: c::COpts,
90
91    #[clap(flatten)]
92    custom: custom::CustomOpts,
93
94    /// Whether or not the calling process's stderr is inherited into child
95    /// processes.
96    ///
97    /// This helps preserving color in compiler error messages but can also
98    /// jumble up output if there are multiple errors.
99    #[clap(short, long)]
100    inherit_stderr: bool,
101
102    /// Configuration of which languages are tested.
103    ///
104    /// Passing `--lang rust` will only test Rust for example.
105    #[clap(short, long, required = true, value_delimiter = ',')]
106    languages: Vec<String>,
107}
108
109impl Opts {
110    pub fn run(&self, wit_bindgen: &Path) -> Result<()> {
111        Runner {
112            opts: self,
113            rust_state: None,
114            wit_bindgen,
115            test_runner: runner::TestRunner::new(&self.runner)?,
116        }
117        .run()
118    }
119}
120
121/// Helper structure representing a discovered `test.wit` file.
122struct Test {
123    /// The name of this test, unique amongst all tests.
124    ///
125    /// Inferred from the directory name.
126    name: String,
127
128    /// Path to the root of this test.
129    path: PathBuf,
130
131    /// Configuration for this test, specified in the WIT file.
132    config: config::WitConfig,
133
134    kind: TestKind,
135}
136
137enum TestKind {
138    Runtime(Vec<Component>),
139    Codegen(PathBuf),
140}
141
142/// Helper structure representing a single component found in a test directory.
143struct Component {
144    /// The name of this component, inferred from the file stem.
145    ///
146    /// May be shared across different languages.
147    name: String,
148
149    /// The path to the source file for this component.
150    path: PathBuf,
151
152    /// Whether or not this component is a "runner" or a "test"
153    kind: Kind,
154
155    /// The detected language for this component.
156    language: Language,
157
158    /// The WIT world that's being used with this component, loaded from
159    /// `test.wit`.
160    bindgen: Bindgen,
161
162    /// The contents of the test file itself.
163    contents: String,
164
165    /// The contents of the test file itself.
166    lang_config: Option<HashMap<String, toml::Value>>,
167}
168
169#[derive(Clone)]
170struct Bindgen {
171    /// The arguments to the bindings generator that this component will be
172    /// using.
173    args: Vec<String>,
174    /// The path to the `*.wit` file or files that are having bindings
175    /// generated.
176    wit_path: PathBuf,
177    /// The name of the world within `wit_path` that's having bindings generated
178    /// for it.
179    world: String,
180    /// Configuration found in `wit_path`
181    wit_config: config::WitConfig,
182}
183
184#[derive(Debug, PartialEq, Copy, Clone)]
185enum Kind {
186    Runner,
187    Test,
188}
189
190#[derive(Clone, Debug, PartialEq, Eq, Hash)]
191enum Language {
192    Rust,
193    C,
194    Cpp,
195    Wat,
196    Csharp,
197    MoonBit,
198    Custom(custom::Language),
199}
200
201/// Helper structure to package up arguments when sent to language-specific
202/// compilation backends for `LanguageMethods::compile`
203struct Compile<'a> {
204    component: &'a Component,
205    bindings_dir: &'a Path,
206    artifacts_dir: &'a Path,
207    output: &'a Path,
208}
209
210/// Helper structure to package up arguments when sent to language-specific
211/// compilation backends for `LanguageMethods::verify`
212struct Verify<'a> {
213    wit_test: &'a Path,
214    bindings_dir: &'a Path,
215    artifacts_dir: &'a Path,
216    args: &'a [String],
217    world: &'a str,
218}
219
220/// Helper structure to package up runtime state associated with executing tests.
221struct Runner<'a> {
222    opts: &'a Opts,
223    rust_state: Option<rust::State>,
224    wit_bindgen: &'a Path,
225    test_runner: runner::TestRunner,
226}
227
228impl Runner<'_> {
229    /// Executes all tests.
230    fn run(&mut self) -> Result<()> {
231        // First step, discover all tests in the specified test directory.
232        let mut tests = HashMap::new();
233        for test in self.opts.test.iter() {
234            self.discover_tests(&mut tests, test)
235                .with_context(|| format!("failed to discover tests in {test:?}"))?;
236        }
237        if tests.is_empty() {
238            bail!(
239                "no `test.wit` files found were found in {:?}",
240                self.opts.test,
241            );
242        }
243
244        self.prepare_languages(&tests)?;
245        self.run_codegen_tests(&tests)?;
246        self.run_runtime_tests(&tests)?;
247
248        println!("PASSED");
249
250        Ok(())
251    }
252
253    /// Walks over `dir`, recursively, inserting located cases into `tests`.
254    fn discover_tests(&self, tests: &mut HashMap<String, Test>, path: &Path) -> Result<()> {
255        if path.is_file() {
256            if path.extension().and_then(|s| s.to_str()) == Some("wit") {
257                let config =
258                    fs::read_to_string(path).with_context(|| format!("failed to read {path:?}"))?;
259                let config = config::parse_test_config::<config::WitConfig>(&config, "//@")
260                    .with_context(|| format!("failed to parse test config from {path:?}"))?;
261                return self.insert_test(&path, config, TestKind::Codegen(path.to_owned()), tests);
262            }
263
264            return Ok(());
265        }
266
267        let runtime_candidate = path.join("test.wit");
268        if runtime_candidate.is_file() {
269            let (config, components) = self
270                .load_runtime_test(&runtime_candidate, path)
271                .with_context(|| format!("failed to load test in {path:?}"))?;
272            return self.insert_test(path, config, TestKind::Runtime(components), tests);
273        }
274
275        let codegen_candidate = path.join("wit");
276        if codegen_candidate.is_dir() {
277            return self.insert_test(
278                path,
279                Default::default(),
280                TestKind::Codegen(codegen_candidate),
281                tests,
282            );
283        }
284
285        for entry in path.read_dir().context("failed to read test directory")? {
286            let entry = entry.context("failed to read test directory entry")?;
287            let path = entry.path();
288
289            self.discover_tests(tests, &path)?;
290        }
291
292        Ok(())
293    }
294
295    fn insert_test(
296        &self,
297        path: &Path,
298        config: config::WitConfig,
299        kind: TestKind,
300        tests: &mut HashMap<String, Test>,
301    ) -> Result<()> {
302        let test_name = path
303            .file_name()
304            .and_then(|s| s.to_str())
305            .context("non-utf-8 filename")?;
306        let prev = tests.insert(
307            test_name.to_string(),
308            Test {
309                name: test_name.to_string(),
310                path: path.to_path_buf(),
311                config,
312                kind,
313            },
314        );
315        if prev.is_some() {
316            bail!("duplicate test name `{test_name}` found");
317        }
318        Ok(())
319    }
320
321    /// Loads a test from `dir` using the `wit` file in the directory specified.
322    ///
323    /// Returns a list of components that were found within this directory.
324    fn load_runtime_test(
325        &self,
326        wit: &Path,
327        dir: &Path,
328    ) -> Result<(config::WitConfig, Vec<Component>)> {
329        let mut resolve = wit_parser::Resolve::default();
330
331        let wit_path = if dir.join("deps").exists() { dir } else { wit };
332        let (pkg, _files) = resolve.push_path(wit_path).context(format!(
333            "failed to load `test.wit` in test directory: {:?}",
334            &wit
335        ))?;
336        let resolve = Arc::new(resolve);
337
338        let wit_contents = std::fs::read_to_string(wit)?;
339        let wit_config: config::WitConfig = config::parse_test_config(&wit_contents, "//@")
340            .context("failed to parse WIT test config")?;
341
342        let mut worlds = Vec::new();
343
344        let mut push_world = |kind: Kind, name: &str| -> Result<()> {
345            let world = resolve.select_world(&[pkg], Some(name)).with_context(|| {
346                format!("failed to find expected `{name}` world to generate bindings")
347            })?;
348            worlds.push((world, kind));
349            Ok(())
350        };
351        push_world(Kind::Runner, wit_config.runner_world())?;
352        for world in wit_config.dependency_worlds() {
353            push_world(Kind::Test, &world)?;
354        }
355
356        let mut components = Vec::new();
357        let mut any_runner = false;
358        let mut any_test = false;
359
360        for entry in dir.read_dir().context("failed to read test directory")? {
361            let entry = entry.context("failed to read test directory entry")?;
362            let path = entry.path();
363
364            let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
365                continue;
366            };
367            if name == "test.wit" {
368                continue;
369            }
370
371            let Some((world, kind)) = worlds
372                .iter()
373                .find(|(world, _kind)| name.starts_with(&resolve.worlds[*world].name))
374            else {
375                log::debug!("skipping file {name:?}");
376                continue;
377            };
378            match kind {
379                Kind::Runner => any_runner = true,
380                Kind::Test => any_test = true,
381            }
382            let bindgen = Bindgen {
383                args: Vec::new(),
384                wit_config: wit_config.clone(),
385                world: resolve.worlds[*world].name.clone(),
386                wit_path: wit_path.to_path_buf(),
387            };
388            let component = self
389                .parse_component(&path, *kind, bindgen)
390                .with_context(|| format!("failed to parse component source file {path:?}"))?;
391            components.push(component);
392        }
393
394        if !any_runner {
395            bail!("no runner files found in test directory");
396        }
397        if !any_test {
398            bail!("no test files found in test directory");
399        }
400
401        Ok((wit_config, components))
402    }
403
404    /// Parsers the component located at `path` and creates all information
405    /// necessary for a `Component` return value.
406    fn parse_component(&self, path: &Path, kind: Kind, mut bindgen: Bindgen) -> Result<Component> {
407        let extension = path
408            .extension()
409            .and_then(|s| s.to_str())
410            .context("non-utf-8 path extension")?;
411
412        let language = match extension {
413            "rs" => Language::Rust,
414            "c" => Language::C,
415            "cpp" => Language::Cpp,
416            "wat" => Language::Wat,
417            "cs" => Language::Csharp,
418            "mbt" => Language::MoonBit,
419            other => Language::Custom(custom::Language::lookup(self, other)?),
420        };
421
422        let contents = fs::read_to_string(&path)?;
423        let config = match language.obj().comment_prefix_for_test_config() {
424            Some(comment) => {
425                config::parse_test_config::<config::RuntimeTestConfig>(&contents, comment)?
426            }
427            None => Default::default(),
428        };
429        assert!(bindgen.args.is_empty());
430        bindgen.args = config.args.into();
431
432        Ok(Component {
433            name: path.file_stem().unwrap().to_str().unwrap().to_string(),
434            path: path.to_path_buf(),
435            language,
436            bindgen,
437            kind,
438            contents,
439            lang_config: config.lang,
440        })
441    }
442
443    /// Prepares all languages in use in `test` as part of a one-time
444    /// initialization step.
445    fn prepare_languages(&mut self, tests: &HashMap<String, Test>) -> Result<()> {
446        let all_languages = self.all_languages();
447
448        let mut prepared = HashSet::new();
449        let mut prepare = |lang: &Language| -> Result<()> {
450            if !self.include_language(lang) || !prepared.insert(lang.clone()) {
451                return Ok(());
452            }
453            lang.obj()
454                .prepare(self)
455                .with_context(|| format!("failed to prepare language {lang}"))
456        };
457
458        for test in tests.values() {
459            match &test.kind {
460                TestKind::Runtime(c) => {
461                    for component in c {
462                        prepare(&component.language)?
463                    }
464                }
465                TestKind::Codegen(_) => {
466                    for lang in all_languages.iter() {
467                        prepare(lang)?;
468                    }
469                }
470            }
471        }
472
473        Ok(())
474    }
475
476    fn all_languages(&self) -> Vec<Language> {
477        let mut languages = Language::ALL.to_vec();
478        for (ext, _) in self.opts.custom.custom.iter() {
479            languages.push(Language::Custom(
480                custom::Language::lookup(self, ext).unwrap(),
481            ));
482        }
483        languages
484    }
485
486    /// Executes all tests that are `TestKind::Codegen`.
487    fn run_codegen_tests(&mut self, tests: &HashMap<String, Test>) -> Result<()> {
488        let mut codegen_tests = Vec::new();
489        let languages = self.all_languages();
490        for (name, config, test) in tests.iter().filter_map(|(name, t)| match &t.kind {
491            TestKind::Runtime(_) => None,
492            TestKind::Codegen(p) => Some((name, &t.config, p)),
493        }) {
494            if let Some(filter) = &self.opts.filter {
495                if !filter.is_match(name) {
496                    continue;
497                }
498            }
499            for language in languages.iter() {
500                // If the CLI arguments filter out this language, then discard
501                // the test case.
502                if !self.include_language(&language) {
503                    continue;
504                }
505
506                let mut args = Vec::new();
507                for arg in language.obj().default_bindgen_args_for_codegen() {
508                    args.push(arg.to_string());
509                }
510
511                codegen_tests.push((
512                    language.clone(),
513                    test,
514                    name.to_string(),
515                    args.clone(),
516                    config.clone(),
517                ));
518
519                for (args_kind, new_args) in language.obj().codegen_test_variants() {
520                    let mut args = args.clone();
521                    for arg in new_args.iter() {
522                        args.push(arg.to_string());
523                    }
524                    codegen_tests.push((
525                        language.clone(),
526                        test,
527                        format!("{name}-{args_kind}"),
528                        args,
529                        config.clone(),
530                    ));
531                }
532            }
533        }
534
535        if codegen_tests.is_empty() {
536            return Ok(());
537        }
538
539        println!("Running {} codegen tests:", codegen_tests.len());
540
541        let results = codegen_tests
542            .par_iter()
543            .map(|(language, test, args_kind, args, config)| {
544                let should_fail = language.obj().should_fail_verify(args_kind, config, args);
545                let result = self
546                    .codegen_test(language, test, &args_kind, args, config)
547                    .with_context(|| {
548                        format!("failed to codegen test for `{language}` over {test:?}")
549                    });
550                self.update_status(&result, should_fail);
551                (result, should_fail, language, test, args_kind)
552            })
553            .collect::<Vec<_>>();
554
555        println!("");
556
557        self.render_errors(results.into_iter().map(
558            |(result, should_fail, language, test, args_kind)| {
559                StepResult::new(test.to_str().unwrap(), result)
560                    .should_fail(should_fail)
561                    .metadata("language", language)
562                    .metadata("variant", args_kind)
563            },
564        ));
565
566        Ok(())
567    }
568
569    /// Runs a single codegen test.
570    ///
571    /// This will generate bindings for `test` in the `language` specified. The
572    /// test name is mangled by `args_kind` and the `args` are arguments to pass
573    /// to the bindings generator.
574    fn codegen_test(
575        &self,
576        language: &Language,
577        test: &Path,
578        args_kind: &str,
579        args: &[String],
580        config: &config::WitConfig,
581    ) -> Result<()> {
582        let mut resolve = wit_parser::Resolve::default();
583        let (pkg, _) = resolve.push_path(test).context("failed to load WIT")?;
584        let world = resolve
585            .select_world(&[pkg], None)
586            .or_else(|err| {
587                resolve
588                    .select_world(&[pkg], Some("imports"))
589                    .map_err(|_| err)
590            })
591            .context("failed to select a world for bindings generation")?;
592        let world = resolve.worlds[world].name.clone();
593
594        let artifacts_dir = std::env::current_dir()?
595            .join(&self.opts.artifacts)
596            .join("codegen")
597            .join(language.to_string())
598            .join(args_kind);
599        let _ = fs::remove_dir_all(&artifacts_dir);
600        let bindings_dir = artifacts_dir.join("bindings");
601        let bindgen = Bindgen {
602            args: args.to_vec(),
603            wit_path: test.to_path_buf(),
604            world: world.clone(),
605            wit_config: config.clone(),
606        };
607        language
608            .obj()
609            .generate_bindings(self, &bindgen, &bindings_dir)
610            .context("failed to generate bindings")?;
611
612        language
613            .obj()
614            .verify(
615                self,
616                &Verify {
617                    world: &world,
618                    artifacts_dir: &artifacts_dir,
619                    bindings_dir: &bindings_dir,
620                    wit_test: test,
621                    args: &bindgen.args,
622                },
623            )
624            .context("failed to verify generated bindings")?;
625
626        Ok(())
627    }
628
629    /// Execute all `TestKind::Runtime` tests
630    fn run_runtime_tests(&mut self, tests: &HashMap<String, Test>) -> Result<()> {
631        let components = tests
632            .values()
633            .filter(|t| match &self.opts.filter {
634                Some(filter) => filter.is_match(&t.name),
635                None => true,
636            })
637            .filter_map(|t| match &t.kind {
638                TestKind::Runtime(c) => Some(c.iter().map(move |c| (t, c))),
639                TestKind::Codegen(_) => None,
640            })
641            .flat_map(|i| i)
642            // Discard components that are unrelated to the languages being
643            // tested.
644            .filter(|(_test, component)| self.include_language(&component.language))
645            .collect::<Vec<_>>();
646
647        println!("Compiling {} components:", components.len());
648
649        // In parallel compile all sources to their binary component
650        // form.
651        let compile_results = components
652            .par_iter()
653            .map(|(test, component)| {
654                let path = self
655                    .compile_component(test, component)
656                    .with_context(|| format!("failed to compile component {:?}", component.path));
657                self.update_status(&path, false);
658                (test, component, path)
659            })
660            .collect::<Vec<_>>();
661        println!("");
662
663        let mut compilations = Vec::new();
664        self.render_errors(
665            compile_results
666                .into_iter()
667                .map(|(test, component, result)| match result {
668                    Ok(path) => {
669                        compilations.push((test, component, path));
670                        StepResult::new("", Ok(()))
671                    }
672                    Err(e) => StepResult::new(&test.name, Err(e))
673                        .metadata("component", &component.name)
674                        .metadata("path", component.path.display()),
675                }),
676        );
677
678        // Next, massage the data a bit. Create a map of all tests to where
679        // their components are located. Then perform a product of runners/tests
680        // to generate a list of test cases. Finally actually execute the testj
681        // cases.
682        let mut compiled_components = HashMap::new();
683        for (test, component, path) in compilations {
684            let list = compiled_components.entry(&test.name).or_insert(Vec::new());
685            list.push((*component, path));
686        }
687
688        let mut to_run = Vec::new();
689        for (test, components) in compiled_components.iter() {
690            for a in components.iter().filter(|(c, _)| c.kind == Kind::Runner) {
691                self.push_tests(&tests[test.as_str()], components, a, &mut to_run)
692                    .with_context(|| format!("failed to make test for `{test}`"))?;
693            }
694        }
695
696        println!("Running {} runtime tests:", to_run.len());
697
698        let results = to_run
699            .par_iter()
700            .map(|(case_name, (runner, runner_path), test_components)| {
701                let case = &tests[*case_name];
702                let result = self
703                    .runtime_test(case, runner, runner_path, test_components)
704                    .with_context(|| format!("failed to run `{}`", case.name));
705                self.update_status(&result, false);
706                (result, case_name, runner, runner_path, test_components)
707            })
708            .collect::<Vec<_>>();
709
710        println!("");
711
712        self.render_errors(results.into_iter().map(
713            |(result, case_name, runner, runner_path, test_components)| {
714                let mut result = StepResult::new(case_name, result)
715                    .metadata("runner", runner.path.display())
716                    .metadata("compiled runner", runner_path.display());
717                for (test, path) in test_components {
718                    result = result
719                        .metadata("test", test.path.display())
720                        .metadata("compiled test", path.display());
721                }
722                result
723            },
724        ));
725
726        Ok(())
727    }
728
729    /// For the `test` provided, and the selected `runner`, determines all
730    /// permutations of tests from `components` and pushes them on to `to_run`.
731    fn push_tests<'a>(
732        &self,
733        test: &'a Test,
734        components: &'a [(&'a Component, PathBuf)],
735        runner: &'a (&'a Component, PathBuf),
736        to_run: &mut Vec<(
737            &'a str,
738            (&'a Component, &'a Path),
739            Vec<(&'a Component, &'a Path)>,
740        )>,
741    ) -> Result<()> {
742        /// Recursive function which walks over `worlds`, the list of worlds
743        /// that `test` expects, one by one. For each world it finds a matching
744        /// component in `components` adn then recurses for the next item in the
745        /// `worlds` list.
746        ///
747        /// Once `worlds` is empty the `test` list, a temporary vector, is
748        /// cloned and pushed into `commit`.
749        fn push<'a>(
750            worlds: &[String],
751            components: &'a [(&'a Component, PathBuf)],
752            test: &mut Vec<(&'a Component, &'a Path)>,
753            commit: &mut dyn FnMut(Vec<(&'a Component, &'a Path)>),
754        ) -> Result<()> {
755            match worlds.split_first() {
756                Some((world, rest)) => {
757                    let mut any = false;
758                    for (component, path) in components {
759                        if component.bindgen.world == *world {
760                            any = true;
761                            test.push((component, path));
762                            push(rest, components, test, commit)?;
763                            test.pop();
764                        }
765                    }
766                    if !any {
767                        bail!("no components found for `{world}`");
768                    }
769                }
770
771                // No more `worlds`? Then `test` is our set of test components.
772                None => commit(test.clone()),
773            }
774            Ok(())
775        }
776
777        push(
778            &test.config.dependency_worlds(),
779            components,
780            &mut Vec::new(),
781            &mut |test_components| {
782                to_run.push((&test.name, (runner.0, &runner.1), test_components));
783            },
784        )
785    }
786
787    /// Compiles the `component` specified to wasm for the `test` given.
788    ///
789    /// This will generate bindings for `component` and then perform
790    /// language-specific compilation to convert the files into a component.
791    fn compile_component(&self, test: &Test, component: &Component) -> Result<PathBuf> {
792        let root_dir = std::env::current_dir()?
793            .join(&self.opts.artifacts)
794            .join(&test.name);
795        let artifacts_dir = root_dir.join(format!("{}-{}", component.name, component.language));
796        let _ = fs::remove_dir_all(&artifacts_dir);
797        let bindings_dir = artifacts_dir.join("bindings");
798        let output = root_dir.join(format!("{}-{}.wasm", component.name, component.language));
799        component
800            .language
801            .obj()
802            .generate_bindings(self, &component.bindgen, &bindings_dir)?;
803        let result = Compile {
804            component,
805            bindings_dir: &bindings_dir,
806            artifacts_dir: &artifacts_dir,
807            output: &output,
808        };
809        component.language.obj().compile(self, &result)?;
810
811        // Double-check the output is indeed a component and it's indeed valid.
812        let wasm = fs::read(&output)
813            .with_context(|| format!("failed to read output wasm file {output:?}"))?;
814        if !wasmparser::Parser::is_component(&wasm) {
815            bail!("output file {output:?} is not a component");
816        }
817        wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
818            .validate_all(&wasm)
819            .with_context(|| format!("compiler produced invalid wasm file {output:?}"))?;
820
821        Ok(output)
822    }
823
824    /// Executes a single test case.
825    ///
826    /// Composes `runner_wasm` with the components in `test_components` and then
827    /// executes it with the runner specified in CLI flags.
828    fn runtime_test(
829        &self,
830        case: &Test,
831        runner: &Component,
832        runner_wasm: &Path,
833        test_components: &[(&Component, &Path)],
834    ) -> Result<()> {
835        // If possible use `wasm-compose` to compose the test together. This is
836        // only possible when customization isn't used though. This is also only
837        // done for async tests at this time to ensure that there's a version of
838        // composition that's done which is at the same version as wasmparser
839        // and friends.
840        let composed = if case.config.wac.is_none() && test_components.len() == 1 {
841            self.compose_wasm_with_wasm_compose(runner_wasm, test_components)?
842        } else {
843            self.compose_wasm_with_wac(case, runner, runner_wasm, test_components)?
844        };
845
846        let dst = runner_wasm.parent().unwrap();
847        let mut filename = format!(
848            "composed-{}",
849            runner.path.file_name().unwrap().to_str().unwrap(),
850        );
851        for (test, _) in test_components {
852            filename.push_str("-");
853            filename.push_str(test.path.file_name().unwrap().to_str().unwrap());
854        }
855        filename.push_str(".wasm");
856        let composed_wasm = dst.join(filename);
857        write_if_different(&composed_wasm, &composed)?;
858
859        self.run_command(self.test_runner.command().arg(&composed_wasm))?;
860        Ok(())
861    }
862
863    fn compose_wasm_with_wasm_compose(
864        &self,
865        runner_wasm: &Path,
866        test_components: &[(&Component, &Path)],
867    ) -> Result<Vec<u8>> {
868        assert!(test_components.len() == 1);
869        let test_wasm = test_components[0].1;
870        let mut config = wasm_compose::config::Config::default();
871        config.definitions = vec![test_wasm.to_path_buf()];
872        wasm_compose::composer::ComponentComposer::new(runner_wasm, &config)
873            .compose()
874            .with_context(|| format!("failed to compose {runner_wasm:?} with {test_wasm:?}"))
875    }
876
877    fn compose_wasm_with_wac(
878        &self,
879        case: &Test,
880        runner: &Component,
881        runner_wasm: &Path,
882        test_components: &[(&Component, &Path)],
883    ) -> Result<Vec<u8>> {
884        let document = match &case.config.wac {
885            Some(path) => {
886                let wac_config = case.path.join(path);
887                fs::read_to_string(&wac_config)
888                    .with_context(|| format!("failed to read {wac_config:?}"))?
889            }
890            // Default wac script is to just make `test_components` available
891            // to the `runner`.
892            None => {
893                let mut script = String::from("package example:composition;\n");
894                let mut args = Vec::new();
895                for (component, _path) in test_components {
896                    let world = &component.bindgen.world;
897                    args.push(format!("...{world}"));
898                    script.push_str(&format!("let {world} = new test:{world} {{ ... }};\n"));
899                }
900                args.push("...".to_string());
901                let runner = &runner.bindgen.world;
902                script.push_str(&format!(
903                    "let runner = new test:{runner} {{ {} }};\n\
904                     export runner...;",
905                    args.join(", ")
906                ));
907
908                script
909            }
910        };
911
912        // Get allocations for `test:{world}` rooted on the stack as
913        // `BorrowedPackageKey` below requires `&str`.
914        let components_as_packages = test_components
915            .iter()
916            .map(|(component, path)| {
917                Ok((format!("test:{}", component.bindgen.world), fs::read(path)?))
918            })
919            .collect::<Result<Vec<_>>>()?;
920
921        let runner_name = format!("test:{}", runner.bindgen.world);
922        let mut packages = indexmap::IndexMap::new();
923        packages.insert(
924            wac_types::BorrowedPackageKey {
925                name: &runner_name,
926                version: None,
927            },
928            fs::read(runner_wasm)?,
929        );
930        for (name, contents) in components_as_packages.iter() {
931            packages.insert(
932                wac_types::BorrowedPackageKey {
933                    name,
934                    version: None,
935                },
936                contents.clone(),
937            );
938        }
939
940        // TODO: should figure out how to render these errors better.
941        let document =
942            wac_parser::Document::parse(&document).context("failed to parse wac script")?;
943        document
944            .resolve(packages)
945            .context("failed to run `wac` resolve")?
946            .encode(wac_graph::EncodeOptions {
947                define_components: true,
948                validate: false,
949                processor: None,
950            })
951            .context("failed to encode `wac` result")
952    }
953
954    /// Helper to execute an external process and generate a helpful error
955    /// message on failure.
956    fn run_command(&self, cmd: &mut Command) -> Result<()> {
957        if self.opts.inherit_stderr {
958            cmd.stderr(Stdio::inherit());
959        }
960        let output = cmd
961            .output()
962            .with_context(|| format!("failed to spawn {cmd:?}"))?;
963        if output.status.success() {
964            return Ok(());
965        }
966
967        let mut error = format!(
968            "\
969command execution failed
970command: {cmd:?}
971status: {}",
972            output.status,
973        );
974
975        if !output.stdout.is_empty() {
976            error.push_str(&format!(
977                "\nstdout:\n  {}",
978                String::from_utf8_lossy(&output.stdout).replace("\n", "\n  ")
979            ));
980        }
981        if !output.stderr.is_empty() {
982            error.push_str(&format!(
983                "\nstderr:\n  {}",
984                String::from_utf8_lossy(&output.stderr).replace("\n", "\n  ")
985            ));
986        }
987
988        bail!("{error}")
989    }
990
991    /// Converts the WASIp1 module at `p1` to a component using the information
992    /// stored within `compile`.
993    ///
994    /// Stores the output at `compile.output`.
995    fn convert_p1_to_component(&self, p1: &Path, compile: &Compile<'_>) -> Result<()> {
996        let mut resolve = wit_parser::Resolve::default();
997        let (pkg, _) = resolve
998            .push_path(&compile.component.bindgen.wit_path)
999            .context("failed to load WIT")?;
1000        let world = resolve.select_world(&[pkg], Some(&compile.component.bindgen.world))?;
1001        let mut module = fs::read(&p1).context("failed to read wasm file")?;
1002        let encoded = wit_component::metadata::encode(&resolve, world, StringEncoding::UTF8, None)?;
1003
1004        let section = wasm_encoder::CustomSection {
1005            name: Cow::Borrowed("component-type"),
1006            data: Cow::Borrowed(&encoded),
1007        };
1008        module.push(section.id());
1009        section.encode(&mut module);
1010
1011        let wasi_adapter = match compile.component.kind {
1012            Kind::Runner => {
1013                wasi_preview1_component_adapter_provider::WASI_SNAPSHOT_PREVIEW1_COMMAND_ADAPTER
1014            }
1015            Kind::Test => {
1016                wasi_preview1_component_adapter_provider::WASI_SNAPSHOT_PREVIEW1_REACTOR_ADAPTER
1017            }
1018        };
1019
1020        let component = ComponentEncoder::default()
1021            .module(module.as_slice())
1022            .context("failed to load custom sections from input module")?
1023            .validate(true)
1024            .adapter("wasi_snapshot_preview1", wasi_adapter)
1025            .context("failed to load wasip1 adapter")?
1026            .encode()
1027            .context("failed to convert to a component")?;
1028        write_if_different(compile.output, component)?;
1029        Ok(())
1030    }
1031
1032    /// "poor man's test output progress"
1033    fn update_status<T>(&self, result: &Result<T>, should_fail: bool) {
1034        if result.is_ok() == !should_fail {
1035            print!(".");
1036        } else {
1037            print!("F");
1038        }
1039        let _ = std::io::stdout().flush();
1040    }
1041
1042    /// Returns whether `languages` is included in this testing session.
1043    fn include_language(&self, language: &Language) -> bool {
1044        self.opts
1045            .languages
1046            .iter()
1047            .any(|l| l == language.obj().display())
1048    }
1049
1050    fn render_errors<'a>(&self, results: impl Iterator<Item = StepResult<'a>>) {
1051        let mut failures = 0;
1052        for result in results {
1053            let err = match (result.result, result.should_fail) {
1054                (Ok(()), false) | (Err(_), true) => continue,
1055                (Err(e), false) => e,
1056                (Ok(()), true) => anyhow!("test should have failed, but passed"),
1057            };
1058            failures += 1;
1059
1060            println!("------ Failure: {} --------", result.name);
1061            for (k, v) in result.metadata {
1062                println!("  {k}: {v}");
1063            }
1064            println!("  error: {}", format!("{err:?}").replace("\n", "\n  "));
1065        }
1066
1067        if failures > 0 {
1068            println!("{failures} tests FAILED");
1069            std::process::exit(1);
1070        }
1071    }
1072}
1073
1074struct StepResult<'a> {
1075    result: Result<()>,
1076    should_fail: bool,
1077    name: &'a str,
1078    metadata: Vec<(&'a str, String)>,
1079}
1080
1081impl<'a> StepResult<'a> {
1082    fn new(name: &'a str, result: Result<()>) -> StepResult<'a> {
1083        StepResult {
1084            name,
1085            result,
1086            should_fail: false,
1087            metadata: Vec::new(),
1088        }
1089    }
1090
1091    fn should_fail(mut self, fail: bool) -> Self {
1092        self.should_fail = fail;
1093        self
1094    }
1095
1096    fn metadata(mut self, name: &'a str, value: impl fmt::Display) -> Self {
1097        self.metadata.push((name, value.to_string()));
1098        self
1099    }
1100}
1101
1102/// Helper trait for each language to implement which encapsulates
1103/// language-specific logic.
1104trait LanguageMethods {
1105    /// Display name for this language, used in filenames.
1106    fn display(&self) -> &str;
1107
1108    /// Returns the prefix that this language uses to annotate configuration in
1109    /// the top of source files.
1110    ///
1111    /// This should be the language's line-comment syntax followed by `@`, e.g.
1112    /// `//@` for Rust or `;;@` for WebAssembly Text.
1113    fn comment_prefix_for_test_config(&self) -> Option<&str>;
1114
1115    /// Returns the extra permutations, if any, of arguments to use with codegen
1116    /// tests.
1117    ///
1118    /// This is used to run all codegen tests with a variety of bindings
1119    /// generator options. The first element in the tuple is a descriptive
1120    /// string that should be unique (used in file names) and the second elemtn
1121    /// is the list of arguments for that variant to pass to the bindings
1122    /// generator.
1123    fn codegen_test_variants(&self) -> &[(&str, &[&str])] {
1124        &[]
1125    }
1126
1127    /// Performs any one-time preparation necessary for this language, such as
1128    /// downloading or caching dependencies.
1129    fn prepare(&self, runner: &mut Runner<'_>) -> Result<()>;
1130
1131    /// Add some files to the generated directory _before_ calling bindgen
1132    fn generate_bindings_prepare(
1133        &self,
1134        _runner: &Runner<'_>,
1135        _bindgen: &Bindgen,
1136        _dir: &Path,
1137    ) -> Result<()> {
1138        Ok(())
1139    }
1140
1141    /// Generates bindings for `component` into `dir`.
1142    ///
1143    /// Runs `wit-bindgen` in aa subprocess to catch failures such as panics.
1144    fn generate_bindings(&self, runner: &Runner<'_>, bindgen: &Bindgen, dir: &Path) -> Result<()> {
1145        let name = match self.bindgen_name() {
1146            Some(name) => name,
1147            None => return Ok(()),
1148        };
1149        self.generate_bindings_prepare(runner, bindgen, dir)?;
1150        let mut cmd = Command::new(runner.wit_bindgen);
1151        cmd.arg(name)
1152            .arg(&bindgen.wit_path)
1153            .arg("--world")
1154            .arg(format!("%{}", bindgen.world))
1155            .arg("--out-dir")
1156            .arg(dir);
1157
1158        match bindgen.wit_config.default_bindgen_args {
1159            Some(true) | None => {
1160                for arg in self.default_bindgen_args() {
1161                    cmd.arg(arg);
1162                }
1163            }
1164            Some(false) => {}
1165        }
1166
1167        for arg in bindgen.args.iter() {
1168            cmd.arg(arg);
1169        }
1170
1171        runner.run_command(&mut cmd)
1172    }
1173
1174    /// Returns the default set of arguments that will be passed to
1175    /// `wit-bindgen`.
1176    ///
1177    /// Defaults to empty, but each language can override it.
1178    fn default_bindgen_args(&self) -> &[&str] {
1179        &[]
1180    }
1181
1182    /// Same as `default_bindgen_args` but specifically applied during codegen
1183    /// tests, such as generating stub impls by default.
1184    fn default_bindgen_args_for_codegen(&self) -> &[&str] {
1185        &[]
1186    }
1187
1188    /// Returns the name of this bindings generator when passed to
1189    /// `wit-bindgen`.
1190    ///
1191    /// By default this is `Some(self.display())`, but it can be overridden if
1192    /// necessary. Returning `None` here means that no bindings generator is
1193    /// supported.
1194    fn bindgen_name(&self) -> Option<&str> {
1195        Some(self.display())
1196    }
1197
1198    /// Performs compilation as specified by `compile`.
1199    fn compile(&self, runner: &Runner<'_>, compile: &Compile) -> Result<()>;
1200
1201    /// Returns whether this language is supposed to fail this codegen tests
1202    /// given the `config` and `args` for the test.
1203    fn should_fail_verify(&self, name: &str, config: &config::WitConfig, args: &[String]) -> bool;
1204
1205    /// Performs a "check" or a verify that the generated bindings described by
1206    /// `Verify` are indeed valid.
1207    fn verify(&self, runner: &Runner<'_>, verify: &Verify) -> Result<()>;
1208}
1209
1210impl Language {
1211    const ALL: &[Language] = &[
1212        Language::Rust,
1213        Language::C,
1214        Language::Cpp,
1215        Language::Wat,
1216        Language::Csharp,
1217        Language::MoonBit,
1218    ];
1219
1220    fn obj(&self) -> &dyn LanguageMethods {
1221        match self {
1222            Language::Rust => &rust::Rust,
1223            Language::C => &c::C,
1224            Language::Cpp => &cpp::Cpp,
1225            Language::Wat => &wat::Wat,
1226            Language::Csharp => &csharp::Csharp,
1227            Language::MoonBit => &moonbit::MoonBit,
1228            Language::Custom(custom) => custom,
1229        }
1230    }
1231}
1232
1233impl fmt::Display for Language {
1234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1235        self.obj().display().fmt(f)
1236    }
1237}
1238
1239impl fmt::Display for Kind {
1240    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1241        match self {
1242            Kind::Runner => "runner".fmt(f),
1243            Kind::Test => "test".fmt(f),
1244        }
1245    }
1246}
1247
1248/// Returns `true` if the file was written, or `false` if the file is the same
1249/// as it was already on disk.
1250fn write_if_different(path: &Path, contents: impl AsRef<[u8]>) -> Result<bool> {
1251    let contents = contents.as_ref();
1252    if let Ok(prev) = fs::read(path) {
1253        if prev == contents {
1254            return Ok(false);
1255        }
1256    }
1257
1258    if let Some(parent) = path.parent() {
1259        fs::create_dir_all(parent)
1260            .with_context(|| format!("failed to create directory {parent:?}"))?;
1261    }
1262    fs::write(path, contents).with_context(|| format!("failed to write {path:?}"))?;
1263    Ok(true)
1264}
1265
1266impl Component {
1267    /// Helper to convert `RuntimeTestConfig` to a `RuntimeTestConfig<T>` and
1268    /// then extract the `T`.
1269    ///
1270    /// This is called from within each language's implementation with a
1271    /// specific `T` necessary for that language.
1272    fn deserialize_lang_config<T>(&self) -> Result<T>
1273    where
1274        T: Default + serde::de::DeserializeOwned,
1275    {
1276        // If this test has no language-specific configuration then return this
1277        // language's default configuration.
1278        if self.lang_config.is_none() {
1279            return Ok(T::default());
1280        }
1281
1282        // Otherwise re-parse the TOML at the top of the file but this time
1283        // with the specific `T` that we're interested in. This is expected
1284        // to then produce a value in the `lang` field since
1285        // `self.lang_config.is_some()` is true.
1286        let config = config::parse_test_config::<config::RuntimeTestConfig<T>>(
1287            &self.contents,
1288            self.language
1289                .obj()
1290                .comment_prefix_for_test_config()
1291                .unwrap(),
1292        )?;
1293        Ok(config.lang.unwrap())
1294    }
1295}