Skip to main content

rune/cli/
mod.rs

1//! Helper to build customized commandline interfaces using custom rune
2//! contexts.
3//!
4//! This can be used to:
5//! * Generate documentation using types only available in your context.
6//! * Build a language server, which is aware of things only available in your
7//!   context.
8
9mod ace;
10mod benches;
11mod check;
12mod doc;
13mod format;
14mod languageserver;
15mod loader;
16mod naming;
17mod out;
18mod run;
19mod tests;
20mod visitor;
21
22use std::fmt;
23use std::fs::File;
24use std::io::{self, IsTerminal, Write};
25use std::path::{Path, PathBuf};
26
27use rust_alloc::string::String;
28use rust_alloc::vec::Vec;
29
30use crate as rune;
31use crate::alloc;
32use crate::alloc::prelude::*;
33use crate::workspace::{self, FoundKind, WorkspaceFilter};
34
35use anyhow::{bail, Context as _, Error, Result};
36use clap::{Parser, Subcommand, ValueEnum};
37use tracing_subscriber::filter::EnvFilter;
38
39use crate::compile::ParseOptionError;
40use crate::modules::capture_io::CaptureIo;
41use crate::termcolor::{ColorChoice, StandardStream};
42use crate::{Context, ContextError, Hash, ItemBuf, Options, Source, Sources};
43
44use self::out::{Color, Io, Stream};
45
46/// Default about splash.
47const DEFAULT_ABOUT: &str = "The Rune Language Interpreter";
48
49/// Options for building context.
50#[non_exhaustive]
51pub struct ContextOptions<'a> {
52    /// If we need to capture I/O this is set to the capture instance you should
53    /// be using to do so.
54    pub capture: Option<&'a CaptureIo>,
55    /// If we're running in a test context.
56    pub test: bool,
57}
58
59/// Type used to build a context.
60pub type ContextBuilder = dyn FnMut(ContextOptions<'_>) -> Result<Context, ContextError>;
61
62/// A rune-based entrypoint used for custom applications.
63///
64/// This can be used to construct your own rune-based environment, with a custom
65/// configuration such as your own modules.
66#[derive(Default)]
67pub struct Entry<'a> {
68    about: Option<alloc::String>,
69    context: Option<&'a mut ContextBuilder>,
70}
71
72impl<'a> Entry<'a> {
73    /// Entry point.
74    pub fn new() -> Self {
75        Self::default()
76    }
77
78    /// Set about string used in cli output.
79    ///
80    /// For example, this is the first row outputted when the command prints its
81    /// help text.
82    ///
83    /// # Examples
84    ///
85    /// ```no_run
86    /// rune::cli::Entry::new()
87    ///     .about("My own interpreter")
88    ///     .run();
89    ///```
90    pub fn about(mut self, about: impl fmt::Display) -> Self {
91        self.about = Some(
92            about
93                .try_to_string()
94                .expect("Failed to format about string"),
95        );
96        self
97    }
98
99    /// Configure context to use using a builder.
100    ///
101    /// # Examples
102    ///
103    /// ```no_run
104    /// use rune::{Context, ContextError, Module};
105    ///
106    /// fn my_module() -> Result<Module, ContextError> {
107    ///     let module = Module::default();
108    ///     /* install things into module */
109    ///     Ok(module)
110    /// }
111    ///
112    /// rune::cli::Entry::new()
113    ///     .about("My own interpreter")
114    ///     .context(&mut |opts| {
115    ///         let mut c = Context::with_config(opts.capture.is_none())?;
116    ///         c.install(my_module()?);
117    ///         Ok(c)
118    ///     })
119    ///     .run();
120    ///```
121    pub fn context(mut self, context: &'a mut ContextBuilder) -> Self {
122        self.context = Some(context);
123        self
124    }
125
126    /// Run the configured application.
127    ///
128    /// This will take over stdout and stdin.
129    pub fn run(self) -> ! {
130        let runtime = tokio::runtime::Builder::new_current_thread()
131            .enable_all()
132            .build()
133            .expect("Failed to build runtime");
134
135        match runtime.block_on(self.inner()) {
136            Ok(exit_code) => {
137                std::process::exit(exit_code as i32);
138            }
139            Err(error) => {
140                let o = std::io::stderr();
141                // ignore error because stdout / stderr might've been closed.
142                let _ = format_errors(&mut o.lock(), &error);
143                std::process::exit(ExitCode::Failure as i32);
144            }
145        }
146    }
147
148    /// Run the configured application without starting a new tokio runtime.
149    ///
150    /// This will take over stdout and stdin.
151    pub async fn run_async(self) -> ! {
152        match self.inner().await {
153            Ok(exit_code) => {
154                std::process::exit(exit_code as i32);
155            }
156            Err(error) => {
157                let o = std::io::stderr();
158                // ignore error because stdout / stderr might've been closed.
159                let _ = format_errors(&mut o.lock(), &error);
160                std::process::exit(ExitCode::Failure as i32);
161            }
162        }
163    }
164
165    async fn inner(mut self) -> Result<ExitCode> {
166        let args = match Args::try_parse() {
167            Ok(args) => args,
168            Err(e) => {
169                let about = self.about.as_deref().unwrap_or(DEFAULT_ABOUT);
170
171                let code = if e.use_stderr() {
172                    let o = std::io::stderr();
173                    let mut o = o.lock();
174                    o.write_all(about.as_bytes())?;
175                    writeln!(o)?;
176                    writeln!(o)?;
177                    writeln!(o, "{e}")?;
178                    o.flush()?;
179                    ExitCode::Failure
180                } else {
181                    let o = std::io::stdout();
182                    let mut o = o.lock();
183                    o.write_all(about.as_bytes())?;
184                    writeln!(o)?;
185                    writeln!(o)?;
186                    writeln!(o, "{e}")?;
187                    o.flush()?;
188                    ExitCode::Success
189                };
190
191                return Ok(code);
192            }
193        };
194
195        if args.version {
196            let o = std::io::stdout();
197            let mut o = o.lock();
198            let about = self.about.as_deref().unwrap_or(DEFAULT_ABOUT);
199            o.write_all(about.as_bytes())?;
200            o.flush()?;
201            return Ok(ExitCode::Success);
202        }
203
204        let choice = match args.color {
205            ColorArgument::Always => ColorChoice::Always,
206            ColorArgument::Ansi => ColorChoice::AlwaysAnsi,
207            ColorArgument::Auto => {
208                if std::io::stdin().is_terminal() {
209                    ColorChoice::Auto
210                } else {
211                    ColorChoice::Never
212                }
213            }
214            ColorArgument::Never => ColorChoice::Never,
215        };
216
217        let mut stdout = StandardStream::stdout(choice);
218        let mut stderr = StandardStream::stderr(choice);
219
220        let mut io = Io::new(&mut stdout, &mut stderr);
221
222        if matches!(args.cmd, Some(Command::LanguageServer(..))) {
223            setup_languageserver_logging()?;
224        } else {
225            tracing_subscriber::fmt()
226                .with_env_filter(EnvFilter::from_default_env())
227                .init();
228        }
229
230        match main_with_out(&mut io, &mut self, args).await {
231            Ok(code) => Ok(code),
232            Err(error) => {
233                let o = io.with_color(Stream::Stdout, Color::Error)?;
234                format_errors(o, &error)?;
235                o.close()?;
236                Ok(ExitCode::Failure)
237            }
238        }
239    }
240}
241
242/// Configure tracing for the language server without writing to stdout, which
243/// is reserved for the LSP JSON-RPC transport.
244fn setup_languageserver_logging() -> Result<()> {
245    let env_filter =
246        match EnvFilter::try_from_env("RUNE_LOG").or_else(|_| EnvFilter::try_from_default_env()) {
247            Ok(env_filter) => env_filter,
248            Err(_) => return Ok(()),
249        };
250
251    if let Some(log_path) = std::env::var_os("RUNE_LOG_FILE") {
252        let log_path = PathBuf::from(log_path);
253
254        if let Some(d) = log_path.parent() {
255            let _ = std::fs::create_dir_all(d);
256        }
257
258        let file = File::options().append(true).create(true).open(log_path)?;
259
260        tracing_subscriber::fmt()
261            .with_env_filter(env_filter)
262            .with_writer(file)
263            .with_ansi(false)
264            .try_init()
265            .map_err(|e| anyhow::anyhow!("{e}"))?;
266    } else {
267        tracing_subscriber::fmt()
268            .with_env_filter(env_filter)
269            .with_writer(io::stderr)
270            .with_ansi(false)
271            .try_init()
272            .map_err(|e| anyhow::anyhow!("{e}"))?;
273    }
274
275    Ok(())
276}
277
278/// A single entrypoint that can be built or processed.
279#[derive(TryClone)]
280pub(crate) enum EntryPoint<'a> {
281    /// A plain path entrypoint.
282    Path(PathBuf, bool),
283    /// A package entrypoint.
284    Package(workspace::FoundPackage<'a>),
285}
286
287impl EntryPoint<'_> {
288    /// Path to entrypoint.
289    pub(crate) fn path(&self) -> &Path {
290        match self {
291            EntryPoint::Path(path, _) => path,
292            EntryPoint::Package(p) => &p.found.path,
293        }
294    }
295
296    /// The declaration sources compiled beside the entrypoint, which are those
297    /// of its package's dependencies.
298    pub(crate) fn declarations(&self) -> &[PathBuf] {
299        match self {
300            EntryPoint::Path(..) => &[],
301            EntryPoint::Package(p) => &p.package.declarations,
302        }
303    }
304
305    /// If a path is an additional argument.
306    pub(crate) fn is_argument(&self) -> bool {
307        match self {
308            EntryPoint::Path(_, explicit) => *explicit,
309            EntryPoint::Package(..) => false,
310        }
311    }
312}
313
314impl fmt::Display for EntryPoint<'_> {
315    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316        match self {
317            EntryPoint::Path(path, false) => {
318                write!(f, "path in {}", path.display())
319            }
320            EntryPoint::Path(path, true) => {
321                write!(f, "path in {} (argument)", path.display())
322            }
323            EntryPoint::Package(package) => {
324                write!(
325                    f,
326                    "package `{}` in {} ({})",
327                    package.package.name,
328                    package.found.path.display(),
329                    package.found.kind
330                )
331            }
332        }
333    }
334}
335
336#[derive(Parser, Debug, Clone)]
337#[command(rename_all = "kebab-case")]
338struct CommandShared<T>
339where
340    T: clap::Args,
341{
342    #[command(flatten)]
343    shared: SharedFlags,
344    #[command(flatten)]
345    command: T,
346}
347
348impl<T> CommandShared<T>
349where
350    T: CommandBase + clap::Args,
351{
352    /// Construct compiler options from arguments.
353    fn options(&self) -> Result<Options, ParseOptionError> {
354        let mut options = Options::from_default_env()?;
355
356        // Command-specific override defaults.
357        if self.command.is_debug() {
358            options.debug_info(true);
359            options.test(true);
360            options.bytecode(false);
361        }
362
363        for option in &self.shared.compiler_option {
364            options.parse_option(option)?;
365        }
366
367        Ok(options)
368    }
369}
370
371#[derive(Clone, Copy)]
372struct CommandSharedRef<'a> {
373    shared: &'a SharedFlags,
374    command: &'a dyn CommandBase,
375}
376
377impl<'a> CommandSharedRef<'a> {
378    fn find(
379        &self,
380        all_targets: bool,
381        kind: AssetKind,
382        name: Option<&'a str>,
383    ) -> Option<WorkspaceFilter<'a>> {
384        if !all_targets && !self.command.is_workspace(kind) {
385            return None;
386        }
387
388        if let Some(name) = name {
389            return Some(WorkspaceFilter::Name(name));
390        }
391
392        self.shared.is_unfiltered().then_some(WorkspaceFilter::All)
393    }
394
395    #[inline]
396    fn find_bins(&self, all_targets: bool) -> Option<WorkspaceFilter<'a>> {
397        self.find(all_targets, AssetKind::Bin, self.shared.bin.as_deref())
398    }
399
400    #[inline]
401    fn find_libs(&self, all_targets: bool) -> Option<WorkspaceFilter<'a>> {
402        self.find(all_targets, AssetKind::Lib, self.shared.lib.as_deref())
403    }
404
405    #[inline]
406    fn find_tests(&self, all_targets: bool) -> Option<WorkspaceFilter<'a>> {
407        self.find(all_targets, AssetKind::Test, self.shared.test.as_deref())
408    }
409
410    #[inline]
411    fn find_examples(&self, all_targets: bool) -> Option<WorkspaceFilter<'a>> {
412        self.find(all_targets, AssetKind::Bin, self.shared.example.as_deref())
413    }
414
415    #[inline]
416    fn find_benches(&self, all_targets: bool) -> Option<WorkspaceFilter<'a>> {
417        self.find(all_targets, AssetKind::Bench, self.shared.bench.as_deref())
418    }
419}
420
421#[derive(Parser, Debug)]
422#[command(rename_all = "kebab-case")]
423struct HashFlags {
424    /// Generate a random hash.
425    #[arg(long)]
426    random: bool,
427    /// When generating a random hash, generate the given number of hashes.
428    #[arg(long)]
429    count: Option<usize>,
430    /// Items to generate hashes for.
431    item: Vec<String>,
432}
433
434enum AssetKind {
435    Bin,
436    Lib,
437    Test,
438    Bench,
439}
440
441trait CommandBase {
442    /// Test if the command should perform a debug build by default.
443    #[inline]
444    fn is_debug(&self) -> bool {
445        false
446    }
447
448    /// Test if the command should acquire workspace assets for the given asset kind.
449    #[inline]
450    fn is_workspace(&self, _: AssetKind) -> bool {
451        false
452    }
453
454    /// Describe the current command.
455    #[inline]
456    fn describe(&self) -> &str {
457        "Running"
458    }
459
460    /// Propagate related flags from command and config.
461    #[inline]
462    fn propagate(&mut self, _: &mut Config, _: &mut SharedFlags) {}
463
464    /// Extra paths to run.
465    #[inline]
466    fn paths(&self) -> &[PathBuf] {
467        &[]
468    }
469}
470
471#[derive(Subcommand, Debug)]
472enum Command {
473    /// Run checks but do not execute
474    Check(CommandShared<check::Flags>),
475    /// Build documentation.
476    Doc(CommandShared<doc::Flags>),
477    /// Build ace autocompletion.
478    Ace(CommandShared<ace::Flags>),
479    /// Run all tests but do not execute
480    Test(CommandShared<tests::Flags>),
481    /// Run the given program as a benchmark
482    Bench(CommandShared<benches::Flags>),
483    /// Run the designated script
484    Run(CommandShared<run::Flags>),
485    /// Format the provided file
486    Fmt(CommandShared<format::Flags>),
487    /// Run a language server.
488    LanguageServer(SharedFlags),
489    /// Helper command to generate type hashes.
490    Hash(HashFlags),
491}
492
493impl Command {
494    const ALL: [&'static str; 9] = [
495        "check",
496        "doc",
497        "ace",
498        "test",
499        "bench",
500        "run",
501        "fmt",
502        "language-server",
503        "hash",
504    ];
505
506    fn as_command_base_mut(&mut self) -> Option<(&mut SharedFlags, &mut dyn CommandBase)> {
507        let (shared, command): (_, &mut dyn CommandBase) = match self {
508            Command::Check(shared) => (&mut shared.shared, &mut shared.command),
509            Command::Doc(shared) => (&mut shared.shared, &mut shared.command),
510            Command::Ace(shared) => (&mut shared.shared, &mut shared.command),
511            Command::Test(shared) => (&mut shared.shared, &mut shared.command),
512            Command::Bench(shared) => (&mut shared.shared, &mut shared.command),
513            Command::Run(shared) => (&mut shared.shared, &mut shared.command),
514            Command::Fmt(shared) => (&mut shared.shared, &mut shared.command),
515            Command::LanguageServer(..) => return None,
516            Command::Hash(..) => return None,
517        };
518
519        Some((shared, command))
520    }
521
522    fn as_command_shared_ref(&self) -> Option<CommandSharedRef<'_>> {
523        let (shared, command): (_, &dyn CommandBase) = match self {
524            Command::Check(shared) => (&shared.shared, &shared.command),
525            Command::Doc(shared) => (&shared.shared, &shared.command),
526            Command::Ace(shared) => (&shared.shared, &shared.command),
527            Command::Test(shared) => (&shared.shared, &shared.command),
528            Command::Bench(shared) => (&shared.shared, &shared.command),
529            Command::Run(shared) => (&shared.shared, &shared.command),
530            Command::Fmt(shared) => (&shared.shared, &shared.command),
531            Command::LanguageServer(..) => return None,
532            Command::Hash(..) => return None,
533        };
534
535        Some(CommandSharedRef { shared, command })
536    }
537}
538
539enum BuildPath<'a> {
540    /// A plain path entry.
541    Path(&'a Path, bool),
542    /// An entry from the specified package.
543    Package(workspace::FoundPackage<'a>),
544}
545
546#[derive(Default)]
547struct Config {
548    /// Whether the touput has been filtered at all.
549    filtered: bool,
550    /// Whether or not the test module should be included.
551    test: bool,
552    /// Whether or not to use verbose output.
553    verbose: bool,
554    /// Always include all targets.
555    all_targets: bool,
556    /// Manifest root directory.
557    manifest_root: Option<PathBuf>,
558}
559
560#[derive(Default)]
561struct Inputs {
562    /// Loaded build manifest.
563    manifest: workspace::Manifest,
564    /// Immediate found paths.
565    found_paths: alloc::Vec<(PathBuf, bool)>,
566}
567
568impl Inputs {
569    /// Construct build paths from configuration.
570    fn build_paths<'m>(
571        &'m self,
572        cmd: CommandSharedRef<'_>,
573        c: &mut Config,
574    ) -> Result<alloc::Vec<BuildPath<'m>>> {
575        let mut build_paths = alloc::Vec::new();
576
577        if !self.found_paths.is_empty() {
578            build_paths.try_extend(self.found_paths.iter().map(|(p, e)| BuildPath::Path(p, *e)))?;
579
580            if !cmd.shared.workspace {
581                return Ok(build_paths);
582            }
583        }
584
585        if let Some(filter) = cmd.find_bins(c.all_targets) {
586            c.filtered |= !matches!(filter, WorkspaceFilter::All);
587
588            for p in self.manifest.find_by_kind(filter, FoundKind::Binary)? {
589                build_paths.try_push(BuildPath::Package(p))?;
590            }
591        }
592
593        if let Some(filter) = cmd.find_libs(c.all_targets) {
594            c.filtered |= !matches!(filter, WorkspaceFilter::All);
595
596            for p in self.manifest.find_by_kind(filter, FoundKind::Library)? {
597                build_paths.try_push(BuildPath::Package(p))?;
598            }
599        }
600
601        if let Some(filter) = cmd.find_tests(c.all_targets) {
602            c.filtered |= !matches!(filter, WorkspaceFilter::All);
603
604            for p in self.manifest.find_by_kind(filter, FoundKind::Test)? {
605                build_paths.try_push(BuildPath::Package(p))?;
606            }
607        }
608
609        if let Some(filter) = cmd.find_examples(c.all_targets) {
610            c.filtered |= !matches!(filter, WorkspaceFilter::All);
611
612            for p in self.manifest.find_by_kind(filter, FoundKind::Example)? {
613                build_paths.try_push(BuildPath::Package(p))?;
614            }
615        }
616
617        if let Some(filter) = cmd.find_benches(c.all_targets) {
618            c.filtered |= !matches!(filter, WorkspaceFilter::All);
619
620            for p in self.manifest.find_by_kind(filter, FoundKind::Bench)? {
621                build_paths.try_push(BuildPath::Package(p))?;
622            }
623        }
624
625        if let Some(package) = &cmd.shared.package {
626            build_paths.retain(|path| match path {
627                BuildPath::Path(_, _) => true,
628                BuildPath::Package(found_package) => found_package.package.name.as_str() == package,
629            })
630        }
631
632        Ok(build_paths)
633    }
634}
635
636impl SharedFlags {
637    /// Setup build context.
638    fn context(
639        &self,
640        entry: &mut Entry<'_>,
641        c: &Config,
642        capture: Option<&CaptureIo>,
643    ) -> Result<Context> {
644        let opts = ContextOptions {
645            capture,
646            test: c.test,
647        };
648
649        let mut context =
650            entry
651                .context
652                .as_mut()
653                .context("Context builder not configured with Entry::context")?(opts)?;
654
655        if let Some(capture) = capture {
656            context.install(crate::modules::capture_io::module(capture)?)?;
657        }
658
659        Ok(context)
660    }
661}
662
663#[derive(Default, Debug, Clone, Copy, ValueEnum)]
664enum ColorArgument {
665    #[default]
666    /// Automatically enable coloring if the output is a terminal.
667    Auto,
668    /// Force ANSI coloring.
669    Ansi,
670    /// Always color using the platform-specific coloring implementation.
671    Always,
672    /// Never color output.
673    Never,
674}
675
676#[derive(Parser, Debug)]
677#[command(name = "rune", about = None)]
678struct Args {
679    /// Print the version of the command.
680    #[arg(long)]
681    version: bool,
682
683    /// Control if output is colored or not.
684    #[arg(short = 'C', long, default_value = "auto")]
685    color: ColorArgument,
686
687    /// The command to execute
688    #[command(subcommand)]
689    cmd: Option<Command>,
690}
691
692#[derive(Parser, Debug, Clone)]
693#[command(rename_all = "kebab-case")]
694struct SharedFlags {
695    /// Recursively load all files if a specified build `<path>` is a directory.
696    #[arg(long, short = 'R')]
697    recursive: bool,
698
699    /// Display warnings.
700    #[arg(long)]
701    warnings: bool,
702
703    /// Display verbose output.
704    #[arg(long)]
705    verbose: bool,
706
707    /// Collect sources to operate over from the workspace.
708    ///
709    /// This is what happens by default, but is disabled in case any `<paths>`
710    /// are specified.
711    #[arg(long)]
712    workspace: bool,
713
714    /// Set the given compiler option (see `--list-options` for available options).
715    #[arg(short = 'O', num_args = 1)]
716    compiler_option: Vec<String>,
717
718    /// List available compiler options.
719    #[arg(long)]
720    list_options: bool,
721
722    /// Run with the following binary from a loaded manifest. This requires a
723    /// `Rune.toml` manifest.
724    #[arg(long)]
725    bin: Option<String>,
726
727    /// Run with the following library from a loaded manifest. This requires a
728    /// `Rune.toml` manifest.
729    #[arg(long)]
730    lib: Option<String>,
731
732    /// Run with the following test from a loaded manifest. This requires a
733    /// `Rune.toml` manifest.
734    #[arg(long)]
735    test: Option<String>,
736
737    /// Run with the following example from a loaded manifest. This requires a
738    /// `Rune.toml` manifest.
739    #[arg(long)]
740    example: Option<String>,
741
742    /// Run with the following benchmark by name from a loaded manifest. This
743    /// requires a `Rune.toml` manifest.
744    #[arg(long)]
745    bench: Option<String>,
746
747    /// Only include targets from the given package.
748    /// This requires a `Rune.toml` workspace manifest.
749    #[arg(long, short = 'p')]
750    package: Option<String>,
751
752    /// Include all targets, and not just the ones which are default for the
753    /// current command.
754    #[arg(long)]
755    all_targets: bool,
756
757    /// Build paths to include in the command.
758    ///
759    /// By default, the tool searches for:
760    ///
761    /// * A `Rune.toml` file in a parent directory, in which case this treated
762    ///   as a workspace.
763    ///
764    /// * In order: `main.rn`, `lib.rn`, `src/main.rn`, `src/lib.rn`,
765    ///   `script/main.rn`, and `script/lib.rn`.
766    #[arg(long)]
767    path: Vec<PathBuf>,
768}
769
770impl SharedFlags {
771    fn is_unfiltered(&self) -> bool {
772        self.bin.is_none()
773            && self.test.is_none()
774            && self.example.is_none()
775            && self.bench.is_none()
776            && self.path.is_empty()
777    }
778}
779
780const SPECIAL_FILES: &[&str] = &[
781    "main.rn",
782    "lib.rn",
783    "src/main.rn",
784    "src/lib.rn",
785    "script/main.rn",
786    "script/lib.rn",
787];
788
789// Our own private ExitCode since std::process::ExitCode is nightly only. Note
790// that these numbers are actually meaningful on Windows, but we don't care.
791#[repr(i32)]
792enum ExitCode {
793    Success = 0,
794    Failure = 1,
795    VmError = 2,
796}
797
798/// Format the given error.
799fn format_errors<O>(o: &mut O, error: &Error) -> io::Result<()>
800where
801    O: ?Sized + io::Write,
802{
803    writeln!(o, "Error: {error}")?;
804
805    for error in error.chain().skip(1) {
806        writeln!(o, "Caused by: {error}")?;
807    }
808
809    Ok(())
810}
811
812fn find_manifest() -> Option<(PathBuf, PathBuf)> {
813    let mut path = PathBuf::new();
814
815    loop {
816        let manifest_path = path.join(workspace::MANIFEST_FILE);
817
818        if manifest_path.is_file() {
819            return Some((path, manifest_path));
820        }
821
822        path.push("..");
823
824        if !path.is_dir() {
825            return None;
826        }
827    }
828}
829
830fn populate_config(
831    io: &mut Io<'_>,
832    c: &mut Config,
833    inputs: &mut Inputs,
834    cmd: CommandSharedRef<'_>,
835) -> Result<()> {
836    c.all_targets = cmd.shared.all_targets;
837
838    inputs
839        .found_paths
840        .try_extend(cmd.shared.path.iter().map(|p| (p.clone(), false)))?;
841
842    inputs
843        .found_paths
844        .try_extend(cmd.command.paths().iter().map(|p| (p.clone(), true)))?;
845
846    if !inputs.found_paths.is_empty() && !cmd.shared.workspace {
847        return Ok(());
848    }
849
850    let Some((manifest_root, manifest_path)) = find_manifest() else {
851        for file in SPECIAL_FILES {
852            let path = Path::new(file);
853
854            if path.is_file() {
855                inputs.found_paths.try_push((path.try_to_owned()?, false))?;
856                return Ok(());
857            }
858        }
859
860        let special = SPECIAL_FILES.join(", ");
861
862        bail!(
863            "Could not find `{}` in this or parent directories nor any of the special files: {special}",
864            workspace::MANIFEST_FILE
865        )
866    };
867
868    // When building or running a workspace we need to be more verbose so that
869    // users understand what exactly happens.
870    c.verbose = true;
871    c.manifest_root = Some(manifest_root);
872
873    let mut sources = crate::Sources::new();
874    sources.insert(crate::Source::from_path(manifest_path)?)?;
875
876    let mut diagnostics = workspace::Diagnostics::new();
877
878    let result = workspace::prepare(&mut sources)
879        .with_diagnostics(&mut diagnostics)
880        .build();
881
882    diagnostics.emit(io.stdout, &sources)?;
883    inputs.manifest = result?;
884    Ok(())
885}
886
887async fn main_with_out(io: &mut Io<'_>, entry: &mut Entry<'_>, mut args: Args) -> Result<ExitCode> {
888    let mut c = Config::default();
889    let mut inputs = Inputs::default();
890
891    if let Some((shared, base)) = args.cmd.as_mut().and_then(|c| c.as_command_base_mut()) {
892        base.propagate(&mut c, shared);
893    }
894
895    let Some(cmd) = &args.cmd else {
896        let commands: alloc::String = Command::ALL.into_iter().try_join(", ")?;
897        writeln!(io.stdout, "Expected a subcommand: {commands}")?;
898        return Ok(ExitCode::Failure);
899    };
900
901    let mut entries = alloc::Vec::new();
902
903    if let Some(cmd) = cmd.as_command_shared_ref() {
904        if cmd.shared.list_options {
905            writeln!(
906                io.stdout,
907                "Available compiler options (set with -O <option>=<value>):"
908            )?;
909            writeln!(io.stdout)?;
910
911            for (i, option) in Options::available().iter().enumerate() {
912                if i > 0 {
913                    writeln!(io.stdout)?;
914                }
915
916                io.write(
917                    format_args!("{}", option.key),
918                    Stream::Stdout,
919                    Color::Highlight,
920                )?;
921
922                write!(io.stdout, "={}", option.default)?;
923
924                if option.unstable {
925                    io.write(" (unstable)", Stream::Stdout, Color::Error)?;
926                }
927
928                writeln!(io.stdout, ":")?;
929                writeln!(io.stdout, "    Options: {}", option.options)?;
930                writeln!(io.stdout)?;
931
932                for &line in option.doc {
933                    let line = line.strip_prefix(' ').unwrap_or(line);
934                    writeln!(io.stdout, "    {line}")?;
935                }
936            }
937
938            return Ok(ExitCode::Success);
939        }
940
941        populate_config(io, &mut c, &mut inputs, cmd)?;
942
943        let build_paths = inputs.build_paths(cmd, &mut c)?;
944
945        let what = cmd.command.describe();
946        let verbose = c.verbose;
947        let recursive = cmd.shared.recursive;
948
949        for build_path in build_paths {
950            match build_path {
951                BuildPath::Path(path, explicit) => {
952                    for path in loader::recurse_paths(recursive, path.try_to_owned()?) {
953                        entries.try_push(EntryPoint::Path(path?, explicit))?;
954                    }
955                }
956                BuildPath::Package(p) => {
957                    if verbose {
958                        let mut section = io.section(what, Stream::Stderr, Color::Highlight)?;
959
960                        section.append(format_args!(
961                            " {} `{}` (from {})",
962                            p.found.kind,
963                            p.found.path.display(),
964                            p.package.name
965                        ))?;
966
967                        section.close()?;
968                    }
969
970                    entries.try_push(EntryPoint::Package(p))?;
971                }
972            }
973        }
974    }
975
976    match run_path(io, &c, cmd, entry, entries).await? {
977        ExitCode::Success => (),
978        other => {
979            return Ok(other);
980        }
981    }
982
983    Ok(ExitCode::Success)
984}
985
986/// Run a single path.
987async fn run_path<'p, I>(
988    io: &mut Io<'_>,
989    c: &Config,
990    cmd: &Command,
991    entry: &mut Entry<'_>,
992    entries: I,
993) -> Result<ExitCode>
994where
995    I: IntoIterator<Item = EntryPoint<'p>>,
996{
997    match cmd {
998        Command::Check(f) => {
999            let options = f.options()?;
1000
1001            for e in entries {
1002                let mut options = options.clone();
1003
1004                if e.is_argument() {
1005                    options.script = true;
1006                }
1007
1008                match check::run(
1009                    io,
1010                    entry,
1011                    c,
1012                    &f.command,
1013                    &f.shared,
1014                    &options,
1015                    e.path(),
1016                    e.declarations(),
1017                )? {
1018                    ExitCode::Success => (),
1019                    other => return Ok(other),
1020                }
1021            }
1022        }
1023        Command::Doc(f) => {
1024            let options = f.options()?;
1025            return doc::run(io, entry, c, &f.command, &f.shared, &options, entries);
1026        }
1027        Command::Ace(f) => {
1028            let options = f.options()?;
1029            return ace::run(io, entry, c, &f.command, &f.shared, &options, entries);
1030        }
1031        Command::Fmt(f) => {
1032            let options = f.options()?;
1033            return format::run(io, entry, c, entries, &f.command, &f.shared, &options);
1034        }
1035        Command::Test(f) => {
1036            let options = f.options()?;
1037
1038            match tests::run(io, c, &f.command, &f.shared, &options, entry, entries).await? {
1039                ExitCode::Success => (),
1040                other => return Ok(other),
1041            }
1042        }
1043        Command::Bench(f) => {
1044            let options = f.options()?;
1045
1046            for e in entries {
1047                let mut options = options.clone();
1048
1049                if e.is_argument() {
1050                    options.script = true;
1051                }
1052
1053                let capture_io = crate::modules::capture_io::CaptureIo::new();
1054                let context = f.shared.context(entry, c, Some(&capture_io))?;
1055
1056                let load = loader::load(
1057                    io,
1058                    &context,
1059                    &f.shared,
1060                    &options,
1061                    e.path(),
1062                    e.declarations(),
1063                    visitor::Attribute::Bench,
1064                )?;
1065
1066                match benches::run(
1067                    io,
1068                    &f.command,
1069                    &context,
1070                    Some(&capture_io),
1071                    load.unit,
1072                    &load.sources,
1073                    &load.functions,
1074                )
1075                .await?
1076                {
1077                    ExitCode::Success => (),
1078                    other => return Ok(other),
1079                }
1080            }
1081        }
1082        Command::Run(f) => {
1083            let options = f.options()?;
1084            let context = f.shared.context(entry, c, None)?;
1085
1086            for e in entries {
1087                let mut options = options.clone();
1088
1089                if e.is_argument() {
1090                    options.script = true;
1091                }
1092
1093                let load = loader::load(
1094                    io,
1095                    &context,
1096                    &f.shared,
1097                    &options,
1098                    e.path(),
1099                    e.declarations(),
1100                    visitor::Attribute::None,
1101                )?;
1102
1103                let main = Hash::type_hash(["main"]);
1104
1105                let entry = if e.is_argument() {
1106                    // A path given as an argument is compiled as a script, so
1107                    // what runs is its top level. A file which only declares
1108                    // `main` has nothing at its top level, so running it did
1109                    // nothing at all and reported success - and that is what
1110                    // every example the book says to run this way looks like.
1111                    if load.unit.function(&main).is_some() {
1112                        main
1113                    } else {
1114                        Hash::EMPTY
1115                    }
1116                } else {
1117                    main
1118                };
1119
1120                match run::run(io, c, &f.command, &context, load.unit, &load.sources, entry).await?
1121                {
1122                    ExitCode::Success => (),
1123                    other => return Ok(other),
1124                }
1125            }
1126        }
1127        Command::LanguageServer(shared) => {
1128            let context = shared.context(entry, c, None)?;
1129            languageserver::run(context).await?;
1130        }
1131        Command::Hash(args) => {
1132            use rand::prelude::*;
1133
1134            if args.random {
1135                let mut rand = rand::rng();
1136
1137                for _ in 0..args.count.unwrap_or(1) {
1138                    writeln!(io.stdout, "{}", Hash::new(rand.random::<u64>()))?;
1139                }
1140            }
1141
1142            for item in &args.item {
1143                let item: ItemBuf = item.parse()?;
1144                let hash = Hash::type_hash(&item);
1145                writeln!(io.stdout, "{item} => {hash}")?;
1146            }
1147        }
1148    }
1149
1150    Ok(ExitCode::Success)
1151}
1152
1153/// Insert the declaration sources at `paths` into `sources`.
1154fn insert_declarations(sources: &mut Sources, paths: &[PathBuf]) -> Result<()> {
1155    for path in paths {
1156        let source = Source::from_path(path)
1157            .with_context(|| format!("reading declaration source: {}", path.display()))?;
1158        sources.insert(source)?;
1159    }
1160
1161    Ok(())
1162}