Skip to content

Commit c82c10c

Browse files
committed
hygiene: Asserts, comments, code cleanup
1 parent ecade53 commit c82c10c

File tree

1 file changed

+91
-53
lines changed

1 file changed

+91
-53
lines changed

compiler/rustc_span/src/hygiene.rs

Lines changed: 91 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@
2727
use std::cell::RefCell;
2828
use std::collections::hash_map::Entry;
2929
use std::collections::hash_set::Entry as SetEntry;
30-
use std::fmt;
3130
use std::hash::Hash;
3231
use std::sync::Arc;
32+
use std::{fmt, iter, mem};
3333

3434
use rustc_data_structures::fingerprint::Fingerprint;
3535
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
@@ -57,7 +57,11 @@ pub struct SyntaxContext(u32);
5757
impl !Ord for SyntaxContext {}
5858
impl !PartialOrd for SyntaxContext {}
5959

60-
#[derive(Debug, Encodable, Decodable, Clone)]
60+
/// If this part of two syntax contexts is equal, then the whole syntax contexts should be equal.
61+
/// The other fields are only for caching.
62+
type SyntaxContextKey = (SyntaxContext, ExpnId, Transparency);
63+
64+
#[derive(Clone, Copy, PartialEq, Debug, Encodable, Decodable)]
6165
pub struct SyntaxContextData {
6266
outer_expn: ExpnId,
6367
outer_transparency: Transparency,
@@ -70,6 +74,27 @@ pub struct SyntaxContextData {
7074
dollar_crate_name: Symbol,
7175
}
7276

77+
impl SyntaxContextData {
78+
fn root() -> SyntaxContextData {
79+
SyntaxContextData {
80+
outer_expn: ExpnId::root(),
81+
outer_transparency: Transparency::Opaque,
82+
parent: SyntaxContext::root(),
83+
opaque: SyntaxContext::root(),
84+
opaque_and_semitransparent: SyntaxContext::root(),
85+
dollar_crate_name: kw::DollarCrate,
86+
}
87+
}
88+
89+
fn decode_placeholder() -> SyntaxContextData {
90+
SyntaxContextData { dollar_crate_name: kw::Empty, ..SyntaxContextData::root() }
91+
}
92+
93+
fn is_decode_placeholder(&self) -> bool {
94+
self.dollar_crate_name == kw::Empty
95+
}
96+
}
97+
7398
rustc_index::newtype_index! {
7499
/// A unique ID associated with a macro invocation and expansion.
75100
#[orderable]
@@ -342,7 +367,7 @@ pub(crate) struct HygieneData {
342367
foreign_expn_hashes: FxHashMap<ExpnId, ExpnHash>,
343368
expn_hash_to_expn_id: UnhashMap<ExpnHash, ExpnId>,
344369
syntax_context_data: Vec<SyntaxContextData>,
345-
syntax_context_map: FxHashMap<(SyntaxContext, ExpnId, Transparency), SyntaxContext>,
370+
syntax_context_map: FxHashMap<SyntaxContextKey, SyntaxContext>,
346371
/// Maps the `local_hash` of an `ExpnData` to the next disambiguator value.
347372
/// This is used by `update_disambiguator` to keep track of which `ExpnData`s
348373
/// would have collisions without a disambiguator.
@@ -361,21 +386,15 @@ impl HygieneData {
361386
None,
362387
);
363388

389+
let root_ctxt_data = SyntaxContextData::root();
364390
HygieneData {
365391
local_expn_data: IndexVec::from_elem_n(Some(root_data), 1),
366392
local_expn_hashes: IndexVec::from_elem_n(ExpnHash(Fingerprint::ZERO), 1),
367393
foreign_expn_data: FxHashMap::default(),
368394
foreign_expn_hashes: FxHashMap::default(),
369-
expn_hash_to_expn_id: std::iter::once((ExpnHash(Fingerprint::ZERO), ExpnId::root()))
395+
expn_hash_to_expn_id: iter::once((ExpnHash(Fingerprint::ZERO), ExpnId::root()))
370396
.collect(),
371-
syntax_context_data: vec![SyntaxContextData {
372-
outer_expn: ExpnId::root(),
373-
outer_transparency: Transparency::Opaque,
374-
parent: SyntaxContext(0),
375-
opaque: SyntaxContext(0),
376-
opaque_and_semitransparent: SyntaxContext(0),
377-
dollar_crate_name: kw::DollarCrate,
378-
}],
397+
syntax_context_data: vec![root_ctxt_data],
379398
syntax_context_map: FxHashMap::default(),
380399
expn_data_disambiguators: UnhashMap::default(),
381400
}
@@ -425,23 +444,28 @@ impl HygieneData {
425444
}
426445

427446
fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext {
447+
assert!(!self.syntax_context_data[ctxt.0 as usize].is_decode_placeholder());
428448
self.syntax_context_data[ctxt.0 as usize].opaque
429449
}
430450

431451
fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext {
452+
assert!(!self.syntax_context_data[ctxt.0 as usize].is_decode_placeholder());
432453
self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent
433454
}
434455

435456
fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId {
457+
assert!(!self.syntax_context_data[ctxt.0 as usize].is_decode_placeholder());
436458
self.syntax_context_data[ctxt.0 as usize].outer_expn
437459
}
438460

439461
fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) {
462+
assert!(!self.syntax_context_data[ctxt.0 as usize].is_decode_placeholder());
440463
let data = &self.syntax_context_data[ctxt.0 as usize];
441464
(data.outer_expn, data.outer_transparency)
442465
}
443466

444467
fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext {
468+
assert!(!self.syntax_context_data[ctxt.0 as usize].is_decode_placeholder());
445469
self.syntax_context_data[ctxt.0 as usize].parent
446470
}
447471

@@ -551,6 +575,7 @@ impl HygieneData {
551575
transparency: Transparency,
552576
) -> SyntaxContext {
553577
let syntax_context_data = &mut self.syntax_context_data;
578+
assert!(!syntax_context_data[ctxt.0 as usize].is_decode_placeholder());
554579
let mut opaque = syntax_context_data[ctxt.0 as usize].opaque;
555580
let mut opaque_and_semitransparent =
556581
syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent;
@@ -561,7 +586,7 @@ impl HygieneData {
561586
.syntax_context_map
562587
.entry((parent, expn_id, transparency))
563588
.or_insert_with(|| {
564-
let new_opaque = SyntaxContext(syntax_context_data.len() as u32);
589+
let new_opaque = SyntaxContext::from_usize(syntax_context_data.len());
565590
syntax_context_data.push(SyntaxContextData {
566591
outer_expn: expn_id,
567592
outer_transparency: transparency,
@@ -581,7 +606,7 @@ impl HygieneData {
581606
.entry((parent, expn_id, transparency))
582607
.or_insert_with(|| {
583608
let new_opaque_and_semitransparent =
584-
SyntaxContext(syntax_context_data.len() as u32);
609+
SyntaxContext::from_usize(syntax_context_data.len());
585610
syntax_context_data.push(SyntaxContextData {
586611
outer_expn: expn_id,
587612
outer_transparency: transparency,
@@ -596,8 +621,6 @@ impl HygieneData {
596621

597622
let parent = ctxt;
598623
*self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| {
599-
let new_opaque_and_semitransparent_and_transparent =
600-
SyntaxContext(syntax_context_data.len() as u32);
601624
syntax_context_data.push(SyntaxContextData {
602625
outer_expn: expn_id,
603626
outer_transparency: transparency,
@@ -606,7 +629,7 @@ impl HygieneData {
606629
opaque_and_semitransparent,
607630
dollar_crate_name: kw::DollarCrate,
608631
});
609-
new_opaque_and_semitransparent_and_transparent
632+
SyntaxContext::from_usize(syntax_context_data.len() - 1)
610633
})
611634
}
612635
}
@@ -713,6 +736,10 @@ impl SyntaxContext {
713736
SyntaxContext(raw as u32)
714737
}
715738

739+
fn from_usize(raw: usize) -> SyntaxContext {
740+
SyntaxContext(u32::try_from(raw).unwrap())
741+
}
742+
716743
/// Extend a syntax context with a given expansion and transparency.
717744
pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext {
718745
HygieneData::with(|data| data.apply_mark(self, expn_id, transparency))
@@ -893,7 +920,10 @@ impl SyntaxContext {
893920
}
894921

895922
pub(crate) fn dollar_crate_name(self) -> Symbol {
896-
HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name)
923+
HygieneData::with(|data| {
924+
assert!(!data.syntax_context_data[self.0 as usize].is_decode_placeholder());
925+
data.syntax_context_data[self.0 as usize].dollar_crate_name
926+
})
897927
}
898928

899929
pub fn edition(self) -> Edition {
@@ -1239,7 +1269,7 @@ impl HygieneEncodeContext {
12391269

12401270
// Consume the current round of SyntaxContexts.
12411271
// Drop the lock() temporary early
1242-
let latest_ctxts = { std::mem::take(&mut *self.latest_ctxts.lock()) };
1272+
let latest_ctxts = { mem::take(&mut *self.latest_ctxts.lock()) };
12431273

12441274
// It's fine to iterate over a HashMap, because the serialization
12451275
// of the table that we insert data into doesn't depend on insertion
@@ -1251,7 +1281,7 @@ impl HygieneEncodeContext {
12511281
}
12521282
});
12531283

1254-
let latest_expns = { std::mem::take(&mut *self.latest_expns.lock()) };
1284+
let latest_expns = { mem::take(&mut *self.latest_expns.lock()) };
12551285

12561286
// Same as above, this is fine as we are inserting into a order-independent hashset
12571287
#[allow(rustc::potential_query_instability)]
@@ -1368,28 +1398,33 @@ pub fn decode_syntax_context<D: Decoder, F: FnOnce(&mut D, u32) -> SyntaxContext
13681398
return SyntaxContext::root();
13691399
}
13701400

1371-
let ctxt = {
1401+
let pending_ctxt = {
13721402
let mut inner = context.inner.lock();
13731403

1404+
// Reminder: `HygieneDecodeContext` is per-crate, so there are no collisions between
1405+
// raw ids from different crate metadatas.
13741406
if let Some(ctxt) = inner.remapped_ctxts.get(raw_id as usize).copied().flatten() {
13751407
// This has already been decoded.
13761408
return ctxt;
13771409
}
13781410

13791411
match inner.decoding.entry(raw_id) {
13801412
Entry::Occupied(ctxt_entry) => {
1413+
let pending_ctxt = *ctxt_entry.get();
13811414
match context.local_in_progress.borrow_mut().entry(raw_id) {
1382-
SetEntry::Occupied(..) => {
1383-
// We're decoding this already on the current thread. Return here
1384-
// and let the function higher up the stack finish decoding to handle
1385-
// recursive cases.
1386-
return *ctxt_entry.get();
1387-
}
1415+
// We're decoding this already on the current thread. Return here and let the
1416+
// function higher up the stack finish decoding to handle recursive cases.
1417+
// Hopefully having a `SyntaxContext` that refers to an incorrect data is ok
1418+
// during reminder of the decoding process, it's certainly not ok after the
1419+
// top level decoding function returns.
1420+
SetEntry::Occupied(..) => return pending_ctxt,
1421+
// Some other thread is currently decoding this.
1422+
// Race with it (alternatively we could wait here).
1423+
// We cannot return this value, unlike in the recursive case above, because it
1424+
// may expose a `SyntaxContext` pointing to incorrect data to arbitrary code.
13881425
SetEntry::Vacant(entry) => {
13891426
entry.insert();
1390-
1391-
// Some other thread is current decoding this. Race with it.
1392-
*ctxt_entry.get()
1427+
pending_ctxt
13931428
}
13941429
}
13951430
}
@@ -1400,18 +1435,10 @@ pub fn decode_syntax_context<D: Decoder, F: FnOnce(&mut D, u32) -> SyntaxContext
14001435
// Allocate and store SyntaxContext id *before* calling the decoder function,
14011436
// as the SyntaxContextData may reference itself.
14021437
let new_ctxt = HygieneData::with(|hygiene_data| {
1403-
let new_ctxt = SyntaxContext(hygiene_data.syntax_context_data.len() as u32);
14041438
// Push a dummy SyntaxContextData to ensure that nobody else can get the
1405-
// same ID as us. This will be overwritten after call `decode_Data`
1406-
hygiene_data.syntax_context_data.push(SyntaxContextData {
1407-
outer_expn: ExpnId::root(),
1408-
outer_transparency: Transparency::Transparent,
1409-
parent: SyntaxContext::root(),
1410-
opaque: SyntaxContext::root(),
1411-
opaque_and_semitransparent: SyntaxContext::root(),
1412-
dollar_crate_name: kw::Empty,
1413-
});
1414-
new_ctxt
1439+
// same ID as us. This will be overwritten after call `decode_data`.
1440+
hygiene_data.syntax_context_data.push(SyntaxContextData::decode_placeholder());
1441+
SyntaxContext::from_usize(hygiene_data.syntax_context_data.len() - 1)
14151442
});
14161443
entry.insert(new_ctxt);
14171444
new_ctxt
@@ -1421,27 +1448,38 @@ pub fn decode_syntax_context<D: Decoder, F: FnOnce(&mut D, u32) -> SyntaxContext
14211448

14221449
// Don't try to decode data while holding the lock, since we need to
14231450
// be able to recursively decode a SyntaxContext
1424-
let mut ctxt_data = decode_data(d, raw_id);
1425-
// Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names`
1426-
// We don't care what the encoding crate set this to - we want to resolve it
1427-
// from the perspective of the current compilation session
1428-
ctxt_data.dollar_crate_name = kw::DollarCrate;
1451+
let ctxt_data = decode_data(d, raw_id);
14291452

1430-
// Overwrite the dummy data with our decoded SyntaxContextData
1431-
HygieneData::with(|hygiene_data| {
1432-
if let Some(old) = hygiene_data.syntax_context_data.get(raw_id as usize)
1453+
let ctxt = HygieneData::with(|hygiene_data| {
1454+
let old = if let Some(old) = hygiene_data.syntax_context_data.get(raw_id as usize)
14331455
&& old.outer_expn == ctxt_data.outer_expn
14341456
&& old.outer_transparency == ctxt_data.outer_transparency
14351457
&& old.parent == ctxt_data.parent
14361458
{
1437-
ctxt_data = old.clone();
1459+
Some(old.clone())
1460+
} else {
1461+
None
1462+
};
1463+
// Overwrite its placeholder data with our decoded data.
1464+
let ctxt_data_ref = &mut hygiene_data.syntax_context_data[pending_ctxt.as_u32() as usize];
1465+
let prev_ctxt_data = mem::replace(ctxt_data_ref, ctxt_data);
1466+
// Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names`.
1467+
// We don't care what the encoding crate set this to - we want to resolve it
1468+
// from the perspective of the current compilation session
1469+
ctxt_data_ref.dollar_crate_name = kw::DollarCrate;
1470+
if let Some(old) = old {
1471+
*ctxt_data_ref = old;
14381472
}
1439-
1440-
hygiene_data.syntax_context_data[ctxt.as_u32() as usize] = ctxt_data;
1473+
// Make sure nothing weird happened while `decode_data` was running.
1474+
if !prev_ctxt_data.is_decode_placeholder() {
1475+
// Another thread may have already inserted the decoded data,
1476+
// but the decoded data should match.
1477+
assert_eq!(prev_ctxt_data, *ctxt_data_ref);
1478+
}
1479+
pending_ctxt
14411480
});
14421481

14431482
// Mark the context as completed
1444-
14451483
context.local_in_progress.borrow_mut().remove(&raw_id);
14461484

14471485
let mut inner = context.inner.lock();

0 commit comments

Comments
 (0)