1use crate::{
2 ByteSymbol, ColorChoice, SessionGlobals, SourceMap, Symbol,
3 diagnostics::{DiagCtxt, EmittedDiagnostics},
4 source_map::absolute_path,
5};
6use solar_config::{
7 CompileOpts, CompilerOutput, CompilerStage, Language, SINGLE_THREADED_TARGET, UnstableOpts,
8};
9use std::{
10 fmt,
11 path::{Path, PathBuf},
12 sync::{
13 Arc, OnceLock,
14 atomic::{AtomicUsize, Ordering},
15 },
16};
17
18pub struct Session {
20 pub opts: CompileOpts,
22
23 pub dcx: DiagCtxt,
25 globals: Arc<SessionGlobals>,
27 thread_pool: OnceLock<rayon::ThreadPool>,
30 queued_jobs: AtomicUsize,
32}
33
34impl Default for Session {
35 fn default() -> Self {
36 Self::new(CompileOpts::default())
37 }
38}
39
40impl fmt::Debug for Session {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 f.debug_struct("Session")
43 .field("opts", &self.opts)
44 .field("dcx", &self.dcx)
45 .finish_non_exhaustive()
46 }
47}
48
49#[derive(Default)]
51#[must_use = "builders don't do anything unless you call `build`"]
52pub struct SessionBuilder {
53 dcx: Option<DiagCtxt>,
54 globals: Option<SessionGlobals>,
55 opts: Option<CompileOpts>,
56}
57
58impl SessionBuilder {
59 pub fn dcx(mut self, dcx: DiagCtxt) -> Self {
65 self.dcx = Some(dcx);
66 self
67 }
68
69 pub fn source_map(mut self, source_map: Arc<SourceMap>) -> Self {
71 self.get_globals().source_map = source_map;
72 self
73 }
74
75 pub fn opts(mut self, opts: CompileOpts) -> Self {
77 self.opts = Some(opts);
78 self
79 }
80
81 #[inline]
83 pub fn with_test_emitter(mut self) -> Self {
84 let sm = self.get_source_map();
85 self.dcx(DiagCtxt::with_test_emitter(Some(sm)))
86 }
87
88 #[inline]
90 pub fn with_stderr_emitter(self) -> Self {
91 self.with_stderr_emitter_and_color(ColorChoice::Auto)
92 }
93
94 #[inline]
96 pub fn with_stderr_emitter_and_color(mut self, color_choice: ColorChoice) -> Self {
97 let sm = self.get_source_map();
98 self.dcx(DiagCtxt::with_stderr_emitter_and_color(Some(sm), color_choice))
99 }
100
101 #[inline]
103 pub fn with_buffer_emitter(mut self, color_choice: ColorChoice) -> Self {
104 let sm = self.get_source_map();
105 self.dcx(DiagCtxt::with_buffer_emitter(Some(sm), color_choice))
106 }
107
108 #[inline]
110 pub fn with_silent_emitter(self, fatal_note: Option<String>) -> Self {
111 self.dcx(DiagCtxt::with_silent_emitter(fatal_note))
112 }
113
114 #[inline]
116 pub fn single_threaded(self) -> Self {
117 self.threads(1)
118 }
119
120 #[inline]
123 pub fn threads(mut self, threads: usize) -> Self {
124 self.opts_mut().threads = threads.into();
125 self
126 }
127
128 fn get_source_map(&mut self) -> Arc<SourceMap> {
130 self.get_globals().source_map.clone()
131 }
132
133 fn get_globals(&mut self) -> &mut SessionGlobals {
134 self.globals.get_or_insert_default()
135 }
136
137 fn opts_mut(&mut self) -> &mut CompileOpts {
139 self.opts.get_or_insert_default()
140 }
141
142 #[track_caller]
154 pub fn build(mut self) -> Session {
155 let opts = self.opts.take();
156 let dcx = self.dcx.take().unwrap_or_else(|| {
157 opts.as_ref()
158 .map(DiagCtxt::from_opts)
159 .unwrap_or_else(|| panic!("either diagnostics context or options must be set"))
160 });
161 let globals = Arc::new(match self.globals.take() {
162 Some(globals) => {
163 if let Some(sm) = dcx.source_map() {
165 assert!(
166 Arc::ptr_eq(&globals.source_map, &sm),
167 "session source map does not match the one in the diagnostics context"
168 );
169 }
170 globals
171 }
172 None => {
173 let sm = dcx.source_map().unwrap_or_default();
175 SessionGlobals::new(sm)
176 }
177 });
178 let mut opts = opts.unwrap_or_default();
179 Session::infer_language(&mut opts);
180 let sess = Session {
181 globals,
182 dcx,
183 opts,
184 thread_pool: OnceLock::new(),
185 queued_jobs: AtomicUsize::new(0),
186 };
187 sess.reconfigure();
188 debug!(version = %solar_config::version::SEMVER_VERSION, "created new session");
189 sess
190 }
191}
192
193impl Session {
194 fn infer_language(opts: &mut CompileOpts) {
195 if opts.standard_json {
196 return;
197 }
198
199 let mut inputs = opts.input.iter().filter(|input| !input.contains('='));
200 if let Some(language) = inputs.clone().find_map(|input| {
201 match Path::new(input).extension().and_then(|extension| extension.to_str()) {
202 Some("mir") => Some(Language::Mir),
203 Some("evmir") => Some(Language::EvmIr),
204 _ => None,
205 }
206 }) {
207 opts.language = language;
208 } else if inputs.clone().next().is_some()
209 && inputs.all(|input| Path::new(input).extension() == Some("yul".as_ref()))
210 {
211 opts.language = Language::Yul;
212 }
213
214 if opts.language.is_mir() && opts.unstable.mir_pipeline.is_none() {
215 opts.unstable.mir_pipeline = Some("none".to_string());
216 } else if opts.language.is_evm_ir() && opts.unstable.evm_ir_pipeline.is_none() {
217 opts.unstable.evm_ir_pipeline = Some("none".to_string());
218 }
219 }
220
221 #[inline]
223 pub fn builder() -> SessionBuilder {
224 SessionBuilder::default()
225 }
226
227 pub fn new(opts: CompileOpts) -> Self {
231 Self::builder().opts(opts).build()
232 }
233
234 pub fn validate(&self) -> crate::Result<()> {
236 let mut result = Ok(());
237 result = result.and(self.check_unique("emit", &self.opts.emit));
238 result = result.and(self.validate_language());
239 result = result.and(self.validate_base_path());
240 result
241 }
242
243 fn validate_language(&self) -> crate::Result<()> {
244 if self.opts.language.is_source() {
245 return Ok(());
246 }
247
248 let input_count = self.opts.input.iter().filter(|input| !input.contains('=')).count();
249 if input_count != 1 {
250 return Err(self.dcx.err("IR compilation requires exactly one input file").emit());
251 }
252 if self.opts.language.is_mir() && self.opts.unstable.evm_ir_pipeline.is_some() {
253 return Err(self.dcx.err("`-Zevm-ir-pipeline` requires an .evmir input file").emit());
254 }
255 if self.opts.language.is_evm_ir() && self.opts.unstable.mir_pipeline.is_some() {
256 return Err(self.dcx.err("`-Zmir-pipeline` requires a .sol or .mir input file").emit());
257 }
258 Ok(())
259 }
260
261 fn validate_base_path(&self) -> crate::Result<()> {
262 let Some(base_path) = self.opts.base_path.as_deref().filter(|_| !self.opts.standard_json)
264 else {
265 return Ok(());
266 };
267 let msg = if self.source_map().file_loader().canonicalize_path(base_path).is_err() {
268 "does not exist"
269 } else if std::fs::metadata(base_path).is_ok_and(|metadata| !metadata.is_dir()) {
270 "is not a directory"
271 } else {
272 return Ok(());
273 };
274 Err(self.dcx.err(format!("base path `{}` {msg}", base_path.display())).emit())
275 }
276
277 pub fn reconfigure(&self) {
281 let (base_path, include_paths, current_dir) = if self.opts.unstable.ui_testing {
282 (None, Vec::new(), None)
284 } else if self.opts.standard_json {
285 (Some(PathBuf::new()), Vec::new(), None)
288 } else {
289 let current_dir = std::env::current_dir().ok();
290 let absolute = |path: &Path| absolute_path(current_dir.as_deref(), path);
291 let include_paths = self.opts.include_paths.iter().map(|path| absolute(path)).collect();
292 let base_path = self.opts.base_path.as_deref().map(absolute).or(current_dir.clone());
293 (base_path, include_paths, current_dir)
294 };
295 self.source_map().set_roots(base_path, include_paths, current_dir);
296 }
297
298 fn check_unique<T: Eq + std::hash::Hash + std::fmt::Display>(
299 &self,
300 name: &str,
301 list: &[T],
302 ) -> crate::Result<()> {
303 let mut result = Ok(());
304 let mut seen = std::collections::HashSet::new();
305 for item in list {
306 if !seen.insert(item) {
307 let msg = format!("cannot specify `--{name} {item}` twice");
308 result = Err(self.dcx.err(msg).emit());
309 }
310 }
311 result
312 }
313
314 #[inline]
316 pub fn unstable(&self) -> &UnstableOpts {
317 &self.opts.unstable
318 }
319
320 #[inline]
338 pub fn emitted_diagnostics_result(
339 &self,
340 ) -> Option<Result<EmittedDiagnostics, EmittedDiagnostics>> {
341 self.dcx.emitted_diagnostics_result()
342 }
343
344 #[inline]
349 pub fn emitted_diagnostics(&self) -> Option<EmittedDiagnostics> {
350 self.dcx.emitted_diagnostics()
351 }
352
353 #[inline]
358 pub fn emitted_errors(&self) -> Option<Result<(), EmittedDiagnostics>> {
359 self.dcx.emitted_errors()
360 }
361
362 #[inline]
364 pub fn source_map(&self) -> &SourceMap {
365 &self.globals.source_map
366 }
367
368 #[inline]
370 pub fn clone_source_map(&self) -> Arc<SourceMap> {
371 self.globals.source_map.clone()
372 }
373
374 #[inline]
376 pub fn stop_after(&self, stage: CompilerStage) -> bool {
377 self.opts.stop_after.is_some_and(|stop_after| stop_after <= stage)
378 }
379
380 #[inline]
382 pub fn threads(&self) -> usize {
383 self.opts.threads().get()
384 }
385
386 #[inline]
388 pub fn is_sequential(&self) -> bool {
389 self.threads() == 1
390 }
391
392 #[inline]
394 pub fn is_parallel(&self) -> bool {
395 !self.is_sequential()
396 }
397
398 #[inline]
402 pub fn is_parallel_codegen(&self) -> bool {
403 let unstable = &self.opts.unstable;
404 self.is_parallel()
405 && !unstable.print_after_each
406 && !unstable.pass_diff
407 && !unstable.time_passes
408 }
409
410 pub fn queue_job(&self) {
412 self.queued_jobs.fetch_add(1, Ordering::Relaxed);
413 }
414
415 pub fn start_job(&self) {
417 self.queued_jobs.fetch_sub(1, Ordering::Relaxed);
418 }
419
420 pub fn has_queued_jobs(&self) -> bool {
423 self.queued_jobs.load(Ordering::Relaxed) != 0
424 }
425
426 #[inline]
428 pub fn do_emit(&self, output: CompilerOutput) -> bool {
429 self.opts.emit.contains(&output)
430 }
431
432 #[inline]
438 pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {
439 if self.is_sequential() {
440 f();
441 } else {
442 rayon::spawn(f);
443 }
444 }
445
446 #[inline]
452 pub fn join<A, B, RA, RB>(&self, oper_a: A, oper_b: B) -> (RA, RB)
453 where
454 A: FnOnce() -> RA + Send,
455 B: FnOnce() -> RB + Send,
456 RA: Send,
457 RB: Send,
458 {
459 if self.is_sequential() { (oper_a(), oper_b()) } else { rayon::join(oper_a, oper_b) }
460 }
461
462 #[inline]
466 pub fn scope<'scope, OP, R>(&self, op: OP) -> R
467 where
468 OP: FnOnce(solar_data_structures::sync::Scope<'_, 'scope>) -> R + Send,
469 R: Send,
470 {
471 solar_data_structures::sync::scope(self.is_parallel(), op)
472 }
473
474 #[track_caller]
479 pub fn enter<R: Send>(&self, f: impl FnOnce() -> R + Send) -> R {
480 if in_rayon() {
481 if self.is_sequential() {
483 reentrant_log();
484 return self.enter_sequential(f);
485 }
486 if self.is_entered() {
488 return f();
490 }
491 }
492
493 self.enter_sequential(|| self.thread_pool().install(f))
494 }
495
496 #[inline]
504 #[track_caller]
505 pub fn enter_sequential<R>(&self, f: impl FnOnce() -> R) -> R {
506 self.globals.set(f)
507 }
508
509 #[inline]
513 #[cfg_attr(debug_assertions, track_caller)]
514 pub fn intern(&self, s: &str) -> Symbol {
515 self.globals.symbol_interner.intern(s)
516 }
517
518 #[inline]
522 #[cfg_attr(debug_assertions, track_caller)]
523 pub fn resolve_symbol(&self, s: Symbol) -> &str {
524 self.globals.symbol_interner.get(s)
525 }
526
527 #[inline]
531 #[cfg_attr(debug_assertions, track_caller)]
532 pub fn intern_byte_str(&self, s: &[u8]) -> ByteSymbol {
533 self.globals.symbol_interner.intern_byte_str(s)
534 }
535
536 #[inline]
540 #[cfg_attr(debug_assertions, track_caller)]
541 pub fn resolve_byte_str(&self, s: ByteSymbol) -> &[u8] {
542 self.globals.symbol_interner.get_byte_str(s)
543 }
544
545 pub fn is_entered(&self) -> bool {
547 SessionGlobals::try_with(|g| g.is_some_and(|g| g.maybe_eq(&self.globals)))
548 }
549
550 fn thread_pool(&self) -> &rayon::ThreadPool {
551 self.thread_pool.get_or_init(|| {
552 trace!(threads = self.threads(), "building rayon thread pool");
553 self.thread_pool_builder()
554 .spawn_handler(|thread| {
555 let mut builder = std::thread::Builder::new();
556 if let Some(name) = thread.name() {
557 builder = builder.name(name.to_string());
558 }
559 if let Some(size) = thread.stack_size() {
560 builder = builder.stack_size(size);
561 }
562 let globals = self.globals.clone();
563 builder.spawn(move || globals.set(|| thread.run()))?;
564 Ok(())
565 })
566 .build()
567 .unwrap_or_else(|e| self.handle_thread_pool_build_error(e))
568 })
569 }
570
571 fn thread_pool_builder(&self) -> rayon::ThreadPoolBuilder {
572 let threads = self.threads();
573 debug_assert!(threads > 0, "number of threads must already be resolved");
574 let mut builder = rayon::ThreadPoolBuilder::new()
575 .thread_name(|i| format!("solar-{i}"))
576 .num_threads(threads)
577 .stack_size(thread_stack_size());
578 if threads == 1 {
581 builder = builder.use_current_thread();
582 }
583 builder
584 }
585
586 #[cold]
587 fn handle_thread_pool_build_error(&self, e: rayon::ThreadPoolBuildError) -> ! {
588 let mut err = self.dcx.fatal(format!("failed to build the rayon thread pool: {e}"));
589 if self.is_parallel() {
590 if SINGLE_THREADED_TARGET {
591 err = err.note("the current target might not support multi-threaded execution");
592 }
593 err = err.help("try running with `--threads 1` / `-j1` to disable parallelism");
594 }
595 err.emit()
596 }
597}
598
599pub fn thread_stack_size() -> usize {
604 std::env::var("RUST_MIN_STACK")
605 .ok()
606 .and_then(|s| s.trim().parse().ok())
607 .unwrap_or(16 * 1024 * 1024)
608}
609
610fn reentrant_log() {
611 debug!(
612 "running in the current thread's rayon thread pool; \
613 this could cause panics later on if it was created without setting the session globals!"
614 );
615}
616
617#[inline]
618fn in_rayon() -> bool {
619 rayon::current_thread_index().is_some()
620}
621
622#[cfg(test)]
623mod tests {
624 use super::*;
625 use std::path::PathBuf;
626
627 fn enter_tests_session() -> Session {
629 let sess = Session::builder().with_buffer_emitter(ColorChoice::Never).build();
630 sess.source_map().new_source_file(PathBuf::from("test"), "abcd").unwrap();
631 sess
632 }
633
634 #[track_caller]
635 fn use_globals_parallel(sess: &Session) {
636 use rayon::prelude::*;
637
638 use_globals();
639 sess.spawn(|| use_globals());
640 sess.join(|| use_globals(), || use_globals());
641 [1, 2, 3].par_iter().for_each(|_| use_globals());
642 use_globals();
643 }
644
645 #[track_caller]
646 fn use_globals() {
647 use_globals_no_sm();
648
649 let span = crate::Span::new(crate::BytePos(0), crate::BytePos(1));
650 assert_eq!(format!("{span:?}"), "test:1:1: 1:2");
651 assert_eq!(format!("{span:#?}"), "test:1:1: 1:2");
652 }
653
654 #[track_caller]
655 fn use_globals_no_sm() {
656 SessionGlobals::with(|_globals| {});
657
658 let s = "hello";
659 let sym = crate::Symbol::intern(s);
660 assert_eq!(sym.as_str(), s);
661 }
662
663 #[track_caller]
664 fn cant_use_globals() {
665 std::panic::catch_unwind(|| use_globals()).unwrap_err();
666 }
667
668 #[test]
669 fn builder() {
670 let _ = Session::builder().with_stderr_emitter().build();
671 }
672
673 #[test]
674 fn not_builder() {
675 let _ = Session::new(CompileOpts::default());
676 let _ = Session::default();
677 }
678
679 #[test]
680 fn infer_language() {
681 let mut opts = CompileOpts::default();
682 opts.input.push("input.mir".to_string());
683 let sess = Session::new(opts);
684 assert_eq!(sess.opts.language, Language::Mir);
685 assert_eq!(sess.opts.unstable.mir_pipeline.as_deref(), Some("none"));
686
687 let mut opts = CompileOpts::default();
688 opts.input.push("input.evmir".to_string());
689 let sess = Session::new(opts);
690 assert_eq!(sess.opts.language, Language::EvmIr);
691 assert_eq!(sess.opts.unstable.evm_ir_pipeline.as_deref(), Some("none"));
692
693 let mut opts = CompileOpts { standard_json: true, ..Default::default() };
694 opts.input.push("input.mir".to_string());
695 let sess = Session::new(opts);
696 assert_eq!(sess.opts.language, Language::Solidity);
697 assert!(sess.opts.unstable.mir_pipeline.is_none());
698 }
699
700 #[test]
701 #[should_panic = "session source map does not match the one in the diagnostics context"]
702 fn sm_mismatch() {
703 let sm1 = Arc::<SourceMap>::default();
704 let sm2 = Arc::<SourceMap>::default();
705 assert!(!Arc::ptr_eq(&sm1, &sm2));
706 Session::builder().source_map(sm1).dcx(DiagCtxt::with_stderr_emitter(Some(sm2))).build();
707 }
708
709 #[test]
710 #[should_panic = "either diagnostics context or options must be set"]
711 fn no_dcx() {
712 Session::builder().build();
713 }
714
715 #[test]
716 fn dcx() {
717 let _ = Session::builder().dcx(DiagCtxt::with_stderr_emitter(None)).build();
718 let _ =
719 Session::builder().dcx(DiagCtxt::with_stderr_emitter(Some(Default::default()))).build();
720 }
721
722 #[test]
723 fn local() {
724 let sess = Session::builder().with_stderr_emitter().build();
725 assert!(sess.emitted_diagnostics().is_none());
726 assert!(sess.emitted_errors().is_none());
727
728 let sess = Session::builder().with_buffer_emitter(ColorChoice::Never).build();
729 sess.dcx.err("test").emit();
730 let err = sess.dcx.emitted_errors().unwrap().unwrap_err();
731 let err = Box::new(err) as Box<dyn std::error::Error>;
732 assert!(err.to_string().contains("error: test"), "{err:?}");
733 }
734
735 #[test]
736 fn enter() {
737 crate::enter(|| {
738 use_globals_no_sm();
739 cant_use_globals();
740 });
741
742 let sess = enter_tests_session();
743 sess.enter(|| use_globals());
744 assert!(sess.dcx.emitted_diagnostics().unwrap().is_empty());
745 assert!(sess.dcx.emitted_errors().unwrap().is_ok());
746 sess.enter(|| {
747 use_globals();
748 sess.enter(|| use_globals());
749 use_globals();
750 });
751 assert!(sess.dcx.emitted_diagnostics().unwrap().is_empty());
752 assert!(sess.dcx.emitted_errors().unwrap().is_ok());
753
754 sess.enter_sequential(|| {
755 use_globals();
756 sess.enter(|| {
757 use_globals_parallel(&sess);
758 sess.enter(|| use_globals_parallel(&sess));
759 use_globals_parallel(&sess);
760 });
761 use_globals();
762 });
763 assert!(sess.dcx.emitted_diagnostics().unwrap().is_empty());
764 assert!(sess.dcx.emitted_errors().unwrap().is_ok());
765 }
766
767 #[test]
768 fn enter_diags() {
769 let sess = Session::builder().with_buffer_emitter(ColorChoice::Never).build();
770 assert!(sess.dcx.emitted_errors().unwrap().is_ok());
771 sess.enter(|| {
772 sess.dcx.err("test1").emit();
773 assert!(sess.dcx.emitted_errors().unwrap().is_err());
774 });
775 assert!(sess.dcx.emitted_errors().unwrap().unwrap_err().to_string().contains("test1"));
776 sess.enter(|| {
777 sess.dcx.err("test2").emit();
778 assert!(sess.dcx.emitted_errors().unwrap().is_err());
779 });
780 assert!(sess.dcx.emitted_errors().unwrap().unwrap_err().to_string().contains("test1"));
781 assert!(sess.dcx.emitted_errors().unwrap().unwrap_err().to_string().contains("test2"));
782 }
783
784 #[test]
785 fn enter_thread_pool() {
786 let sess = enter_tests_session();
787
788 assert!(!in_rayon());
789 sess.enter(|| {
790 assert!(in_rayon());
791 sess.enter(|| {
792 assert!(in_rayon());
793 });
794 assert!(in_rayon());
795 });
796 sess.enter_sequential(|| {
797 assert!(!in_rayon());
798 sess.enter(|| {
799 assert!(in_rayon());
800 });
801 assert!(!in_rayon());
802 sess.enter_sequential(|| {
803 assert!(!in_rayon());
804 });
805 assert!(!in_rayon());
806 });
807 assert!(!in_rayon());
808
809 let pool = rayon::ThreadPoolBuilder::new().build().unwrap();
810 pool.install(|| {
811 assert!(in_rayon());
812 cant_use_globals();
813 sess.enter(|| use_globals_parallel(&sess));
814 assert!(in_rayon());
815 cant_use_globals();
816 });
817 assert!(!in_rayon());
818 }
819
820 #[test]
821 fn enter_different_nested_sessions() {
822 let sess1 = enter_tests_session();
823 let sess2 = enter_tests_session();
824 assert!(!sess1.globals.maybe_eq(&sess2.globals));
825 sess1.enter(|| {
826 SessionGlobals::with(|g| assert!(g.maybe_eq(&sess1.globals)));
827 use_globals();
828 sess2.enter(|| {
829 SessionGlobals::with(|g| assert!(g.maybe_eq(&sess2.globals)));
830 use_globals();
831 });
832 use_globals();
833 });
834 }
835
836 #[test]
837 fn set_opts() {
838 let _ = Session::builder()
839 .with_test_emitter()
840 .opts(CompileOpts {
841 evm_version: solar_config::EvmVersion::Berlin,
842 unstable: UnstableOpts { ast_stats: false, ..Default::default() },
843 ..Default::default()
844 })
845 .build();
846 }
847}