solar_cli/
lib.rs

1#![doc = include_str!("../README.md")]
2#![doc(
3    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/solar/main/assets/logo.png",
4    html_favicon_url = "https://raw.githubusercontent.com/paradigmxyz/solar/main/assets/favicon.ico"
5)]
6#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
7
8use clap::Parser as _;
9use solar_config::{ErrorFormat, ImportRemapping};
10use solar_interface::{
11    diagnostics::{DiagCtxt, DynEmitter, HumanEmitter, JsonEmitter},
12    Result, Session, SourceMap,
13};
14use std::sync::Arc;
15
16pub use solar_config::{self as config, version, Opts, UnstableOpts};
17
18pub mod utils;
19
20#[cfg(all(unix, any(target_env = "gnu", target_os = "macos")))]
21pub mod sigsegv_handler;
22
23/// Signal handler to extract a backtrace from stack overflow.
24///
25/// This is a no-op because this platform doesn't support our signal handler's requirements.
26#[cfg(not(all(unix, any(target_env = "gnu", target_os = "macos"))))]
27pub mod sigsegv_handler {
28    #[cfg(unix)]
29    use libc as _;
30
31    /// No-op function.
32    pub fn install() {}
33}
34
35// `asm` feature.
36use alloy_primitives as _;
37
38use tracing as _;
39
40pub fn parse_args<I, T>(itr: I) -> Result<Opts, clap::Error>
41where
42    I: IntoIterator<Item = T>,
43    T: Into<std::ffi::OsString> + Clone,
44{
45    let mut opts = Opts::try_parse_from(itr)?;
46    opts.finish()?;
47    Ok(opts)
48}
49
50pub fn run_compiler_args(opts: Opts) -> Result<()> {
51    run_compiler_with(opts, Compiler::run_default)
52}
53
54pub struct Compiler {
55    pub sess: Session,
56}
57
58impl Compiler {
59    pub fn run_default(&self) -> Result<()> {
60        let Self { sess } = self;
61
62        if sess.opts.language.is_yul() && !sess.opts.unstable.parse_yul {
63            return Err(sess.dcx.err("Yul is not supported yet").emit());
64        }
65
66        let mut pcx = solar_sema::ParsingContext::new(sess);
67        pcx.file_resolver.add_include_paths(sess.opts.include_path.iter().cloned());
68
69        // Partition arguments into three categories:
70        // - `stdin`: `-`, occurrences after the first are ignored
71        // - remappings: `[context:]prefix=path`
72        // - paths: everything else
73        let mut seen_stdin = false;
74        for arg in sess.opts.input.iter().map(String::as_str) {
75            if arg == "-" {
76                if !seen_stdin {
77                    pcx.load_stdin()?;
78                }
79                seen_stdin = true;
80                continue;
81            }
82
83            if arg.contains('=') {
84                let remapping = arg.parse::<ImportRemapping>().map_err(|e| {
85                    self.sess.dcx.err(format!("invalid remapping {arg:?}: {e}")).emit()
86                })?;
87                pcx.file_resolver.add_import_remapping(remapping);
88                continue;
89            }
90
91            pcx.load_file(arg.as_ref())?;
92        }
93
94        pcx.parse_and_resolve()?;
95
96        Ok(())
97    }
98
99    fn finish_diagnostics(&self) -> Result {
100        self.sess.dcx.print_error_count()
101    }
102}
103
104fn run_compiler_with(opts: Opts, f: impl FnOnce(&Compiler) -> Result + Send) -> Result {
105    let ui_testing = opts.unstable.ui_testing;
106    let source_map = Arc::new(SourceMap::empty());
107    let emitter: Box<DynEmitter> = match opts.error_format {
108        ErrorFormat::Human => {
109            let color = match opts.color {
110                clap::ColorChoice::Always => solar_interface::ColorChoice::Always,
111                clap::ColorChoice::Auto => solar_interface::ColorChoice::Auto,
112                clap::ColorChoice::Never => solar_interface::ColorChoice::Never,
113            };
114            let human = HumanEmitter::stderr(color)
115                .source_map(Some(source_map.clone()))
116                .ui_testing(ui_testing);
117            Box::new(human)
118        }
119        ErrorFormat::Json | ErrorFormat::RustcJson => {
120            // `io::Stderr` is not buffered.
121            let writer = Box::new(std::io::BufWriter::new(std::io::stderr()));
122            let json = JsonEmitter::new(writer, source_map.clone())
123                .pretty(opts.pretty_json_err)
124                .rustc_like(matches!(opts.error_format, ErrorFormat::RustcJson))
125                .ui_testing(ui_testing);
126            Box::new(json)
127        }
128    };
129    let dcx = DiagCtxt::new(emitter).set_flags(|flags| {
130        flags.deduplicate_diagnostics &= !ui_testing;
131        flags.track_diagnostics &= !ui_testing;
132        flags.track_diagnostics |= opts.unstable.track_diagnostics;
133    });
134
135    let mut sess = Session::builder().dcx(dcx).source_map(source_map).opts(opts).build();
136    sess.infer_language();
137    sess.validate()?;
138
139    let compiler = Compiler { sess };
140    compiler.sess.enter_parallel(|| {
141        let mut r = f(&compiler);
142        r = compiler.finish_diagnostics().and(r);
143        r
144    })
145}