Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit e05ee1f

Browse files
committedJun 10, 2021
Rework SESSION_GLOBALS API to prevent overwriting it
1 parent a50d721 commit e05ee1f

File tree

27 files changed

+146
-100
lines changed

27 files changed

+146
-100
lines changed
 

‎compiler/rustc_ast/src/util/comments/tests.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
use super::*;
2-
use rustc_span::with_default_session_globals;
2+
use rustc_span::create_default_session_globals_then;
33

44
#[test]
55
fn test_block_doc_comment_1() {
6-
with_default_session_globals(|| {
6+
create_default_session_globals_then(|| {
77
let comment = "\n * Test \n ** Test\n * Test\n";
88
let stripped = beautify_doc_string(Symbol::intern(comment));
99
assert_eq!(stripped.as_str(), " Test \n* Test\n Test");
@@ -12,7 +12,7 @@ fn test_block_doc_comment_1() {
1212

1313
#[test]
1414
fn test_block_doc_comment_2() {
15-
with_default_session_globals(|| {
15+
create_default_session_globals_then(|| {
1616
let comment = "\n * Test\n * Test\n";
1717
let stripped = beautify_doc_string(Symbol::intern(comment));
1818
assert_eq!(stripped.as_str(), " Test\n Test");
@@ -21,7 +21,7 @@ fn test_block_doc_comment_2() {
2121

2222
#[test]
2323
fn test_block_doc_comment_3() {
24-
with_default_session_globals(|| {
24+
create_default_session_globals_then(|| {
2525
let comment = "\n let a: *i32;\n *a = 5;\n";
2626
let stripped = beautify_doc_string(Symbol::intern(comment));
2727
assert_eq!(stripped.as_str(), " let a: *i32;\n *a = 5;");
@@ -30,7 +30,7 @@ fn test_block_doc_comment_3() {
3030

3131
#[test]
3232
fn test_line_doc_comment() {
33-
with_default_session_globals(|| {
33+
create_default_session_globals_then(|| {
3434
let stripped = beautify_doc_string(Symbol::intern(" test"));
3535
assert_eq!(stripped.as_str(), " test");
3636
let stripped = beautify_doc_string(Symbol::intern("! test"));

‎compiler/rustc_ast_pretty/src/pprust/tests.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use super::*;
22

33
use rustc_ast as ast;
4+
use rustc_span::create_default_session_globals_then;
45
use rustc_span::symbol::Ident;
5-
use rustc_span::with_default_session_globals;
66

77
fn fun_to_string(
88
decl: &ast::FnDecl,
@@ -24,7 +24,7 @@ fn variant_to_string(var: &ast::Variant) -> String {
2424

2525
#[test]
2626
fn test_fun_to_string() {
27-
with_default_session_globals(|| {
27+
create_default_session_globals_then(|| {
2828
let abba_ident = Ident::from_str("abba");
2929

3030
let decl =
@@ -39,7 +39,7 @@ fn test_fun_to_string() {
3939

4040
#[test]
4141
fn test_variant_to_string() {
42-
with_default_session_globals(|| {
42+
create_default_session_globals_then(|| {
4343
let ident = Ident::from_str("principal_skinner");
4444

4545
let var = ast::Variant {

‎compiler/rustc_errors/src/json/tests.rs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,16 +39,11 @@ impl<T: Write> Write for Shared<T> {
3939
}
4040
}
4141

42-
fn with_default_session_globals(f: impl FnOnce()) {
43-
let session_globals = rustc_span::SessionGlobals::new(rustc_span::edition::DEFAULT_EDITION);
44-
rustc_span::SESSION_GLOBALS.set(&session_globals, f);
45-
}
46-
4742
/// Test the span yields correct positions in JSON.
4843
fn test_positions(code: &str, span: (u32, u32), expected_output: SpanTestData) {
4944
let expected_output = TestData { spans: vec![expected_output] };
5045

51-
with_default_session_globals(|| {
46+
rustc_span::create_default_session_globals_then(|| {
5247
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
5348
sm.new_source_file(Path::new("test.rs").to_owned().into(), code.to_owned());
5449

‎compiler/rustc_expand/src/mut_visit/tests.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ use crate::tests::{matches_codepattern, string_to_crate};
33
use rustc_ast as ast;
44
use rustc_ast::mut_visit::MutVisitor;
55
use rustc_ast_pretty::pprust;
6+
use rustc_span::create_default_session_globals_then;
67
use rustc_span::symbol::Ident;
7-
use rustc_span::with_default_session_globals;
88

99
// This version doesn't care about getting comments or doc-strings in.
1010
fn print_crate_items(krate: &ast::Crate) -> String {
@@ -38,7 +38,7 @@ macro_rules! assert_pred {
3838
// Make sure idents get transformed everywhere.
3939
#[test]
4040
fn ident_transformation() {
41-
with_default_session_globals(|| {
41+
create_default_session_globals_then(|| {
4242
let mut zz_visitor = ToZzIdentMutVisitor;
4343
let mut krate =
4444
string_to_crate("#[a] mod b {fn c (d : e, f : g) {h!(i,j,k);l;m}}".to_string());
@@ -55,7 +55,7 @@ fn ident_transformation() {
5555
// Make sure idents get transformed even inside macro defs.
5656
#[test]
5757
fn ident_transformation_in_defs() {
58-
with_default_session_globals(|| {
58+
create_default_session_globals_then(|| {
5959
let mut zz_visitor = ToZzIdentMutVisitor;
6060
let mut krate = string_to_crate(
6161
"macro_rules! a {(b $c:expr $(d $e:token)f+ => \

‎compiler/rustc_expand/src/parse/tests.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ use rustc_errors::PResult;
1010
use rustc_parse::new_parser_from_source_str;
1111
use rustc_parse::parser::ForceCollect;
1212
use rustc_session::parse::ParseSess;
13+
use rustc_span::create_default_session_globals_then;
1314
use rustc_span::source_map::FilePathMapping;
1415
use rustc_span::symbol::{kw, sym, Symbol};
15-
use rustc_span::with_default_session_globals;
1616
use rustc_span::{BytePos, FileName, Pos, Span};
1717

1818
use std::path::PathBuf;
@@ -51,15 +51,15 @@ fn string_to_item(source_str: String) -> Option<P<ast::Item>> {
5151
#[should_panic]
5252
#[test]
5353
fn bad_path_expr_1() {
54-
with_default_session_globals(|| {
54+
create_default_session_globals_then(|| {
5555
string_to_expr("::abc::def::return".to_string());
5656
})
5757
}
5858

5959
// Checks the token-tree-ization of macros.
6060
#[test]
6161
fn string_to_tts_macro() {
62-
with_default_session_globals(|| {
62+
create_default_session_globals_then(|| {
6363
let tts: Vec<_> =
6464
string_to_stream("macro_rules! zip (($a)=>($a))".to_string()).trees().collect();
6565
let tts: &[TokenTree] = &tts[..];
@@ -96,7 +96,7 @@ fn string_to_tts_macro() {
9696

9797
#[test]
9898
fn string_to_tts_1() {
99-
with_default_session_globals(|| {
99+
create_default_session_globals_then(|| {
100100
let tts = string_to_stream("fn a (b : i32) { b; }".to_string());
101101

102102
let expected = TokenStream::new(vec![
@@ -131,7 +131,7 @@ fn string_to_tts_1() {
131131

132132
#[test]
133133
fn parse_use() {
134-
with_default_session_globals(|| {
134+
create_default_session_globals_then(|| {
135135
let use_s = "use foo::bar::baz;";
136136
let vitem = string_to_item(use_s.to_string()).unwrap();
137137
let vitem_s = item_to_string(&vitem);
@@ -146,7 +146,7 @@ fn parse_use() {
146146

147147
#[test]
148148
fn parse_extern_crate() {
149-
with_default_session_globals(|| {
149+
create_default_session_globals_then(|| {
150150
let ex_s = "extern crate foo;";
151151
let vitem = string_to_item(ex_s.to_string()).unwrap();
152152
let vitem_s = item_to_string(&vitem);
@@ -184,7 +184,7 @@ fn get_spans_of_pat_idents(src: &str) -> Vec<Span> {
184184

185185
#[test]
186186
fn span_of_self_arg_pat_idents_are_correct() {
187-
with_default_session_globals(|| {
187+
create_default_session_globals_then(|| {
188188
let srcs = [
189189
"impl z { fn a (&self, &myarg: i32) {} }",
190190
"impl z { fn a (&mut self, &myarg: i32) {} }",
@@ -208,7 +208,7 @@ fn span_of_self_arg_pat_idents_are_correct() {
208208

209209
#[test]
210210
fn parse_exprs() {
211-
with_default_session_globals(|| {
211+
create_default_session_globals_then(|| {
212212
// just make sure that they parse....
213213
string_to_expr("3 + 4".to_string());
214214
string_to_expr("a::z.froob(b,&(987+3))".to_string());
@@ -217,7 +217,7 @@ fn parse_exprs() {
217217

218218
#[test]
219219
fn attrs_fix_bug() {
220-
with_default_session_globals(|| {
220+
create_default_session_globals_then(|| {
221221
string_to_item(
222222
"pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
223223
-> Result<Box<Writer>, String> {
@@ -238,7 +238,7 @@ let mut fflags: c_int = wb();
238238

239239
#[test]
240240
fn crlf_doc_comments() {
241-
with_default_session_globals(|| {
241+
create_default_session_globals_then(|| {
242242
let sess = sess();
243243

244244
let name_1 = FileName::Custom("crlf_source_1".to_string());
@@ -272,7 +272,7 @@ fn ttdelim_span() {
272272
new_parser_from_source_str(sess, name, source).parse_expr()
273273
}
274274

275-
with_default_session_globals(|| {
275+
create_default_session_globals_then(|| {
276276
let sess = sess();
277277
let expr = parse_expr_from_source_str(
278278
PathBuf::from("foo").into(),
@@ -300,7 +300,7 @@ fn ttdelim_span() {
300300
// See `recurse_into_file_modules` in the parser.
301301
#[test]
302302
fn out_of_line_mod() {
303-
with_default_session_globals(|| {
303+
create_default_session_globals_then(|| {
304304
let item = parse_item_from_source_str(
305305
PathBuf::from("foo").into(),
306306
"mod foo { struct S; mod this_does_not_exist; }".to_owned(),

‎compiler/rustc_expand/src/tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ use rustc_ast as ast;
22
use rustc_ast::tokenstream::TokenStream;
33
use rustc_parse::{new_parser_from_source_str, parser::Parser, source_file_to_stream};
44
use rustc_session::parse::ParseSess;
5+
use rustc_span::create_default_session_if_not_set_then;
56
use rustc_span::source_map::{FilePathMapping, SourceMap};
6-
use rustc_span::with_default_session_globals;
77
use rustc_span::{BytePos, MultiSpan, Span};
88

99
use rustc_data_structures::sync::Lrc;
@@ -124,7 +124,7 @@ impl<T: Write> Write for Shared<T> {
124124
}
125125

126126
fn test_harness(file_text: &str, span_labels: Vec<SpanLabel>, expected_output: &str) {
127-
with_default_session_globals(|| {
127+
create_default_session_if_not_set_then(|_| {
128128
let output = Arc::new(Mutex::new(Vec::new()));
129129

130130
let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));

‎compiler/rustc_expand/src/tokenstream/tests.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use crate::tests::string_to_stream;
22

33
use rustc_ast::token;
44
use rustc_ast::tokenstream::{Spacing, TokenStream, TokenStreamBuilder, TokenTree};
5-
use rustc_span::with_default_session_globals;
5+
use rustc_span::create_default_session_globals_then;
66
use rustc_span::{BytePos, Span, Symbol};
77
use smallvec::smallvec;
88

@@ -20,7 +20,7 @@ fn joint(tree: TokenTree) -> TokenStream {
2020

2121
#[test]
2222
fn test_concat() {
23-
with_default_session_globals(|| {
23+
create_default_session_globals_then(|| {
2424
let test_res = string_to_ts("foo::bar::baz");
2525
let test_fst = string_to_ts("foo::bar");
2626
let test_snd = string_to_ts("::baz");
@@ -33,7 +33,7 @@ fn test_concat() {
3333

3434
#[test]
3535
fn test_to_from_bijection() {
36-
with_default_session_globals(|| {
36+
create_default_session_globals_then(|| {
3737
let test_start = string_to_ts("foo::bar(baz)");
3838
let test_end = test_start.trees().collect();
3939
assert_eq!(test_start, test_end)
@@ -42,7 +42,7 @@ fn test_to_from_bijection() {
4242

4343
#[test]
4444
fn test_eq_0() {
45-
with_default_session_globals(|| {
45+
create_default_session_globals_then(|| {
4646
let test_res = string_to_ts("foo");
4747
let test_eqs = string_to_ts("foo");
4848
assert_eq!(test_res, test_eqs)
@@ -51,7 +51,7 @@ fn test_eq_0() {
5151

5252
#[test]
5353
fn test_eq_1() {
54-
with_default_session_globals(|| {
54+
create_default_session_globals_then(|| {
5555
let test_res = string_to_ts("::bar::baz");
5656
let test_eqs = string_to_ts("::bar::baz");
5757
assert_eq!(test_res, test_eqs)
@@ -60,7 +60,7 @@ fn test_eq_1() {
6060

6161
#[test]
6262
fn test_eq_3() {
63-
with_default_session_globals(|| {
63+
create_default_session_globals_then(|| {
6464
let test_res = string_to_ts("");
6565
let test_eqs = string_to_ts("");
6666
assert_eq!(test_res, test_eqs)
@@ -69,7 +69,7 @@ fn test_eq_3() {
6969

7070
#[test]
7171
fn test_diseq_0() {
72-
with_default_session_globals(|| {
72+
create_default_session_globals_then(|| {
7373
let test_res = string_to_ts("::bar::baz");
7474
let test_eqs = string_to_ts("bar::baz");
7575
assert_eq!(test_res == test_eqs, false)
@@ -78,7 +78,7 @@ fn test_diseq_0() {
7878

7979
#[test]
8080
fn test_diseq_1() {
81-
with_default_session_globals(|| {
81+
create_default_session_globals_then(|| {
8282
let test_res = string_to_ts("(bar,baz)");
8383
let test_eqs = string_to_ts("bar,baz");
8484
assert_eq!(test_res == test_eqs, false)
@@ -87,7 +87,7 @@ fn test_diseq_1() {
8787

8888
#[test]
8989
fn test_is_empty() {
90-
with_default_session_globals(|| {
90+
create_default_session_globals_then(|| {
9191
let test0: TokenStream = Vec::<TokenTree>::new().into_iter().collect();
9292
let test1: TokenStream =
9393
TokenTree::token(token::Ident(Symbol::intern("a"), false), sp(0, 1)).into();
@@ -101,7 +101,7 @@ fn test_is_empty() {
101101

102102
#[test]
103103
fn test_dotdotdot() {
104-
with_default_session_globals(|| {
104+
create_default_session_globals_then(|| {
105105
let mut builder = TokenStreamBuilder::new();
106106
builder.push(joint(TokenTree::token(token::Dot, sp(0, 1))));
107107
builder.push(joint(TokenTree::token(token::Dot, sp(1, 2))));

‎compiler/rustc_interface/src/interface.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ impl Compiler {
7676

7777
/// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`.
7878
pub fn parse_cfgspecs(cfgspecs: Vec<String>) -> FxHashSet<(String, Option<String>)> {
79-
rustc_span::with_default_session_globals(move || {
79+
rustc_span::create_default_session_if_not_set_then(move |_| {
8080
let cfg = cfgspecs
8181
.into_iter()
8282
.map(|s| {

‎compiler/rustc_interface/src/tests.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ fn assert_different_hash(x: &Options, y: &Options) {
9999
// When the user supplies --test we should implicitly supply --cfg test
100100
#[test]
101101
fn test_switch_implies_cfg_test() {
102-
rustc_span::with_default_session_globals(|| {
102+
rustc_span::create_default_session_globals_then(|| {
103103
let matches = optgroups().parse(&["--test".to_string()]).unwrap();
104104
let (sess, cfg) = mk_session(matches);
105105
let cfg = build_configuration(&sess, to_crate_config(cfg));
@@ -110,7 +110,7 @@ fn test_switch_implies_cfg_test() {
110110
// When the user supplies --test and --cfg test, don't implicitly add another --cfg test
111111
#[test]
112112
fn test_switch_implies_cfg_test_unless_cfg_test() {
113-
rustc_span::with_default_session_globals(|| {
113+
rustc_span::create_default_session_globals_then(|| {
114114
let matches = optgroups().parse(&["--test".to_string(), "--cfg=test".to_string()]).unwrap();
115115
let (sess, cfg) = mk_session(matches);
116116
let cfg = build_configuration(&sess, to_crate_config(cfg));
@@ -122,20 +122,20 @@ fn test_switch_implies_cfg_test_unless_cfg_test() {
122122

123123
#[test]
124124
fn test_can_print_warnings() {
125-
rustc_span::with_default_session_globals(|| {
125+
rustc_span::create_default_session_globals_then(|| {
126126
let matches = optgroups().parse(&["-Awarnings".to_string()]).unwrap();
127127
let (sess, _) = mk_session(matches);
128128
assert!(!sess.diagnostic().can_emit_warnings());
129129
});
130130

131-
rustc_span::with_default_session_globals(|| {
131+
rustc_span::create_default_session_globals_then(|| {
132132
let matches =
133133
optgroups().parse(&["-Awarnings".to_string(), "-Dwarnings".to_string()]).unwrap();
134134
let (sess, _) = mk_session(matches);
135135
assert!(sess.diagnostic().can_emit_warnings());
136136
});
137137

138-
rustc_span::with_default_session_globals(|| {
138+
rustc_span::create_default_session_globals_then(|| {
139139
let matches = optgroups().parse(&["-Adead_code".to_string()]).unwrap();
140140
let (sess, _) = mk_session(matches);
141141
assert!(sess.diagnostic().can_emit_warnings());

‎compiler/rustc_interface/src/util.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ pub fn setup_callbacks_and_run_in_thread_pool_with_globals<F: FnOnce() -> R + Se
153153
crate::callbacks::setup_callbacks();
154154

155155
let main_handler = move || {
156-
rustc_span::with_session_globals(edition, || {
156+
rustc_span::create_session_globals_then(edition, || {
157157
io::set_output_capture(stderr.clone());
158158
f()
159159
})
@@ -174,12 +174,13 @@ unsafe fn handle_deadlock() {
174174
rustc_data_structures::sync::assert_sync::<tls::ImplicitCtxt<'_, '_>>();
175175
let icx: &tls::ImplicitCtxt<'_, '_> = &*(context as *const tls::ImplicitCtxt<'_, '_>);
176176

177-
let session_globals = rustc_span::SESSION_GLOBALS.with(|sg| sg as *const _);
177+
let session_globals = rustc_span::with_session_globals(|sg| sg as *const _);
178178
let session_globals = &*session_globals;
179179
thread::spawn(move || {
180180
tls::enter_context(icx, |_| {
181-
rustc_span::SESSION_GLOBALS
182-
.set(session_globals, || tls::with(|tcx| tcx.queries.deadlock(tcx, &registry)))
181+
rustc_span::set_session_globals_then(session_globals, || {
182+
tls::with(|tcx| tcx.queries.deadlock(tcx, &registry))
183+
})
183184
});
184185
});
185186
}
@@ -206,13 +207,13 @@ pub fn setup_callbacks_and_run_in_thread_pool_with_globals<F: FnOnce() -> R + Se
206207

207208
let with_pool = move |pool: &rayon::ThreadPool| pool.install(f);
208209

209-
rustc_span::with_session_globals(edition, || {
210-
rustc_span::SESSION_GLOBALS.with(|session_globals| {
210+
rustc_span::create_session_globals_then(edition, || {
211+
rustc_span::with_session_globals(|session_globals| {
211212
// The main handler runs for each Rayon worker thread and sets up
212213
// the thread local rustc uses. `session_globals` is captured and set
213214
// on the new threads.
214215
let main_handler = move |thread: rayon::ThreadBuilder| {
215-
rustc_span::SESSION_GLOBALS.set(session_globals, || {
216+
rustc_span::set_session_globals_then(session_globals, || {
216217
io::set_output_capture(stderr.clone());
217218
thread.run()
218219
})

‎compiler/rustc_mir/src/transform/coverage/tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
//! are unrelated to the `TyCtxt` global. Without initializing the `Span` session globals, some
2323
//! basic, coverage-specific features would be impossible to test, but thankfully initializing these
2424
//! globals is comparatively simpler. The easiest way is to wrap the test in a closure argument
25-
//! to: `rustc_span::with_default_session_globals(|| { test_here(); })`.
25+
//! to: `rustc_span::create_default_session_globals_then(|| { test_here(); })`.
2626
2727
use super::counters;
2828
use super::debug;
@@ -677,7 +677,7 @@ fn synthesize_body_span_from_terminators(mir_body: &Body<'_>) -> Span {
677677

678678
#[test]
679679
fn test_make_bcb_counters() {
680-
rustc_span::with_default_session_globals(|| {
680+
rustc_span::create_default_session_globals_then(|| {
681681
let mir_body = goto_switchint();
682682
let body_span = synthesize_body_span_from_terminators(&mir_body);
683683
let mut basic_coverage_blocks = graph::CoverageGraph::from_mir(&mir_body);

‎compiler/rustc_parse_format/src/tests.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,8 +144,7 @@ fn format_align_fill() {
144144
}
145145
#[test]
146146
fn format_counts() {
147-
use rustc_span::{edition, SessionGlobals, SESSION_GLOBALS};
148-
SESSION_GLOBALS.set(&SessionGlobals::new(edition::DEFAULT_EDITION), || {
147+
rustc_span::create_default_session_globals_then(|| {
149148
same(
150149
"{:10x}",
151150
&[NextArgument(Argument {

‎compiler/rustc_span/src/hygiene.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626

2727
use crate::edition::Edition;
2828
use crate::symbol::{kw, sym, Symbol};
29-
use crate::SESSION_GLOBALS;
29+
use crate::with_session_globals;
3030
use crate::{BytePos, CachingSourceMapView, ExpnIdCache, SourceFile, Span, DUMMY_SP};
3131

3232
use crate::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
@@ -200,7 +200,7 @@ impl HygieneData {
200200
}
201201

202202
pub fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T {
203-
SESSION_GLOBALS.with(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut()))
203+
with_session_globals(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut()))
204204
}
205205

206206
fn fresh_expn(&mut self, mut expn_data: Option<ExpnData>) -> ExpnId {
@@ -1359,8 +1359,9 @@ fn update_disambiguator(expn_id: ExpnId) {
13591359
}
13601360
}
13611361

1362-
let source_map = SESSION_GLOBALS
1363-
.with(|session_globals| session_globals.source_map.borrow().as_ref().unwrap().clone());
1362+
let source_map = with_session_globals(|session_globals| {
1363+
session_globals.source_map.borrow().as_ref().unwrap().clone()
1364+
});
13641365

13651366
let mut ctx =
13661367
DummyHashStableContext { caching_source_map: CachingSourceMapView::new(&source_map) };

‎compiler/rustc_span/src/lev_distance/tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ fn test_lev_distance() {
2121

2222
#[test]
2323
fn test_find_best_match_for_name() {
24-
use crate::with_default_session_globals;
25-
with_default_session_globals(|| {
24+
use crate::create_default_session_globals_then;
25+
create_default_session_globals_then(|| {
2626
let input = vec![Symbol::intern("aaab"), Symbol::intern("aaabc")];
2727
assert_eq!(
2828
find_best_match_for_name(&input, Symbol::intern("aaaa"), None),

‎compiler/rustc_span/src/lib.rs

Lines changed: 53 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -99,19 +99,65 @@ impl SessionGlobals {
9999
}
100100
}
101101

102-
pub fn with_session_globals<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
102+
#[inline]
103+
pub fn create_session_globals_then<R>(edition: Edition, f: impl FnOnce() -> R) -> R {
104+
assert!(
105+
!SESSION_GLOBALS.is_set(),
106+
"SESSION_GLOBALS should never be overwritten! \
107+
Use another thread if you need another SessionGlobals"
108+
);
103109
let session_globals = SessionGlobals::new(edition);
104110
SESSION_GLOBALS.set(&session_globals, f)
105111
}
106112

107-
pub fn with_default_session_globals<R>(f: impl FnOnce() -> R) -> R {
108-
with_session_globals(edition::DEFAULT_EDITION, f)
113+
#[inline]
114+
pub fn set_session_globals_then<R>(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R {
115+
assert!(
116+
!SESSION_GLOBALS.is_set(),
117+
"SESSION_GLOBALS should never be overwritten! \
118+
Use another thread if you need another SessionGlobals"
119+
);
120+
SESSION_GLOBALS.set(session_globals, f)
121+
}
122+
123+
#[inline]
124+
pub fn create_default_session_if_not_set_then<R, F>(f: F) -> R
125+
where
126+
F: FnOnce(&SessionGlobals) -> R,
127+
{
128+
create_session_if_not_set_then(edition::DEFAULT_EDITION, f)
129+
}
130+
131+
#[inline]
132+
pub fn create_session_if_not_set_then<R, F>(edition: Edition, f: F) -> R
133+
where
134+
F: FnOnce(&SessionGlobals) -> R,
135+
{
136+
if !SESSION_GLOBALS.is_set() {
137+
let session_globals = SessionGlobals::new(edition);
138+
SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f))
139+
} else {
140+
SESSION_GLOBALS.with(f)
141+
}
142+
}
143+
144+
#[inline]
145+
pub fn with_session_globals<R, F>(f: F) -> R
146+
where
147+
F: FnOnce(&SessionGlobals) -> R,
148+
{
149+
SESSION_GLOBALS.with(f)
150+
}
151+
152+
#[inline]
153+
pub fn create_default_session_globals_then<R>(f: impl FnOnce() -> R) -> R {
154+
create_session_globals_then(edition::DEFAULT_EDITION, f)
109155
}
110156

111157
// If this ever becomes non thread-local, `decode_syntax_context`
112158
// and `decode_expn_id` will need to be updated to handle concurrent
113159
// deserialization.
114-
scoped_tls::scoped_thread_local!(pub static SESSION_GLOBALS: SessionGlobals);
160+
scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals);
115161

116162
// FIXME: We should use this enum or something like it to get rid of the
117163
// use of magic `/rust/1.x/...` paths across the board.
@@ -857,13 +903,13 @@ impl<D: Decoder> Decodable<D> for Span {
857903
/// the `SourceMap` provided to this function. If that is not available,
858904
/// we fall back to printing the raw `Span` field values.
859905
pub fn with_source_map<T, F: FnOnce() -> T>(source_map: Lrc<SourceMap>, f: F) -> T {
860-
SESSION_GLOBALS.with(|session_globals| {
906+
with_session_globals(|session_globals| {
861907
*session_globals.source_map.borrow_mut() = Some(source_map);
862908
});
863909
struct ClearSourceMap;
864910
impl Drop for ClearSourceMap {
865911
fn drop(&mut self) {
866-
SESSION_GLOBALS.with(|session_globals| {
912+
with_session_globals(|session_globals| {
867913
session_globals.source_map.borrow_mut().take();
868914
});
869915
}
@@ -882,7 +928,7 @@ pub fn debug_with_source_map(
882928
}
883929

884930
pub fn default_span_debug(span: Span, f: &mut fmt::Formatter<'_>) -> fmt::Result {
885-
SESSION_GLOBALS.with(|session_globals| {
931+
with_session_globals(|session_globals| {
886932
if let Some(source_map) = &*session_globals.source_map.borrow() {
887933
debug_with_source_map(span, f, source_map)
888934
} else {

‎compiler/rustc_span/src/span_encoding.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
// See https://internals.rust-lang.org/t/rfc-compiler-refactoring-spans/1357/28
66

77
use crate::hygiene::SyntaxContext;
8-
use crate::SESSION_GLOBALS;
98
use crate::{BytePos, SpanData};
109

1110
use rustc_data_structures::fx::FxIndexSet;
@@ -122,5 +121,5 @@ impl SpanInterner {
122121
// If an interner exists, return it. Otherwise, prepare a fresh one.
123122
#[inline]
124123
fn with_span_interner<T, F: FnOnce(&mut SpanInterner) -> T>(f: F) -> T {
125-
SESSION_GLOBALS.with(|session_globals| f(&mut *session_globals.span_interner.lock()))
124+
crate::with_session_globals(|session_globals| f(&mut *session_globals.span_interner.lock()))
126125
}

‎compiler/rustc_span/src/symbol.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use std::fmt;
1313
use std::hash::{Hash, Hasher};
1414
use std::str;
1515

16-
use crate::{Edition, Span, DUMMY_SP, SESSION_GLOBALS};
16+
use crate::{with_session_globals, Edition, Span, DUMMY_SP};
1717

1818
#[cfg(test)]
1919
mod tests;
@@ -1783,7 +1783,7 @@ impl Ident {
17831783

17841784
#[inline]
17851785
fn with_interner<T, F: FnOnce(&mut Interner) -> T>(f: F) -> T {
1786-
SESSION_GLOBALS.with(|session_globals| f(&mut *session_globals.symbol_interner.lock()))
1786+
with_session_globals(|session_globals| f(&mut *session_globals.symbol_interner.lock()))
17871787
}
17881788

17891789
/// An alternative to [`Symbol`], useful when the chars within the symbol need to

‎compiler/rustc_span/src/symbol/tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use super::*;
22

3-
use crate::{edition, SessionGlobals};
3+
use crate::create_default_session_globals_then;
44

55
#[test]
66
fn interner_tests() {
@@ -18,7 +18,7 @@ fn interner_tests() {
1818

1919
#[test]
2020
fn without_first_quote_test() {
21-
SESSION_GLOBALS.set(&SessionGlobals::new(edition::DEFAULT_EDITION), || {
21+
create_default_session_globals_then(|| {
2222
let i = Ident::from_str("'break");
2323
assert_eq!(i.without_first_quote().name, kw::Break);
2424
});

‎src/librustdoc/clean/cfg/tests.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ use super::*;
22

33
use rustc_ast::attr;
44
use rustc_ast::Path;
5+
use rustc_span::create_default_session_globals_then;
56
use rustc_span::symbol::{Ident, Symbol};
6-
use rustc_span::with_default_session_globals;
77
use rustc_span::DUMMY_SP;
88

99
fn word_cfg(s: &str) -> Cfg {
@@ -52,7 +52,7 @@ macro_rules! dummy_meta_item_list {
5252

5353
#[test]
5454
fn test_cfg_not() {
55-
with_default_session_globals(|| {
55+
create_default_session_globals_then(|| {
5656
assert_eq!(!Cfg::False, Cfg::True);
5757
assert_eq!(!Cfg::True, Cfg::False);
5858
assert_eq!(!word_cfg("test"), Cfg::Not(Box::new(word_cfg("test"))));
@@ -70,7 +70,7 @@ fn test_cfg_not() {
7070

7171
#[test]
7272
fn test_cfg_and() {
73-
with_default_session_globals(|| {
73+
create_default_session_globals_then(|| {
7474
let mut x = Cfg::False;
7575
x &= Cfg::True;
7676
assert_eq!(x, Cfg::False);
@@ -154,7 +154,7 @@ fn test_cfg_and() {
154154

155155
#[test]
156156
fn test_cfg_or() {
157-
with_default_session_globals(|| {
157+
create_default_session_globals_then(|| {
158158
let mut x = Cfg::True;
159159
x |= Cfg::False;
160160
assert_eq!(x, Cfg::True);
@@ -238,7 +238,7 @@ fn test_cfg_or() {
238238

239239
#[test]
240240
fn test_parse_ok() {
241-
with_default_session_globals(|| {
241+
create_default_session_globals_then(|| {
242242
let mi = dummy_meta_item_word("all");
243243
assert_eq!(Cfg::parse(&mi), Ok(word_cfg("all")));
244244

@@ -271,7 +271,7 @@ fn test_parse_ok() {
271271

272272
#[test]
273273
fn test_parse_err() {
274-
with_default_session_globals(|| {
274+
create_default_session_globals_then(|| {
275275
let mi = attr::mk_name_value_item(Ident::from_str("foo"), LitKind::Bool(false), DUMMY_SP);
276276
assert!(Cfg::parse(&mi).is_err());
277277

@@ -303,7 +303,7 @@ fn test_parse_err() {
303303

304304
#[test]
305305
fn test_render_short_html() {
306-
with_default_session_globals(|| {
306+
create_default_session_globals_then(|| {
307307
assert_eq!(word_cfg("unix").render_short_html(), "Unix");
308308
assert_eq!(name_value_cfg("target_os", "macos").render_short_html(), "macOS");
309309
assert_eq!(name_value_cfg("target_pointer_width", "16").render_short_html(), "16-bit");
@@ -358,7 +358,7 @@ fn test_render_short_html() {
358358

359359
#[test]
360360
fn test_render_long_html() {
361-
with_default_session_globals(|| {
361+
create_default_session_globals_then(|| {
362362
assert_eq!(
363363
word_cfg("unix").render_long_html(),
364364
"This is supported on <strong>Unix</strong> only."
@@ -442,7 +442,7 @@ fn test_render_long_html() {
442442
fn test_simplify_with() {
443443
// This is a tiny subset of things that could be simplified, but it likely covers 90% of
444444
// real world usecases well.
445-
with_default_session_globals(|| {
445+
create_default_session_globals_then(|| {
446446
let foo = word_cfg("foo");
447447
let bar = word_cfg("bar");
448448
let baz = word_cfg("baz");

‎src/librustdoc/doctest.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,7 @@ crate fn make_test(
514514
// Uses librustc_ast to parse the doctest and find if there's a main fn and the extern
515515
// crate already is included.
516516
let result = rustc_driver::catch_fatal_errors(|| {
517-
rustc_span::with_session_globals(edition, || {
517+
rustc_span::create_session_if_not_set_then(edition, |_| {
518518
use rustc_errors::emitter::{Emitter, EmitterWriter};
519519
use rustc_errors::Handler;
520520
use rustc_parse::maybe_new_parser_from_source_str;

‎src/librustdoc/html/highlight/tests.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
use super::write_code;
22
use crate::html::format::Buffer;
33
use expect_test::expect_file;
4+
use rustc_span::create_default_session_globals_then;
45
use rustc_span::edition::Edition;
5-
use rustc_span::with_default_session_globals;
66

77
const STYLE: &str = r#"
88
<style>
@@ -18,7 +18,7 @@ const STYLE: &str = r#"
1818

1919
#[test]
2020
fn test_html_highlighting() {
21-
with_default_session_globals(|| {
21+
create_default_session_globals_then(|| {
2222
let src = include_str!("fixtures/sample.rs");
2323
let html = {
2424
let mut out = Buffer::new();
@@ -31,7 +31,7 @@ fn test_html_highlighting() {
3131

3232
#[test]
3333
fn test_dos_backline() {
34-
with_default_session_globals(|| {
34+
create_default_session_globals_then(|| {
3535
let src = "pub fn foo() {\r\n\
3636
println!(\"foo\");\r\n\
3737
}\r\n";

‎src/librustdoc/passes/unindent_comments/tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use super::*;
2+
use rustc_span::create_default_session_globals_then;
23
use rustc_span::source_map::DUMMY_SP;
34
use rustc_span::symbol::Symbol;
4-
use rustc_span::with_default_session_globals;
55

66
fn create_doc_fragment(s: &str) -> Vec<DocFragment> {
77
vec![DocFragment {
@@ -17,7 +17,7 @@ fn create_doc_fragment(s: &str) -> Vec<DocFragment> {
1717

1818
#[track_caller]
1919
fn run_test(input: &str, expected: &str) {
20-
with_default_session_globals(|| {
20+
create_default_session_globals_then(|| {
2121
let mut s = create_doc_fragment(input);
2222
unindent_fragments(&mut s);
2323
assert_eq!(&s.iter().collect::<String>(), expected);

‎src/test/ui-fulldeps/mod_dir_path_canonicalized.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use std::path::Path;
1919
mod gravy;
2020

2121
pub fn main() {
22-
rustc_span::with_default_session_globals(|| parse());
22+
rustc_span::create_default_session_globals_then(|| parse());
2323

2424
assert_eq!(gravy::foo(), 10);
2525
}

‎src/test/ui-fulldeps/pprust-expr-roundtrip.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ impl MutVisitor for AddParens {
212212
}
213213

214214
fn main() {
215-
rustc_span::with_default_session_globals(|| run());
215+
rustc_span::create_default_session_globals_then(|| run());
216216
}
217217

218218
fn run() {

‎src/tools/clippy/clippy_lints/src/doc.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ use rustc_span::source_map::{BytePos, FilePathMapping, MultiSpan, SourceMap, Spa
2525
use rustc_span::{sym, FileName, Pos};
2626
use std::io;
2727
use std::ops::Range;
28+
use std::thread;
2829
use url::Url;
2930

3031
declare_clippy_lint! {
@@ -548,10 +549,10 @@ fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize
548549
}
549550

550551
fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
551-
fn has_needless_main(code: &str, edition: Edition) -> bool {
552+
fn has_needless_main(code: String, edition: Edition) -> bool {
552553
rustc_driver::catch_fatal_errors(|| {
553-
rustc_span::with_session_globals(edition, || {
554-
let filename = FileName::anon_source_code(code);
554+
rustc_span::create_session_globals_then(edition, || {
555+
let filename = FileName::anon_source_code(&code);
555556

556557
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
557558
let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
@@ -613,7 +614,10 @@ fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
613614
.unwrap_or_default()
614615
}
615616

616-
if has_needless_main(text, edition) {
617+
// Because of the global session, we need to create a new session in a different thread with
618+
// the edition we need.
619+
let text = text.to_owned();
620+
if thread::spawn(move || has_needless_main(text, edition)).join().expect("thread::spawn failed") {
617621
span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
618622
}
619623
}

‎src/tools/error_index_generator/main.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,8 @@ fn parse_args() -> (OutputFormat, PathBuf) {
283283
fn main() {
284284
rustc_driver::init_env_logger("RUST_LOG");
285285
let (format, dst) = parse_args();
286-
let result = rustc_span::with_default_session_globals(move || main_with_result(format, &dst));
286+
let result =
287+
rustc_span::create_default_session_globals_then(move || main_with_result(format, &dst));
287288
if let Err(e) = result {
288289
panic!("{}", e.to_string());
289290
}

‎src/tools/rustfmt/src/formatting.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ impl<'b, T: Write + 'b> Session<'b, T> {
3434
return Err(ErrorKind::VersionMismatch);
3535
}
3636

37-
rustc_span::with_session_globals(self.config.edition().into(), || {
37+
rustc_span::create_session_if_not_set_then(self.config.edition().into(), |_| {
3838
if self.config.disable_all_formatting() {
3939
// When the input is from stdin, echo back the input.
4040
if let Input::Text(ref buf) = input {

0 commit comments

Comments
 (0)
Please sign in to comment.