solar-interface 0.3.1

Source positions, diagnostics, and related helper functions
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
use crate::{
    ByteSymbol, ColorChoice, SessionGlobals, SourceMap, Symbol,
    diagnostics::{DiagCtxt, EmittedDiagnostics},
    source_map::absolute_path,
};
use solar_config::{
    CompileOpts, CompilerOutput, CompilerStage, Language, SINGLE_THREADED_TARGET, UnstableOpts,
};
use std::{
    fmt, io,
    path::{Path, PathBuf},
    sync::{
        Arc, OnceLock,
        atomic::{AtomicUsize, Ordering},
        mpsc,
    },
};

/// Information about the current compiler session.
pub struct Session {
    /// The compiler options.
    pub opts: CompileOpts,

    /// The diagnostics context.
    pub dcx: DiagCtxt,
    /// The globals.
    globals: Arc<SessionGlobals>,
    /// The rayon thread pool. This is spawned lazily on first use, rather than always constructing
    /// one with `SessionBuilder`.
    thread_pool: OnceLock<rayon::ThreadPool>,
    /// The code generation jobs that wait for a worker.
    queued_jobs: AtomicUsize,
}

impl Default for Session {
    fn default() -> Self {
        Self::new(CompileOpts::default())
    }
}

impl fmt::Debug for Session {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Session")
            .field("opts", &self.opts)
            .field("dcx", &self.dcx)
            .finish_non_exhaustive()
    }
}

/// [`Session`] builder.
#[derive(Default)]
#[must_use = "builders don't do anything unless you call `build`"]
pub struct SessionBuilder {
    dcx: Option<DiagCtxt>,
    globals: Option<SessionGlobals>,
    opts: Option<CompileOpts>,
}

impl SessionBuilder {
    /// Sets the diagnostic context.
    ///
    /// If `opts` is set this will default to [`DiagCtxt::from_opts`], otherwise this is required.
    ///
    /// See also the `with_*_emitter*` methods.
    pub fn dcx(mut self, dcx: DiagCtxt) -> Self {
        self.dcx = Some(dcx);
        self
    }

    /// Sets the source map.
    pub fn source_map(mut self, source_map: Arc<SourceMap>) -> Self {
        self.get_globals().source_map = source_map;
        self
    }

    /// Sets the compiler options.
    pub fn opts(mut self, opts: CompileOpts) -> Self {
        self.opts = Some(opts);
        self
    }

    /// Sets the diagnostic context to a test emitter.
    #[inline]
    pub fn with_test_emitter(mut self) -> Self {
        let sm = self.get_source_map();
        self.dcx(DiagCtxt::with_test_emitter(Some(sm)))
    }

    /// Sets the diagnostic context to a stderr emitter.
    #[inline]
    pub fn with_stderr_emitter(self) -> Self {
        self.with_stderr_emitter_and_color(ColorChoice::Auto)
    }

    /// Sets the diagnostic context to a stderr emitter and a color choice.
    #[inline]
    pub fn with_stderr_emitter_and_color(mut self, color_choice: ColorChoice) -> Self {
        let sm = self.get_source_map();
        self.dcx(DiagCtxt::with_stderr_emitter_and_color(Some(sm), color_choice))
    }

    /// Sets the diagnostic context to a human emitter that emits diagnostics to a local buffer.
    #[inline]
    pub fn with_buffer_emitter(mut self, color_choice: ColorChoice) -> Self {
        let sm = self.get_source_map();
        self.dcx(DiagCtxt::with_buffer_emitter(Some(sm), color_choice))
    }

    /// Sets the diagnostic context to a silent emitter.
    #[inline]
    pub fn with_silent_emitter(self, fatal_note: Option<String>) -> Self {
        self.dcx(DiagCtxt::with_silent_emitter(fatal_note))
    }

    /// Sets the number of threads to use for parallelism to 1.
    #[inline]
    pub fn single_threaded(self) -> Self {
        self.threads(1)
    }

    /// Sets the number of threads to use for parallelism. Zero specifies the number of logical
    /// cores.
    #[inline]
    pub fn threads(mut self, threads: usize) -> Self {
        self.opts_mut().threads = threads.into();
        self
    }

    /// Gets the source map from the diagnostics context.
    fn get_source_map(&mut self) -> Arc<SourceMap> {
        self.get_globals().source_map.clone()
    }

    fn get_globals(&mut self) -> &mut SessionGlobals {
        self.globals.get_or_insert_default()
    }

    /// Returns a mutable reference to the options.
    fn opts_mut(&mut self) -> &mut CompileOpts {
        self.opts.get_or_insert_default()
    }

    /// Consumes the builder to create a new session.
    ///
    /// The diagnostics context must be set before calling this method, either by calling
    /// [`dcx`](Self::dcx) or by using one of the provided helper methods, like
    /// [`with_stderr_emitter`](Self::with_stderr_emitter).
    ///
    /// # Panics
    ///
    /// Panics if:
    /// - the diagnostics context is not set
    /// - the source map in the diagnostics context does not match the one set in the builder
    #[track_caller]
    pub fn build(mut self) -> Session {
        let opts = self.opts.take();
        let dcx = self.dcx.take().unwrap_or_else(|| {
            opts.as_ref()
                .map(DiagCtxt::from_opts)
                .unwrap_or_else(|| panic!("either diagnostics context or options must be set"))
        });
        let globals = Arc::new(match self.globals.take() {
            Some(globals) => {
                // Check that the source map matches the one in the diagnostics context.
                if let Some(sm) = dcx.source_map() {
                    assert!(
                        Arc::ptr_eq(&globals.source_map, &sm),
                        "session source map does not match the one in the diagnostics context"
                    );
                }
                globals
            }
            None => {
                // Set the source map from the diagnostics context.
                let sm = dcx.source_map().unwrap_or_default();
                SessionGlobals::new(sm)
            }
        });
        let mut opts = opts.unwrap_or_default();
        Session::infer_language(&mut opts);
        let sess = Session {
            globals,
            dcx,
            opts,
            thread_pool: OnceLock::new(),
            queued_jobs: AtomicUsize::new(0),
        };
        sess.reconfigure();
        debug!(version = %solar_config::version::SEMVER_VERSION, "created new session");
        sess
    }
}

impl Session {
    fn infer_language(opts: &mut CompileOpts) {
        if opts.standard_json {
            return;
        }

        let mut inputs = opts.input.iter().filter(|input| !input.contains('='));
        if let Some(language) = inputs.clone().find_map(|input| {
            match Path::new(input).extension().and_then(|extension| extension.to_str()) {
                Some("mir") => Some(Language::Mir),
                Some("evmir") => Some(Language::EvmIr),
                _ => None,
            }
        }) {
            opts.language = language;
        } else if inputs.clone().next().is_some()
            && inputs.all(|input| Path::new(input).extension() == Some("yul".as_ref()))
        {
            opts.language = Language::Yul;
        }

        if opts.language.is_mir() && opts.unstable.mir_pipeline.is_none() {
            opts.unstable.mir_pipeline = Some("none".to_string());
        } else if opts.language.is_evm_ir() && opts.unstable.evm_ir_pipeline.is_none() {
            opts.unstable.evm_ir_pipeline = Some("none".to_string());
        }
    }

    /// Creates a new session builder.
    #[inline]
    pub fn builder() -> SessionBuilder {
        SessionBuilder::default()
    }

    /// Creates a new session from the given options.
    ///
    /// See [`builder`](Self::builder) for a more flexible way to create a session.
    pub fn new(opts: CompileOpts) -> Self {
        Self::builder().opts(opts).build()
    }

    /// Validates the session options.
    pub fn validate(&self) -> crate::Result<()> {
        let mut result = Ok(());
        result = result.and(self.check_unique("emit", &self.opts.emit));
        result = result.and(self.validate_language());
        result = result.and(self.validate_base_path());
        result
    }

    fn validate_language(&self) -> crate::Result<()> {
        if self.opts.language.is_source() {
            return Ok(());
        }

        let input_count = self.opts.input.iter().filter(|input| !input.contains('=')).count();
        if input_count != 1 {
            return Err(self.dcx.err("IR compilation requires exactly one input file").emit());
        }
        if self.opts.language.is_mir() && self.opts.unstable.evm_ir_pipeline.is_some() {
            return Err(self.dcx.err("`-Zevm-ir-pipeline` requires an .evmir input file").emit());
        }
        if self.opts.language.is_evm_ir() && self.opts.unstable.mir_pipeline.is_some() {
            return Err(self.dcx.err("`-Zmir-pipeline` requires a .sol or .mir input file").emit());
        }
        Ok(())
    }

    fn validate_base_path(&self) -> crate::Result<()> {
        // Standard JSON does not check the base path, which a library read callback need not use.
        let Some(base_path) = self.opts.base_path.as_deref().filter(|_| !self.opts.standard_json)
        else {
            return Ok(());
        };
        let msg = if self.source_map().file_loader().canonicalize_path(base_path).is_err() {
            "does not exist"
        } else if std::fs::metadata(base_path).is_ok_and(|metadata| !metadata.is_dir()) {
            "is not a directory"
        } else {
            return Ok(());
        };
        Err(self.dcx.err(format!("base path `{}` {msg}", base_path.display())).emit())
    }

    /// Reconfigures inner state to match any new options.
    ///
    /// Call this after updating options.
    pub fn reconfigure(&self) {
        let (base_path, include_paths, current_dir) = if self.opts.standard_json {
            // Standard JSON keys are source unit names, so display them verbatim. An empty
            // base path also makes imports resolve by source unit name without `--base-path`.
            (Some(PathBuf::new()), Vec::new(), None)
        } else if self.opts.unstable.ui_testing {
            // `ui_test` relies on absolute paths.
            (None, Vec::new(), None)
        } else {
            let current_dir = std::env::current_dir().ok();
            let absolute = |path: &Path| absolute_path(current_dir.as_deref(), path);
            let include_paths = self.opts.include_paths.iter().map(|path| absolute(path)).collect();
            let base_path = self.opts.base_path.as_deref().map(absolute).or(current_dir.clone());
            (base_path, include_paths, current_dir)
        };
        self.source_map().set_roots(base_path, include_paths, current_dir);
    }

    fn check_unique<T: Eq + std::hash::Hash + std::fmt::Display>(
        &self,
        name: &str,
        list: &[T],
    ) -> crate::Result<()> {
        let mut result = Ok(());
        let mut seen = std::collections::HashSet::new();
        for item in list {
            if !seen.insert(item) {
                let msg = format!("cannot specify `--{name} {item}` twice");
                result = Err(self.dcx.err(msg).emit());
            }
        }
        result
    }

    /// Returns the unstable options.
    #[inline]
    pub fn unstable(&self) -> &UnstableOpts {
        &self.opts.unstable
    }

    /// Returns the emitted diagnostics as a result. Can be empty.
    ///
    /// Returns `None` if the underlying emitter is not a human buffer emitter created with
    /// [`with_buffer_emitter`](SessionBuilder::with_buffer_emitter).
    ///
    /// Results `Ok` if there are no errors, `Err` otherwise.
    ///
    /// # Examples
    ///
    /// Print diagnostics to `stdout` if there are no errors, otherwise propagate with `?`:
    ///
    /// ```no_run
    /// # fn f(dcx: solar_interface::diagnostics::DiagCtxt) -> Result<(), Box<dyn std::error::Error>> {
    /// println!("{}", dcx.emitted_diagnostics_result().unwrap()?);
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn emitted_diagnostics_result(
        &self,
    ) -> Option<Result<EmittedDiagnostics, EmittedDiagnostics>> {
        self.dcx.emitted_diagnostics_result()
    }

    /// Returns the emitted diagnostics. Can be empty.
    ///
    /// Returns `None` if the underlying emitter is not a human buffer emitter created with
    /// [`with_buffer_emitter`](SessionBuilder::with_buffer_emitter).
    #[inline]
    pub fn emitted_diagnostics(&self) -> Option<EmittedDiagnostics> {
        self.dcx.emitted_diagnostics()
    }

    /// Returns `Err` with the printed diagnostics if any errors have been emitted.
    ///
    /// Returns `None` if the underlying emitter is not a human buffer emitter created with
    /// [`with_buffer_emitter`](SessionBuilder::with_buffer_emitter).
    #[inline]
    pub fn emitted_errors(&self) -> Option<Result<(), EmittedDiagnostics>> {
        self.dcx.emitted_errors()
    }

    /// Returns a reference to the source map.
    #[inline]
    pub fn source_map(&self) -> &SourceMap {
        &self.globals.source_map
    }

    /// Clones the source map.
    #[inline]
    pub fn clone_source_map(&self) -> Arc<SourceMap> {
        self.globals.source_map.clone()
    }

    /// Returns `true` if compilation should stop after the given stage.
    #[inline]
    pub fn stop_after(&self, stage: CompilerStage) -> bool {
        self.opts.stop_after.is_some_and(|stop_after| stop_after <= stage)
    }

    /// Returns the number of threads to use for parallelism.
    #[inline]
    pub fn threads(&self) -> usize {
        self.opts.threads().get()
    }

    /// Returns `true` if parallelism is not enabled.
    #[inline]
    pub fn is_sequential(&self) -> bool {
        self.threads() == 1
    }

    /// Returns `true` if parallelism is enabled.
    #[inline]
    pub fn is_parallel(&self) -> bool {
        !self.is_sequential()
    }

    /// Returns `true` if code generation may run on several threads: parallelism is enabled and
    /// no pass-debugging flag is set. Pass debugging writes directly to stdout and stderr, so it
    /// keeps its output ordered.
    #[inline]
    pub fn is_parallel_codegen(&self) -> bool {
        let unstable = &self.opts.unstable;
        self.is_parallel()
            && !unstable.print_after_each
            && !unstable.pass_diff
            && !unstable.time_passes
    }

    /// Records a code generation job that waits for a worker.
    pub fn queue_job(&self) {
        self.queued_jobs.fetch_add(1, Ordering::Relaxed);
    }

    /// Records that a worker took a queued code generation job.
    pub fn start_job(&self) {
        self.queued_jobs.fetch_sub(1, Ordering::Relaxed);
    }

    /// Returns `true` if code generation jobs wait for a worker, so that work split off a running
    /// job would only compete with them.
    pub fn has_queued_jobs(&self) -> bool {
        self.queued_jobs.load(Ordering::Relaxed) != 0
    }

    /// Returns `true` if the given output should be emitted.
    #[inline]
    pub fn do_emit(&self, output: CompilerOutput) -> bool {
        self.opts.emit.contains(&output)
    }

    /// Spawns the given closure on the thread pool or executes it immediately if parallelism is not
    /// enabled.
    ///
    /// NOTE: on a `use_current_thread` thread pool `rayon::spawn` will never execute without
    /// yielding to rayon, so prefer using this method over `rayon::spawn`.
    #[inline]
    pub fn spawn(&self, f: impl FnOnce() + Send + 'static) {
        if self.is_sequential() {
            f();
        } else {
            rayon::spawn(f);
        }
    }

    /// Takes two closures and potentially runs them in parallel. It returns a pair of the results
    /// from those closures.
    ///
    /// NOTE: on a `use_current_thread` thread pool `rayon::join` will never execute without
    /// yielding to rayon, so prefer using this method over `rayon::join`.
    #[inline]
    pub fn join<A, B, RA, RB>(&self, oper_a: A, oper_b: B) -> (RA, RB)
    where
        A: FnOnce() -> RA + Send,
        B: FnOnce() -> RB + Send,
        RA: Send,
        RB: Send,
    {
        if self.is_sequential() { (oper_a(), oper_b()) } else { rayon::join(oper_a, oper_b) }
    }

    /// Executes the given closure in a fork-join scope.
    ///
    /// See [`rayon::scope`] for more details.
    #[inline]
    pub fn scope<'scope, OP, R>(&self, op: OP) -> R
    where
        OP: FnOnce(solar_data_structures::sync::Scope<'_, 'scope>) -> R + Send,
        R: Send,
    {
        solar_data_structures::sync::scope(self.is_parallel(), op)
    }

    /// Sets up the session globals and executes the given closure in the thread pool.
    ///
    /// The thread pool and globals are stored in this [`Session`] itself, meaning multiple
    /// consecutive calls to [`enter`](Self::enter) will share the same globals and resources.
    #[track_caller]
    pub fn enter<R: Send>(&self, f: impl FnOnce() -> R + Send) -> R {
        if in_rayon() {
            // Avoid panicking if we were to build a `current_thread` thread pool.
            if self.is_sequential() {
                reentrant_log();
                return self.enter_sequential(f);
            }
            // Avoid creating a new thread pool if it's already set up with the same globals.
            if self.is_entered() {
                // No need to set again.
                return f();
            }
        }

        // Set the globals inside `install`, not around it. When the caller is a worker of another
        // thread pool, `install` steals and runs that pool's jobs while it waits, and they must not
        // see these globals. The workers of this pool already have them.
        self.thread_pool().install(|| self.enter_sequential(f))
    }

    /// Sets up the session globals and executes the given closure in the current thread.
    ///
    /// Note that this does not set up the rayon thread pool. This is only useful when parsing
    /// sequentially, like manually using `Parser`. Otherwise, it might cause panics later on if a
    /// thread pool is expected to be set up correctly.
    ///
    /// See [`enter`](Self::enter) for more details.
    #[inline]
    #[track_caller]
    pub fn enter_sequential<R>(&self, f: impl FnOnce() -> R) -> R {
        self.globals.set(f)
    }

    /// Interns a string in this session's symbol interner.
    ///
    /// The symbol may not be usable on its own if the session has not been [entered](Self::enter).
    #[inline]
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn intern(&self, s: &str) -> Symbol {
        self.globals.symbol_interner.intern(s)
    }

    /// Resolves a symbol to its string representation.
    ///
    /// The given symbol must have been interned in this session.
    #[inline]
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn resolve_symbol(&self, s: Symbol) -> &str {
        self.globals.symbol_interner.get(s)
    }

    /// Interns a byte string in this session's symbol interner.
    ///
    /// The symbol may not be usable on its own if the session has not been [entered](Self::enter).
    #[inline]
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn intern_byte_str(&self, s: &[u8]) -> ByteSymbol {
        self.globals.symbol_interner.intern_byte_str(s)
    }

    /// Resolves a byte symbol to its string representation.
    ///
    /// The given symbol must have been interned in this session.
    #[inline]
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn resolve_byte_str(&self, s: ByteSymbol) -> &[u8] {
        self.globals.symbol_interner.get_byte_str(s)
    }

    /// Returns `true` if this session has been entered.
    pub fn is_entered(&self) -> bool {
        SessionGlobals::try_with(|g| g.is_some_and(|g| g.maybe_eq(&self.globals)))
    }

    fn thread_pool(&self) -> &rayon::ThreadPool {
        self.thread_pool.get_or_init(|| {
            trace!(threads = self.threads(), "building rayon thread pool");
            // Spawning every worker takes about 40 us each, which dominates small inputs at high
            // thread counts. Spawn the first worker here, so that failing to spawn threads at all
            // is reported, and let a helper thread spawn the others while the first one already
            // runs.
            //
            // NOTE: a later worker that fails to spawn leaves the pool smaller, so rayon's
            // `broadcast`, which waits for every registered worker, must not be used on this pool.
            let mut spawner = None;
            self.thread_pool_builder()
                .spawn_handler(|thread| {
                    if thread.index() == 0 {
                        return spawn_worker(&self.globals, thread);
                    }
                    if spawner.is_none() {
                        let (tx, rx) = mpsc::channel::<rayon::ThreadBuilder>();
                        let globals = self.globals.clone();
                        std::thread::Builder::new().name("solar-spawn".into()).spawn(
                            move || {
                                for thread in rx {
                                    if let Err(e) = spawn_worker(&globals, thread) {
                                        debug!(%e, "failed to spawn a worker thread");
                                    }
                                }
                            },
                        )?;
                        spawner = Some(tx);
                    }
                    spawner
                        .as_ref()
                        .unwrap()
                        .send(thread)
                        .map_err(|_| io::Error::other("worker spawner exited"))
                })
                .build()
                .unwrap_or_else(|e| self.handle_thread_pool_build_error(e))
        })
    }

    fn thread_pool_builder(&self) -> rayon::ThreadPoolBuilder {
        let threads = self.threads();
        debug_assert!(threads > 0, "number of threads must already be resolved");
        let mut builder = rayon::ThreadPoolBuilder::new()
            .thread_name(|i| format!("solar-{i}"))
            .num_threads(threads)
            .stack_size(thread_stack_size());
        // We still want to use a rayon thread pool with 1 thread so that `ParallelIterator`s don't
        // install and run in the default global thread pool.
        if threads == 1 {
            builder = builder.use_current_thread();
        }
        builder
    }

    #[cold]
    fn handle_thread_pool_build_error(&self, e: rayon::ThreadPoolBuildError) -> ! {
        let mut err = self.dcx.fatal(format!("failed to build the rayon thread pool: {e}"));
        if self.is_parallel() {
            if SINGLE_THREADED_TARGET {
                err = err.note("the current target might not support multi-threaded execution");
            }
            err = err.help("try running with `--threads 1` / `-j1` to disable parallelism");
        }
        err.emit()
    }
}

/// Returns the stack size of compiler threads: `RUST_MIN_STACK` if set, or 16 MiB.
///
/// Like rustc, we do not grow the stack manually: deeply nested input recurses deeply, and the OS
/// commits stack pages only when they are used, so a large limit costs nothing until it is needed.
pub fn thread_stack_size() -> usize {
    std::env::var("RUST_MIN_STACK")
        .ok()
        .and_then(|s| s.trim().parse().ok())
        .unwrap_or(16 * 1024 * 1024)
}

/// Spawns a rayon worker thread that runs with the session globals set.
fn spawn_worker(globals: &Arc<SessionGlobals>, thread: rayon::ThreadBuilder) -> io::Result<()> {
    let mut builder = std::thread::Builder::new();
    if let Some(name) = thread.name() {
        builder = builder.name(name.to_string());
    }
    if let Some(size) = thread.stack_size() {
        builder = builder.stack_size(size);
    }
    let globals = globals.clone();
    builder.spawn(move || globals.set(|| thread.run()))?;
    Ok(())
}

fn reentrant_log() {
    debug!(
        "running in the current thread's rayon thread pool; \
         this could cause panics later on if it was created without setting the session globals!"
    );
}

#[inline]
fn in_rayon() -> bool {
    rayon::current_thread_index().is_some()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{
        path::PathBuf,
        sync::atomic::AtomicBool,
        time::{Duration, Instant},
    };

    /// Session to test `enter`.
    fn enter_tests_session() -> Session {
        let sess = Session::builder().with_buffer_emitter(ColorChoice::Never).build();
        sess.source_map().new_source_file(PathBuf::from("test"), "abcd").unwrap();
        sess
    }

    #[track_caller]
    fn use_globals_parallel(sess: &Session) {
        use rayon::prelude::*;

        use_globals();
        sess.spawn(|| use_globals());
        sess.join(|| use_globals(), || use_globals());
        [1, 2, 3].par_iter().for_each(|_| use_globals());
        use_globals();
    }

    #[track_caller]
    fn use_globals() {
        use_globals_no_sm();

        let span = crate::Span::new(crate::BytePos(0), crate::BytePos(1));
        assert_eq!(format!("{span:?}"), "test:1:1: 1:2");
        assert_eq!(format!("{span:#?}"), "test:1:1: 1:2");
    }

    #[track_caller]
    fn use_globals_no_sm() {
        SessionGlobals::with(|_globals| {});

        let s = "hello";
        let sym = crate::Symbol::intern(s);
        assert_eq!(sym.as_str(), s);
    }

    #[track_caller]
    fn cant_use_globals() {
        std::panic::catch_unwind(|| use_globals()).unwrap_err();
    }

    #[test]
    fn builder() {
        let _ = Session::builder().with_stderr_emitter().build();
    }

    #[test]
    fn not_builder() {
        let _ = Session::new(CompileOpts::default());
        let _ = Session::default();
    }

    #[test]
    fn infer_language() {
        let mut opts = CompileOpts::default();
        opts.input.push("input.mir".to_string());
        let sess = Session::new(opts);
        assert_eq!(sess.opts.language, Language::Mir);
        assert_eq!(sess.opts.unstable.mir_pipeline.as_deref(), Some("none"));

        let mut opts = CompileOpts::default();
        opts.input.push("input.evmir".to_string());
        let sess = Session::new(opts);
        assert_eq!(sess.opts.language, Language::EvmIr);
        assert_eq!(sess.opts.unstable.evm_ir_pipeline.as_deref(), Some("none"));

        let mut opts = CompileOpts { standard_json: true, ..Default::default() };
        opts.input.push("input.mir".to_string());
        let sess = Session::new(opts);
        assert_eq!(sess.opts.language, Language::Solidity);
        assert!(sess.opts.unstable.mir_pipeline.is_none());
    }

    #[test]
    #[should_panic = "session source map does not match the one in the diagnostics context"]
    fn sm_mismatch() {
        let sm1 = Arc::<SourceMap>::default();
        let sm2 = Arc::<SourceMap>::default();
        assert!(!Arc::ptr_eq(&sm1, &sm2));
        Session::builder().source_map(sm1).dcx(DiagCtxt::with_stderr_emitter(Some(sm2))).build();
    }

    #[test]
    #[should_panic = "either diagnostics context or options must be set"]
    fn no_dcx() {
        Session::builder().build();
    }

    #[test]
    fn dcx() {
        let _ = Session::builder().dcx(DiagCtxt::with_stderr_emitter(None)).build();
        let _ =
            Session::builder().dcx(DiagCtxt::with_stderr_emitter(Some(Default::default()))).build();
    }

    #[test]
    fn local() {
        let sess = Session::builder().with_stderr_emitter().build();
        assert!(sess.emitted_diagnostics().is_none());
        assert!(sess.emitted_errors().is_none());

        let sess = Session::builder().with_buffer_emitter(ColorChoice::Never).build();
        sess.dcx.err("test").emit();
        let err = sess.dcx.emitted_errors().unwrap().unwrap_err();
        let err = Box::new(err) as Box<dyn std::error::Error>;
        assert!(err.to_string().contains("error: test"), "{err:?}");
    }

    #[test]
    fn enter() {
        crate::enter(|| {
            use_globals_no_sm();
            cant_use_globals();
        });

        let sess = enter_tests_session();
        sess.enter(|| use_globals());
        assert!(sess.dcx.emitted_diagnostics().unwrap().is_empty());
        assert!(sess.dcx.emitted_errors().unwrap().is_ok());
        sess.enter(|| {
            use_globals();
            sess.enter(|| use_globals());
            use_globals();
        });
        assert!(sess.dcx.emitted_diagnostics().unwrap().is_empty());
        assert!(sess.dcx.emitted_errors().unwrap().is_ok());

        sess.enter_sequential(|| {
            use_globals();
            sess.enter(|| {
                use_globals_parallel(&sess);
                sess.enter(|| use_globals_parallel(&sess));
                use_globals_parallel(&sess);
            });
            use_globals();
        });
        assert!(sess.dcx.emitted_diagnostics().unwrap().is_empty());
        assert!(sess.dcx.emitted_errors().unwrap().is_ok());
    }

    #[test]
    fn enter_diags() {
        let sess = Session::builder().with_buffer_emitter(ColorChoice::Never).build();
        assert!(sess.dcx.emitted_errors().unwrap().is_ok());
        sess.enter(|| {
            sess.dcx.err("test1").emit();
            assert!(sess.dcx.emitted_errors().unwrap().is_err());
        });
        assert!(sess.dcx.emitted_errors().unwrap().unwrap_err().to_string().contains("test1"));
        sess.enter(|| {
            sess.dcx.err("test2").emit();
            assert!(sess.dcx.emitted_errors().unwrap().is_err());
        });
        assert!(sess.dcx.emitted_errors().unwrap().unwrap_err().to_string().contains("test1"));
        assert!(sess.dcx.emitted_errors().unwrap().unwrap_err().to_string().contains("test2"));
    }

    #[test]
    fn enter_thread_pool() {
        let sess = enter_tests_session();

        assert!(!in_rayon());
        sess.enter(|| {
            assert!(in_rayon());
            sess.enter(|| {
                assert!(in_rayon());
            });
            assert!(in_rayon());
        });
        sess.enter_sequential(|| {
            assert!(!in_rayon());
            sess.enter(|| {
                assert!(in_rayon());
            });
            assert!(!in_rayon());
            sess.enter_sequential(|| {
                assert!(!in_rayon());
            });
            assert!(!in_rayon());
        });
        assert!(!in_rayon());

        let pool = rayon::ThreadPoolBuilder::new().build().unwrap();
        pool.install(|| {
            assert!(in_rayon());
            cant_use_globals();
            sess.enter(|| use_globals_parallel(&sess));
            assert!(in_rayon());
            cant_use_globals();
        });
        assert!(!in_rayon());
    }

    #[test]
    fn enter_different_nested_sessions() {
        let sess1 = enter_tests_session();
        let sess2 = enter_tests_session();
        assert!(!sess1.globals.maybe_eq(&sess2.globals));
        sess1.enter(|| {
            SessionGlobals::with(|g| assert!(g.maybe_eq(&sess1.globals)));
            use_globals();
            sess2.enter(|| {
                SessionGlobals::with(|g| assert!(g.maybe_eq(&sess2.globals)));
                use_globals();
            });
            use_globals();
        });
    }

    #[test]
    fn enter_different_nested_sessions_no_steal() {
        let sess1 = Session::builder().with_buffer_emitter(ColorChoice::Never).threads(4).build();
        let sess2 = Session::builder().with_buffer_emitter(ColorChoice::Never).threads(4).build();
        sess1.enter(|| {
            for _ in 0..50 {
                let done = AtomicBool::new(false);
                let mut ok = false;
                rayon::join(
                    || {
                        sess2.enter(|| {
                            let start = Instant::now();
                            while !done.load(Ordering::Acquire)
                                && start.elapsed() < Duration::from_millis(200)
                            {
                                std::hint::spin_loop();
                            }
                        })
                    },
                    || {
                        ok = sess1.is_entered();
                        done.store(true, Ordering::Release);
                    },
                );
                assert!(ok, "job ran with the wrong session globals");
            }
        });
    }

    #[test]
    fn set_opts() {
        let _ = Session::builder()
            .with_test_emitter()
            .opts(CompileOpts {
                evm_version: solar_config::EvmVersion::Berlin,
                unstable: UnstableOpts { ast_stats: false, ..Default::default() },
                ..Default::default()
            })
            .build();
    }
}