Skip to content

Commit 1581278

Browse files
committed
Auto merge of #66364 - Centril:cleanup-macro-def, r=petrochenkov,eddyb
Cleanup `rmeta::MacroDef` Avoid using rountrip parsing in the encoder and in `fn load_macro_untracked`. The main reason I was interested in this was to remove `rustc_parse` as a dependency of `rustc_metadata` but it seems like this had other benefits as well. Fixes #49511. r? @eddyb cc @matthewjasper @estebank @petrochenkov
2 parents dd155df + bafa5cc commit 1581278

33 files changed

+190
-289
lines changed

Cargo.lock

-2
Original file line numberDiff line numberDiff line change
@@ -3891,14 +3891,12 @@ dependencies = [
38913891
"memmap",
38923892
"rustc",
38933893
"rustc_ast",
3894-
"rustc_ast_pretty",
38953894
"rustc_attr",
38963895
"rustc_data_structures",
38973896
"rustc_errors",
38983897
"rustc_expand",
38993898
"rustc_hir",
39003899
"rustc_index",
3901-
"rustc_parse",
39023900
"rustc_span",
39033901
"rustc_target",
39043902
"serialize",

src/librustc/dep_graph/dep_node.rs

+2
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ macro_rules! define_dep_nodes {
111111
) => (
112112
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
113113
RustcEncodable, RustcDecodable)]
114+
#[allow(non_camel_case_types)]
114115
pub enum DepKind {
115116
$($variant),*
116117
}
@@ -173,6 +174,7 @@ macro_rules! define_dep_nodes {
173174

174175
pub struct DepConstructor;
175176

177+
#[allow(non_camel_case_types)]
176178
impl DepConstructor {
177179
$(
178180
#[inline(always)]

src/librustc/lint.rs

+2-9
Original file line numberDiff line numberDiff line change
@@ -344,15 +344,8 @@ pub fn in_external_macro(sess: &Session, span: Span) -> bool {
344344
ExpnKind::Root | ExpnKind::Desugaring(DesugaringKind::ForLoop) => false,
345345
ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
346346
ExpnKind::Macro(MacroKind::Bang, _) => {
347-
if expn_data.def_site.is_dummy() {
348-
// Dummy span for the `def_site` means it's an external macro.
349-
return true;
350-
}
351-
match sess.source_map().span_to_snippet(expn_data.def_site) {
352-
Ok(code) => !code.starts_with("macro_rules"),
353-
// No snippet means external macro or compiler-builtin expansion.
354-
Err(_) => true,
355-
}
347+
// Dummy span for the `def_site` means it's an external macro.
348+
expn_data.def_site.is_dummy() || sess.source_map().is_imported(expn_data.def_site)
356349
}
357350
ExpnKind::Macro(..) => true, // definitely a plugin
358351
}

src/librustc/middle/stability.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ pub fn report_unstable(
110110
let span_key = msp.primary_span().and_then(|sp: Span| {
111111
if !sp.is_dummy() {
112112
let file = sm.lookup_char_pos(sp.lo()).file;
113-
if file.name.is_macros() { None } else { Some(span) }
113+
if file.is_imported() { None } else { Some(span) }
114114
} else {
115115
None
116116
}

src/librustc_errors/emitter.rs

+13-9
Original file line numberDiff line numberDiff line change
@@ -414,22 +414,24 @@ pub trait Emitter {
414414
}
415415

416416
// This does a small "fix" for multispans by looking to see if it can find any that
417-
// point directly at <*macros>. Since these are often difficult to read, this
418-
// will change the span to point at the use site.
417+
// point directly at external macros. Since these are often difficult to read,
418+
// this will change the span to point at the use site.
419419
fn fix_multispans_in_extern_macros(
420420
&self,
421421
source_map: &Option<Lrc<SourceMap>>,
422422
span: &mut MultiSpan,
423423
children: &mut Vec<SubDiagnostic>,
424424
) {
425-
for span in iter::once(span).chain(children.iter_mut().map(|child| &mut child.span)) {
425+
debug!("fix_multispans_in_extern_macros: before: span={:?} children={:?}", span, children);
426+
for span in iter::once(&mut *span).chain(children.iter_mut().map(|child| &mut child.span)) {
426427
self.fix_multispan_in_extern_macros(source_map, span);
427428
}
429+
debug!("fix_multispans_in_extern_macros: after: span={:?} children={:?}", span, children);
428430
}
429431

430-
// This "fixes" MultiSpans that contain Spans that are pointing to locations inside of
431-
// <*macros>. Since these locations are often difficult to read, we move these Spans from
432-
// <*macros> to their corresponding use site.
432+
// This "fixes" MultiSpans that contain `Span`s pointing to locations inside of external macros.
433+
// Since these locations are often difficult to read,
434+
// we move these spans from the external macros to their corresponding use site.
433435
fn fix_multispan_in_extern_macros(
434436
&self,
435437
source_map: &Option<Lrc<SourceMap>>,
@@ -440,14 +442,14 @@ pub trait Emitter {
440442
None => return,
441443
};
442444

443-
// First, find all the spans in <*macros> and point instead at their use site
445+
// First, find all the spans in external macros and point instead at their use site.
444446
let replacements: Vec<(Span, Span)> = span
445447
.primary_spans()
446448
.iter()
447449
.copied()
448450
.chain(span.span_labels().iter().map(|sp_label| sp_label.span))
449451
.filter_map(|sp| {
450-
if !sp.is_dummy() && sm.span_to_filename(sp).is_macros() {
452+
if !sp.is_dummy() && sm.is_imported(sp) {
451453
let maybe_callsite = sp.source_callsite();
452454
if sp != maybe_callsite {
453455
return Some((sp, maybe_callsite));
@@ -457,7 +459,7 @@ pub trait Emitter {
457459
})
458460
.collect();
459461

460-
// After we have them, make sure we replace these 'bad' def sites with their use sites
462+
// After we have them, make sure we replace these 'bad' def sites with their use sites.
461463
for (from, to) in replacements {
462464
span.replace(from, to);
463465
}
@@ -472,6 +474,7 @@ impl Emitter for EmitterWriter {
472474
fn emit_diagnostic(&mut self, diag: &Diagnostic) {
473475
let mut children = diag.children.clone();
474476
let (mut primary_span, suggestions) = self.primary_span_formatted(&diag);
477+
debug!("emit_diagnostic: suggestions={:?}", suggestions);
475478

476479
self.fix_multispans_in_extern_macros_and_render_macro_backtrace(
477480
&self.sm,
@@ -1533,6 +1536,7 @@ impl EmitterWriter {
15331536

15341537
// Render the replacements for each suggestion
15351538
let suggestions = suggestion.splice_lines(&**sm);
1539+
debug!("emit_suggestion_default: suggestions={:?}", suggestions);
15361540

15371541
if suggestions.is_empty() {
15381542
// Suggestions coming from macros can have malformed spans. This is a heavy handed

src/librustc_errors/json.rs

+5
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,11 @@ impl DiagnosticSpanLine {
394394
je.sm
395395
.span_to_lines(span)
396396
.map(|lines| {
397+
// We can't get any lines if the source is unavailable.
398+
if !je.sm.ensure_source_file_source_present(lines.file.clone()) {
399+
return vec![];
400+
}
401+
397402
let sf = &*lines.file;
398403
lines
399404
.lines

src/librustc_errors/lib.rs

+5
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,11 @@ impl CodeSuggestion {
196196
let lines = sm.span_to_lines(bounding_span).ok()?;
197197
assert!(!lines.lines.is_empty());
198198

199+
// We can't splice anything if the source is unavailable.
200+
if !sm.ensure_source_file_source_present(lines.file.clone()) {
201+
return None;
202+
}
203+
199204
// To build up the result, we do this for each span:
200205
// - push the line segment trailing the previous span
201206
// (at the beginning a "phantom" span pointing at the start of the line)

src/librustc_expand/mbe/macro_rules.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -105,10 +105,10 @@ impl<'a> ParserAnyMacro<'a> {
105105
if e.span.is_dummy() {
106106
// Get around lack of span in error (#30128)
107107
e.replace_span_with(site_span);
108-
if parser.sess.source_map().span_to_filename(arm_span).is_real() {
108+
if !parser.sess.source_map().is_imported(arm_span) {
109109
e.span_label(arm_span, "in this macro arm");
110110
}
111-
} else if !parser.sess.source_map().span_to_filename(parser.token.span).is_real() {
111+
} else if parser.sess.source_map().is_imported(parser.token.span) {
112112
e.span_label(site_span, "in this macro invocation");
113113
}
114114
match kind {
@@ -297,7 +297,7 @@ fn generic_extension<'cx>(
297297
let span = token.span.substitute_dummy(sp);
298298
let mut err = cx.struct_span_err(span, &parse_failure_msg(&token));
299299
err.span_label(span, label);
300-
if !def_span.is_dummy() && cx.source_map().span_to_filename(def_span).is_real() {
300+
if !def_span.is_dummy() && !cx.source_map().is_imported(def_span) {
301301
err.span_label(cx.source_map().def_span(def_span), "when calling this macro");
302302
}
303303

src/librustc_macros/src/symbols.rs

+4
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ pub fn symbols(input: TokenStream) -> TokenStream {
103103
#value,
104104
});
105105
keyword_stream.extend(quote! {
106+
#[allow(non_upper_case_globals)]
106107
pub const #name: Symbol = Symbol::new(#counter);
107108
});
108109
counter += 1;
@@ -120,6 +121,8 @@ pub fn symbols(input: TokenStream) -> TokenStream {
120121
#value,
121122
});
122123
symbols_stream.extend(quote! {
124+
#[allow(rustc::default_hash_types)]
125+
#[allow(non_upper_case_globals)]
123126
pub const #name: Symbol = Symbol::new(#counter);
124127
});
125128
counter += 1;
@@ -149,6 +152,7 @@ pub fn symbols(input: TokenStream) -> TokenStream {
149152
() => {
150153
#symbols_stream
151154

155+
#[allow(non_upper_case_globals)]
152156
pub const digits_array: &[Symbol; 10] = &[
153157
#digits_stream
154158
];

src/librustc_metadata/Cargo.toml

-2
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ log = "0.4"
1515
memmap = "0.7"
1616
smallvec = { version = "1.0", features = ["union", "may_dangle"] }
1717
rustc = { path = "../librustc" }
18-
rustc_ast_pretty = { path = "../librustc_ast_pretty" }
1918
rustc_attr = { path = "../librustc_attr" }
2019
rustc_data_structures = { path = "../librustc_data_structures" }
2120
rustc_errors = { path = "../librustc_errors" }
@@ -26,7 +25,6 @@ rustc_serialize = { path = "../libserialize", package = "serialize" }
2625
stable_deref_trait = "1.0.0"
2726
rustc_ast = { path = "../librustc_ast" }
2827
rustc_expand = { path = "../librustc_expand" }
29-
rustc_parse = { path = "../librustc_parse" }
3028
rustc_span = { path = "../librustc_span" }
3129

3230
[target.'cfg(windows)'.dependencies]

src/librustc_metadata/rmeta/decoder.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1275,9 +1275,9 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
12751275
}
12761276
}
12771277

1278-
fn get_macro(&self, id: DefIndex) -> MacroDef {
1278+
fn get_macro(&self, id: DefIndex, sess: &Session) -> MacroDef {
12791279
match self.kind(id) {
1280-
EntryKind::MacroDef(macro_def) => macro_def.decode(self),
1280+
EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)),
12811281
_ => bug!(),
12821282
}
12831283
}

src/librustc_metadata/rmeta/decoder/cstore_impl.rs

+14-27
Original file line numberDiff line numberDiff line change
@@ -14,27 +14,22 @@ use rustc::session::{CrateDisambiguator, Session};
1414
use rustc::ty::query::Providers;
1515
use rustc::ty::query::QueryConfig;
1616
use rustc::ty::{self, TyCtxt};
17+
use rustc_ast::ast;
18+
use rustc_ast::attr;
19+
use rustc_ast::expand::allocator::AllocatorKind;
20+
use rustc_ast::ptr::P;
21+
use rustc_ast::tokenstream::DelimSpan;
1722
use rustc_data_structures::svh::Svh;
1823
use rustc_hir as hir;
1924
use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
20-
use rustc_parse::parser::emit_unclosed_delims;
21-
use rustc_parse::source_file_to_stream;
25+
use rustc_span::source_map::{self, Span, Spanned};
26+
use rustc_span::symbol::Symbol;
2227

2328
use rustc_data_structures::sync::Lrc;
2429
use smallvec::SmallVec;
2530
use std::any::Any;
2631
use std::sync::Arc;
2732

28-
use rustc_ast::ast;
29-
use rustc_ast::attr;
30-
use rustc_ast::expand::allocator::AllocatorKind;
31-
use rustc_ast::ptr::P;
32-
use rustc_ast::tokenstream::DelimSpan;
33-
use rustc_span::source_map;
34-
use rustc_span::source_map::Spanned;
35-
use rustc_span::symbol::Symbol;
36-
use rustc_span::{FileName, Span};
37-
3833
macro_rules! provide {
3934
(<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
4035
$($name:ident => $compute:block)*) => {
@@ -419,15 +414,9 @@ impl CStore {
419414
return LoadedMacro::ProcMacro(data.load_proc_macro(id.index, sess));
420415
}
421416

422-
let def = data.get_macro(id.index);
423-
let macro_full_name = data.def_path(id.index).to_string_friendly(|_| data.root.name);
424-
let source_name = FileName::Macros(macro_full_name);
425-
426-
let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
427-
let local_span = Span::with_root_ctxt(source_file.start_pos, source_file.end_pos);
428-
let dspan = DelimSpan::from_single(local_span);
429-
let (body, mut errors) = source_file_to_stream(&sess.parse_sess, source_file, None);
430-
emit_unclosed_delims(&mut errors, &sess.parse_sess);
417+
let span = data.get_span(id.index, sess);
418+
let dspan = DelimSpan::from_single(span);
419+
let rmeta::MacroDef { body, legacy } = data.get_macro(id.index, sess);
431420

432421
// Mark the attrs as used
433422
let attrs = data.get_item_attrs(id.index, sess);
@@ -441,22 +430,20 @@ impl CStore {
441430
.data
442431
.get_opt_name()
443432
.expect("no name in load_macro");
444-
sess.imported_macro_spans
445-
.borrow_mut()
446-
.insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
433+
sess.imported_macro_spans.borrow_mut().insert(span, (name.to_string(), span));
447434

448435
LoadedMacro::MacroDef(
449436
ast::Item {
450437
// FIXME: cross-crate hygiene
451438
ident: ast::Ident::with_dummy_span(name),
452439
id: ast::DUMMY_NODE_ID,
453-
span: local_span,
440+
span,
454441
attrs: attrs.iter().cloned().collect(),
455442
kind: ast::ItemKind::MacroDef(ast::MacroDef {
456443
body: P(ast::MacArgs::Delimited(dspan, ast::MacDelimiter::Brace, body)),
457-
legacy: def.legacy,
444+
legacy,
458445
}),
459-
vis: source_map::respan(local_span.shrink_to_lo(), ast::VisibilityKind::Inherited),
446+
vis: source_map::respan(span.shrink_to_lo(), ast::VisibilityKind::Inherited),
460447
tokens: None,
461448
},
462449
data.root.edition,

src/librustc_metadata/rmeta/encoder.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -1235,10 +1235,9 @@ impl EncodeContext<'tcx> {
12351235

12361236
/// Serialize the text of exported macros
12371237
fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1238-
use rustc_ast_pretty::pprust;
12391238
let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
12401239
record!(self.per_def.kind[def_id] <- EntryKind::MacroDef(self.lazy(MacroDef {
1241-
body: pprust::tts_to_string(macro_def.body.clone()),
1240+
body: macro_def.body.clone(),
12421241
legacy: macro_def.legacy,
12431242
})));
12441243
record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);

src/librustc_metadata/rmeta/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use rustc::session::config::SymbolManglingVersion;
1111
use rustc::session::CrateDisambiguator;
1212
use rustc::ty::{self, ReprOptions, Ty};
1313
use rustc_ast::ast;
14+
use rustc_ast::tokenstream::TokenStream;
1415
use rustc_attr as attr;
1516
use rustc_data_structures::svh::Svh;
1617
use rustc_data_structures::sync::MetadataRef;
@@ -324,7 +325,7 @@ struct ModData {
324325

325326
#[derive(RustcEncodable, RustcDecodable)]
326327
struct MacroDef {
327-
body: String,
328+
body: TokenStream,
328329
legacy: bool,
329330
}
330331

src/librustc_span/lib.rs

+1-21
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,6 @@ scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
8383
)]
8484
pub enum FileName {
8585
Real(PathBuf),
86-
/// A macro. This includes the full name of the macro, so that there are no clashes.
87-
Macros(String),
8886
/// Call to `quote!`.
8987
QuoteExpansion(u64),
9088
/// Command line.
@@ -107,7 +105,6 @@ impl std::fmt::Display for FileName {
107105
use FileName::*;
108106
match *self {
109107
Real(ref path) => write!(fmt, "{}", path.display()),
110-
Macros(ref name) => write!(fmt, "<{} macros>", name),
111108
QuoteExpansion(_) => write!(fmt, "<quote expansion>"),
112109
MacroExpansion(_) => write!(fmt, "<macro expansion>"),
113110
Anon(_) => write!(fmt, "<anon>"),
@@ -132,8 +129,7 @@ impl FileName {
132129
use FileName::*;
133130
match *self {
134131
Real(_) => true,
135-
Macros(_)
136-
| Anon(_)
132+
Anon(_)
137133
| MacroExpansion(_)
138134
| ProcMacroSourceCode(_)
139135
| CfgSpec(_)
@@ -144,22 +140,6 @@ impl FileName {
144140
}
145141
}
146142

147-
pub fn is_macros(&self) -> bool {
148-
use FileName::*;
149-
match *self {
150-
Real(_)
151-
| Anon(_)
152-
| MacroExpansion(_)
153-
| ProcMacroSourceCode(_)
154-
| CfgSpec(_)
155-
| CliCrateAttr(_)
156-
| Custom(_)
157-
| QuoteExpansion(_)
158-
| DocTest(_, _) => false,
159-
Macros(_) => true,
160-
}
161-
}
162-
163143
pub fn quote_expansion_source_code(src: &str) -> FileName {
164144
let mut hasher = StableHasher::new();
165145
src.hash(&mut hasher);

0 commit comments

Comments
 (0)