Skip to content

Commit 1dc8df2

Browse files
SparrowLiifutile
andcommitted
make declare macro a part of query system
does not compile after rebase (by @futile) Co-authored-by: Felix Rath <[email protected]>
1 parent 1932602 commit 1dc8df2

File tree

23 files changed

+314
-33
lines changed

23 files changed

+314
-33
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -3895,6 +3895,7 @@ dependencies = [
38953895
"rustc_lexer",
38963896
"rustc_lint_defs",
38973897
"rustc_macros",
3898+
"rustc_middle",
38983899
"rustc_parse",
38993900
"rustc_serialize",
39003901
"rustc_session",

compiler/rustc_ast/src/ast.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2837,7 +2837,7 @@ impl UseTree {
28372837
/// Distinguishes between `Attribute`s that decorate items and Attributes that
28382838
/// are contained as statements within items. These two cases need to be
28392839
/// distinguished for pretty-printing.
2840-
#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)]
2840+
#[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic, Hash)]
28412841
pub enum AttrStyle {
28422842
Outer,
28432843
Inner,

compiler/rustc_ast/src/token.rs

+14-7
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use std::borrow::Cow;
22
use std::fmt;
3+
use std::hash::{Hash, Hasher};
34

45
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
56
use rustc_data_structures::sync::Lrc;
@@ -21,7 +22,7 @@ use crate::ast;
2122
use crate::ptr::P;
2223
use crate::util::case::Case;
2324

24-
#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
25+
#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, Hash)]
2526
pub enum CommentKind {
2627
Line,
2728
Block,
@@ -66,7 +67,7 @@ pub enum Delimiter {
6667
// type. This means that float literals like `1f32` are classified by this type
6768
// as `Int`. Only upon conversion to `ast::LitKind` will such a literal be
6869
// given the `Float` kind.
69-
#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
70+
#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, Hash)]
7071
pub enum LitKind {
7172
Bool, // AST only, must never appear in a `Token`
7273
Byte,
@@ -83,7 +84,7 @@ pub enum LitKind {
8384
}
8485

8586
/// A literal token.
86-
#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
87+
#[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, Hash)]
8788
pub struct Lit {
8889
pub kind: LitKind,
8990
pub symbol: Symbol,
@@ -228,7 +229,7 @@ fn ident_can_begin_type(name: Symbol, span: Span, is_raw: IdentIsRaw) -> bool {
228229
.contains(&name)
229230
}
230231

231-
#[derive(PartialEq, Encodable, Decodable, Debug, Copy, Clone, HashStable_Generic)]
232+
#[derive(PartialEq, Encodable, Decodable, Debug, Copy, Clone, HashStable_Generic, Hash)]
232233
pub enum IdentIsRaw {
233234
No,
234235
Yes,
@@ -248,7 +249,7 @@ impl From<IdentIsRaw> for bool {
248249

249250
// SAFETY: due to the `Clone` impl below, all fields of all variants other than
250251
// `Interpolated` must impl `Copy`.
251-
#[derive(PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
252+
#[derive(PartialEq, Encodable, Decodable, Debug, HashStable_Generic, Hash)]
252253
pub enum TokenKind {
253254
/* Expression-operator symbols. */
254255
/// `=`
@@ -374,7 +375,7 @@ impl Clone for TokenKind {
374375
}
375376
}
376377

377-
#[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)]
378+
#[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic, Hash)]
378379
pub struct Token {
379380
pub kind: TokenKind,
380381
pub span: Span,
@@ -910,7 +911,7 @@ pub enum Nonterminal {
910911
NtVis(P<ast::Visibility>),
911912
}
912913

913-
#[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable)]
914+
#[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, Hash)]
914915
pub enum NonterminalKind {
915916
Item,
916917
Block,
@@ -1060,6 +1061,12 @@ where
10601061
}
10611062
}
10621063

1064+
impl Hash for Nonterminal {
1065+
fn hash<H: Hasher>(&self, _state: &mut H) {
1066+
panic!("interpolated tokens should not be present in the HIR")
1067+
}
1068+
}
1069+
10631070
// Some types are used a lot. Make sure they don't unintentionally get bigger.
10641071
#[cfg(target_pointer_width = "64")]
10651072
mod size_asserts {

compiler/rustc_ast/src/tokenstream.rs

+13-4
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
//! ownership of the original.
1515
1616
use std::borrow::Cow;
17+
use std::hash::{Hash, Hasher};
1718
use std::{cmp, fmt, iter};
1819

1920
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
@@ -28,7 +29,7 @@ use crate::token::{self, Delimiter, Nonterminal, Token, TokenKind};
2829
use crate::{AttrVec, Attribute};
2930

3031
/// Part of a `TokenStream`.
31-
#[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
32+
#[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic, Hash)]
3233
pub enum TokenTree {
3334
/// A single token. Should never be `OpenDelim` or `CloseDelim`, because
3435
/// delimiters are implicitly represented by `Delimited`.
@@ -106,6 +107,14 @@ where
106107
}
107108
}
108109

110+
impl Hash for TokenStream {
111+
fn hash<H: Hasher>(&self, state: &mut H) {
112+
for sub_tt in self.trees() {
113+
sub_tt.hash(state);
114+
}
115+
}
116+
}
117+
109118
pub trait ToAttrTokenStream: sync::DynSend + sync::DynSync {
110119
fn to_attr_token_stream(&self) -> AttrTokenStream;
111120
}
@@ -300,7 +309,7 @@ pub struct TokenStream(pub(crate) Lrc<Vec<TokenTree>>);
300309
/// compound token. Used for conversions to `proc_macro::Spacing`. Also used to
301310
/// guide pretty-printing, which is where the `JointHidden` value (which isn't
302311
/// part of `proc_macro::Spacing`) comes in useful.
303-
#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
312+
#[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic, Hash)]
304313
pub enum Spacing {
305314
/// The token cannot join with the following token to form a compound
306315
/// token.
@@ -728,7 +737,7 @@ impl TokenTreeCursor {
728737
}
729738
}
730739

731-
#[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)]
740+
#[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic, Hash)]
732741
pub struct DelimSpan {
733742
pub open: Span,
734743
pub close: Span,
@@ -752,7 +761,7 @@ impl DelimSpan {
752761
}
753762
}
754763

755-
#[derive(Copy, Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)]
764+
#[derive(Copy, Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic, Hash)]
756765
pub struct DelimSpacing {
757766
pub open: Spacing,
758767
pub close: Spacing,

compiler/rustc_expand/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ rustc_fluent_macro = { path = "../rustc_fluent_macro" }
2020
rustc_lexer = { path = "../rustc_lexer" }
2121
rustc_lint_defs = { path = "../rustc_lint_defs" }
2222
rustc_macros = { path = "../rustc_macros" }
23+
rustc_middle = { path = "../rustc_middle" }
2324
rustc_parse = { path = "../rustc_parse" }
2425
rustc_serialize = { path = "../rustc_serialize" }
2526
rustc_session = { path = "../rustc_session" }

compiler/rustc_expand/src/base.rs

+15-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use rustc_data_structures::sync::{self, Lrc};
1515
use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, PResult};
1616
use rustc_feature::Features;
1717
use rustc_lint_defs::{BufferedEarlyLint, RegisteredTools};
18+
use rustc_middle::expand::{CanRetry, TcxMacroExpander};
1819
use rustc_parse::parser::Parser;
1920
use rustc_parse::MACRO_ARGUMENTS;
2021
use rustc_session::config::CollapseMacroDebuginfo;
@@ -676,6 +677,11 @@ pub enum SyntaxExtensionKind {
676677
Box<dyn TTMacroExpander + sync::DynSync + sync::DynSend>,
677678
),
678679

680+
TcxLegacyBang(
681+
/// An expander with signature TokenStream -> AST.
682+
Lrc<dyn TcxMacroExpander + sync::DynSync + sync::DynSend>,
683+
),
684+
679685
/// A token-based attribute macro.
680686
Attr(
681687
/// An expander with signature (TokenStream, TokenStream) -> TokenStream.
@@ -754,7 +760,8 @@ impl SyntaxExtension {
754760
match self.kind {
755761
SyntaxExtensionKind::Bang(..)
756762
| SyntaxExtensionKind::LegacyBang(..)
757-
| SyntaxExtensionKind::GlobDelegation(..) => MacroKind::Bang,
763+
| SyntaxExtensionKind::GlobDelegation(..)
764+
| SyntaxExtensionKind::TcxLegacyBang(..) => MacroKind::Bang,
758765
SyntaxExtensionKind::Attr(..)
759766
| SyntaxExtensionKind::LegacyAttr(..)
760767
| SyntaxExtensionKind::NonMacroAttr => MacroKind::Attr,
@@ -1072,6 +1079,13 @@ pub trait ResolverExpand {
10721079
trait_def_id: DefId,
10731080
impl_def_id: LocalDefId,
10741081
) -> Result<Vec<(Ident, Option<Ident>)>, Indeterminate>;
1082+
1083+
fn expand_legacy_bang(
1084+
&self,
1085+
invoc_id: LocalExpnId,
1086+
span: Span,
1087+
current_expansion: LocalExpnId,
1088+
) -> Result<(TokenStream, usize), CanRetry>;
10751089
}
10761090

10771091
pub trait LintStoreExpand {

compiler/rustc_expand/src/expand.rs

+78-1
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,15 @@ use rustc_ast::visit::{self, try_visit, walk_list, AssocCtxt, Visitor, VisitorRe
1212
use rustc_ast::{
1313
AssocItemKind, AstNodeWrapper, AttrArgs, AttrStyle, AttrVec, ExprKind, ForeignItemKind,
1414
HasAttrs, HasNodeId, Inline, ItemKind, MacStmtStyle, MetaItemKind, ModKind, NestedMetaItem,
15-
NodeId, PatKind, StmtKind, TyKind,
15+
NodeId, PatKind, StmtKind, TyKind, DUMMY_NODE_ID,
1616
};
1717
use rustc_ast_pretty::pprust;
1818
use rustc_data_structures::flat_map_in_place::FlatMapInPlace;
1919
use rustc_data_structures::sync::Lrc;
2020
use rustc_errors::PResult;
2121
use rustc_feature::Features;
22+
use rustc_middle::expand::CanRetry;
23+
use rustc_middle::ty::TyCtxt;
2224
use rustc_parse::parser::{
2325
AttemptLocalParseRecovery, CommaRecoveryMode, ForceCollect, Parser, RecoverColon, RecoverComma,
2426
};
@@ -31,6 +33,7 @@ use rustc_span::hygiene::SyntaxContext;
3133
use rustc_span::symbol::{sym, Ident};
3234
use rustc_span::{ErrorGuaranteed, FileName, LocalExpnId, Span};
3335
use smallvec::SmallVec;
36+
use tracing::debug;
3437

3538
use crate::base::*;
3639
use crate::config::StripUnconfigured;
@@ -40,6 +43,7 @@ use crate::errors::{
4043
WrongFragmentKind,
4144
};
4245
use crate::mbe::diagnostics::annotate_err_with_kind;
46+
use crate::mbe::macro_rules::{trace_macros_note, ParserAnyMacro};
4347
use crate::module::{mod_dir_path, parse_external_mod, DirOwnership, ParsedExternalMod};
4448
use crate::placeholders::{placeholder, PlaceholderExpander};
4549

@@ -394,6 +398,18 @@ pub struct MacroExpander<'a, 'b> {
394398
monotonic: bool, // cf. `cx.monotonic_expander()`
395399
}
396400

401+
pub fn expand_legacy_bang<'tcx>(
402+
tcx: TyCtxt<'tcx>,
403+
key: (LocalExpnId, Span, LocalExpnId),
404+
) -> Result<(&'tcx TokenStream, usize), CanRetry> {
405+
let (invoc_id, span, current_expansion) = key;
406+
let map = tcx.macro_map.borrow();
407+
let (arg, expander) = map.get(&invoc_id).as_ref().unwrap();
408+
expander
409+
.expand(&tcx.sess, span, arg.clone(), current_expansion)
410+
.map(|(tts, i)| (tcx.arena.alloc(tts) as &TokenStream, i))
411+
}
412+
397413
impl<'a, 'b> MacroExpander<'a, 'b> {
398414
pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self {
399415
MacroExpander { cx, monotonic }
@@ -679,6 +695,67 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
679695
Err(guar) => return ExpandResult::Ready(fragment_kind.dummy(span, guar)),
680696
}
681697
}
698+
SyntaxExtensionKind::TcxLegacyBang(expander) => {
699+
// Macros defined in the current crate have a real node id,
700+
// whereas macros from an external crate have a dummy id.
701+
if self.cx.trace_macros() {
702+
let msg = format!(
703+
"expanding `{}! {{ {} }}`",
704+
expander.name(),
705+
pprust::tts_to_string(&mac.args.tokens)
706+
);
707+
trace_macros_note(&mut self.cx.expansions, span, msg);
708+
}
709+
710+
// Macros defined in the current crate have a real node id,
711+
// whereas macros from an external crate have a dummy id.\
712+
let tok_result: Box<dyn MacResult> = match self.cx.resolver.expand_legacy_bang(
713+
invoc.expansion_data.id,
714+
span,
715+
self.cx.current_expansion.id,
716+
) {
717+
Ok((tts, i)) => {
718+
if self.cx.trace_macros() {
719+
let msg = format!("to `{}`", pprust::tts_to_string(&tts));
720+
trace_macros_note(&mut self.cx.expansions, span, msg);
721+
}
722+
let is_local = expander.node_id() != DUMMY_NODE_ID;
723+
if is_local {
724+
self.cx.resolver.record_macro_rule_usage(expander.node_id(), i);
725+
}
726+
727+
// Let the context choose how to interpret the result.
728+
// Weird, but useful for X-macros.
729+
Box::new(ParserAnyMacro::new(
730+
Parser::new(&self.cx.sess.psess, tts.clone(), None),
731+
// Pass along the original expansion site and the name of the macro,
732+
// so we can print a useful error message if the parse of the expanded
733+
// macro leaves unparsed tokens.
734+
span,
735+
expander.name(),
736+
self.cx.current_expansion.lint_node_id,
737+
self.cx.current_expansion.is_trailing_mac,
738+
expander.arm_span(i),
739+
is_local,
740+
))
741+
}
742+
Err(CanRetry::No(guar)) => {
743+
debug!("Will not retry matching as an error was emitted already");
744+
DummyResult::any(span, guar)
745+
}
746+
Err(CanRetry::Yes) => {
747+
// Retry and emit a better error.
748+
DummyResult::any_valid(span)
749+
}
750+
};
751+
let result = if let Some(result) = fragment_kind.make_from(tok_result) {
752+
result
753+
} else {
754+
let guar = self.error_wrong_fragment_kind(fragment_kind, &mac, span);
755+
fragment_kind.dummy(span, guar)
756+
};
757+
result
758+
}
682759
SyntaxExtensionKind::LegacyBang(expander) => {
683760
let tok_result = match expander.expand(self.cx, span, mac.args.tokens.clone()) {
684761
ExpandResult::Ready(tok_result) => tok_result,

compiler/rustc_expand/src/lib.rs

+5
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ mod placeholders;
2626
mod proc_macro_server;
2727

2828
pub use mbe::macro_rules::compile_declarative_macro;
29+
use rustc_middle::query::Providers;
2930
pub mod base;
3031
pub mod config;
3132
pub mod expand;
@@ -34,4 +35,8 @@ pub mod module;
3435
#[allow(rustc::untranslatable_diagnostic)]
3536
pub mod proc_macro;
3637

38+
pub fn provide(providers: &mut Providers) {
39+
providers.expand_legacy_bang = expand::expand_legacy_bang;
40+
}
41+
3742
rustc_fluent_macro::fluent_messages! { "../messages.ftl" }

compiler/rustc_expand/src/mbe/diagnostics.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use crate::mbe::macro_parser::ParseResult::*;
1818
use crate::mbe::macro_parser::{MatcherLoc, NamedParseResult, TtParser};
1919
use crate::mbe::macro_rules::{try_match_macro, Tracker};
2020

21-
pub(super) fn failed_to_match_macro<'cx>(
21+
pub(crate) fn failed_to_match_macro<'cx>(
2222
cx: &'cx mut ExtCtxt<'_>,
2323
sp: Span,
2424
def_span: Span,

0 commit comments

Comments
 (0)