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| resolve.select_world(pkg, Some("imports")).map_err(|_| err))
587            .context("failed to select a world for bindings generation")?;
588        let world = resolve.worlds[world].name.clone();
589
590        let artifacts_dir = std::env::current_dir()?
591            .join(&self.opts.artifacts)
592            .join("codegen")
593            .join(language.to_string())
594            .join(args_kind);
595        let _ = fs::remove_dir_all(&artifacts_dir);
596        let bindings_dir = artifacts_dir.join("bindings");
597        let bindgen = Bindgen {
598            args: args.to_vec(),
599            wit_path: test.to_path_buf(),
600            world: world.clone(),
601            wit_config: config.clone(),
602        };
603        language
604            .obj()
605            .generate_bindings(self, &bindgen, &bindings_dir)
606            .context("failed to generate bindings")?;
607
608        language
609            .obj()
610            .verify(
611                self,
612                &Verify {
613                    world: &world,
614                    artifacts_dir: &artifacts_dir,
615                    bindings_dir: &bindings_dir,
616                    wit_test: test,
617                    args: &bindgen.args,
618                },
619            )
620            .context("failed to verify generated bindings")?;
621
622        Ok(())
623    }
624
625    /// Execute all `TestKind::Runtime` tests
626    fn run_runtime_tests(&mut self, tests: &HashMap<String, Test>) -> Result<()> {
627        let components = tests
628            .values()
629            .filter(|t| match &self.opts.filter {
630                Some(filter) => filter.is_match(&t.name),
631                None => true,
632            })
633            .filter_map(|t| match &t.kind {
634                TestKind::Runtime(c) => Some(c.iter().map(move |c| (t, c))),
635                TestKind::Codegen(_) => None,
636            })
637            .flat_map(|i| i)
638            // Discard components that are unrelated to the languages being
639            // tested.
640            .filter(|(_test, component)| self.include_language(&component.language))
641            .collect::<Vec<_>>();
642
643        println!("Compiling {} components:", components.len());
644
645        // In parallel compile all sources to their binary component
646        // form.
647        let compile_results = components
648            .par_iter()
649            .map(|(test, component)| {
650                let path = self
651                    .compile_component(test, component)
652                    .with_context(|| format!("failed to compile component {:?}", component.path));
653                self.update_status(&path, false);
654                (test, component, path)
655            })
656            .collect::<Vec<_>>();
657        println!("");
658
659        let mut compilations = Vec::new();
660        self.render_errors(
661            compile_results
662                .into_iter()
663                .map(|(test, component, result)| match result {
664                    Ok(path) => {
665                        compilations.push((test, component, path));
666                        StepResult::new("", Ok(()))
667                    }
668                    Err(e) => StepResult::new(&test.name, Err(e))
669                        .metadata("component", &component.name)
670                        .metadata("path", component.path.display()),
671                }),
672        );
673
674        // Next, massage the data a bit. Create a map of all tests to where
675        // their components are located. Then perform a product of runners/tests
676        // to generate a list of test cases. Finally actually execute the testj
677        // cases.
678        let mut compiled_components = HashMap::new();
679        for (test, component, path) in compilations {
680            let list = compiled_components.entry(&test.name).or_insert(Vec::new());
681            list.push((*component, path));
682        }
683
684        let mut to_run = Vec::new();
685        for (test, components) in compiled_components.iter() {
686            for a in components.iter().filter(|(c, _)| c.kind == Kind::Runner) {
687                self.push_tests(&tests[test.as_str()], components, a, &mut to_run)?;
688            }
689        }
690
691        println!("Running {} runtime tests:", to_run.len());
692
693        let results = to_run
694            .par_iter()
695            .map(|(case_name, (runner, runner_path), test_components)| {
696                let case = &tests[*case_name];
697                let result = self
698                    .runtime_test(case, runner, runner_path, test_components)
699                    .with_context(|| format!("failed to run `{}`", case.name));
700                self.update_status(&result, false);
701                (result, case_name, runner, runner_path, test_components)
702            })
703            .collect::<Vec<_>>();
704
705        println!("");
706
707        self.render_errors(results.into_iter().map(
708            |(result, case_name, runner, runner_path, test_components)| {
709                let mut result = StepResult::new(case_name, result)
710                    .metadata("runner", runner.path.display())
711                    .metadata("compiled runner", runner_path.display());
712                for (test, path) in test_components {
713                    result = result
714                        .metadata("test", test.path.display())
715                        .metadata("compiled test", path.display());
716                }
717                result
718            },
719        ));
720
721        Ok(())
722    }
723
724    /// For the `test` provided, and the selected `runner`, determines all
725    /// permutations of tests from `components` and pushes them on to `to_run`.
726    fn push_tests<'a>(
727        &self,
728        test: &'a Test,
729        components: &'a [(&'a Component, PathBuf)],
730        runner: &'a (&'a Component, PathBuf),
731        to_run: &mut Vec<(
732            &'a str,
733            (&'a Component, &'a Path),
734            Vec<(&'a Component, &'a Path)>,
735        )>,
736    ) -> Result<()> {
737        /// Recursive function which walks over `worlds`, the list of worlds
738        /// that `test` expects, one by one. For each world it finds a matching
739        /// component in `components` adn then recurses for the next item in the
740        /// `worlds` list.
741        ///
742        /// Once `worlds` is empty the `test` list, a temporary vector, is
743        /// cloned and pushed into `commit`.
744        fn push<'a>(
745            worlds: &[String],
746            components: &'a [(&'a Component, PathBuf)],
747            test: &mut Vec<(&'a Component, &'a Path)>,
748            commit: &mut dyn FnMut(Vec<(&'a Component, &'a Path)>),
749        ) -> Result<()> {
750            match worlds.split_first() {
751                Some((world, rest)) => {
752                    let mut any = false;
753                    for (component, path) in components {
754                        if component.bindgen.world == *world {
755                            any = true;
756                            test.push((component, path));
757                            push(rest, components, test, commit)?;
758                            test.pop();
759                        }
760                    }
761                    if !any {
762                        bail!("no components found for `{world}`");
763                    }
764                }
765
766                // No more `worlds`? Then `test` is our set of test components.
767                None => commit(test.clone()),
768            }
769            Ok(())
770        }
771
772        push(
773            &test.config.dependency_worlds(),
774            components,
775            &mut Vec::new(),
776            &mut |test_components| {
777                to_run.push((&test.name, (runner.0, &runner.1), test_components));
778            },
779        )
780    }
781
782    /// Compiles the `component` specified to wasm for the `test` given.
783    ///
784    /// This will generate bindings for `component` and then perform
785    /// language-specific compilation to convert the files into a component.
786    fn compile_component(&self, test: &Test, component: &Component) -> Result<PathBuf> {
787        let root_dir = std::env::current_dir()?
788            .join(&self.opts.artifacts)
789            .join(&test.name);
790        let artifacts_dir = root_dir.join(format!("{}-{}", component.name, component.language));
791        let _ = fs::remove_dir_all(&artifacts_dir);
792        let bindings_dir = artifacts_dir.join("bindings");
793        let output = root_dir.join(format!("{}-{}.wasm", component.name, component.language));
794        component
795            .language
796            .obj()
797            .generate_bindings(self, &component.bindgen, &bindings_dir)?;
798        let result = Compile {
799            component,
800            bindings_dir: &bindings_dir,
801            artifacts_dir: &artifacts_dir,
802            output: &output,
803        };
804        component.language.obj().compile(self, &result)?;
805
806        // Double-check the output is indeed a component and it's indeed valid.
807        let wasm = fs::read(&output)
808            .with_context(|| format!("failed to read output wasm file {output:?}"))?;
809        if !wasmparser::Parser::is_component(&wasm) {
810            bail!("output file {output:?} is not a component");
811        }
812        wasmparser::Validator::new_with_features(wasmparser::WasmFeatures::all())
813            .validate_all(&wasm)
814            .with_context(|| format!("compiler produced invalid wasm file {output:?}"))?;
815
816        Ok(output)
817    }
818
819    /// Executes a single test case.
820    ///
821    /// Composes `runner_wasm` with the components in `test_components` and then
822    /// executes it with the runner specified in CLI flags.
823    fn runtime_test(
824        &self,
825        case: &Test,
826        runner: &Component,
827        runner_wasm: &Path,
828        test_components: &[(&Component, &Path)],
829    ) -> Result<()> {
830        // If possible use `wasm-compose` to compose the test together. This is
831        // only possible when customization isn't used though. This is also only
832        // done for async tests at this time to ensure that there's a version of
833        // composition that's done which is at the same version as wasmparser
834        // and friends.
835        let composed = if case.config.wac.is_none() && test_components.len() == 1 {
836            self.compose_wasm_with_wasm_compose(runner_wasm, test_components)?
837        } else {
838            self.compose_wasm_with_wac(case, runner, runner_wasm, test_components)?
839        };
840
841        let dst = runner_wasm.parent().unwrap();
842        let mut filename = format!(
843            "composed-{}",
844            runner.path.file_name().unwrap().to_str().unwrap(),
845        );
846        for (test, _) in test_components {
847            filename.push_str("-");
848            filename.push_str(test.path.file_name().unwrap().to_str().unwrap());
849        }
850        filename.push_str(".wasm");
851        let composed_wasm = dst.join(filename);
852        write_if_different(&composed_wasm, &composed)?;
853
854        self.run_command(self.test_runner.command().arg(&composed_wasm))?;
855        Ok(())
856    }
857
858    fn compose_wasm_with_wasm_compose(
859        &self,
860        runner_wasm: &Path,
861        test_components: &[(&Component, &Path)],
862    ) -> Result<Vec<u8>> {
863        assert!(test_components.len() == 1);
864        let test_wasm = test_components[0].1;
865        let mut config = wasm_compose::config::Config::default();
866        config.definitions = vec![test_wasm.to_path_buf()];
867        wasm_compose::composer::ComponentComposer::new(runner_wasm, &config)
868            .compose()
869            .with_context(|| format!("failed to compose {runner_wasm:?} with {test_wasm:?}"))
870    }
871
872    fn compose_wasm_with_wac(
873        &self,
874        case: &Test,
875        runner: &Component,
876        runner_wasm: &Path,
877        test_components: &[(&Component, &Path)],
878    ) -> Result<Vec<u8>> {
879        let document = match &case.config.wac {
880            Some(path) => {
881                let wac_config = case.path.join(path);
882                fs::read_to_string(&wac_config)
883                    .with_context(|| format!("failed to read {wac_config:?}"))?
884            }
885            // Default wac script is to just make `test_components` available
886            // to the `runner`.
887            None => {
888                let mut script = String::from("package example:composition;\n");
889                let mut args = Vec::new();
890                for (component, _path) in test_components {
891                    let world = &component.bindgen.world;
892                    args.push(format!("...{world}"));
893                    script.push_str(&format!("let {world} = new test:{world} {{ ... }};\n"));
894                }
895                args.push("...".to_string());
896                let runner = &runner.bindgen.world;
897                script.push_str(&format!(
898                    "let runner = new test:{runner} {{ {} }};\n\
899                     export runner...;",
900                    args.join(", ")
901                ));
902
903                script
904            }
905        };
906
907        // Get allocations for `test:{world}` rooted on the stack as
908        // `BorrowedPackageKey` below requires `&str`.
909        let components_as_packages = test_components
910            .iter()
911            .map(|(component, path)| {
912                Ok((format!("test:{}", component.bindgen.world), fs::read(path)?))
913            })
914            .collect::<Result<Vec<_>>>()?;
915
916        let runner_name = format!("test:{}", runner.bindgen.world);
917        let mut packages = indexmap::IndexMap::new();
918        packages.insert(
919            wac_types::BorrowedPackageKey {
920                name: &runner_name,
921                version: None,
922            },
923            fs::read(runner_wasm)?,
924        );
925        for (name, contents) in components_as_packages.iter() {
926            packages.insert(
927                wac_types::BorrowedPackageKey {
928                    name,
929                    version: None,
930                },
931                contents.clone(),
932            );
933        }
934
935        // TODO: should figure out how to render these errors better.
936        let document =
937            wac_parser::Document::parse(&document).context("failed to parse wac script")?;
938        document
939            .resolve(packages)
940            .context("failed to run `wac` resolve")?
941            .encode(wac_graph::EncodeOptions {
942                define_components: true,
943                validate: false,
944                processor: None,
945            })
946            .context("failed to encode `wac` result")
947    }
948
949    /// Helper to execute an external process and generate a helpful error
950    /// message on failure.
951    fn run_command(&self, cmd: &mut Command) -> Result<()> {
952        if self.opts.inherit_stderr {
953            cmd.stderr(Stdio::inherit());
954        }
955        let output = cmd
956            .output()
957            .with_context(|| format!("failed to spawn {cmd:?}"))?;
958        if output.status.success() {
959            return Ok(());
960        }
961
962        let mut error = format!(
963            "\
964command execution failed
965command: {cmd:?}
966status: {}",
967            output.status,
968        );
969
970        if !output.stdout.is_empty() {
971            error.push_str(&format!(
972                "\nstdout:\n  {}",
973                String::from_utf8_lossy(&output.stdout).replace("\n", "\n  ")
974            ));
975        }
976        if !output.stderr.is_empty() {
977            error.push_str(&format!(
978                "\nstderr:\n  {}",
979                String::from_utf8_lossy(&output.stderr).replace("\n", "\n  ")
980            ));
981        }
982
983        bail!("{error}")
984    }
985
986    /// Converts the WASIp1 module at `p1` to a component using the information
987    /// stored within `compile`.
988    ///
989    /// Stores the output at `compile.output`.
990    fn convert_p1_to_component(&self, p1: &Path, compile: &Compile<'_>) -> Result<()> {
991        let mut resolve = wit_parser::Resolve::default();
992        let (pkg, _) = resolve
993            .push_path(&compile.component.bindgen.wit_path)
994            .context("failed to load WIT")?;
995        let world = resolve.select_world(pkg, Some(&compile.component.bindgen.world))?;
996        let mut module = fs::read(&p1).context("failed to read wasm file")?;
997        let encoded = wit_component::metadata::encode(&resolve, world, StringEncoding::UTF8, None)?;
998
999        let section = wasm_encoder::CustomSection {
1000            name: Cow::Borrowed("component-type"),
1001            data: Cow::Borrowed(&encoded),
1002        };
1003        module.push(section.id());
1004        section.encode(&mut module);
1005
1006        let wasi_adapter = match compile.component.kind {
1007            Kind::Runner => {
1008                wasi_preview1_component_adapter_provider::WASI_SNAPSHOT_PREVIEW1_COMMAND_ADAPTER
1009            }
1010            Kind::Test => {
1011                wasi_preview1_component_adapter_provider::WASI_SNAPSHOT_PREVIEW1_REACTOR_ADAPTER
1012            }
1013        };
1014
1015        let component = ComponentEncoder::default()
1016            .module(module.as_slice())
1017            .context("failed to load custom sections from input module")?
1018            .validate(true)
1019            .adapter("wasi_snapshot_preview1", wasi_adapter)
1020            .context("failed to load wasip1 adapter")?
1021            .encode()
1022            .context("failed to convert to a component")?;
1023        write_if_different(compile.output, component)?;
1024        Ok(())
1025    }
1026
1027    /// "poor man's test output progress"
1028    fn update_status<T>(&self, result: &Result<T>, should_fail: bool) {
1029        if result.is_ok() == !should_fail {
1030            print!(".");
1031        } else {
1032            print!("F");
1033        }
1034        let _ = std::io::stdout().flush();
1035    }
1036
1037    /// Returns whether `languages` is included in this testing session.
1038    fn include_language(&self, language: &Language) -> bool {
1039        self.opts
1040            .languages
1041            .iter()
1042            .any(|l| l == language.obj().display())
1043    }
1044
1045    fn render_errors<'a>(&self, results: impl Iterator<Item = StepResult<'a>>) {
1046        let mut failures = 0;
1047        for result in results {
1048            let err = match (result.result, result.should_fail) {
1049                (Ok(()), false) | (Err(_), true) => continue,
1050                (Err(e), false) => e,
1051                (Ok(()), true) => anyhow!("test should have failed, but passed"),
1052            };
1053            failures += 1;
1054
1055            println!("------ Failure: {} --------", result.name);
1056            for (k, v) in result.metadata {
1057                println!("  {k}: {v}");
1058            }
1059            println!("  error: {}", format!("{err:?}").replace("\n", "\n  "));
1060        }
1061
1062        if failures > 0 {
1063            println!("{failures} tests FAILED");
1064            std::process::exit(1);
1065        }
1066    }
1067}
1068
1069struct StepResult<'a> {
1070    result: Result<()>,
1071    should_fail: bool,
1072    name: &'a str,
1073    metadata: Vec<(&'a str, String)>,
1074}
1075
1076impl<'a> StepResult<'a> {
1077    fn new(name: &'a str, result: Result<()>) -> StepResult<'a> {
1078        StepResult {
1079            name,
1080            result,
1081            should_fail: false,
1082            metadata: Vec::new(),
1083        }
1084    }
1085
1086    fn should_fail(mut self, fail: bool) -> Self {
1087        self.should_fail = fail;
1088        self
1089    }
1090
1091    fn metadata(mut self, name: &'a str, value: impl fmt::Display) -> Self {
1092        self.metadata.push((name, value.to_string()));
1093        self
1094    }
1095}
1096
1097/// Helper trait for each language to implement which encapsulates
1098/// language-specific logic.
1099trait LanguageMethods {
1100    /// Display name for this language, used in filenames.
1101    fn display(&self) -> &str;
1102
1103    /// Returns the prefix that this language uses to annotate configuration in
1104    /// the top of source files.
1105    ///
1106    /// This should be the language's line-comment syntax followed by `@`, e.g.
1107    /// `//@` for Rust or `;;@` for WebAssembly Text.
1108    fn comment_prefix_for_test_config(&self) -> Option<&str>;
1109
1110    /// Returns the extra permutations, if any, of arguments to use with codegen
1111    /// tests.
1112    ///
1113    /// This is used to run all codegen tests with a variety of bindings
1114    /// generator options. The first element in the tuple is a descriptive
1115    /// string that should be unique (used in file names) and the second elemtn
1116    /// is the list of arguments for that variant to pass to the bindings
1117    /// generator.
1118    fn codegen_test_variants(&self) -> &[(&str, &[&str])] {
1119        &[]
1120    }
1121
1122    /// Performs any one-time preparation necessary for this language, such as
1123    /// downloading or caching dependencies.
1124    fn prepare(&self, runner: &mut Runner<'_>) -> Result<()>;
1125
1126    /// Add some files to the generated directory _before_ calling bindgen
1127    fn generate_bindings_prepare(
1128        &self,
1129        _runner: &Runner<'_>,
1130        _bindgen: &Bindgen,
1131        _dir: &Path,
1132    ) -> Result<()> {
1133        Ok(())
1134    }
1135
1136    /// Generates bindings for `component` into `dir`.
1137    ///
1138    /// Runs `wit-bindgen` in aa subprocess to catch failures such as panics.
1139    fn generate_bindings(&self, runner: &Runner<'_>, bindgen: &Bindgen, dir: &Path) -> Result<()> {
1140        let name = match self.bindgen_name() {
1141            Some(name) => name,
1142            None => return Ok(()),
1143        };
1144        self.generate_bindings_prepare(runner, bindgen, dir)?;
1145        let mut cmd = Command::new(runner.wit_bindgen);
1146        cmd.arg(name)
1147            .arg(&bindgen.wit_path)
1148            .arg("--world")
1149            .arg(format!("%{}", bindgen.world))
1150            .arg("--out-dir")
1151            .arg(dir);
1152
1153        match bindgen.wit_config.default_bindgen_args {
1154            Some(true) | None => {
1155                for arg in self.default_bindgen_args() {
1156                    cmd.arg(arg);
1157                }
1158            }
1159            Some(false) => {}
1160        }
1161
1162        for arg in bindgen.args.iter() {
1163            cmd.arg(arg);
1164        }
1165
1166        runner.run_command(&mut cmd)
1167    }
1168
1169    /// Returns the default set of arguments that will be passed to
1170    /// `wit-bindgen`.
1171    ///
1172    /// Defaults to empty, but each language can override it.
1173    fn default_bindgen_args(&self) -> &[&str] {
1174        &[]
1175    }
1176
1177    /// Same as `default_bindgen_args` but specifically applied during codegen
1178    /// tests, such as generating stub impls by default.
1179    fn default_bindgen_args_for_codegen(&self) -> &[&str] {
1180        &[]
1181    }
1182
1183    /// Returns the name of this bindings generator when passed to
1184    /// `wit-bindgen`.
1185    ///
1186    /// By default this is `Some(self.display())`, but it can be overridden if
1187    /// necessary. Returning `None` here means that no bindings generator is
1188    /// supported.
1189    fn bindgen_name(&self) -> Option<&str> {
1190        Some(self.display())
1191    }
1192
1193    /// Performs compilation as specified by `compile`.
1194    fn compile(&self, runner: &Runner<'_>, compile: &Compile) -> Result<()>;
1195
1196    /// Returns whether this language is supposed to fail this codegen tests
1197    /// given the `config` and `args` for the test.
1198    fn should_fail_verify(&self, name: &str, config: &config::WitConfig, args: &[String]) -> bool;
1199
1200    /// Performs a "check" or a verify that the generated bindings described by
1201    /// `Verify` are indeed valid.
1202    fn verify(&self, runner: &Runner<'_>, verify: &Verify) -> Result<()>;
1203}
1204
1205impl Language {
1206    const ALL: &[Language] = &[
1207        Language::Rust,
1208        Language::C,
1209        Language::Cpp,
1210        Language::Wat,
1211        Language::Csharp,
1212        Language::MoonBit,
1213    ];
1214
1215    fn obj(&self) -> &dyn LanguageMethods {
1216        match self {
1217            Language::Rust => &rust::Rust,
1218            Language::C => &c::C,
1219            Language::Cpp => &cpp::Cpp,
1220            Language::Wat => &wat::Wat,
1221            Language::Csharp => &csharp::Csharp,
1222            Language::MoonBit => &moonbit::MoonBit,
1223            Language::Custom(custom) => custom,
1224        }
1225    }
1226}
1227
1228impl fmt::Display for Language {
1229    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1230        self.obj().display().fmt(f)
1231    }
1232}
1233
1234impl fmt::Display for Kind {
1235    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1236        match self {
1237            Kind::Runner => "runner".fmt(f),
1238            Kind::Test => "test".fmt(f),
1239        }
1240    }
1241}
1242
1243/// Returns `true` if the file was written, or `false` if the file is the same
1244/// as it was already on disk.
1245fn write_if_different(path: &Path, contents: impl AsRef<[u8]>) -> Result<bool> {
1246    let contents = contents.as_ref();
1247    if let Ok(prev) = fs::read(path) {
1248        if prev == contents {
1249            return Ok(false);
1250        }
1251    }
1252
1253    if let Some(parent) = path.parent() {
1254        fs::create_dir_all(parent)
1255            .with_context(|| format!("failed to create directory {parent:?}"))?;
1256    }
1257    fs::write(path, contents).with_context(|| format!("failed to write {path:?}"))?;
1258    Ok(true)
1259}
1260
1261impl Component {
1262    /// Helper to convert `RuntimeTestConfig` to a `RuntimeTestConfig<T>` and
1263    /// then extract the `T`.
1264    ///
1265    /// This is called from within each language's implementation with a
1266    /// specific `T` necessary for that language.
1267    fn deserialize_lang_config<T>(&self) -> Result<T>
1268    where
1269        T: Default + serde::de::DeserializeOwned,
1270    {
1271        // If this test has no language-specific configuration then return this
1272        // language's default configuration.
1273        if self.lang_config.is_none() {
1274            return Ok(T::default());
1275        }
1276
1277        // Otherwise re-parse the TOML at the top of the file but this time
1278        // with the specific `T` that we're interested in. This is expected
1279        // to then produce a value in the `lang` field since
1280        // `self.lang_config.is_some()` is true.
1281        let config = config::parse_test_config::<config::RuntimeTestConfig<T>>(
1282            &self.contents,
1283            self.language
1284                .obj()
1285                .comment_prefix_for_test_config()
1286                .unwrap(),
1287        )?;
1288        Ok(config.lang.unwrap())
1289    }
1290}