4394: Simplify r=matklad a=Veetaha



4414: Highlighting improvements r=matklad a=matthewjasper

- `static mut`s are highlighted as `mutable`.
- The name of the macro declared by `macro_rules!` is now highlighted.

Co-authored-by: veetaha <veetaha2@gmail.com>
Co-authored-by: Matthew Jasper <mjjasper1@gmail.com>
This commit is contained in:
bors[bot] 2020-05-10 17:47:27 +00:00 committed by GitHub
commit 74e72e9afa
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 99 additions and 47 deletions

View file

@ -678,6 +678,10 @@ impl Static {
pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
db.static_data(self.id).name.clone() db.static_data(self.id).name.clone()
} }
pub fn is_mut(self, db: &dyn HirDatabase) -> bool {
db.static_data(self.id).mutable
}
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]

View file

@ -251,11 +251,6 @@ impl ConstData {
Arc::new(ConstData::new(db, vis_default, node)) Arc::new(ConstData::new(db, vis_default, node))
} }
pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<ConstData> {
let node = konst.lookup(db).source(db);
Arc::new(ConstData::new(db, RawVisibility::private(), node))
}
fn new<N: NameOwner + TypeAscriptionOwner + VisibilityOwner>( fn new<N: NameOwner + TypeAscriptionOwner + VisibilityOwner>(
db: &dyn DefDatabase, db: &dyn DefDatabase,
vis_default: RawVisibility, vis_default: RawVisibility,
@ -270,6 +265,32 @@ impl ConstData {
} }
} }
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StaticData {
pub name: Option<Name>,
pub type_ref: TypeRef,
pub visibility: RawVisibility,
pub mutable: bool,
}
impl StaticData {
pub(crate) fn static_data_query(db: &dyn DefDatabase, konst: StaticId) -> Arc<StaticData> {
let node = konst.lookup(db).source(db);
let ctx = LowerCtx::new(db, node.file_id);
let name = node.value.name().map(|n| n.as_name());
let type_ref = TypeRef::from_ast_opt(&ctx, node.value.ascribed_type());
let mutable = node.value.mut_token().is_some();
let visibility = RawVisibility::from_ast_with_default(
db,
RawVisibility::private(),
node.map(|n| n.visibility()),
);
Arc::new(StaticData { name, type_ref, visibility, mutable })
}
}
fn collect_items_in_macros( fn collect_items_in_macros(
db: &dyn DefDatabase, db: &dyn DefDatabase,
expander: &mut Expander, expander: &mut Expander,

View file

@ -10,7 +10,7 @@ use crate::{
adt::{EnumData, StructData}, adt::{EnumData, StructData},
attr::Attrs, attr::Attrs,
body::{scope::ExprScopes, Body, BodySourceMap}, body::{scope::ExprScopes, Body, BodySourceMap},
data::{ConstData, FunctionData, ImplData, TraitData, TypeAliasData}, data::{ConstData, FunctionData, ImplData, StaticData, TraitData, TypeAliasData},
docs::Documentation, docs::Documentation,
generics::GenericParams, generics::GenericParams,
lang_item::{LangItemTarget, LangItems}, lang_item::{LangItemTarget, LangItems},
@ -77,8 +77,8 @@ pub trait DefDatabase: InternDatabase + AstDatabase + Upcast<dyn AstDatabase> {
#[salsa::invoke(ConstData::const_data_query)] #[salsa::invoke(ConstData::const_data_query)]
fn const_data(&self, konst: ConstId) -> Arc<ConstData>; fn const_data(&self, konst: ConstId) -> Arc<ConstData>;
#[salsa::invoke(ConstData::static_data_query)] #[salsa::invoke(StaticData::static_data_query)]
fn static_data(&self, konst: StaticId) -> Arc<ConstData>; fn static_data(&self, konst: StaticId) -> Arc<StaticData>;
#[salsa::invoke(Body::body_with_source_map_query)] #[salsa::invoke(Body::body_with_source_map_query)]
fn body_with_source_map(&self, def: DefWithBodyId) -> (Arc<Body>, Arc<BodySourceMap>); fn body_with_source_map(&self, def: DefWithBodyId) -> (Arc<Body>, Arc<BodySourceMap>);

View file

@ -22,7 +22,7 @@ use rustc_hash::FxHashMap;
use hir_def::{ use hir_def::{
body::Body, body::Body,
data::{ConstData, FunctionData}, data::{ConstData, FunctionData, StaticData},
expr::{BindingAnnotation, ExprId, PatId}, expr::{BindingAnnotation, ExprId, PatId},
lang_item::LangItemTarget, lang_item::LangItemTarget,
path::{path, Path}, path::{path, Path},
@ -71,7 +71,7 @@ pub(crate) fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<Infer
match def { match def {
DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)), DefWithBodyId::ConstId(c) => ctx.collect_const(&db.const_data(c)),
DefWithBodyId::FunctionId(f) => ctx.collect_fn(&db.function_data(f)), DefWithBodyId::FunctionId(f) => ctx.collect_fn(&db.function_data(f)),
DefWithBodyId::StaticId(s) => ctx.collect_const(&db.static_data(s)), DefWithBodyId::StaticId(s) => ctx.collect_static(&db.static_data(s)),
} }
ctx.infer_body(); ctx.infer_body();
@ -485,6 +485,10 @@ impl<'a> InferenceContext<'a> {
self.return_ty = self.make_ty(&data.type_ref); self.return_ty = self.make_ty(&data.type_ref);
} }
fn collect_static(&mut self, data: &StaticData) {
self.return_ty = self.make_ty(&data.type_ref);
}
fn collect_fn(&mut self, data: &FunctionData) { fn collect_fn(&mut self, data: &FunctionData) {
let body = Arc::clone(&self.body); // avoid borrow checker problem let body = Arc::clone(&self.body); // avoid borrow checker problem
let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver) let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver)

View file

@ -27,13 +27,13 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd
.keyword.unsafe { color: #BC8383; font-weight: bold; } .keyword.unsafe { color: #BC8383; font-weight: bold; }
.control { font-style: italic; } .control { font-style: italic; }
</style> </style>
<pre><code><span class="macro">macro_rules!</span> println { <pre><code><span class="macro">macro_rules!</span> <span class="macro declaration">println</span> {
($($arg:tt)*) =&gt; ({ ($($arg:tt)*) =&gt; ({
$<span class="keyword">crate</span>::io::_print($<span class="keyword">crate</span>::format_args_nl!($($arg)*)); $<span class="keyword">crate</span>::io::_print($<span class="keyword">crate</span>::format_args_nl!($($arg)*));
}) })
} }
#[rustc_builtin_macro] #[rustc_builtin_macro]
<span class="macro">macro_rules!</span> format_args_nl { <span class="macro">macro_rules!</span> <span class="macro declaration">format_args_nl</span> {
($fmt:expr) =&gt; {{ <span class="comment">/* compiler built-in */</span> }}; ($fmt:expr) =&gt; {{ <span class="comment">/* compiler built-in */</span> }};
($fmt:expr, $($args:tt)*) =&gt; {{ <span class="comment">/* compiler built-in */</span> }}; ($fmt:expr, $($args:tt)*) =&gt; {{ <span class="comment">/* compiler built-in */</span> }};
} }

View file

@ -33,11 +33,13 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd
<span class="keyword">pub</span> <span class="field declaration">y</span>: <span class="builtin_type">i32</span>, <span class="keyword">pub</span> <span class="field declaration">y</span>: <span class="builtin_type">i32</span>,
} }
<span class="keyword">static</span> <span class="keyword">mut</span> <span class="static declaration mutable">STATIC_MUT</span>: <span class="builtin_type">i32</span> = <span class="numeric_literal">0</span>;
<span class="keyword">fn</span> <span class="function declaration">foo</span>&lt;<span class="lifetime declaration">'a</span>, <span class="type_param declaration">T</span>&gt;() -&gt; <span class="type_param">T</span> { <span class="keyword">fn</span> <span class="function declaration">foo</span>&lt;<span class="lifetime declaration">'a</span>, <span class="type_param declaration">T</span>&gt;() -&gt; <span class="type_param">T</span> {
<span class="function">foo</span>::&lt;<span class="lifetime">'a</span>, <span class="builtin_type">i32</span>&gt;() <span class="function">foo</span>::&lt;<span class="lifetime">'a</span>, <span class="builtin_type">i32</span>&gt;()
} }
<span class="macro">macro_rules!</span> def_fn { <span class="macro">macro_rules!</span> <span class="macro declaration">def_fn</span> {
($($tt:tt)*) =&gt; {$($tt)*} ($($tt:tt)*) =&gt; {$($tt)*}
} }
@ -56,7 +58,10 @@ pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padd
<span class="keyword">let</span> <span class="variable declaration">x</span> = <span class="numeric_literal">92</span>; <span class="keyword">let</span> <span class="variable declaration">x</span> = <span class="numeric_literal">92</span>;
<span class="variable mutable">vec</span>.<span class="unresolved_reference">push</span>(<span class="struct">Foo</span> { <span class="field">x</span>, <span class="field">y</span>: <span class="numeric_literal">1</span> }); <span class="variable mutable">vec</span>.<span class="unresolved_reference">push</span>(<span class="struct">Foo</span> { <span class="field">x</span>, <span class="field">y</span>: <span class="numeric_literal">1</span> });
} }
<span class="keyword unsafe">unsafe</span> { <span class="variable mutable">vec</span>.<span class="unresolved_reference">set_len</span>(<span class="numeric_literal">0</span>); } <span class="keyword unsafe">unsafe</span> {
<span class="variable mutable">vec</span>.<span class="unresolved_reference">set_len</span>(<span class="numeric_literal">0</span>);
<span class="static mutable">STATIC_MUT</span> = <span class="numeric_literal">1</span>;
}
<span class="keyword">let</span> <span class="keyword">mut</span> <span class="variable declaration mutable">x</span> = <span class="numeric_literal">42</span>; <span class="keyword">let</span> <span class="keyword">mut</span> <span class="variable declaration mutable">x</span> = <span class="numeric_literal">42</span>;
<span class="keyword">let</span> <span class="variable declaration mutable">y</span> = &<span class="keyword">mut</span> <span class="variable mutable">x</span>; <span class="keyword">let</span> <span class="variable declaration mutable">y</span> = &<span class="keyword">mut</span> <span class="variable mutable">x</span>;

View file

@ -167,6 +167,19 @@ pub(crate) fn highlight(
binding_hash: None, binding_hash: None,
}); });
} }
if let Some(name) = mc.is_macro_rules() {
if let Some((highlight, binding_hash)) = highlight_element(
&sema,
&mut bindings_shadow_count,
name.syntax().clone().into(),
) {
stack.add(HighlightedRange {
range: name.syntax().text_range(),
highlight,
binding_hash,
});
}
}
continue; continue;
} }
WalkEvent::Leave(Some(mc)) => { WalkEvent::Leave(Some(mc)) => {
@ -431,10 +444,16 @@ fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union, hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant, hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
hir::ModuleDef::Const(_) => HighlightTag::Constant, hir::ModuleDef::Const(_) => HighlightTag::Constant,
hir::ModuleDef::Static(_) => HighlightTag::Static,
hir::ModuleDef::Trait(_) => HighlightTag::Trait, hir::ModuleDef::Trait(_) => HighlightTag::Trait,
hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias, hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType, hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
hir::ModuleDef::Static(s) => {
let mut h = Highlight::new(HighlightTag::Static);
if s.is_mut(db) {
h |= HighlightModifier::Mutable;
}
return h;
}
}, },
Definition::SelfType(_) => HighlightTag::SelfType, Definition::SelfType(_) => HighlightTag::SelfType,
Definition::TypeParam(_) => HighlightTag::TypeParam, Definition::TypeParam(_) => HighlightTag::TypeParam,

View file

@ -17,6 +17,8 @@ struct Foo {
pub y: i32, pub y: i32,
} }
static mut STATIC_MUT: i32 = 0;
fn foo<'a, T>() -> T { fn foo<'a, T>() -> T {
foo::<'a, i32>() foo::<'a, i32>()
} }
@ -40,7 +42,10 @@ fn main() {
let x = 92; let x = 92;
vec.push(Foo { x, y: 1 }); vec.push(Foo { x, y: 1 });
} }
unsafe { vec.set_len(0); } unsafe {
vec.set_len(0);
STATIC_MUT = 1;
}
let mut x = 42; let mut x = 42;
let y = &mut x; let y = &mut x;

View file

@ -53,10 +53,9 @@ fn lookup_in_path(exec: &str) -> bool {
let paths = env::var_os("PATH").unwrap_or_default(); let paths = env::var_os("PATH").unwrap_or_default();
let mut candidates = env::split_paths(&paths).flat_map(|path| { let mut candidates = env::split_paths(&paths).flat_map(|path| {
let candidate = path.join(&exec); let candidate = path.join(&exec);
let with_exe = if env::consts::EXE_EXTENSION == "" { let with_exe = match env::consts::EXE_EXTENSION {
None "" => None,
} else { it => Some(candidate.with_extension(it)),
Some(candidate.with_extension(env::consts::EXE_EXTENSION))
}; };
iter::once(candidate).chain(with_exe) iter::once(candidate).chain(with_exe)
}); });

View file

@ -174,7 +174,6 @@ pub fn main_loop(ws_roots: Vec<PathBuf>, config: Config, connection: Connection)
}; };
loop_state.roots_total = world_state.vfs.read().n_roots(); loop_state.roots_total = world_state.vfs.read().n_roots();
loop_state.roots_scanned = 0;
let pool = ThreadPool::default(); let pool = ThreadPool::default();
let (task_sender, task_receiver) = unbounded::<Task>(); let (task_sender, task_receiver) = unbounded::<Task>();
@ -401,10 +400,12 @@ fn loop_turn(
} }
let max_in_flight_libs = pool.max_count().saturating_sub(2).max(1); let max_in_flight_libs = pool.max_count().saturating_sub(2).max(1);
while loop_state.in_flight_libraries < max_in_flight_libs while loop_state.in_flight_libraries < max_in_flight_libs {
&& !loop_state.pending_libraries.is_empty() let (root, files) = match loop_state.pending_libraries.pop() {
{ Some(it) => it,
let (root, files) = loop_state.pending_libraries.pop().unwrap(); None => break,
};
loop_state.in_flight_libraries += 1; loop_state.in_flight_libraries += 1;
let sender = libdata_sender.clone(); let sender = libdata_sender.clone();
pool.execute(move || { pool.execute(move || {

View file

@ -137,15 +137,6 @@ impl WorldState {
opts opts
}; };
// Create crate graph from all the workspaces
let mut crate_graph = CrateGraph::default();
let mut load = |path: &std::path::Path| {
// Some path from metadata will be non canonicalized, e.g. /foo/../bar/lib.rs
let path = path.canonicalize().ok()?;
let vfs_file = vfs.load(&path);
vfs_file.map(|f| FileId(f.0))
};
let proc_macro_client = match &config.proc_macro_srv { let proc_macro_client = match &config.proc_macro_srv {
None => ProcMacroClient::dummy(), None => ProcMacroClient::dummy(),
Some((path, args)) => match ProcMacroClient::extern_process(path.into(), args) { Some((path, args)) => match ProcMacroClient::extern_process(path.into(), args) {
@ -161,19 +152,22 @@ impl WorldState {
}, },
}; };
workspaces // Create crate graph from all the workspaces
.iter() let mut crate_graph = CrateGraph::default();
.map(|ws| { let mut load = |path: &Path| {
ws.to_crate_graph( // Some path from metadata will be non canonicalized, e.g. /foo/../bar/lib.rs
&default_cfg_options, let path = path.canonicalize().ok()?;
&extern_source_roots, let vfs_file = vfs.load(&path);
&proc_macro_client, vfs_file.map(|f| FileId(f.0))
&mut load, };
) for ws in workspaces.iter() {
}) crate_graph.extend(ws.to_crate_graph(
.for_each(|graph| { &default_cfg_options,
crate_graph.extend(graph); &extern_source_roots,
}); &proc_macro_client,
&mut load,
));
}
change.set_crate_graph(crate_graph); change.set_crate_graph(crate_graph);
let flycheck = config.check.as_ref().and_then(|c| create_flycheck(&workspaces, c)); let flycheck = config.check.as_ref().and_then(|c| create_flycheck(&workspaces, c));