midenc-compile 0.8.1

The compiler frontend for Miden
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
#[cfg(feature = "std")]
use alloc::{borrow::ToOwned, format, string::ToString, vec};
use alloc::{string::String, sync::Arc, vec::Vec};
#[cfg(feature = "std")]
use std::ffi::OsString;

#[cfg(feature = "std")]
use clap::{Parser, builder::ArgPredicate};
use midenc_session::{
    ColorChoice, DebugInfo, InputFile, IrFilter, LinkLibrary, OptLevel, Options, OutputFile,
    OutputType, OutputTypeSpec, OutputTypes, Path, PathBuf, ProjectType, Session, TargetEnv,
    Verbosity, Warnings, add_target_link_libraries,
    diagnostics::{DefaultSourceManager, Emitter},
};

/// Compile a program from WebAssembly or Miden IR, to Miden Assembly.
#[derive(Debug)]
#[cfg_attr(feature = "std", derive(Parser))]
#[cfg_attr(feature = "std", command(name = "midenc"))]
pub struct Compiler {
    /// Write all intermediate compiler artifacts to `<dir>`
    ///
    /// Defaults to a directory named `target/midenc` in the current working directory
    #[cfg_attr(
        feature = "std",
        arg(
            long,
            value_name = "DIR",
            env = "MIDENC_TARGET_DIR",
            default_value = "target/midenc",
            help_heading = "Output"
        )
    )]
    pub target_dir: PathBuf,
    /// The working directory for the compiler
    ///
    /// By default this will be the working directory the compiler is executed from
    #[cfg_attr(
        feature = "std",
        arg(long, value_name = "DIR", help_heading = "Output")
    )]
    pub working_dir: Option<PathBuf>,
    /// The path to the root directory of the Miden toolchain libraries
    ///
    /// By default this is assumed to be `~/.miden/toolchains/<version>`
    #[cfg_attr(
        feature = "std",
        arg(
            long,
            value_name = "DIR",
            env = "MIDENC_SYSROOT",
            help_heading = "Compiler"
        )
    )]
    pub sysroot: Option<PathBuf>,
    /// Write compiled output to compiler-chosen filename in `<dir>`
    #[cfg_attr(
        feature = "std",
        arg(
            long,
            short = 'O',
            value_name = "DIR",
            env = "MIDENC_OUT_DIR",
            help_heading = "Output"
        )
    )]
    pub output_dir: Option<PathBuf>,
    /// Write compiled output to `<filename>`
    #[cfg_attr(
        feature = "std",
        arg(long, short = 'o', value_name = "FILENAME", help_heading = "Output")
    )]
    pub output_file: Option<PathBuf>,
    /// Write output to stdout
    #[cfg_attr(
        feature = "std",
        arg(long, conflicts_with("output_file"), help_heading = "Output")
    )]
    pub stdout: bool,
    /// Specify the name of the project being compiled
    ///
    /// The default is derived from the name of the first input file, or if reading from stdin,
    /// the base name of the working directory.
    #[cfg_attr(feature = "std", arg(
        long,
        short = 'n',
        value_name = "NAME",
        default_value = None,
        help_heading = "Diagnostics"
    ))]
    pub name: Option<String>,
    /// Specify what type and level of informational output to emit
    #[cfg_attr(feature = "std", arg(
        long = "verbose",
        short = 'v',
        value_enum,
        value_name = "LEVEL",
        default_value_t = Verbosity::Info,
        default_missing_value = "debug",
        num_args(0..=1),
        help_heading = "Diagnostics"
    ))]
    pub verbosity: Verbosity,
    /// Specify how warnings should be treated by the compiler.
    #[cfg_attr(feature = "std", arg(
        long,
        short = 'W',
        value_enum,
        value_name = "LEVEL",
        default_value_t = Warnings::All,
        default_missing_value = "all",
        num_args(0..=1),
        help_heading = "Diagnostics"
    ))]
    pub warn: Warnings,
    /// Whether, and how, to color terminal output
    #[cfg_attr(feature = "std", arg(
        long,
        value_enum,
        default_value_t = ColorChoice::Auto,
        default_missing_value = "auto",
        num_args(0..=1),
        help_heading = "Diagnostics"
    ))]
    pub color: ColorChoice,
    /// The target environment to compile for
    #[cfg_attr(feature = "std", arg(
        long,
        value_name = "TARGET",
        default_value_t = TargetEnv::Base,
        help_heading = "Compiler"
    ))]
    pub target: TargetEnv,
    /// Specify the function to call as the entrypoint for the program
    /// in the format `<module_name>::<function>`
    #[cfg_attr(feature = "std", arg(long, help_heading = "Compiler", hide(true)))]
    pub entrypoint: Option<String>,
    /// Tells the compiler to produce an executable Miden program
    ///
    /// Implied by `--entrypoint`, defaults to true for non-rollup targets.
    #[cfg_attr(feature = "std", arg(
        long = "exe",
        default_value_t = true,
        default_value_ifs([
            // When targeting the rollup, never build an executable
            ("target", "rollup".into(), Some("false")),
            // Setting the entrypoint implies building an executable in all other cases
            ("entrypoint", ArgPredicate::IsPresent, Some("true")),
        ]),
        help_heading = "Linker"
    ))]
    pub is_program: bool,
    /// Tells the compiler to produce a Miden library
    ///
    /// Implied by `--target rollup`, defaults to false.
    #[cfg_attr(feature = "std", arg(
        long = "lib",
        conflicts_with("is_program"),
        conflicts_with("entrypoint"),
        default_value_t = false,
        default_value_ifs([
            // When an entrypoint is specified, always set the default to false
            ("entrypoint", ArgPredicate::IsPresent, Some("false")),
            // When targeting the rollup, we always build as a library
            ("target", "rollup".into(), Some("true")),
        ]),
        help_heading = "Linker"
    ))]
    pub is_library: bool,
    /// Specify one or more search paths for link libraries requested via `-l`
    #[cfg_attr(
        feature = "std",
        arg(
            long = "search-path",
            short = 'L',
            value_name = "PATH",
            help_heading = "Linker"
        )
    )]
    pub search_path: Vec<PathBuf>,
    /// Link compiled projects to the specified library NAME.
    ///
    /// The optional KIND can be provided to indicate what type of library it is.
    ///
    /// NAME must either be an absolute path (with extension when applicable), or
    /// a library namespace (no extension). The former will be used as the path
    /// to load the library, without looking for it in the library search paths,
    /// while the latter will be located in the search path based on its KIND.
    ///
    /// See below for valid KINDs:
    #[cfg_attr(
        feature = "std",
        arg(
            long = "link-library",
            short = 'l',
            value_name = "[KIND=]NAME",
            value_delimiter = ',',
            next_line_help(true),
            help_heading = "Linker"
        )
    )]
    pub link_libraries: Vec<LinkLibrary>,
    /// Specify one or more output types for the compiler to emit
    ///
    /// The format for SPEC is `KIND[=PATH]`. You can specify multiple items at
    /// once by separating each SPEC with a comma, you can also pass this flag
    /// multiple times.
    ///
    /// PATH must be a directory in which to place the outputs, or `-` for stdout.
    #[cfg_attr(
        feature = "std",
        arg(
            long = "emit",
            value_name = "SPEC",
            value_delimiter = ',',
            env = "MIDENC_EMIT",
            next_line_help(true),
            help_heading = "Output"
        )
    )]
    pub output_types: Vec<OutputTypeSpec>,
    /// Specify what level of debug information to emit in compilation artifacts
    #[cfg_attr(feature = "std", arg(
        long,
        value_enum,
        value_name = "LEVEL",
        next_line_help(true),
        default_value_t = DebugInfo::Full,
        default_missing_value = "full",
        num_args(0..=1),
        help_heading = "Output"
    ))]
    pub debug: DebugInfo,
    /// Specify what type, and to what degree, of optimizations to apply to code during
    /// compilation.
    #[cfg_attr(feature = "std", arg(
        long = "optimize",
        value_enum,
        value_name = "LEVEL",
        next_line_help(true),
        default_value_t = OptLevel::None,
        default_missing_value = "balanced",
        num_args(0..=1),
        help_heading = "Output"
    ))]
    pub opt_level: OptLevel,
    /// Set a codegen option
    ///
    /// Use `-C help` to print available options
    #[cfg_attr(
        feature = "std",
        arg(
            long,
            short = 'C',
            value_name = "OPT[=VALUE]",
            help_heading = "Compiler"
        )
    )]
    pub codegen: Vec<String>,
    /// Set an unstable compiler option
    ///
    /// Use `-Z help` to print available options
    #[cfg_attr(
        feature = "std",
        arg(
            long,
            short = 'Z',
            value_name = "OPT[=VALUE]",
            help_heading = "Compiler"
        )
    )]
    pub unstable: Vec<String>,

    // The following options are primarily used by `cargo miden build` to pass through
    // familiar Cargo options. They are hidden from `midenc --help` output.
    /// Build in release mode (used by cargo miden build)
    #[cfg_attr(feature = "std", arg(long, hide = true, default_value_t = false))]
    pub release: bool,
    /// Path to Cargo.toml (used by cargo miden build)
    #[cfg_attr(feature = "std", arg(long, value_name = "PATH", hide = true))]
    pub manifest_path: Option<PathBuf>,
    /// Build all packages in the workspace (used by cargo miden build)
    #[cfg_attr(feature = "std", arg(long, hide = true, default_value_t = false))]
    pub workspace: bool,
    /// Package(s) to build (used by cargo miden build)
    #[cfg_attr(feature = "std", arg(long, value_name = "SPEC", hide = true))]
    pub package: Vec<String>,
}

#[derive(Default, Debug, Clone)]
#[cfg_attr(feature = "std", derive(Parser))]
#[cfg_attr(feature = "std", command(name = "-C"))]
pub struct CodegenOptions {
    /// Tell the compiler to exit after it has parsed the inputs
    #[cfg_attr(feature = "std", arg(
        long,
        conflicts_with_all(["analyze_only", "link_only"]),
        default_value_t = false,
    ))]
    pub parse_only: bool,
    /// Tell the compiler to exit after it has performed semantic analysis on the inputs
    #[cfg_attr(feature = "std", arg(
        long,
        conflicts_with_all(["parse_only", "link_only"]),
        default_value_t = false,
    ))]
    pub analyze_only: bool,
    /// Tell the compiler to exit after linking the inputs, without generating Miden Assembly
    #[cfg_attr(feature = "std", arg(
        long,
        conflicts_with_all(["no_link"]),
        default_value_t = false,
    ))]
    pub link_only: bool,
    /// Tell the compiler to generate Miden Assembly from the inputs without linking them
    #[cfg_attr(feature = "std", arg(long, default_value_t = false))]
    pub no_link: bool,
}

#[derive(Default, Debug, Clone)]
#[cfg_attr(feature = "std", derive(Parser))]
#[cfg_attr(feature = "std", command(name = "-Z"))]
pub struct UnstableOptions {
    /// Print the CFG after each HIR pass is applied
    #[cfg_attr(
        feature = "std",
        arg(long, default_value_t = false, help_heading = "Passes")
    )]
    pub print_cfg_after_all: bool,
    /// Print the CFG after running a specific HIR pass
    #[cfg_attr(
        feature = "std",
        arg(
            long,
            value_name = "PASS",
            value_delimiter = ',',
            help_heading = "Passes"
        )
    )]
    pub print_cfg_after_pass: Vec<String>,
    /// Print the IR before each compiler stage.
    ///
    /// The available stages are:
    ///
    /// * `link`     - performs initial translation to HIR, and links dependencies into the graph
    ///
    /// * `rewrite`  - performs rewrites/optimizations on the initial unmodified HIR
    ///
    /// * `codegen`  - performs lowering from HIR to Miden Assembly
    ///
    /// * `assemble` - performs assembly of a program or library package
    #[cfg_attr(
        feature = "std",
        arg(
            long,
            value_name = "STAGE",
            value_delimiter = ',',
            next_line_help(true),
            help_heading = "Passes"
        )
    )]
    pub print_ir_before_stage: Vec<String>,
    /// Print the IR after each pass is applied
    #[cfg_attr(
        feature = "std",
        arg(long, default_value_t = false, help_heading = "Passes")
    )]
    pub print_ir_after_all: bool,
    /// Print the IR after running a specific pass
    #[cfg_attr(
        feature = "std",
        arg(
            long,
            value_name = "PASS",
            value_delimiter = ',',
            help_heading = "Passes"
        )
    )]
    pub print_ir_after_pass: Vec<String>,
    /// Only print the IR if the pass modified the IR structure. If this flag is set, and no IR
    /// filter flag is; then the default behavior is to print the IR after every pass.
    #[cfg_attr(
        feature = "std",
        arg(long, default_value_t = false, help_heading = "Passes")
    )]
    pub print_ir_after_modified: bool,
    /// Only print IR that matches the given filter.
    ///
    /// The syntax for filters are as follows:
    ///
    /// * `any` (default)         - matches any operation
    ///
    /// * `symbol:*`              - matches any symbol
    ///
    /// * `symbol:<pattern>`      - matches any symbol whose name contains <pattern>
    ///
    /// * `op:<dialect>.<opcode>` - matches any instance of the given operation name
    #[cfg_attr(
        feature = "std",
        arg(
            long,
            action = clap::ArgAction::Append,
            value_name = "FILTER",
            value_delimiter = ',',
            next_line_help(true),
            help_heading = "Passes"
        )
    )]
    pub print_ir_filter: Vec<IrFilter>,
    /// Print source location information in HIR output
    ///
    /// When enabled, HIR output will include #loc() annotations showing the source file,
    /// line, and column for each operation.
    #[cfg_attr(
        feature = "std",
        arg(
            long = "print-hir-source-locations",
            default_value_t = false,
            help_heading = "Printers"
        )
    )]
    pub print_hir_source_locations: bool,
    /// Specify path prefixes to try when resolving relative paths from DWARF debug info
    #[cfg_attr(
        feature = "std",
        arg(
            long = "trim-path-prefix",
            value_name = "PATH",
            help_heading = "Debugging"
        )
    )]
    pub trim_path_prefixes: Vec<PathBuf>,
}

impl CodegenOptions {
    #[cfg(feature = "std")]
    fn parse_argv(argv: Vec<String>) -> Self {
        let command = <CodegenOptions as clap::CommandFactory>::command()
            .no_binary_name(true)
            .arg_required_else_help(false)
            .help_template(
                "\
Available codegen options:

Usage: midenc -C <opt>

{all-args}{after-help}

NOTE: When specifying these options, strip the leading '--'",
            );

        let argv = if argv.iter().any(|arg| matches!(arg.as_str(), "--help" | "-h" | "help")) {
            vec!["--help".to_string()]
        } else {
            argv.into_iter()
                .flat_map(|arg| match arg.split_once('=') {
                    None => vec![format!("--{arg}")],
                    Some((opt, value)) => {
                        vec![format!("--{opt}"), value.to_string()]
                    }
                })
                .collect::<Vec<_>>()
        };

        let mut matches = command.try_get_matches_from(argv).unwrap_or_else(|err| err.exit());
        <CodegenOptions as clap::FromArgMatches>::from_arg_matches_mut(&mut matches)
            .map_err(format_error::<CodegenOptions>)
            .unwrap_or_else(|err| err.exit())
    }

    #[cfg(not(feature = "std"))]
    fn parse_argv(_argv: Vec<String>) -> Self {
        Self::default()
    }
}

impl UnstableOptions {
    #[cfg(feature = "std")]
    fn parse_argv(argv: Vec<String>) -> Self {
        let command = <UnstableOptions as clap::CommandFactory>::command()
            .no_binary_name(true)
            .arg_required_else_help(false)
            .help_template(
                "\
Available unstable options:

Usage: midenc -Z <opt>

{all-args}{after-help}

NOTE: When specifying these options, strip the leading '--'",
            );

        let argv = if argv.iter().any(|arg| matches!(arg.as_str(), "--help" | "-h" | "help")) {
            vec!["--help".to_string()]
        } else {
            argv.into_iter()
                .flat_map(|arg| match arg.split_once('=') {
                    None => vec![format!("--{arg}")],
                    Some((opt, value)) => {
                        vec![format!("--{opt}"), value.to_string()]
                    }
                })
                .collect::<Vec<_>>()
        };

        let mut matches = command.try_get_matches_from(argv).unwrap_or_else(|err| err.exit());
        <UnstableOptions as clap::FromArgMatches>::from_arg_matches_mut(&mut matches)
            .map_err(format_error::<UnstableOptions>)
            .unwrap_or_else(|err| err.exit())
    }

    #[cfg(not(feature = "std"))]
    fn parse_argv(_argv: Vec<String>) -> Self {
        Self::default()
    }
}

impl Compiler {
    /// Parse compiler options from command-line arguments.
    ///
    /// Returns the parsed options or an error if parsing failed.
    /// This is used by `cargo miden build` to parse all arguments into `Compiler`
    /// options before selectively forwarding them to `cargo build` and `midenc`.
    #[cfg(feature = "std")]
    pub fn try_parse_from<I, T>(iter: I) -> Result<Self, clap::Error>
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        let argv = [OsString::from("midenc")]
            .into_iter()
            .chain(iter.into_iter().map(|arg| arg.into()));
        let command = <Self as clap::CommandFactory>::command();
        let command = midenc_session::flags::register_flags(command);
        let mut matches = command.try_get_matches_from(argv)?;

        <Self as clap::FromArgMatches>::from_arg_matches_mut(&mut matches)
            .map_err(format_error::<Self>)
    }

    /// Construct a [Compiler] programatically
    #[cfg(feature = "std")]
    pub fn new_session<I, A, S>(inputs: I, emitter: Option<Arc<dyn Emitter>>, argv: A) -> Session
    where
        I: IntoIterator<Item = InputFile>,
        A: IntoIterator<Item = S>,
        S: Into<std::ffi::OsString> + Clone,
    {
        let argv = [OsString::from("midenc")]
            .into_iter()
            .chain(argv.into_iter().map(|arg| arg.into()));
        let command = <Self as clap::CommandFactory>::command();
        let command = midenc_session::flags::register_flags(command);
        let mut matches = command.try_get_matches_from(argv).unwrap_or_else(|err| err.exit());
        let compile_matches = matches.clone();

        let opts = <Self as clap::FromArgMatches>::from_arg_matches_mut(&mut matches)
            .map_err(format_error::<Self>)
            .unwrap_or_else(|err| err.exit());

        let inputs = inputs.into_iter().collect();
        opts.into_session(inputs, emitter).with_extra_flags(compile_matches.into())
    }

    /// Use this configuration to obtain a [Session] used for compilation
    pub fn into_session(
        self,
        inputs: Vec<InputFile>,
        emitter: Option<Arc<dyn Emitter>>,
    ) -> Session {
        let cwd = self.working_dir.unwrap_or_else(current_dir);

        log::trace!(target: "driver", "current working directory = {}", cwd.display());

        // Determine if a specific output file has been requested
        let output_file = match self.output_file {
            Some(path) => Some(OutputFile::Real(path)),
            None if self.stdout => Some(OutputFile::Stdout),
            None => None,
        };

        // Initialize output types
        let mut output_types = OutputTypes::new(self.output_types).unwrap_or_else(|err| err.exit());
        let has_final_output =
            output_types.keys().any(|ty| matches!(ty, OutputType::Mast | OutputType::Masp));
        if !has_final_output {
            // By default, we always produce a final artifact; `--emit` selects additional outputs.
            output_types.insert(OutputType::Masp, output_file.clone());
        } else if output_file.is_some() && output_types.get(&OutputType::Masp).is_some() {
            // The -o flag overrides --emit
            output_types.insert(OutputType::Masp, output_file.clone());
        }

        // Rollup note scripts and components are always packaged as libraries, even when the CLI
        // defaulted `--exe` before the target was resolved.
        let project_type = match self.target {
            TargetEnv::Rollup {
                target:
                    midenc_session::RollupTarget::Account
                    | midenc_session::RollupTarget::NoteScript
                    | midenc_session::RollupTarget::AuthComponent,
            } => ProjectType::Library,
            _ if self.is_program => ProjectType::Program,
            _ => ProjectType::Library,
        };

        let codegen = CodegenOptions::parse_argv(self.codegen);
        let unstable = UnstableOptions::parse_argv(self.unstable);

        // Consolidate all compiler options
        let mut options = Options::new(self.name, self.target, project_type, cwd, self.sysroot)
            .with_color(self.color)
            .with_verbosity(self.verbosity)
            .with_warnings(self.warn)
            .with_debug_info(self.debug)
            .with_optimization(self.opt_level)
            .with_output_types(output_types);
        options.search_paths = self.search_path;
        let link_libraries = add_target_link_libraries(self.link_libraries, &self.target);
        options.link_libraries = link_libraries;
        options.entrypoint = self.entrypoint;
        options.parse_only = codegen.parse_only;
        options.analyze_only = codegen.analyze_only;
        options.link_only = codegen.link_only;
        options.no_link = codegen.no_link;
        options.print_cfg_after_all = unstable.print_cfg_after_all;
        options.print_cfg_after_pass = unstable.print_cfg_after_pass;
        options.print_ir_after_all = unstable.print_ir_after_all;
        options.print_ir_after_pass = unstable.print_ir_after_pass;
        options.print_ir_after_modified = unstable.print_ir_after_modified;
        options.print_ir_filters = unstable.print_ir_filter;
        options.print_hir_source_locations = unstable.print_hir_source_locations;
        options.trim_path_prefixes = unstable.trim_path_prefixes;

        // Establish --target-dir
        let target_dir = if self.target_dir.is_absolute() {
            self.target_dir
        } else {
            options.current_dir.join(&self.target_dir)
        };
        create_target_dir(target_dir.as_path());

        // Raise an error if no inputs were provided
        if inputs.is_empty() {
            let cmd = <Compiler as clap::CommandFactory>::command();
            let mut err =
                clap::Error::new(clap::error::ErrorKind::MissingRequiredArgument).with_cmd(&cmd);
            err.insert(
                clap::error::ContextKind::InvalidArg,
                clap::error::ContextValue::String("INPUT".to_string()),
            );
            err.exit();
        }

        let source_manager = Arc::new(DefaultSourceManager::default());
        Session::new(
            inputs,
            self.output_dir,
            output_file,
            target_dir,
            options,
            emitter,
            source_manager,
        )
    }
}

#[cfg(feature = "std")]
fn format_error<I: clap::CommandFactory>(err: clap::Error) -> clap::Error {
    let mut cmd = I::command();
    err.format(&mut cmd)
}

#[cfg(feature = "std")]
fn current_dir() -> PathBuf {
    std::env::current_dir().expect("no working directory available")
}

#[cfg(not(feature = "std"))]
fn current_dir() -> PathBuf {
    <str as AsRef<Path>>::as_ref(".").to_path_buf()
}

#[cfg(feature = "std")]
fn create_target_dir(path: &Path) {
    std::fs::create_dir_all(path)
        .unwrap_or_else(|err| panic!("unable to create --target-dir '{}': {err}", path.display()));
}

#[cfg(not(feature = "std"))]
fn create_target_dir(_path: &Path) {}