Skip to content

Commit 72a6369

Browse files
committed
Move macro resolution into librustc_resolve.
1 parent 20b43b2 commit 72a6369

File tree

11 files changed

+439
-406
lines changed

11 files changed

+439
-406
lines changed

src/librustc/session/mod.rs

+2-7
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use util::nodemap::{NodeMap, FnvHashMap};
2121
use util::common::duration_to_secs_str;
2222
use mir::transform as mir_pass;
2323

24-
use syntax::ast::{NodeId, Name};
24+
use syntax::ast::NodeId;
2525
use errors::{self, DiagnosticBuilder};
2626
use errors::emitter::{Emitter, EmitterWriter};
2727
use syntax::json::JsonEmitter;
@@ -39,7 +39,7 @@ use llvm;
3939

4040
use std::path::{Path, PathBuf};
4141
use std::cell::{self, Cell, RefCell};
42-
use std::collections::{HashMap, HashSet};
42+
use std::collections::HashMap;
4343
use std::env;
4444
use std::ffi::CString;
4545
use std::rc::Rc;
@@ -96,10 +96,6 @@ pub struct Session {
9696
pub injected_allocator: Cell<Option<ast::CrateNum>>,
9797
pub injected_panic_runtime: Cell<Option<ast::CrateNum>>,
9898

99-
/// Names of all bang-style macros and syntax extensions
100-
/// available in this crate
101-
pub available_macros: RefCell<HashSet<Name>>,
102-
10399
/// Map from imported macro spans (which consist of
104100
/// the localized span for the macro body) to the
105101
/// macro name and defintion span in the source crate.
@@ -552,7 +548,6 @@ pub fn build_session_(sopts: config::Options,
552548
next_node_id: Cell::new(1),
553549
injected_allocator: Cell::new(None),
554550
injected_panic_runtime: Cell::new(None),
555-
available_macros: RefCell::new(HashSet::new()),
556551
imported_macro_spans: RefCell::new(HashMap::new()),
557552
incr_comp_session: RefCell::new(IncrCompSession::NotInitialized),
558553
perf_stats: PerfStats {

src/librustc_driver/driver.rs

+3-6
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ use std::io::{self, Write};
5050
use std::path::{Path, PathBuf};
5151
use syntax::{ast, diagnostics, visit};
5252
use syntax::attr;
53+
use syntax::ext::base::ExtCtxt;
5354
use syntax::parse::{self, PResult, token};
5455
use syntax::util::node_count::NodeCounter;
5556
use syntax;
@@ -643,6 +644,7 @@ pub fn phase_2_configure_and_expand<'a, F>(sess: &Session,
643644

644645
let resolver_arenas = Resolver::arenas();
645646
let mut resolver = Resolver::new(sess, make_glob_map, &mut macro_loader, &resolver_arenas);
647+
syntax_ext::register_builtins(&mut resolver, sess.features.borrow().quote);
646648

647649
krate = time(time_passes, "expansion", || {
648650
// Windows dlls do not have rpaths, so they don't know how to find their
@@ -678,16 +680,11 @@ pub fn phase_2_configure_and_expand<'a, F>(sess: &Session,
678680
trace_mac: sess.opts.debugging_opts.trace_macros,
679681
should_test: sess.opts.test,
680682
};
681-
let mut ecx = syntax::ext::base::ExtCtxt::new(&sess.parse_sess,
682-
krate.config.clone(),
683-
cfg,
684-
&mut resolver);
685-
syntax_ext::register_builtins(&mut ecx.syntax_env);
683+
let mut ecx = ExtCtxt::new(&sess.parse_sess, krate.config.clone(), cfg, &mut resolver);
686684
let ret = syntax::ext::expand::expand_crate(&mut ecx, syntax_exts, krate);
687685
if cfg!(windows) {
688686
env::set_var("PATH", &old_path);
689687
}
690-
*sess.available_macros.borrow_mut() = ecx.syntax_env.names;
691688
ret
692689
});
693690

src/librustc_resolve/lib.rs

+8-10
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,6 @@ use rustc::ty;
5454
use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
5555
use rustc::util::nodemap::{NodeMap, NodeSet, FnvHashMap, FnvHashSet};
5656

57-
use syntax::ext;
58-
use syntax::ext::base::LoadedMacro;
5957
use syntax::ext::hygiene::Mark;
6058
use syntax::ast::{self, FloatTy};
6159
use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, IntTy, UintTy};
@@ -82,6 +80,7 @@ use resolve_imports::{ImportDirective, NameResolution};
8280
// registered before they are used.
8381
mod diagnostics;
8482

83+
mod macros;
8584
mod check_unused;
8685
mod build_reduced_graph;
8786
mod resolve_imports;
@@ -1073,6 +1072,10 @@ pub struct Resolver<'a> {
10731072
new_import_semantics: bool, // true if `#![feature(item_like_imports)]`
10741073

10751074
macro_loader: &'a mut MacroLoader,
1075+
macro_names: FnvHashSet<Name>,
1076+
1077+
// Maps the `Mark` of an expansion to its containing module or block.
1078+
expansion_data: Vec<macros::ExpansionData>,
10761079
}
10771080

10781081
pub struct ResolverArenas<'a> {
@@ -1154,12 +1157,6 @@ impl<'a> hir::lowering::Resolver for Resolver<'a> {
11541157
}
11551158
}
11561159

1157-
impl<'a> ext::base::Resolver for Resolver<'a> {
1158-
fn load_crate(&mut self, extern_crate: &ast::Item, allows_macros: bool) -> Vec<LoadedMacro> {
1159-
self.macro_loader.load_crate(extern_crate, allows_macros)
1160-
}
1161-
}
1162-
11631160
trait Named {
11641161
fn name(&self) -> Name;
11651162
}
@@ -1243,6 +1240,8 @@ impl<'a> Resolver<'a> {
12431240
new_import_semantics: session.features.borrow().item_like_imports,
12441241

12451242
macro_loader: macro_loader,
1243+
macro_names: FnvHashSet(),
1244+
expansion_data: vec![macros::ExpansionData::default()],
12461245
}
12471246
}
12481247

@@ -2784,8 +2783,7 @@ impl<'a> Resolver<'a> {
27842783
}
27852784

27862785
fn find_best_match(&mut self, name: &str) -> SuggestionType {
2787-
if let Some(macro_name) = self.session.available_macros
2788-
.borrow().iter().find(|n| n.as_str() == name) {
2786+
if let Some(macro_name) = self.macro_names.iter().find(|n| n.as_str() == name) {
27892787
return SuggestionType::Macro(format!("{}!", macro_name));
27902788
}
27912789

src/librustc_resolve/macros.rs

+213
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
use Resolver;
12+
use rustc::util::nodemap::FnvHashMap;
13+
use std::cell::RefCell;
14+
use std::mem;
15+
use std::rc::Rc;
16+
use syntax::ast::{self, Name};
17+
use syntax::errors::DiagnosticBuilder;
18+
use syntax::ext::base::{self, LoadedMacro, MultiModifier, MultiDecorator};
19+
use syntax::ext::base::{NormalTT, SyntaxExtension};
20+
use syntax::ext::expand::{Expansion, Invocation, InvocationKind};
21+
use syntax::ext::hygiene::Mark;
22+
use syntax::parse::token::intern;
23+
use syntax::util::lev_distance::find_best_match_for_name;
24+
use syntax::visit::{self, Visitor};
25+
26+
#[derive(Clone, Default)]
27+
pub struct ExpansionData {
28+
module: Rc<ModuleData>,
29+
}
30+
31+
// FIXME(jseyfried): merge with `::ModuleS`.
32+
#[derive(Default)]
33+
struct ModuleData {
34+
parent: Option<Rc<ModuleData>>,
35+
macros: RefCell<FnvHashMap<Name, Rc<SyntaxExtension>>>,
36+
macros_escape: bool,
37+
}
38+
39+
impl<'a> base::Resolver for Resolver<'a> {
40+
fn load_crate(&mut self, extern_crate: &ast::Item, allows_macros: bool) -> Vec<LoadedMacro> {
41+
self.macro_loader.load_crate(extern_crate, allows_macros)
42+
}
43+
44+
fn visit_expansion(&mut self, mark: Mark, expansion: &Expansion) {
45+
expansion.visit_with(&mut ExpansionVisitor {
46+
current_module: self.expansion_data[mark.as_u32() as usize].module.clone(),
47+
resolver: self,
48+
});
49+
}
50+
51+
fn add_macro(&mut self, scope: Mark, ident: ast::Ident, ext: Rc<SyntaxExtension>) {
52+
if let NormalTT(..) = *ext {
53+
self.macro_names.insert(ident.name);
54+
}
55+
56+
let mut module = self.expansion_data[scope.as_u32() as usize].module.clone();
57+
while module.macros_escape {
58+
module = module.parent.clone().unwrap();
59+
}
60+
module.macros.borrow_mut().insert(ident.name, ext);
61+
}
62+
63+
fn add_expansions_at_stmt(&mut self, id: ast::NodeId, macros: Vec<Mark>) {
64+
self.macros_at_scope.insert(id, macros);
65+
}
66+
67+
fn find_attr_invoc(&mut self, attrs: &mut Vec<ast::Attribute>) -> Option<ast::Attribute> {
68+
for i in 0..attrs.len() {
69+
let name = intern(&attrs[i].name());
70+
match self.expansion_data[0].module.macros.borrow().get(&name) {
71+
Some(ext) => match **ext {
72+
MultiModifier(..) | MultiDecorator(..) => return Some(attrs.remove(i)),
73+
_ => {}
74+
},
75+
None => {}
76+
}
77+
}
78+
None
79+
}
80+
81+
fn resolve_invoc(&mut self, invoc: &Invocation) -> Option<Rc<SyntaxExtension>> {
82+
let (name, span) = match invoc.kind {
83+
InvocationKind::Bang { ref mac, .. } => {
84+
let path = &mac.node.path;
85+
if path.segments.len() > 1 || path.global ||
86+
!path.segments[0].parameters.is_empty() {
87+
self.session.span_err(path.span,
88+
"expected macro name without module separators");
89+
return None;
90+
}
91+
(path.segments[0].identifier.name, path.span)
92+
}
93+
InvocationKind::Attr { ref attr, .. } => (intern(&*attr.name()), attr.span),
94+
};
95+
96+
let mut module = self.expansion_data[invoc.mark().as_u32() as usize].module.clone();
97+
loop {
98+
if let Some(ext) = module.macros.borrow().get(&name) {
99+
return Some(ext.clone());
100+
}
101+
match module.parent.clone() {
102+
Some(parent) => module = parent,
103+
None => break,
104+
}
105+
}
106+
107+
let mut err =
108+
self.session.struct_span_err(span, &format!("macro undefined: '{}!'", name));
109+
self.suggest_macro_name(&name.as_str(), &mut err);
110+
err.emit();
111+
None
112+
}
113+
}
114+
115+
impl<'a> Resolver<'a> {
116+
fn suggest_macro_name(&mut self, name: &str, err: &mut DiagnosticBuilder<'a>) {
117+
if let Some(suggestion) = find_best_match_for_name(self.macro_names.iter(), name, None) {
118+
if suggestion != name {
119+
err.help(&format!("did you mean `{}!`?", suggestion));
120+
} else {
121+
err.help(&format!("have you added the `#[macro_use]` on the module/import?"));
122+
}
123+
}
124+
}
125+
}
126+
127+
struct ExpansionVisitor<'b, 'a: 'b> {
128+
resolver: &'b mut Resolver<'a>,
129+
current_module: Rc<ModuleData>,
130+
}
131+
132+
impl<'a, 'b> ExpansionVisitor<'a, 'b> {
133+
fn visit_invoc(&mut self, id: ast::NodeId) {
134+
assert_eq!(id, self.resolver.expansion_data.len() as u32);
135+
self.resolver.expansion_data.push(ExpansionData {
136+
module: self.current_module.clone(),
137+
});
138+
}
139+
140+
// does this attribute list contain "macro_use"?
141+
fn contains_macro_use(&mut self, attrs: &[ast::Attribute]) -> bool {
142+
for attr in attrs {
143+
if attr.check_name("macro_escape") {
144+
let msg = "macro_escape is a deprecated synonym for macro_use";
145+
let mut err = self.resolver.session.struct_span_warn(attr.span, msg);
146+
if let ast::AttrStyle::Inner = attr.node.style {
147+
err.help("consider an outer attribute, #[macro_use] mod ...").emit();
148+
} else {
149+
err.emit();
150+
}
151+
} else if !attr.check_name("macro_use") {
152+
continue;
153+
}
154+
155+
if !attr.is_word() {
156+
self.resolver.session.span_err(attr.span,
157+
"arguments to macro_use are not allowed here");
158+
}
159+
return true;
160+
}
161+
162+
false
163+
}
164+
}
165+
166+
macro_rules! method {
167+
($visit:ident: $ty:ty, $invoc:path, $walk:ident) => {
168+
fn $visit(&mut self, node: &$ty) {
169+
match node.node {
170+
$invoc(..) => self.visit_invoc(node.id),
171+
_ => visit::$walk(self, node),
172+
}
173+
}
174+
}
175+
}
176+
177+
impl<'a, 'b> Visitor for ExpansionVisitor<'a, 'b> {
178+
method!(visit_trait_item: ast::TraitItem, ast::TraitItemKind::Macro, walk_trait_item);
179+
method!(visit_impl_item: ast::ImplItem, ast::ImplItemKind::Macro, walk_impl_item);
180+
method!(visit_stmt: ast::Stmt, ast::StmtKind::Mac, walk_stmt);
181+
method!(visit_expr: ast::Expr, ast::ExprKind::Mac, walk_expr);
182+
method!(visit_pat: ast::Pat, ast::PatKind::Mac, walk_pat);
183+
method!(visit_ty: ast::Ty, ast::TyKind::Mac, walk_ty);
184+
185+
fn visit_item(&mut self, item: &ast::Item) {
186+
match item.node {
187+
ast::ItemKind::Mac(..) if item.id == ast::DUMMY_NODE_ID => {} // Scope placeholder
188+
ast::ItemKind::Mac(..) => self.visit_invoc(item.id),
189+
ast::ItemKind::Mod(..) => {
190+
let module_data = ModuleData {
191+
parent: Some(self.current_module.clone()),
192+
macros: RefCell::new(FnvHashMap()),
193+
macros_escape: self.contains_macro_use(&item.attrs),
194+
};
195+
let orig_module = mem::replace(&mut self.current_module, Rc::new(module_data));
196+
visit::walk_item(self, item);
197+
self.current_module = orig_module;
198+
}
199+
_ => visit::walk_item(self, item),
200+
}
201+
}
202+
203+
fn visit_block(&mut self, block: &ast::Block) {
204+
let module_data = ModuleData {
205+
parent: Some(self.current_module.clone()),
206+
macros: RefCell::new(FnvHashMap()),
207+
macros_escape: false,
208+
};
209+
let orig_module = mem::replace(&mut self.current_module, Rc::new(module_data));
210+
visit::walk_block(self, block);
211+
self.current_module = orig_module;
212+
}
213+
}

0 commit comments

Comments
 (0)