aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
Diffstat (limited to 'crates')
-rw-r--r--crates/base_db/src/fixture.rs12
-rw-r--r--crates/base_db/src/input.rs27
-rw-r--r--crates/hir/src/display.rs467
-rw-r--r--crates/hir/src/lib.rs129
-rw-r--r--crates/hir/src/semantics.rs30
-rw-r--r--crates/hir/src/source_analyzer.rs4
-rw-r--r--crates/hir_def/src/adt.rs10
-rw-r--r--crates/hir_def/src/body/lower.rs105
-rw-r--r--crates/hir_def/src/data.rs22
-rw-r--r--crates/hir_def/src/item_tree.rs24
-rw-r--r--crates/hir_def/src/item_tree/lower.rs35
-rw-r--r--crates/hir_def/src/path.rs11
-rw-r--r--crates/hir_expand/src/db.rs3
-rw-r--r--crates/hir_expand/src/lib.rs5
-rw-r--r--crates/hir_ty/src/autoderef.rs4
-rw-r--r--crates/hir_ty/src/diagnostics/decl_check.rs2
-rw-r--r--crates/hir_ty/src/diagnostics/unsafe_check.rs6
-rw-r--r--crates/hir_ty/src/display.rs207
-rw-r--r--crates/hir_ty/src/infer.rs8
-rw-r--r--crates/hir_ty/src/infer/coerce.rs6
-rw-r--r--crates/hir_ty/src/infer/expr.rs37
-rw-r--r--crates/hir_ty/src/infer/pat.rs12
-rw-r--r--crates/hir_ty/src/infer/path.rs20
-rw-r--r--crates/hir_ty/src/infer/unify.rs16
-rw-r--r--crates/hir_ty/src/lib.rs94
-rw-r--r--crates/hir_ty/src/lower.rs46
-rw-r--r--crates/hir_ty/src/method_resolution.rs14
-rw-r--r--crates/hir_ty/src/tests/macros.rs16
-rw-r--r--crates/hir_ty/src/traits.rs4
-rw-r--r--crates/hir_ty/src/traits/chalk.rs20
-rw-r--r--crates/hir_ty/src/traits/chalk/mapping.rs15
-rw-r--r--crates/ide/src/call_hierarchy.rs11
-rw-r--r--crates/ide/src/display.rs4
-rw-r--r--crates/ide/src/display/navigation_target.rs44
-rw-r--r--crates/ide/src/display/short_label.rs128
-rw-r--r--crates/ide/src/doc_links.rs2
-rw-r--r--crates/ide/src/extend_selection.rs13
-rw-r--r--crates/ide/src/goto_definition.rs4
-rw-r--r--crates/ide/src/goto_type_definition.rs2
-rw-r--r--crates/ide/src/hover.rs188
-rw-r--r--crates/ide/src/join_lines.rs44
-rw-r--r--crates/ide/src/matching_brace.rs2
-rw-r--r--crates/ide/src/references.rs30
-rw-r--r--crates/ide/src/runnables.rs3
-rw-r--r--crates/ide/src/syntax_highlighting.rs19
-rw-r--r--crates/ide/src/syntax_highlighting/format.rs2
-rw-r--r--crates/ide/src/syntax_tree.rs2
-rw-r--r--crates/ide/src/typing.rs2
-rw-r--r--crates/ide_assists/src/handlers/add_turbo_fish.rs2
-rw-r--r--crates/ide_assists/src/handlers/change_visibility.rs2
-rw-r--r--crates/ide_assists/src/handlers/expand_glob_import.rs2
-rw-r--r--crates/ide_assists/src/handlers/extract_function.rs20
-rw-r--r--crates/ide_assists/src/handlers/flip_trait_bound.rs2
-rw-r--r--crates/ide_assists/src/handlers/generate_is_empty_from_len.rs35
-rw-r--r--crates/ide_assists/src/handlers/invert_if.rs2
-rw-r--r--crates/ide_assists/src/handlers/move_bounds.rs94
-rw-r--r--crates/ide_assists/src/handlers/split_import.rs2
-rw-r--r--crates/ide_assists/src/handlers/unwrap_block.rs2
-rw-r--r--crates/ide_completion/src/completions/dot.rs24
-rw-r--r--crates/ide_completion/src/completions/flyimport.rs8
-rw-r--r--crates/ide_completion/src/completions/fn_param.rs2
-rw-r--r--crates/ide_completion/src/completions/qualified_path.rs56
-rw-r--r--crates/ide_completion/src/completions/trait_impl.rs7
-rw-r--r--crates/ide_completion/src/completions/unqualified_path.rs50
-rw-r--r--crates/ide_completion/src/context.rs21
-rw-r--r--crates/ide_completion/src/lib.rs6
-rw-r--r--crates/ide_completion/src/patterns.rs16
-rw-r--r--crates/ide_completion/src/render.rs230
-rw-r--r--crates/ide_completion/src/render/enum_variant.rs13
-rw-r--r--crates/ide_completion/src/render/function.rs66
-rw-r--r--crates/ide_db/src/call_info.rs2
-rw-r--r--crates/ide_db/src/search.rs2
-rw-r--r--crates/ide_ssr/src/resolving.rs2
-rw-r--r--crates/mbe/src/tests.rs11
-rw-r--r--crates/parser/src/grammar.rs6
-rw-r--r--crates/parser/src/grammar/expressions.rs6
-rw-r--r--crates/syntax/Cargo.toml2
-rw-r--r--crates/syntax/src/algo.rs35
-rw-r--r--crates/syntax/src/ast.rs7
-rw-r--r--crates/syntax/src/ast/edit_in_place.rs139
-rw-r--r--crates/syntax/src/ast/generated/nodes.rs10
-rw-r--r--crates/syntax/src/ast/make.rs14
-rw-r--r--crates/syntax/src/ast/node_ext.rs4
-rw-r--r--crates/syntax/src/lib.rs1
-rw-r--r--crates/syntax/src/parsing/reparsing.rs6
-rw-r--r--crates/syntax/src/ted.rs78
-rw-r--r--crates/test_utils/src/fixture.rs15
87 files changed, 2070 insertions, 843 deletions
diff --git a/crates/base_db/src/fixture.rs b/crates/base_db/src/fixture.rs
index 5c9824814..cad6866aa 100644
--- a/crates/base_db/src/fixture.rs
+++ b/crates/base_db/src/fixture.rs
@@ -57,7 +57,7 @@
57//! fn insert_source_code_here() {} 57//! fn insert_source_code_here() {}
58//! " 58//! "
59//! ``` 59//! ```
60use std::{str::FromStr, sync::Arc}; 60use std::{mem, str::FromStr, sync::Arc};
61 61
62use cfg::CfgOptions; 62use cfg::CfgOptions;
63use rustc_hash::FxHashMap; 63use rustc_hash::FxHashMap;
@@ -148,6 +148,7 @@ impl ChangeFixture {
148 let mut file_set = FileSet::default(); 148 let mut file_set = FileSet::default();
149 let source_root_prefix = "/".to_string(); 149 let source_root_prefix = "/".to_string();
150 let mut file_id = FileId(0); 150 let mut file_id = FileId(0);
151 let mut roots = Vec::new();
151 152
152 let mut file_position = None; 153 let mut file_position = None;
153 154
@@ -168,6 +169,10 @@ impl ChangeFixture {
168 let meta = FileMeta::from(entry); 169 let meta = FileMeta::from(entry);
169 assert!(meta.path.starts_with(&source_root_prefix)); 170 assert!(meta.path.starts_with(&source_root_prefix));
170 171
172 if meta.introduce_new_source_root {
173 roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
174 }
175
171 if let Some(krate) = meta.krate { 176 if let Some(krate) = meta.krate {
172 let crate_name = CrateName::normalize_dashes(&krate); 177 let crate_name = CrateName::normalize_dashes(&krate);
173 let crate_id = crate_graph.add_crate_root( 178 let crate_id = crate_graph.add_crate_root(
@@ -215,7 +220,8 @@ impl ChangeFixture {
215 } 220 }
216 } 221 }
217 222
218 change.set_roots(vec![SourceRoot::new_local(file_set)]); 223 roots.push(SourceRoot::new_local(mem::take(&mut file_set)));
224 change.set_roots(roots);
219 change.set_crate_graph(crate_graph); 225 change.set_crate_graph(crate_graph);
220 226
221 ChangeFixture { file_position, files, change } 227 ChangeFixture { file_position, files, change }
@@ -229,6 +235,7 @@ struct FileMeta {
229 cfg: CfgOptions, 235 cfg: CfgOptions,
230 edition: Edition, 236 edition: Edition,
231 env: Env, 237 env: Env,
238 introduce_new_source_root: bool,
232} 239}
233 240
234impl From<Fixture> for FileMeta { 241impl From<Fixture> for FileMeta {
@@ -247,6 +254,7 @@ impl From<Fixture> for FileMeta {
247 .as_ref() 254 .as_ref()
248 .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()), 255 .map_or(Edition::Edition2018, |v| Edition::from_str(&v).unwrap()),
249 env: f.env.into_iter().collect(), 256 env: f.env.into_iter().collect(),
257 introduce_new_source_root: f.introduce_new_source_root,
250 } 258 }
251 } 259 }
252} 260}
diff --git a/crates/base_db/src/input.rs b/crates/base_db/src/input.rs
index b5f7e4200..d0def2181 100644
--- a/crates/base_db/src/input.rs
+++ b/crates/base_db/src/input.rs
@@ -274,6 +274,33 @@ impl CrateGraph {
274 deps.into_iter() 274 deps.into_iter()
275 } 275 }
276 276
277 /// Returns an iterator over all transitive reverse dependencies of the given crate.
278 pub fn transitive_reverse_dependencies(
279 &self,
280 of: CrateId,
281 ) -> impl Iterator<Item = CrateId> + '_ {
282 let mut worklist = vec![of];
283 let mut rev_deps = FxHashSet::default();
284 let mut inverted_graph = FxHashMap::<_, Vec<_>>::default();
285 self.arena.iter().for_each(|(&krate, data)| {
286 data.dependencies
287 .iter()
288 .for_each(|dep| inverted_graph.entry(dep.crate_id).or_default().push(krate))
289 });
290
291 while let Some(krate) = worklist.pop() {
292 if let Some(krate_rev_deps) = inverted_graph.get(&krate) {
293 krate_rev_deps
294 .iter()
295 .copied()
296 .filter(|&rev_dep| rev_deps.insert(rev_dep))
297 .for_each(|rev_dep| worklist.push(rev_dep));
298 }
299 }
300
301 rev_deps.into_iter()
302 }
303
277 /// Returns all crates in the graph, sorted in topological order (ie. dependencies of a crate 304 /// Returns all crates in the graph, sorted in topological order (ie. dependencies of a crate
278 /// come before the crate itself). 305 /// come before the crate itself).
279 pub fn crates_in_topological_order(&self) -> Vec<CrateId> { 306 pub fn crates_in_topological_order(&self) -> Vec<CrateId> {
diff --git a/crates/hir/src/display.rs b/crates/hir/src/display.rs
new file mode 100644
index 000000000..9f6d7be48
--- /dev/null
+++ b/crates/hir/src/display.rs
@@ -0,0 +1,467 @@
1//! HirDisplay implementations for various hir types.
2use hir_def::{
3 adt::VariantData,
4 generics::{TypeParamProvenance, WherePredicate, WherePredicateTypeTarget},
5 type_ref::{TypeBound, TypeRef},
6 AdtId, GenericDefId,
7};
8use hir_ty::display::{
9 write_bounds_like_dyn_trait_with_prefix, write_visibility, HirDisplay, HirDisplayError,
10 HirFormatter,
11};
12use syntax::ast::{self, NameOwner};
13
14use crate::{
15 Adt, Const, ConstParam, Enum, Field, Function, GenericParam, HasVisibility, LifetimeParam,
16 Module, Static, Struct, Substitution, Trait, Type, TypeAlias, TypeParam, Union, Variant,
17};
18
19impl HirDisplay for Function {
20 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
21 let data = f.db.function_data(self.id);
22 write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
23 let qual = &data.qualifier;
24 if qual.is_default {
25 write!(f, "default ")?;
26 }
27 if qual.is_const {
28 write!(f, "const ")?;
29 }
30 if qual.is_async {
31 write!(f, "async ")?;
32 }
33 if qual.is_unsafe {
34 write!(f, "unsafe ")?;
35 }
36 if let Some(abi) = &qual.abi {
37 // FIXME: String escape?
38 write!(f, "extern \"{}\" ", abi)?;
39 }
40 write!(f, "fn {}", data.name)?;
41
42 write_generic_params(GenericDefId::FunctionId(self.id), f)?;
43
44 write!(f, "(")?;
45
46 let write_self_param = |ty: &TypeRef, f: &mut HirFormatter| match ty {
47 TypeRef::Path(p) if p.is_self_type() => write!(f, "self"),
48 TypeRef::Reference(inner, lifetime, mut_) if matches!(&**inner,TypeRef::Path(p) if p.is_self_type()) =>
49 {
50 write!(f, "&")?;
51 if let Some(lifetime) = lifetime {
52 write!(f, "{} ", lifetime.name)?;
53 }
54 if let hir_def::type_ref::Mutability::Mut = mut_ {
55 write!(f, "mut ")?;
56 }
57 write!(f, "self")
58 }
59 _ => {
60 write!(f, "self: ")?;
61 ty.hir_fmt(f)
62 }
63 };
64
65 let mut first = true;
66 for (param, type_ref) in self.assoc_fn_params(f.db).into_iter().zip(&data.params) {
67 if !first {
68 write!(f, ", ")?;
69 } else {
70 first = false;
71 if data.has_self_param {
72 write_self_param(type_ref, f)?;
73 continue;
74 }
75 }
76 match param.pattern_source(f.db) {
77 Some(ast::Pat::IdentPat(p)) if p.name().is_some() => {
78 write!(f, "{}: ", p.name().unwrap())?
79 }
80 _ => write!(f, "_: ")?,
81 }
82 // FIXME: Use resolved `param.ty` or raw `type_ref`?
83 // The former will ignore lifetime arguments currently.
84 type_ref.hir_fmt(f)?;
85 }
86 write!(f, ")")?;
87
88 // `FunctionData::ret_type` will be `::core::future::Future<Output = ...>` for async fns.
89 // Use ugly pattern match to strip the Future trait.
90 // Better way?
91 let ret_type = if !qual.is_async {
92 &data.ret_type
93 } else {
94 match &data.ret_type {
95 TypeRef::ImplTrait(bounds) => match &bounds[0] {
96 TypeBound::Path(path) => {
97 path.segments().iter().last().unwrap().args_and_bindings.unwrap().bindings
98 [0]
99 .type_ref
100 .as_ref()
101 .unwrap()
102 }
103 _ => panic!("Async fn ret_type should be impl Future"),
104 },
105 _ => panic!("Async fn ret_type should be impl Future"),
106 }
107 };
108
109 match ret_type {
110 TypeRef::Tuple(tup) if tup.is_empty() => {}
111 ty => {
112 write!(f, " -> ")?;
113 ty.hir_fmt(f)?;
114 }
115 }
116
117 write_where_clause(GenericDefId::FunctionId(self.id), f)?;
118
119 Ok(())
120 }
121}
122
123impl HirDisplay for Adt {
124 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
125 match self {
126 Adt::Struct(it) => it.hir_fmt(f),
127 Adt::Union(it) => it.hir_fmt(f),
128 Adt::Enum(it) => it.hir_fmt(f),
129 }
130 }
131}
132
133impl HirDisplay for Struct {
134 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
135 write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
136 write!(f, "struct ")?;
137 write!(f, "{}", self.name(f.db))?;
138 let def_id = GenericDefId::AdtId(AdtId::StructId(self.id));
139 write_generic_params(def_id, f)?;
140 write_where_clause(def_id, f)?;
141 Ok(())
142 }
143}
144
145impl HirDisplay for Enum {
146 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
147 write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
148 write!(f, "enum ")?;
149 write!(f, "{}", self.name(f.db))?;
150 let def_id = GenericDefId::AdtId(AdtId::EnumId(self.id));
151 write_generic_params(def_id, f)?;
152 write_where_clause(def_id, f)?;
153 Ok(())
154 }
155}
156
157impl HirDisplay for Union {
158 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
159 write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
160 write!(f, "union ")?;
161 write!(f, "{}", self.name(f.db))?;
162 let def_id = GenericDefId::AdtId(AdtId::UnionId(self.id));
163 write_generic_params(def_id, f)?;
164 write_where_clause(def_id, f)?;
165 Ok(())
166 }
167}
168
169impl HirDisplay for Field {
170 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
171 write_visibility(self.parent.module(f.db).id, self.visibility(f.db), f)?;
172 write!(f, "{}: ", self.name(f.db))?;
173 self.signature_ty(f.db).hir_fmt(f)
174 }
175}
176
177impl HirDisplay for Variant {
178 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
179 write!(f, "{}", self.name(f.db))?;
180 let data = self.variant_data(f.db);
181 match &*data {
182 VariantData::Unit => {}
183 VariantData::Tuple(fields) => {
184 write!(f, "(")?;
185 let mut first = true;
186 for (_, field) in fields.iter() {
187 if first {
188 first = false;
189 } else {
190 write!(f, ", ")?;
191 }
192 // Enum variant fields must be pub.
193 field.type_ref.hir_fmt(f)?;
194 }
195 write!(f, ")")?;
196 }
197 VariantData::Record(fields) => {
198 write!(f, " {{")?;
199 let mut first = true;
200 for (_, field) in fields.iter() {
201 if first {
202 first = false;
203 write!(f, " ")?;
204 } else {
205 write!(f, ", ")?;
206 }
207 // Enum variant fields must be pub.
208 write!(f, "{}: ", field.name)?;
209 field.type_ref.hir_fmt(f)?;
210 }
211 write!(f, " }}")?;
212 }
213 }
214 Ok(())
215 }
216}
217
218impl HirDisplay for Type {
219 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
220 self.ty.value.hir_fmt(f)
221 }
222}
223
224impl HirDisplay for GenericParam {
225 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
226 match self {
227 GenericParam::TypeParam(it) => it.hir_fmt(f),
228 GenericParam::LifetimeParam(it) => it.hir_fmt(f),
229 GenericParam::ConstParam(it) => it.hir_fmt(f),
230 }
231 }
232}
233
234impl HirDisplay for TypeParam {
235 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
236 write!(f, "{}", self.name(f.db))?;
237 let bounds = f.db.generic_predicates_for_param(self.id);
238 let substs = Substitution::type_params(f.db, self.id.parent);
239 let predicates = bounds.iter().cloned().map(|b| b.subst(&substs)).collect::<Vec<_>>();
240 if !(predicates.is_empty() || f.omit_verbose_types()) {
241 write_bounds_like_dyn_trait_with_prefix(":", &predicates, f)?;
242 }
243 Ok(())
244 }
245}
246
247impl HirDisplay for LifetimeParam {
248 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
249 write!(f, "{}", self.name(f.db))
250 }
251}
252
253impl HirDisplay for ConstParam {
254 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
255 write!(f, "const {}: ", self.name(f.db))?;
256 self.ty(f.db).hir_fmt(f)
257 }
258}
259
260fn write_generic_params(def: GenericDefId, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
261 let params = f.db.generic_params(def);
262 if params.lifetimes.is_empty()
263 && params.consts.is_empty()
264 && params
265 .types
266 .iter()
267 .all(|(_, param)| !matches!(param.provenance, TypeParamProvenance::TypeParamList))
268 {
269 return Ok(());
270 }
271 write!(f, "<")?;
272
273 let mut first = true;
274 let mut delim = |f: &mut HirFormatter| {
275 if first {
276 first = false;
277 Ok(())
278 } else {
279 write!(f, ", ")
280 }
281 };
282 for (_, lifetime) in params.lifetimes.iter() {
283 delim(f)?;
284 write!(f, "{}", lifetime.name)?;
285 }
286 for (_, ty) in params.types.iter() {
287 if ty.provenance != TypeParamProvenance::TypeParamList {
288 continue;
289 }
290 if let Some(name) = &ty.name {
291 delim(f)?;
292 write!(f, "{}", name)?;
293 if let Some(default) = &ty.default {
294 write!(f, " = ")?;
295 default.hir_fmt(f)?;
296 }
297 }
298 }
299 for (_, konst) in params.consts.iter() {
300 delim(f)?;
301 write!(f, "const {}: ", konst.name)?;
302 konst.ty.hir_fmt(f)?;
303 }
304
305 write!(f, ">")?;
306 Ok(())
307}
308
309fn write_where_clause(def: GenericDefId, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
310 let params = f.db.generic_params(def);
311 if params.where_predicates.is_empty() {
312 return Ok(());
313 }
314
315 let write_target = |target: &WherePredicateTypeTarget, f: &mut HirFormatter| match target {
316 WherePredicateTypeTarget::TypeRef(ty) => ty.hir_fmt(f),
317 WherePredicateTypeTarget::TypeParam(id) => match &params.types[*id].name {
318 Some(name) => write!(f, "{}", name),
319 None => write!(f, "{{unnamed}}"),
320 },
321 };
322
323 write!(f, "\nwhere")?;
324
325 for (pred_idx, pred) in params.where_predicates.iter().enumerate() {
326 let prev_pred =
327 if pred_idx == 0 { None } else { Some(&params.where_predicates[pred_idx - 1]) };
328
329 let new_predicate = |f: &mut HirFormatter| {
330 write!(f, "{}", if pred_idx == 0 { "\n " } else { ",\n " })
331 };
332
333 match pred {
334 WherePredicate::TypeBound { target, bound } => {
335 if matches!(prev_pred, Some(WherePredicate::TypeBound { target: target_, .. }) if target_ == target)
336 {
337 write!(f, " + ")?;
338 } else {
339 new_predicate(f)?;
340 write_target(target, f)?;
341 write!(f, ": ")?;
342 }
343 bound.hir_fmt(f)?;
344 }
345 WherePredicate::Lifetime { target, bound } => {
346 if matches!(prev_pred, Some(WherePredicate::Lifetime { target: target_, .. }) if target_ == target)
347 {
348 write!(f, " + {}", bound.name)?;
349 } else {
350 new_predicate(f)?;
351 write!(f, "{}: {}", target.name, bound.name)?;
352 }
353 }
354 WherePredicate::ForLifetime { lifetimes, target, bound } => {
355 if matches!(
356 prev_pred,
357 Some(WherePredicate::ForLifetime { lifetimes: lifetimes_, target: target_, .. })
358 if lifetimes_ == lifetimes && target_ == target,
359 ) {
360 write!(f, " + ")?;
361 } else {
362 new_predicate(f)?;
363 write!(f, "for<")?;
364 for (idx, lifetime) in lifetimes.iter().enumerate() {
365 if idx != 0 {
366 write!(f, ", ")?;
367 }
368 write!(f, "{}", lifetime)?;
369 }
370 write!(f, "> ")?;
371 write_target(target, f)?;
372 write!(f, ": ")?;
373 }
374 bound.hir_fmt(f)?;
375 }
376 }
377 }
378
379 // End of final predicate. There must be at least one predicate here.
380 write!(f, ",")?;
381
382 Ok(())
383}
384
385impl HirDisplay for Const {
386 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
387 write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
388 let data = f.db.const_data(self.id);
389 write!(f, "const ")?;
390 match &data.name {
391 Some(name) => write!(f, "{}: ", name)?,
392 None => write!(f, "_: ")?,
393 }
394 data.type_ref.hir_fmt(f)?;
395 Ok(())
396 }
397}
398
399impl HirDisplay for Static {
400 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
401 write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
402 let data = f.db.static_data(self.id);
403 write!(f, "static ")?;
404 if data.mutable {
405 write!(f, "mut ")?;
406 }
407 match &data.name {
408 Some(name) => write!(f, "{}: ", name)?,
409 None => write!(f, "_: ")?,
410 }
411 data.type_ref.hir_fmt(f)?;
412 Ok(())
413 }
414}
415
416impl HirDisplay for Trait {
417 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
418 write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
419 let data = f.db.trait_data(self.id);
420 if data.is_unsafe {
421 write!(f, "unsafe ")?;
422 }
423 if data.is_auto {
424 write!(f, "auto ")?;
425 }
426 write!(f, "trait {}", data.name)?;
427 let def_id = GenericDefId::TraitId(self.id);
428 write_generic_params(def_id, f)?;
429 if !data.bounds.is_empty() {
430 write!(f, ": ")?;
431 f.write_joined(&*data.bounds, " + ")?;
432 }
433 write_where_clause(def_id, f)?;
434 Ok(())
435 }
436}
437
438impl HirDisplay for TypeAlias {
439 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
440 write_visibility(self.module(f.db).id, self.visibility(f.db), f)?;
441 let data = f.db.type_alias_data(self.id);
442 write!(f, "type {}", data.name)?;
443 if !data.bounds.is_empty() {
444 write!(f, ": ")?;
445 f.write_joined(&data.bounds, " + ")?;
446 }
447 if let Some(ty) = &data.type_ref {
448 write!(f, " = ")?;
449 ty.hir_fmt(f)?;
450 }
451 Ok(())
452 }
453}
454
455impl HirDisplay for Module {
456 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
457 // FIXME: Module doesn't have visibility saved in data.
458 match self.name(f.db) {
459 Some(name) => write!(f, "mod {}", name),
460 None if self.crate_root(f.db) == *self => match self.krate().display_name(f.db) {
461 Some(name) => write!(f, "extern crate {}", name),
462 None => write!(f, "extern crate {{unknown}}"),
463 },
464 None => write!(f, "mod {{unnamed}}"),
465 }
466 }
467}
diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs
index c5161dadd..12dd5fb38 100644
--- a/crates/hir/src/lib.rs
+++ b/crates/hir/src/lib.rs
@@ -29,6 +29,8 @@ mod has_source;
29pub mod diagnostics; 29pub mod diagnostics;
30pub mod db; 30pub mod db;
31 31
32mod display;
33
32use std::{iter, sync::Arc}; 34use std::{iter, sync::Arc};
33 35
34use arrayvec::ArrayVec; 36use arrayvec::ArrayVec;
@@ -50,14 +52,15 @@ use hir_def::{
50use hir_expand::{diagnostics::DiagnosticSink, name::name, MacroDefKind}; 52use hir_expand::{diagnostics::DiagnosticSink, name::name, MacroDefKind};
51use hir_ty::{ 53use hir_ty::{
52 autoderef, 54 autoderef,
53 display::{write_bounds_like_dyn_trait_with_prefix, HirDisplayError, HirFormatter},
54 method_resolution::{self, TyFingerprint}, 55 method_resolution::{self, TyFingerprint},
56 primitive::UintTy,
55 to_assoc_type_id, 57 to_assoc_type_id,
56 traits::{FnTrait, Solution, SolutionVariables}, 58 traits::{FnTrait, Solution, SolutionVariables},
57 AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, DebruijnIndex, GenericPredicate, 59 AliasTy, BoundVar, CallableDefId, CallableSig, Canonical, DebruijnIndex, GenericPredicate,
58 InEnvironment, Interner, Obligation, ProjectionPredicate, ProjectionTy, Scalar, Substs, Ty, 60 InEnvironment, Interner, Obligation, ProjectionPredicate, ProjectionTy, Scalar, Substitution,
59 TyDefId, TyKind, TyVariableKind, 61 Ty, TyDefId, TyKind, TyVariableKind,
60}; 62};
63use itertools::Itertools;
61use rustc_hash::FxHashSet; 64use rustc_hash::FxHashSet;
62use stdx::{format_to, impl_from}; 65use stdx::{format_to, impl_from};
63use syntax::{ 66use syntax::{
@@ -139,7 +142,6 @@ impl Crate {
139 .collect() 142 .collect()
140 } 143 }
141 144
142 // FIXME: add `transitive_reverse_dependencies`.
143 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> { 145 pub fn reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
144 let crate_graph = db.crate_graph(); 146 let crate_graph = db.crate_graph();
145 crate_graph 147 crate_graph
@@ -151,6 +153,14 @@ impl Crate {
151 .collect() 153 .collect()
152 } 154 }
153 155
156 pub fn transitive_reverse_dependencies(self, db: &dyn HirDatabase) -> Vec<Crate> {
157 db.crate_graph()
158 .transitive_reverse_dependencies(self.id)
159 .into_iter()
160 .map(|id| Crate { id })
161 .collect()
162 }
163
154 pub fn root_module(self, db: &dyn HirDatabase) -> Module { 164 pub fn root_module(self, db: &dyn HirDatabase) -> Module {
155 let def_map = db.crate_def_map(self.id); 165 let def_map = db.crate_def_map(self.id);
156 Module { id: def_map.module_id(def_map.root()) } 166 Module { id: def_map.module_id(def_map.root()) }
@@ -508,7 +518,7 @@ impl Field {
508 VariantDef::Union(it) => it.id.into(), 518 VariantDef::Union(it) => it.id.into(),
509 VariantDef::Variant(it) => it.parent.id.into(), 519 VariantDef::Variant(it) => it.parent.id.into(),
510 }; 520 };
511 let substs = Substs::type_params(db, generic_def_id); 521 let substs = Substitution::type_params(db, generic_def_id);
512 let ty = db.field_types(var_id)[self.id].clone().subst(&substs); 522 let ty = db.field_types(var_id)[self.id].clone().subst(&substs);
513 Type::new(db, self.parent.module(db).id.krate(), var_id, ty) 523 Type::new(db, self.parent.module(db).id.krate(), var_id, ty)
514 } 524 }
@@ -571,6 +581,12 @@ impl Struct {
571 } 581 }
572} 582}
573 583
584impl HasVisibility for Struct {
585 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
586 db.struct_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
587 }
588}
589
574#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 590#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
575pub struct Union { 591pub struct Union {
576 pub(crate) id: UnionId, 592 pub(crate) id: UnionId,
@@ -603,6 +619,12 @@ impl Union {
603 } 619 }
604} 620}
605 621
622impl HasVisibility for Union {
623 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
624 db.union_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
625 }
626}
627
606#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 628#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
607pub struct Enum { 629pub struct Enum {
608 pub(crate) id: EnumId, 630 pub(crate) id: EnumId,
@@ -630,6 +652,12 @@ impl Enum {
630 } 652 }
631} 653}
632 654
655impl HasVisibility for Enum {
656 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
657 db.enum_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
658 }
659}
660
633#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 661#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
634pub struct Variant { 662pub struct Variant {
635 pub(crate) parent: Enum, 663 pub(crate) parent: Enum,
@@ -821,7 +849,8 @@ impl Function {
821 db.function_data(self.id) 849 db.function_data(self.id)
822 .params 850 .params
823 .iter() 851 .iter()
824 .map(|type_ref| { 852 .enumerate()
853 .map(|(idx, type_ref)| {
825 let ty = Type { 854 let ty = Type {
826 krate, 855 krate,
827 ty: InEnvironment { 856 ty: InEnvironment {
@@ -829,7 +858,7 @@ impl Function {
829 environment: environment.clone(), 858 environment: environment.clone(),
830 }, 859 },
831 }; 860 };
832 Param { ty } 861 Param { func: self, ty, idx }
833 }) 862 })
834 .collect() 863 .collect()
835 } 864 }
@@ -843,7 +872,7 @@ impl Function {
843 } 872 }
844 873
845 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool { 874 pub fn is_unsafe(self, db: &dyn HirDatabase) -> bool {
846 db.function_data(self.id).is_unsafe 875 db.function_data(self.id).qualifier.is_unsafe
847 } 876 }
848 877
849 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) { 878 pub fn diagnostics(self, db: &dyn HirDatabase, sink: &mut DiagnosticSink) {
@@ -892,6 +921,9 @@ impl From<hir_ty::Mutability> for Access {
892 921
893#[derive(Debug)] 922#[derive(Debug)]
894pub struct Param { 923pub struct Param {
924 func: Function,
925 /// The index in parameter list, including self parameter.
926 idx: usize,
895 ty: Type, 927 ty: Type,
896} 928}
897 929
@@ -899,6 +931,15 @@ impl Param {
899 pub fn ty(&self) -> &Type { 931 pub fn ty(&self) -> &Type {
900 &self.ty 932 &self.ty
901 } 933 }
934
935 pub fn pattern_source(&self, db: &dyn HirDatabase) -> Option<ast::Pat> {
936 let params = self.func.source(db)?.value.param_list()?;
937 if params.self_param().is_some() {
938 params.params().nth(self.idx.checked_sub(1)?)?.pat()
939 } else {
940 params.params().nth(self.idx)?.pat()
941 }
942 }
902} 943}
903 944
904#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 945#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -921,6 +962,14 @@ impl SelfParam {
921 }) 962 })
922 .unwrap_or(Access::Owned) 963 .unwrap_or(Access::Owned)
923 } 964 }
965
966 pub fn display(self, db: &dyn HirDatabase) -> &'static str {
967 match self.access(db) {
968 Access::Shared => "&self",
969 Access::Exclusive => "&mut self",
970 Access::Owned => "self",
971 }
972 }
924} 973}
925 974
926impl HasVisibility for Function { 975impl HasVisibility for Function {
@@ -948,6 +997,10 @@ impl Const {
948 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> { 997 pub fn name(self, db: &dyn HirDatabase) -> Option<Name> {
949 db.const_data(self.id).name.clone() 998 db.const_data(self.id).name.clone()
950 } 999 }
1000
1001 pub fn type_ref(self, db: &dyn HirDatabase) -> TypeRef {
1002 db.const_data(self.id).type_ref.clone()
1003 }
951} 1004}
952 1005
953impl HasVisibility for Const { 1006impl HasVisibility for Const {
@@ -981,6 +1034,12 @@ impl Static {
981 } 1034 }
982} 1035}
983 1036
1037impl HasVisibility for Static {
1038 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1039 db.static_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1040 }
1041}
1042
984#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 1043#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
985pub struct Trait { 1044pub struct Trait {
986 pub(crate) id: TraitId, 1045 pub(crate) id: TraitId,
@@ -1000,7 +1059,13 @@ impl Trait {
1000 } 1059 }
1001 1060
1002 pub fn is_auto(self, db: &dyn HirDatabase) -> bool { 1061 pub fn is_auto(self, db: &dyn HirDatabase) -> bool {
1003 db.trait_data(self.id).auto 1062 db.trait_data(self.id).is_auto
1063 }
1064}
1065
1066impl HasVisibility for Trait {
1067 fn visibility(&self, db: &dyn HirDatabase) -> Visibility {
1068 db.trait_data(self.id).visibility.resolve(db.upcast(), &self.id.resolver(db.upcast()))
1004 } 1069 }
1005} 1070}
1006 1071
@@ -1406,25 +1471,12 @@ impl TypeParam {
1406 let resolver = self.id.parent.resolver(db.upcast()); 1471 let resolver = self.id.parent.resolver(db.upcast());
1407 let krate = self.id.parent.module(db.upcast()).krate(); 1472 let krate = self.id.parent.module(db.upcast()).krate();
1408 let ty = params.get(local_idx)?.clone(); 1473 let ty = params.get(local_idx)?.clone();
1409 let subst = Substs::type_params(db, self.id.parent); 1474 let subst = Substitution::type_params(db, self.id.parent);
1410 let ty = ty.subst(&subst.prefix(local_idx)); 1475 let ty = ty.subst(&subst.prefix(local_idx));
1411 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty)) 1476 Some(Type::new_with_resolver_inner(db, krate, &resolver, ty))
1412 } 1477 }
1413} 1478}
1414 1479
1415impl HirDisplay for TypeParam {
1416 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1417 write!(f, "{}", self.name(f.db))?;
1418 let bounds = f.db.generic_predicates_for_param(self.id);
1419 let substs = Substs::type_params(f.db, self.id.parent);
1420 let predicates = bounds.iter().cloned().map(|b| b.subst(&substs)).collect::<Vec<_>>();
1421 if !(predicates.is_empty() || f.omit_verbose_types()) {
1422 write_bounds_like_dyn_trait_with_prefix(":", &predicates, f)?;
1423 }
1424 Ok(())
1425 }
1426}
1427
1428#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] 1480#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1429pub struct LifetimeParam { 1481pub struct LifetimeParam {
1430 pub(crate) id: LifetimeParamId, 1482 pub(crate) id: LifetimeParamId,
@@ -1497,11 +1549,17 @@ impl Impl {
1497 }; 1549 };
1498 1550
1499 let mut all = Vec::new(); 1551 let mut all = Vec::new();
1500 def_crates.into_iter().for_each(|id| { 1552 def_crates.iter().for_each(|&id| {
1501 all.extend(db.inherent_impls_in_crate(id).all_impls().map(Self::from).filter(filter)) 1553 all.extend(db.inherent_impls_in_crate(id).all_impls().map(Self::from).filter(filter))
1502 }); 1554 });
1503 let fp = TyFingerprint::for_impl(&ty.value); 1555 let fp = TyFingerprint::for_impl(&ty.value);
1504 for id in db.crate_graph().iter() { 1556 for id in def_crates
1557 .iter()
1558 .flat_map(|&id| Crate { id }.transitive_reverse_dependencies(db))
1559 .map(|Crate { id }| id)
1560 .chain(def_crates.iter().copied())
1561 .unique()
1562 {
1505 match fp { 1563 match fp {
1506 Some(fp) => all.extend( 1564 Some(fp) => all.extend(
1507 db.trait_impls_in_crate(id).for_self_ty(fp).map(Self::from).filter(filter), 1565 db.trait_impls_in_crate(id).for_self_ty(fp).map(Self::from).filter(filter),
@@ -1516,7 +1574,8 @@ impl Impl {
1516 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> { 1574 pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> {
1517 let krate = trait_.module(db).krate(); 1575 let krate = trait_.module(db).krate();
1518 let mut all = Vec::new(); 1576 let mut all = Vec::new();
1519 for Crate { id } in krate.reverse_dependencies(db).into_iter().chain(Some(krate)) { 1577 for Crate { id } in krate.transitive_reverse_dependencies(db).into_iter().chain(Some(krate))
1578 {
1520 let impls = db.trait_impls_in_crate(id); 1579 let impls = db.trait_impls_in_crate(id);
1521 all.extend(impls.for_trait(trait_.id).map(Self::from)) 1580 all.extend(impls.for_trait(trait_.id).map(Self::from))
1522 } 1581 }
@@ -1615,7 +1674,7 @@ impl Type {
1615 krate: CrateId, 1674 krate: CrateId,
1616 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>, 1675 def: impl HasResolver + Into<TyDefId> + Into<GenericDefId>,
1617 ) -> Type { 1676 ) -> Type {
1618 let substs = Substs::build_for_def(db, def).fill_with_unknown().build(); 1677 let substs = Substitution::build_for_def(db, def).fill_with_unknown().build();
1619 let ty = db.ty(def.into()).subst(&substs); 1678 let ty = db.ty(def.into()).subst(&substs);
1620 Type::new(db, krate, def, ty) 1679 Type::new(db, krate, def, ty)
1621 } 1680 }
@@ -1631,6 +1690,10 @@ impl Type {
1631 matches!(self.ty.value.interned(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..)) 1690 matches!(self.ty.value.interned(&Interner), TyKind::Ref(hir_ty::Mutability::Mut, ..))
1632 } 1691 }
1633 1692
1693 pub fn is_usize(&self) -> bool {
1694 matches!(self.ty.value.interned(&Interner), TyKind::Scalar(Scalar::Uint(UintTy::Usize)))
1695 }
1696
1634 pub fn remove_ref(&self) -> Option<Type> { 1697 pub fn remove_ref(&self) -> Option<Type> {
1635 match &self.ty.value.interned(&Interner) { 1698 match &self.ty.value.interned(&Interner) {
1636 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())), 1699 TyKind::Ref(.., ty) => Some(self.derived(ty.clone())),
@@ -1691,7 +1754,7 @@ impl Type {
1691 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool { 1754 pub fn impls_trait(&self, db: &dyn HirDatabase, trait_: Trait, args: &[Type]) -> bool {
1692 let trait_ref = hir_ty::TraitRef { 1755 let trait_ref = hir_ty::TraitRef {
1693 trait_: trait_.id, 1756 trait_: trait_.id,
1694 substs: Substs::build_for_def(db, trait_.id) 1757 substs: Substitution::build_for_def(db, trait_.id)
1695 .push(self.ty.value.clone()) 1758 .push(self.ty.value.clone())
1696 .fill(args.iter().map(|t| t.ty.value.clone())) 1759 .fill(args.iter().map(|t| t.ty.value.clone()))
1697 .build(), 1760 .build(),
@@ -1715,7 +1778,7 @@ impl Type {
1715 args: &[Type], 1778 args: &[Type],
1716 alias: TypeAlias, 1779 alias: TypeAlias,
1717 ) -> Option<Type> { 1780 ) -> Option<Type> {
1718 let subst = Substs::build_for_def(db, trait_.id) 1781 let subst = Substitution::build_for_def(db, trait_.id)
1719 .push(self.ty.value.clone()) 1782 .push(self.ty.value.clone())
1720 .fill(args.iter().map(|t| t.ty.value.clone())) 1783 .fill(args.iter().map(|t| t.ty.value.clone()))
1721 .build(); 1784 .build();
@@ -1982,7 +2045,7 @@ impl Type {
1982 fn walk_substs( 2045 fn walk_substs(
1983 db: &dyn HirDatabase, 2046 db: &dyn HirDatabase,
1984 type_: &Type, 2047 type_: &Type,
1985 substs: &Substs, 2048 substs: &Substitution,
1986 cb: &mut impl FnMut(Type), 2049 cb: &mut impl FnMut(Type),
1987 ) { 2050 ) {
1988 for ty in substs.iter() { 2051 for ty in substs.iter() {
@@ -2054,12 +2117,6 @@ impl Type {
2054 } 2117 }
2055} 2118}
2056 2119
2057impl HirDisplay for Type {
2058 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
2059 self.ty.value.hir_fmt(f)
2060 }
2061}
2062
2063// FIXME: closures 2120// FIXME: closures
2064#[derive(Debug)] 2121#[derive(Debug)]
2065pub struct Callable { 2122pub struct Callable {
diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs
index 519339c0c..03c9371b5 100644
--- a/crates/hir/src/semantics.rs
+++ b/crates/hir/src/semantics.rs
@@ -143,6 +143,12 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
143 self.imp.diagnostics_display_range(diagnostics) 143 self.imp.diagnostics_display_range(diagnostics)
144 } 144 }
145 145
146 pub fn token_ancestors_with_macros(
147 &self,
148 token: SyntaxToken,
149 ) -> impl Iterator<Item = SyntaxNode> + '_ {
150 token.parent().into_iter().flat_map(move |it| self.ancestors_with_macros(it))
151 }
146 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ { 152 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
147 self.imp.ancestors_with_macros(node) 153 self.imp.ancestors_with_macros(node)
148 } 154 }
@@ -270,8 +276,8 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
270 self.imp.scope(node) 276 self.imp.scope(node)
271 } 277 }
272 278
273 pub fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> { 279 pub fn scope_at_offset(&self, token: &SyntaxToken, offset: TextSize) -> SemanticsScope<'db> {
274 self.imp.scope_at_offset(node, offset) 280 self.imp.scope_at_offset(&token.parent().unwrap(), offset)
275 } 281 }
276 282
277 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> { 283 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
@@ -341,7 +347,10 @@ impl<'db> SemanticsImpl<'db> {
341 347
342 fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken { 348 fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
343 let _p = profile::span("descend_into_macros"); 349 let _p = profile::span("descend_into_macros");
344 let parent = token.parent(); 350 let parent = match token.parent() {
351 Some(it) => it,
352 None => return token,
353 };
345 let sa = self.analyze(&parent); 354 let sa = self.analyze(&parent);
346 355
347 let token = successors(Some(InFile::new(sa.file_id, token)), |token| { 356 let token = successors(Some(InFile::new(sa.file_id, token)), |token| {
@@ -360,7 +369,9 @@ impl<'db> SemanticsImpl<'db> {
360 .as_ref()? 369 .as_ref()?
361 .map_token_down(token.as_ref())?; 370 .map_token_down(token.as_ref())?;
362 371
363 self.cache(find_root(&token.value.parent()), token.file_id); 372 if let Some(parent) = token.value.parent() {
373 self.cache(find_root(&parent), token.file_id);
374 }
364 375
365 Some(token) 376 Some(token)
366 }) 377 })
@@ -378,7 +389,7 @@ impl<'db> SemanticsImpl<'db> {
378 // Handle macro token cases 389 // Handle macro token cases
379 node.token_at_offset(offset) 390 node.token_at_offset(offset)
380 .map(|token| self.descend_into_macros(token)) 391 .map(|token| self.descend_into_macros(token))
381 .map(|it| self.ancestors_with_macros(it.parent())) 392 .map(|it| self.token_ancestors_with_macros(it))
382 .flatten() 393 .flatten()
383 } 394 }
384 395
@@ -394,6 +405,13 @@ impl<'db> SemanticsImpl<'db> {
394 src.with_value(&node).original_file_range(self.db.upcast()) 405 src.with_value(&node).original_file_range(self.db.upcast())
395 } 406 }
396 407
408 fn token_ancestors_with_macros(
409 &self,
410 token: SyntaxToken,
411 ) -> impl Iterator<Item = SyntaxNode> + '_ {
412 token.parent().into_iter().flat_map(move |parent| self.ancestors_with_macros(parent))
413 }
414
397 fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ { 415 fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
398 let node = self.find_file(node); 416 let node = self.find_file(node);
399 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value) 417 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
@@ -405,7 +423,7 @@ impl<'db> SemanticsImpl<'db> {
405 offset: TextSize, 423 offset: TextSize,
406 ) -> impl Iterator<Item = SyntaxNode> + '_ { 424 ) -> impl Iterator<Item = SyntaxNode> + '_ {
407 node.token_at_offset(offset) 425 node.token_at_offset(offset)
408 .map(|token| self.ancestors_with_macros(token.parent())) 426 .map(|token| self.token_ancestors_with_macros(token))
409 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len()) 427 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
410 } 428 }
411 429
diff --git a/crates/hir/src/source_analyzer.rs b/crates/hir/src/source_analyzer.rs
index 4d59293e9..117f32a9e 100644
--- a/crates/hir/src/source_analyzer.rs
+++ b/crates/hir/src/source_analyzer.rs
@@ -20,7 +20,7 @@ use hir_def::{
20use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile}; 20use hir_expand::{hygiene::Hygiene, name::AsName, HirFileId, InFile};
21use hir_ty::{ 21use hir_ty::{
22 diagnostics::{record_literal_missing_fields, record_pattern_missing_fields}, 22 diagnostics::{record_literal_missing_fields, record_pattern_missing_fields},
23 InferenceResult, Substs, 23 InferenceResult, Substitution,
24}; 24};
25use syntax::{ 25use syntax::{
26 ast::{self, AstNode}, 26 ast::{self, AstNode},
@@ -329,7 +329,7 @@ impl SourceAnalyzer {
329 &self, 329 &self,
330 db: &dyn HirDatabase, 330 db: &dyn HirDatabase,
331 krate: CrateId, 331 krate: CrateId,
332 substs: &Substs, 332 substs: &Substitution,
333 variant: VariantId, 333 variant: VariantId,
334 missing_fields: Vec<LocalFieldId>, 334 missing_fields: Vec<LocalFieldId>,
335 ) -> Vec<(Field, Type)> { 335 ) -> Vec<(Field, Type)> {
diff --git a/crates/hir_def/src/adt.rs b/crates/hir_def/src/adt.rs
index efbde17d8..1b9bb8235 100644
--- a/crates/hir_def/src/adt.rs
+++ b/crates/hir_def/src/adt.rs
@@ -31,12 +31,14 @@ pub struct StructData {
31 pub name: Name, 31 pub name: Name,
32 pub variant_data: Arc<VariantData>, 32 pub variant_data: Arc<VariantData>,
33 pub repr: Option<ReprKind>, 33 pub repr: Option<ReprKind>,
34 pub visibility: RawVisibility,
34} 35}
35 36
36#[derive(Debug, Clone, PartialEq, Eq)] 37#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct EnumData { 38pub struct EnumData {
38 pub name: Name, 39 pub name: Name,
39 pub variants: Arena<EnumVariantData>, 40 pub variants: Arena<EnumVariantData>,
41 pub visibility: RawVisibility,
40} 42}
41 43
42#[derive(Debug, Clone, PartialEq, Eq)] 44#[derive(Debug, Clone, PartialEq, Eq)]
@@ -102,6 +104,7 @@ impl StructData {
102 name: strukt.name.clone(), 104 name: strukt.name.clone(),
103 variant_data: Arc::new(variant_data), 105 variant_data: Arc::new(variant_data),
104 repr, 106 repr,
107 visibility: item_tree[strukt.visibility].clone(),
105 }) 108 })
106 } 109 }
107 pub(crate) fn union_data_query(db: &dyn DefDatabase, id: UnionId) -> Arc<StructData> { 110 pub(crate) fn union_data_query(db: &dyn DefDatabase, id: UnionId) -> Arc<StructData> {
@@ -118,6 +121,7 @@ impl StructData {
118 name: union.name.clone(), 121 name: union.name.clone(),
119 variant_data: Arc::new(variant_data), 122 variant_data: Arc::new(variant_data),
120 repr, 123 repr,
124 visibility: item_tree[union.visibility].clone(),
121 }) 125 })
122 } 126 }
123} 127}
@@ -150,7 +154,11 @@ impl EnumData {
150 } 154 }
151 } 155 }
152 156
153 Arc::new(EnumData { name: enum_.name.clone(), variants }) 157 Arc::new(EnumData {
158 name: enum_.name.clone(),
159 variants,
160 visibility: item_tree[enum_.visibility].clone(),
161 })
154 } 162 }
155 163
156 pub fn variant(&self, name: &Name) -> Option<LocalEnumVariantId> { 164 pub fn variant(&self, name: &Name) -> Option<LocalEnumVariantId> {
diff --git a/crates/hir_def/src/body/lower.rs b/crates/hir_def/src/body/lower.rs
index 8934ae6c9..7052058f2 100644
--- a/crates/hir_def/src/body/lower.rs
+++ b/crates/hir_def/src/body/lower.rs
@@ -519,7 +519,7 @@ impl ExprCollector<'_> {
519 } 519 }
520 ast::Expr::MacroCall(e) => { 520 ast::Expr::MacroCall(e) => {
521 let mut ids = vec![]; 521 let mut ids = vec![];
522 self.collect_macro_call(e, syntax_ptr.clone(), |this, expansion| { 522 self.collect_macro_call(e, syntax_ptr.clone(), true, |this, expansion| {
523 ids.push(match expansion { 523 ids.push(match expansion {
524 Some(it) => this.collect_expr(it), 524 Some(it) => this.collect_expr(it),
525 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()), 525 None => this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
@@ -527,6 +527,17 @@ impl ExprCollector<'_> {
527 }); 527 });
528 ids[0] 528 ids[0]
529 } 529 }
530 ast::Expr::MacroStmts(e) => {
531 // FIXME: these statements should be held by some hir containter
532 for stmt in e.statements() {
533 self.collect_stmt(stmt);
534 }
535 if let Some(expr) = e.expr() {
536 self.collect_expr(expr)
537 } else {
538 self.alloc_expr(Expr::Missing, syntax_ptr)
539 }
540 }
530 } 541 }
531 } 542 }
532 543
@@ -534,6 +545,7 @@ impl ExprCollector<'_> {
534 &mut self, 545 &mut self,
535 e: ast::MacroCall, 546 e: ast::MacroCall,
536 syntax_ptr: AstPtr<ast::Expr>, 547 syntax_ptr: AstPtr<ast::Expr>,
548 is_error_recoverable: bool,
537 mut collector: F, 549 mut collector: F,
538 ) { 550 ) {
539 // File containing the macro call. Expansion errors will be attached here. 551 // File containing the macro call. Expansion errors will be attached here.
@@ -567,7 +579,7 @@ impl ExprCollector<'_> {
567 Some((mark, expansion)) => { 579 Some((mark, expansion)) => {
568 // FIXME: Statements are too complicated to recover from error for now. 580 // FIXME: Statements are too complicated to recover from error for now.
569 // It is because we don't have any hygiene for local variable expansion right now. 581 // It is because we don't have any hygiene for local variable expansion right now.
570 if T::can_cast(syntax::SyntaxKind::MACRO_STMTS) && res.err.is_some() { 582 if !is_error_recoverable && res.err.is_some() {
571 self.expander.exit(self.db, mark); 583 self.expander.exit(self.db, mark);
572 collector(self, None); 584 collector(self, None);
573 } else { 585 } else {
@@ -591,56 +603,55 @@ impl ExprCollector<'_> {
591 } 603 }
592 604
593 fn collect_stmt(&mut self, s: ast::Stmt) -> Option<Vec<Statement>> { 605 fn collect_stmt(&mut self, s: ast::Stmt) -> Option<Vec<Statement>> {
594 let stmt = 606 let stmt = match s {
595 match s { 607 ast::Stmt::LetStmt(stmt) => {
596 ast::Stmt::LetStmt(stmt) => { 608 self.check_cfg(&stmt)?;
597 self.check_cfg(&stmt)?; 609
598 610 let pat = self.collect_pat_opt(stmt.pat());
599 let pat = self.collect_pat_opt(stmt.pat()); 611 let type_ref = stmt.ty().map(|it| TypeRef::from_ast(&self.ctx(), it));
600 let type_ref = stmt.ty().map(|it| TypeRef::from_ast(&self.ctx(), it)); 612 let initializer = stmt.initializer().map(|e| self.collect_expr(e));
601 let initializer = stmt.initializer().map(|e| self.collect_expr(e)); 613 vec![Statement::Let { pat, type_ref, initializer }]
602 vec![Statement::Let { pat, type_ref, initializer }] 614 }
603 } 615 ast::Stmt::ExprStmt(stmt) => {
604 ast::Stmt::ExprStmt(stmt) => { 616 self.check_cfg(&stmt)?;
605 self.check_cfg(&stmt)?; 617
606 618 // Note that macro could be expended to multiple statements
607 // Note that macro could be expended to multiple statements 619 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() {
608 if let Some(ast::Expr::MacroCall(m)) = stmt.expr() { 620 let syntax_ptr = AstPtr::new(&stmt.expr().unwrap());
609 let syntax_ptr = AstPtr::new(&stmt.expr().unwrap()); 621 let mut stmts = vec![];
610 let mut stmts = vec![]; 622
611 623 self.collect_macro_call(m, syntax_ptr.clone(), false, |this, expansion| {
612 self.collect_macro_call(m, syntax_ptr.clone(), |this, expansion| { 624 match expansion {
613 match expansion { 625 Some(expansion) => {
614 Some(expansion) => { 626 let statements: ast::MacroStmts = expansion;
615 let statements: ast::MacroStmts = expansion; 627
616 628 statements.statements().for_each(|stmt| {
617 statements.statements().for_each(|stmt| { 629 if let Some(mut r) = this.collect_stmt(stmt) {
618 if let Some(mut r) = this.collect_stmt(stmt) { 630 stmts.append(&mut r);
619 stmts.append(&mut r);
620 }
621 });
622 if let Some(expr) = statements.expr() {
623 stmts.push(Statement::Expr(this.collect_expr(expr)));
624 } 631 }
625 } 632 });
626 None => { 633 if let Some(expr) = statements.expr() {
627 stmts.push(Statement::Expr( 634 stmts.push(Statement::Expr(this.collect_expr(expr)));
628 this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
629 ));
630 } 635 }
631 } 636 }
632 }); 637 None => {
633 stmts 638 stmts.push(Statement::Expr(
634 } else { 639 this.alloc_expr(Expr::Missing, syntax_ptr.clone()),
635 vec![Statement::Expr(self.collect_expr_opt(stmt.expr()))] 640 ));
636 } 641 }
642 }
643 });
644 stmts
645 } else {
646 vec![Statement::Expr(self.collect_expr_opt(stmt.expr()))]
637 } 647 }
638 ast::Stmt::Item(item) => { 648 }
639 self.check_cfg(&item)?; 649 ast::Stmt::Item(item) => {
650 self.check_cfg(&item)?;
640 651
641 return None; 652 return None;
642 } 653 }
643 }; 654 };
644 655
645 Some(stmt) 656 Some(stmt)
646 } 657 }
diff --git a/crates/hir_def/src/data.rs b/crates/hir_def/src/data.rs
index aea53d527..74a2194e5 100644
--- a/crates/hir_def/src/data.rs
+++ b/crates/hir_def/src/data.rs
@@ -9,7 +9,7 @@ use crate::{
9 attr::Attrs, 9 attr::Attrs,
10 body::Expander, 10 body::Expander,
11 db::DefDatabase, 11 db::DefDatabase,
12 item_tree::{AssocItem, ItemTreeId, ModItem}, 12 item_tree::{AssocItem, FunctionQualifier, ItemTreeId, ModItem},
13 type_ref::{TypeBound, TypeRef}, 13 type_ref::{TypeBound, TypeRef},
14 visibility::RawVisibility, 14 visibility::RawVisibility,
15 AssocContainerId, AssocItemId, ConstId, ConstLoc, FunctionId, FunctionLoc, HasModule, ImplId, 15 AssocContainerId, AssocItemId, ConstId, ConstLoc, FunctionId, FunctionLoc, HasModule, ImplId,
@@ -26,9 +26,9 @@ pub struct FunctionData {
26 /// can be called as a method. 26 /// can be called as a method.
27 pub has_self_param: bool, 27 pub has_self_param: bool,
28 pub has_body: bool, 28 pub has_body: bool,
29 pub is_unsafe: bool, 29 pub qualifier: FunctionQualifier,
30 pub is_in_extern_block: bool,
30 pub is_varargs: bool, 31 pub is_varargs: bool,
31 pub is_extern: bool,
32 pub visibility: RawVisibility, 32 pub visibility: RawVisibility,
33} 33}
34 34
@@ -46,9 +46,9 @@ impl FunctionData {
46 attrs: item_tree.attrs(db, krate, ModItem::from(loc.id.value).into()), 46 attrs: item_tree.attrs(db, krate, ModItem::from(loc.id.value).into()),
47 has_self_param: func.has_self_param, 47 has_self_param: func.has_self_param,
48 has_body: func.has_body, 48 has_body: func.has_body,
49 is_unsafe: func.is_unsafe, 49 qualifier: func.qualifier.clone(),
50 is_in_extern_block: func.is_in_extern_block,
50 is_varargs: func.is_varargs, 51 is_varargs: func.is_varargs,
51 is_extern: func.is_extern,
52 visibility: item_tree[func.visibility].clone(), 52 visibility: item_tree[func.visibility].clone(),
53 }) 53 })
54 } 54 }
@@ -87,7 +87,10 @@ impl TypeAliasData {
87pub struct TraitData { 87pub struct TraitData {
88 pub name: Name, 88 pub name: Name,
89 pub items: Vec<(Name, AssocItemId)>, 89 pub items: Vec<(Name, AssocItemId)>,
90 pub auto: bool, 90 pub is_auto: bool,
91 pub is_unsafe: bool,
92 pub visibility: RawVisibility,
93 pub bounds: Box<[TypeBound]>,
91} 94}
92 95
93impl TraitData { 96impl TraitData {
@@ -96,10 +99,13 @@ impl TraitData {
96 let item_tree = db.item_tree(tr_loc.id.file_id); 99 let item_tree = db.item_tree(tr_loc.id.file_id);
97 let tr_def = &item_tree[tr_loc.id.value]; 100 let tr_def = &item_tree[tr_loc.id.value];
98 let name = tr_def.name.clone(); 101 let name = tr_def.name.clone();
99 let auto = tr_def.auto; 102 let is_auto = tr_def.is_auto;
103 let is_unsafe = tr_def.is_unsafe;
100 let module_id = tr_loc.container; 104 let module_id = tr_loc.container;
101 let container = AssocContainerId::TraitId(tr); 105 let container = AssocContainerId::TraitId(tr);
102 let mut expander = Expander::new(db, tr_loc.id.file_id, module_id); 106 let mut expander = Expander::new(db, tr_loc.id.file_id, module_id);
107 let visibility = item_tree[tr_def.visibility].clone();
108 let bounds = tr_def.bounds.clone();
103 109
104 let items = collect_items( 110 let items = collect_items(
105 db, 111 db,
@@ -111,7 +117,7 @@ impl TraitData {
111 100, 117 100,
112 ); 118 );
113 119
114 Arc::new(TraitData { name, items, auto }) 120 Arc::new(TraitData { name, items, is_auto, is_unsafe, visibility, bounds })
115 } 121 }
116 122
117 pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ { 123 pub fn associated_types(&self) -> impl Iterator<Item = TypeAliasId> + '_ {
diff --git a/crates/hir_def/src/item_tree.rs b/crates/hir_def/src/item_tree.rs
index 09bcb10dc..7bb22c4c4 100644
--- a/crates/hir_def/src/item_tree.rs
+++ b/crates/hir_def/src/item_tree.rs
@@ -24,7 +24,7 @@ use la_arena::{Arena, Idx, RawIdx};
24use profile::Count; 24use profile::Count;
25use rustc_hash::FxHashMap; 25use rustc_hash::FxHashMap;
26use smallvec::SmallVec; 26use smallvec::SmallVec;
27use syntax::{ast, match_ast, SyntaxKind}; 27use syntax::{ast, match_ast, SmolStr, SyntaxKind};
28 28
29use crate::{ 29use crate::{
30 attr::{Attrs, RawAttrs}, 30 attr::{Attrs, RawAttrs},
@@ -110,6 +110,11 @@ impl ItemTree {
110 // still need to collect inner items. 110 // still need to collect inner items.
111 ctx.lower_inner_items(e.syntax()) 111 ctx.lower_inner_items(e.syntax())
112 }, 112 },
113 ast::ExprStmt(stmt) => {
114 // Macros can expand to stmt. We return an empty item tree in this case, but
115 // still need to collect inner items.
116 ctx.lower_inner_items(stmt.syntax())
117 },
113 _ => { 118 _ => {
114 panic!("cannot create item tree from {:?} {}", syntax, syntax); 119 panic!("cannot create item tree from {:?} {}", syntax, syntax);
115 }, 120 },
@@ -551,16 +556,25 @@ pub struct Function {
551 pub generic_params: GenericParamsId, 556 pub generic_params: GenericParamsId,
552 pub has_self_param: bool, 557 pub has_self_param: bool,
553 pub has_body: bool, 558 pub has_body: bool,
554 pub is_unsafe: bool, 559 pub qualifier: FunctionQualifier,
555 /// Whether the function is located in an `extern` block (*not* whether it is an 560 /// Whether the function is located in an `extern` block (*not* whether it is an
556 /// `extern "abi" fn`). 561 /// `extern "abi" fn`).
557 pub is_extern: bool, 562 pub is_in_extern_block: bool,
558 pub params: Box<[Idx<TypeRef>]>, 563 pub params: Box<[Idx<TypeRef>]>,
559 pub is_varargs: bool, 564 pub is_varargs: bool,
560 pub ret_type: Idx<TypeRef>, 565 pub ret_type: Idx<TypeRef>,
561 pub ast_id: FileAstId<ast::Fn>, 566 pub ast_id: FileAstId<ast::Fn>,
562} 567}
563 568
569#[derive(Debug, Clone, PartialEq, Eq)]
570pub struct FunctionQualifier {
571 pub is_default: bool,
572 pub is_const: bool,
573 pub is_async: bool,
574 pub is_unsafe: bool,
575 pub abi: Option<SmolStr>,
576}
577
564#[derive(Debug, Clone, Eq, PartialEq)] 578#[derive(Debug, Clone, Eq, PartialEq)]
565pub struct Struct { 579pub struct Struct {
566 pub name: Name, 580 pub name: Name,
@@ -624,7 +638,9 @@ pub struct Trait {
624 pub name: Name, 638 pub name: Name,
625 pub visibility: RawVisibilityId, 639 pub visibility: RawVisibilityId,
626 pub generic_params: GenericParamsId, 640 pub generic_params: GenericParamsId,
627 pub auto: bool, 641 pub is_auto: bool,
642 pub is_unsafe: bool,
643 pub bounds: Box<[TypeBound]>,
628 pub items: Box<[AssocItem]>, 644 pub items: Box<[AssocItem]>,
629 pub ast_id: FileAstId<ast::Trait>, 645 pub ast_id: FileAstId<ast::Trait>,
630} 646}
diff --git a/crates/hir_def/src/item_tree/lower.rs b/crates/hir_def/src/item_tree/lower.rs
index 240fdacf9..7e91b991d 100644
--- a/crates/hir_def/src/item_tree/lower.rs
+++ b/crates/hir_def/src/item_tree/lower.rs
@@ -391,14 +391,33 @@ impl Ctx {
391 let has_body = func.body().is_some(); 391 let has_body = func.body().is_some();
392 392
393 let ast_id = self.source_ast_id_map.ast_id(func); 393 let ast_id = self.source_ast_id_map.ast_id(func);
394 let qualifier = FunctionQualifier {
395 is_default: func.default_token().is_some(),
396 is_const: func.const_token().is_some(),
397 is_async: func.async_token().is_some(),
398 is_unsafe: func.unsafe_token().is_some(),
399 abi: func.abi().map(|abi| {
400 // FIXME: Abi::abi() -> Option<SyntaxToken>?
401 match abi.syntax().last_token() {
402 Some(tok) if tok.kind() == SyntaxKind::STRING => {
403 // FIXME: Better way to unescape?
404 tok.text().trim_matches('"').into()
405 }
406 _ => {
407 // `extern` default to be `extern "C"`.
408 "C".into()
409 }
410 }
411 }),
412 };
394 let mut res = Function { 413 let mut res = Function {
395 name, 414 name,
396 visibility, 415 visibility,
397 generic_params: GenericParamsId::EMPTY, 416 generic_params: GenericParamsId::EMPTY,
398 has_self_param, 417 has_self_param,
399 has_body, 418 has_body,
400 is_unsafe: func.unsafe_token().is_some(), 419 qualifier,
401 is_extern: false, 420 is_in_extern_block: false,
402 params, 421 params,
403 is_varargs, 422 is_varargs,
404 ret_type, 423 ret_type,
@@ -481,7 +500,9 @@ impl Ctx {
481 let visibility = self.lower_visibility(trait_def); 500 let visibility = self.lower_visibility(trait_def);
482 let generic_params = 501 let generic_params =
483 self.lower_generic_params_and_inner_items(GenericsOwner::Trait(trait_def), trait_def); 502 self.lower_generic_params_and_inner_items(GenericsOwner::Trait(trait_def), trait_def);
484 let auto = trait_def.auto_token().is_some(); 503 let is_auto = trait_def.auto_token().is_some();
504 let is_unsafe = trait_def.unsafe_token().is_some();
505 let bounds = self.lower_type_bounds(trait_def);
485 let items = trait_def.assoc_item_list().map(|list| { 506 let items = trait_def.assoc_item_list().map(|list| {
486 self.with_inherited_visibility(visibility, |this| { 507 self.with_inherited_visibility(visibility, |this| {
487 list.assoc_items() 508 list.assoc_items()
@@ -501,7 +522,9 @@ impl Ctx {
501 name, 522 name,
502 visibility, 523 visibility,
503 generic_params, 524 generic_params,
504 auto, 525 is_auto,
526 is_unsafe,
527 bounds: bounds.into(),
505 items: items.unwrap_or_default(), 528 items: items.unwrap_or_default(),
506 ast_id, 529 ast_id,
507 }; 530 };
@@ -608,8 +631,8 @@ impl Ctx {
608 ast::ExternItem::Fn(ast) => { 631 ast::ExternItem::Fn(ast) => {
609 let func_id = self.lower_function(&ast)?; 632 let func_id = self.lower_function(&ast)?;
610 let func = &mut self.data().functions[func_id.index]; 633 let func = &mut self.data().functions[func_id.index];
611 func.is_unsafe = is_intrinsic_fn_unsafe(&func.name); 634 func.qualifier.is_unsafe = is_intrinsic_fn_unsafe(&func.name);
612 func.is_extern = true; 635 func.is_in_extern_block = true;
613 func_id.into() 636 func_id.into()
614 } 637 }
615 ast::ExternItem::Static(ast) => { 638 ast::ExternItem::Static(ast) => {
diff --git a/crates/hir_def/src/path.rs b/crates/hir_def/src/path.rs
index 0e60dc2b6..8c923bb7b 100644
--- a/crates/hir_def/src/path.rs
+++ b/crates/hir_def/src/path.rs
@@ -9,7 +9,10 @@ use std::{
9 9
10use crate::{body::LowerCtx, type_ref::LifetimeRef}; 10use crate::{body::LowerCtx, type_ref::LifetimeRef};
11use base_db::CrateId; 11use base_db::CrateId;
12use hir_expand::{hygiene::Hygiene, name::Name}; 12use hir_expand::{
13 hygiene::Hygiene,
14 name::{name, Name},
15};
13use syntax::ast; 16use syntax::ast;
14 17
15use crate::{ 18use crate::{
@@ -209,6 +212,12 @@ impl Path {
209 }; 212 };
210 Some(res) 213 Some(res)
211 } 214 }
215
216 pub fn is_self_type(&self) -> bool {
217 self.type_anchor.is_none()
218 && self.generic_args == &[None]
219 && self.mod_path.as_ident() == Some(&name!(Self))
220 }
212} 221}
213 222
214#[derive(Debug, Clone, PartialEq, Eq, Hash)] 223#[derive(Debug, Clone, PartialEq, Eq, Hash)]
diff --git a/crates/hir_expand/src/db.rs b/crates/hir_expand/src/db.rs
index 9086e6c17..a3070f1f9 100644
--- a/crates/hir_expand/src/db.rs
+++ b/crates/hir_expand/src/db.rs
@@ -401,13 +401,14 @@ fn to_fragment_kind(db: &dyn AstDatabase, id: MacroCallId) -> FragmentKind {
401 401
402 match parent.kind() { 402 match parent.kind() {
403 MACRO_ITEMS | SOURCE_FILE => FragmentKind::Items, 403 MACRO_ITEMS | SOURCE_FILE => FragmentKind::Items,
404 MACRO_STMTS => FragmentKind::Statement,
404 ITEM_LIST => FragmentKind::Items, 405 ITEM_LIST => FragmentKind::Items,
405 LET_STMT => { 406 LET_STMT => {
406 // FIXME: Handle Pattern 407 // FIXME: Handle Pattern
407 FragmentKind::Expr 408 FragmentKind::Expr
408 } 409 }
409 EXPR_STMT => FragmentKind::Statements, 410 EXPR_STMT => FragmentKind::Statements,
410 BLOCK_EXPR => FragmentKind::Expr, 411 BLOCK_EXPR => FragmentKind::Statements,
411 ARG_LIST => FragmentKind::Expr, 412 ARG_LIST => FragmentKind::Expr,
412 TRY_EXPR => FragmentKind::Expr, 413 TRY_EXPR => FragmentKind::Expr,
413 TUPLE_EXPR => FragmentKind::Expr, 414 TUPLE_EXPR => FragmentKind::Expr,
diff --git a/crates/hir_expand/src/lib.rs b/crates/hir_expand/src/lib.rs
index e388ddacc..eee430af1 100644
--- a/crates/hir_expand/src/lib.rs
+++ b/crates/hir_expand/src/lib.rs
@@ -510,7 +510,10 @@ impl InFile<SyntaxToken> {
510 self, 510 self,
511 db: &dyn db::AstDatabase, 511 db: &dyn db::AstDatabase,
512 ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ { 512 ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
513 self.map(|it| it.parent()).ancestors_with_macros(db) 513 self.value
514 .parent()
515 .into_iter()
516 .flat_map(move |parent| InFile::new(self.file_id, parent).ancestors_with_macros(db))
514 } 517 }
515} 518}
516 519
diff --git a/crates/hir_ty/src/autoderef.rs b/crates/hir_ty/src/autoderef.rs
index 56c6b92d4..bd2ff5d38 100644
--- a/crates/hir_ty/src/autoderef.rs
+++ b/crates/hir_ty/src/autoderef.rs
@@ -15,7 +15,7 @@ use crate::{
15 to_assoc_type_id, 15 to_assoc_type_id,
16 traits::{InEnvironment, Solution}, 16 traits::{InEnvironment, Solution},
17 utils::generics, 17 utils::generics,
18 BoundVar, Canonical, DebruijnIndex, Interner, Obligation, Substs, TraitRef, Ty, TyKind, 18 BoundVar, Canonical, DebruijnIndex, Interner, Obligation, Substitution, TraitRef, Ty, TyKind,
19}; 19};
20 20
21const AUTODEREF_RECURSION_LIMIT: usize = 10; 21const AUTODEREF_RECURSION_LIMIT: usize = 10;
@@ -65,7 +65,7 @@ fn deref_by_trait(
65 // FIXME make the Canonical / bound var handling nicer 65 // FIXME make the Canonical / bound var handling nicer
66 66
67 let parameters = 67 let parameters =
68 Substs::build_for_generics(&generic_params).push(ty.value.value.clone()).build(); 68 Substitution::build_for_generics(&generic_params).push(ty.value.value.clone()).build();
69 69
70 // Check that the type implements Deref at all 70 // Check that the type implements Deref at all
71 let trait_ref = TraitRef { trait_: deref_trait, substs: parameters.clone() }; 71 let trait_ref = TraitRef { trait_: deref_trait, substs: parameters.clone() };
diff --git a/crates/hir_ty/src/diagnostics/decl_check.rs b/crates/hir_ty/src/diagnostics/decl_check.rs
index 3605ca581..982ad5b9e 100644
--- a/crates/hir_ty/src/diagnostics/decl_check.rs
+++ b/crates/hir_ty/src/diagnostics/decl_check.rs
@@ -91,7 +91,7 @@ impl<'a, 'b> DeclValidator<'a, 'b> {
91 91
92 fn validate_func(&mut self, func: FunctionId) { 92 fn validate_func(&mut self, func: FunctionId) {
93 let data = self.db.function_data(func); 93 let data = self.db.function_data(func);
94 if data.is_extern { 94 if data.is_in_extern_block {
95 cov_mark::hit!(extern_func_incorrect_case_ignored); 95 cov_mark::hit!(extern_func_incorrect_case_ignored);
96 return; 96 return;
97 } 97 }
diff --git a/crates/hir_ty/src/diagnostics/unsafe_check.rs b/crates/hir_ty/src/diagnostics/unsafe_check.rs
index 20bb64827..44a7e5506 100644
--- a/crates/hir_ty/src/diagnostics/unsafe_check.rs
+++ b/crates/hir_ty/src/diagnostics/unsafe_check.rs
@@ -32,7 +32,7 @@ impl<'a, 'b> UnsafeValidator<'a, 'b> {
32 let def = self.owner.into(); 32 let def = self.owner.into();
33 let unsafe_expressions = unsafe_expressions(db, self.infer.as_ref(), def); 33 let unsafe_expressions = unsafe_expressions(db, self.infer.as_ref(), def);
34 let is_unsafe = match self.owner { 34 let is_unsafe = match self.owner {
35 DefWithBodyId::FunctionId(it) => db.function_data(it).is_unsafe, 35 DefWithBodyId::FunctionId(it) => db.function_data(it).qualifier.is_unsafe,
36 DefWithBodyId::StaticId(_) | DefWithBodyId::ConstId(_) => false, 36 DefWithBodyId::StaticId(_) | DefWithBodyId::ConstId(_) => false,
37 }; 37 };
38 if is_unsafe 38 if is_unsafe
@@ -86,7 +86,7 @@ fn walk_unsafe(
86 match expr { 86 match expr {
87 &Expr::Call { callee, .. } => { 87 &Expr::Call { callee, .. } => {
88 if let Some(func) = infer[callee].as_fn_def(db) { 88 if let Some(func) = infer[callee].as_fn_def(db) {
89 if db.function_data(func).is_unsafe { 89 if db.function_data(func).qualifier.is_unsafe {
90 unsafe_exprs.push(UnsafeExpr { expr: current, inside_unsafe_block }); 90 unsafe_exprs.push(UnsafeExpr { expr: current, inside_unsafe_block });
91 } 91 }
92 } 92 }
@@ -103,7 +103,7 @@ fn walk_unsafe(
103 Expr::MethodCall { .. } => { 103 Expr::MethodCall { .. } => {
104 if infer 104 if infer
105 .method_resolution(current) 105 .method_resolution(current)
106 .map(|func| db.function_data(func).is_unsafe) 106 .map(|func| db.function_data(func).qualifier.is_unsafe)
107 .unwrap_or(false) 107 .unwrap_or(false)
108 { 108 {
109 unsafe_exprs.push(UnsafeExpr { expr: current, inside_unsafe_block }); 109 unsafe_exprs.push(UnsafeExpr { expr: current, inside_unsafe_block });
diff --git a/crates/hir_ty/src/display.rs b/crates/hir_ty/src/display.rs
index c1062387e..7ce0f864c 100644
--- a/crates/hir_ty/src/display.rs
+++ b/crates/hir_ty/src/display.rs
@@ -5,7 +5,13 @@ use std::{borrow::Cow, fmt};
5use arrayvec::ArrayVec; 5use arrayvec::ArrayVec;
6use chalk_ir::Mutability; 6use chalk_ir::Mutability;
7use hir_def::{ 7use hir_def::{
8 db::DefDatabase, find_path, generics::TypeParamProvenance, item_scope::ItemInNs, 8 db::DefDatabase,
9 find_path,
10 generics::TypeParamProvenance,
11 item_scope::ItemInNs,
12 path::{GenericArg, Path, PathKind},
13 type_ref::{TypeBound, TypeRef},
14 visibility::Visibility,
9 AssocContainerId, Lookup, ModuleId, TraitId, 15 AssocContainerId, Lookup, ModuleId, TraitId,
10}; 16};
11use hir_expand::name::Name; 17use hir_expand::name::Name;
@@ -14,7 +20,7 @@ use crate::{
14 db::HirDatabase, from_assoc_type_id, from_foreign_def_id, from_placeholder_idx, primitive, 20 db::HirDatabase, from_assoc_type_id, from_foreign_def_id, from_placeholder_idx, primitive,
15 to_assoc_type_id, traits::chalk::from_chalk, utils::generics, AdtId, AliasTy, CallableDefId, 21 to_assoc_type_id, traits::chalk::from_chalk, utils::generics, AdtId, AliasTy, CallableDefId,
16 CallableSig, GenericPredicate, ImplTraitId, Interner, Lifetime, Obligation, OpaqueTy, 22 CallableSig, GenericPredicate, ImplTraitId, Interner, Lifetime, Obligation, OpaqueTy,
17 ProjectionTy, Scalar, Substs, TraitRef, Ty, TyKind, 23 ProjectionTy, Scalar, Substitution, TraitRef, Ty, TyKind,
18}; 24};
19 25
20pub struct HirFormatter<'a> { 26pub struct HirFormatter<'a> {
@@ -232,7 +238,7 @@ where
232 238
233const TYPE_HINT_TRUNCATION: &str = "…"; 239const TYPE_HINT_TRUNCATION: &str = "…";
234 240
235impl HirDisplay for &Ty { 241impl<T: HirDisplay> HirDisplay for &'_ T {
236 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { 242 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
237 HirDisplay::hir_fmt(*self, f) 243 HirDisplay::hir_fmt(*self, f)
238 } 244 }
@@ -556,7 +562,7 @@ impl HirDisplay for Ty {
556 } 562 }
557 TypeParamProvenance::ArgumentImplTrait => { 563 TypeParamProvenance::ArgumentImplTrait => {
558 let bounds = f.db.generic_predicates_for_param(id); 564 let bounds = f.db.generic_predicates_for_param(id);
559 let substs = Substs::type_params_for_generics(f.db, &generics); 565 let substs = Substitution::type_params_for_generics(f.db, &generics);
560 write_bounds_like_dyn_trait_with_prefix( 566 write_bounds_like_dyn_trait_with_prefix(
561 "impl", 567 "impl",
562 &bounds.iter().map(|b| b.clone().subst(&substs)).collect::<Vec<_>>(), 568 &bounds.iter().map(|b| b.clone().subst(&substs)).collect::<Vec<_>>(),
@@ -761,12 +767,6 @@ impl HirDisplay for TraitRef {
761 } 767 }
762} 768}
763 769
764impl HirDisplay for &GenericPredicate {
765 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
766 HirDisplay::hir_fmt(*self, f)
767 }
768}
769
770impl HirDisplay for GenericPredicate { 770impl HirDisplay for GenericPredicate {
771 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> { 771 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
772 if f.should_truncate() { 772 if f.should_truncate() {
@@ -825,3 +825,190 @@ impl HirDisplay for Obligation {
825 } 825 }
826 } 826 }
827} 827}
828
829pub fn write_visibility(
830 module_id: ModuleId,
831 vis: Visibility,
832 f: &mut HirFormatter,
833) -> Result<(), HirDisplayError> {
834 match vis {
835 Visibility::Public => write!(f, "pub "),
836 Visibility::Module(vis_id) => {
837 let def_map = module_id.def_map(f.db.upcast());
838 let root_module_id = def_map.module_id(def_map.root());
839 if vis_id == module_id {
840 // pub(self) or omitted
841 Ok(())
842 } else if root_module_id == vis_id {
843 write!(f, "pub(crate) ")
844 } else if module_id.containing_module(f.db.upcast()) == Some(vis_id) {
845 write!(f, "pub(super) ")
846 } else {
847 write!(f, "pub(in ...) ")
848 }
849 }
850 }
851}
852
853impl HirDisplay for TypeRef {
854 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
855 match self {
856 TypeRef::Never => write!(f, "!")?,
857 TypeRef::Placeholder => write!(f, "_")?,
858 TypeRef::Tuple(elems) => {
859 write!(f, "(")?;
860 f.write_joined(elems, ", ")?;
861 if elems.len() == 1 {
862 write!(f, ",")?;
863 }
864 write!(f, ")")?;
865 }
866 TypeRef::Path(path) => path.hir_fmt(f)?,
867 TypeRef::RawPtr(inner, mutability) => {
868 let mutability = match mutability {
869 hir_def::type_ref::Mutability::Shared => "*const ",
870 hir_def::type_ref::Mutability::Mut => "*mut ",
871 };
872 write!(f, "{}", mutability)?;
873 inner.hir_fmt(f)?;
874 }
875 TypeRef::Reference(inner, lifetime, mutability) => {
876 let mutability = match mutability {
877 hir_def::type_ref::Mutability::Shared => "",
878 hir_def::type_ref::Mutability::Mut => "mut ",
879 };
880 write!(f, "&")?;
881 if let Some(lifetime) = lifetime {
882 write!(f, "{} ", lifetime.name)?;
883 }
884 write!(f, "{}", mutability)?;
885 inner.hir_fmt(f)?;
886 }
887 TypeRef::Array(inner) => {
888 write!(f, "[")?;
889 inner.hir_fmt(f)?;
890 // FIXME: Array length?
891 write!(f, "; _]")?;
892 }
893 TypeRef::Slice(inner) => {
894 write!(f, "[")?;
895 inner.hir_fmt(f)?;
896 write!(f, "]")?;
897 }
898 TypeRef::Fn(tys, is_varargs) => {
899 // FIXME: Function pointer qualifiers.
900 write!(f, "fn(")?;
901 f.write_joined(&tys[..tys.len() - 1], ", ")?;
902 if *is_varargs {
903 write!(f, "{}...", if tys.len() == 1 { "" } else { ", " })?;
904 }
905 write!(f, ")")?;
906 let ret_ty = tys.last().unwrap();
907 match ret_ty {
908 TypeRef::Tuple(tup) if tup.is_empty() => {}
909 _ => {
910 write!(f, " -> ")?;
911 ret_ty.hir_fmt(f)?;
912 }
913 }
914 }
915 TypeRef::ImplTrait(bounds) => {
916 write!(f, "impl ")?;
917 f.write_joined(bounds, " + ")?;
918 }
919 TypeRef::DynTrait(bounds) => {
920 write!(f, "dyn ")?;
921 f.write_joined(bounds, " + ")?;
922 }
923 TypeRef::Error => write!(f, "{{error}}")?,
924 }
925 Ok(())
926 }
927}
928
929impl HirDisplay for TypeBound {
930 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
931 match self {
932 TypeBound::Path(path) => path.hir_fmt(f),
933 TypeBound::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
934 TypeBound::Error => write!(f, "{{error}}"),
935 }
936 }
937}
938
939impl HirDisplay for Path {
940 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
941 match (self.type_anchor(), self.kind()) {
942 (Some(anchor), _) => {
943 write!(f, "<")?;
944 anchor.hir_fmt(f)?;
945 write!(f, ">")?;
946 }
947 (_, PathKind::Plain) => {}
948 (_, PathKind::Abs) => write!(f, "::")?,
949 (_, PathKind::Crate) => write!(f, "crate")?,
950 (_, PathKind::Super(0)) => write!(f, "self")?,
951 (_, PathKind::Super(n)) => {
952 write!(f, "super")?;
953 for _ in 0..*n {
954 write!(f, "::super")?;
955 }
956 }
957 (_, PathKind::DollarCrate(_)) => write!(f, "{{extern_crate}}")?,
958 }
959
960 for (seg_idx, segment) in self.segments().iter().enumerate() {
961 if seg_idx != 0 {
962 write!(f, "::")?;
963 }
964 write!(f, "{}", segment.name)?;
965 if let Some(generic_args) = segment.args_and_bindings {
966 // We should be in type context, so format as `Foo<Bar>` instead of `Foo::<Bar>`.
967 // Do we actually format expressions?
968 write!(f, "<")?;
969 let mut first = true;
970 for arg in &generic_args.args {
971 if first {
972 first = false;
973 if generic_args.has_self_type {
974 // FIXME: Convert to `<Ty as Trait>` form.
975 write!(f, "Self = ")?;
976 }
977 } else {
978 write!(f, ", ")?;
979 }
980 arg.hir_fmt(f)?;
981 }
982 for binding in &generic_args.bindings {
983 if first {
984 first = false;
985 } else {
986 write!(f, ", ")?;
987 }
988 write!(f, "{}", binding.name)?;
989 match &binding.type_ref {
990 Some(ty) => {
991 write!(f, " = ")?;
992 ty.hir_fmt(f)?
993 }
994 None => {
995 write!(f, ": ")?;
996 f.write_joined(&binding.bounds, " + ")?;
997 }
998 }
999 }
1000 write!(f, ">")?;
1001 }
1002 }
1003 Ok(())
1004 }
1005}
1006
1007impl HirDisplay for GenericArg {
1008 fn hir_fmt(&self, f: &mut HirFormatter) -> Result<(), HirDisplayError> {
1009 match self {
1010 GenericArg::Type(ty) => ty.hir_fmt(f),
1011 GenericArg::Lifetime(lifetime) => write!(f, "{}", lifetime.name),
1012 }
1013 }
1014}
diff --git a/crates/hir_ty/src/infer.rs b/crates/hir_ty/src/infer.rs
index 9c385b845..2610c9279 100644
--- a/crates/hir_ty/src/infer.rs
+++ b/crates/hir_ty/src/infer.rs
@@ -38,7 +38,7 @@ use syntax::SmolStr;
38 38
39use super::{ 39use super::{
40 traits::{Guidance, Obligation, ProjectionPredicate, Solution}, 40 traits::{Guidance, Obligation, ProjectionPredicate, Solution},
41 InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypeWalk, 41 InEnvironment, ProjectionTy, Substitution, TraitEnvironment, TraitRef, Ty, TypeWalk,
42}; 42};
43use crate::{ 43use crate::{
44 db::HirDatabase, infer::diagnostics::InferenceDiagnostic, lower::ImplTraitLoweringMode, 44 db::HirDatabase, infer::diagnostics::InferenceDiagnostic, lower::ImplTraitLoweringMode,
@@ -390,7 +390,7 @@ impl<'a> InferenceContext<'a> {
390 _ => panic!("resolve_associated_type called with non-associated type"), 390 _ => panic!("resolve_associated_type called with non-associated type"),
391 }; 391 };
392 let ty = self.table.new_type_var(); 392 let ty = self.table.new_type_var();
393 let substs = Substs::build_for_def(self.db, res_assoc_ty) 393 let substs = Substitution::build_for_def(self.db, res_assoc_ty)
394 .push(inner_ty) 394 .push(inner_ty)
395 .fill(params.iter().cloned()) 395 .fill(params.iter().cloned())
396 .build(); 396 .build();
@@ -469,7 +469,7 @@ impl<'a> InferenceContext<'a> {
469 } 469 }
470 TypeNs::SelfType(impl_id) => { 470 TypeNs::SelfType(impl_id) => {
471 let generics = crate::utils::generics(self.db.upcast(), impl_id.into()); 471 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
472 let substs = Substs::type_params_for_generics(self.db, &generics); 472 let substs = Substitution::type_params_for_generics(self.db, &generics);
473 let ty = self.db.impl_self_ty(impl_id).subst(&substs); 473 let ty = self.db.impl_self_ty(impl_id).subst(&substs);
474 match unresolved { 474 match unresolved {
475 None => { 475 None => {
@@ -496,7 +496,7 @@ impl<'a> InferenceContext<'a> {
496 } 496 }
497 } 497 }
498 TypeNs::TypeAliasId(it) => { 498 TypeNs::TypeAliasId(it) => {
499 let substs = Substs::build_for_def(self.db, it) 499 let substs = Substitution::build_for_def(self.db, it)
500 .fill(std::iter::repeat_with(|| self.table.new_type_var())) 500 .fill(std::iter::repeat_with(|| self.table.new_type_var()))
501 .build(); 501 .build();
502 let ty = self.db.ty(it.into()).subst(&substs); 502 let ty = self.db.ty(it.into()).subst(&substs);
diff --git a/crates/hir_ty/src/infer/coerce.rs b/crates/hir_ty/src/infer/coerce.rs
index 137419264..b1f98c507 100644
--- a/crates/hir_ty/src/infer/coerce.rs
+++ b/crates/hir_ty/src/infer/coerce.rs
@@ -7,7 +7,9 @@
7use chalk_ir::{Mutability, TyVariableKind}; 7use chalk_ir::{Mutability, TyVariableKind};
8use hir_def::lang_item::LangItemTarget; 8use hir_def::lang_item::LangItemTarget;
9 9
10use crate::{autoderef, traits::Solution, Interner, Obligation, Substs, TraitRef, Ty, TyKind}; 10use crate::{
11 autoderef, traits::Solution, Interner, Obligation, Substitution, TraitRef, Ty, TyKind,
12};
11 13
12use super::{InEnvironment, InferenceContext}; 14use super::{InEnvironment, InferenceContext};
13 15
@@ -134,7 +136,7 @@ impl<'a> InferenceContext<'a> {
134 return None; 136 return None;
135 } 137 }
136 138
137 let substs = Substs::build_for_generics(&generic_params) 139 let substs = Substitution::build_for_generics(&generic_params)
138 .push(from_ty.clone()) 140 .push(from_ty.clone())
139 .push(to_ty.clone()) 141 .push(to_ty.clone())
140 .build(); 142 .build();
diff --git a/crates/hir_ty/src/infer/expr.rs b/crates/hir_ty/src/infer/expr.rs
index f40dec17f..0be8c5a90 100644
--- a/crates/hir_ty/src/infer/expr.rs
+++ b/crates/hir_ty/src/infer/expr.rs
@@ -21,8 +21,8 @@ use crate::{
21 to_assoc_type_id, 21 to_assoc_type_id,
22 traits::{chalk::from_chalk, FnTrait, InEnvironment}, 22 traits::{chalk::from_chalk, FnTrait, InEnvironment},
23 utils::{generics, variant_data, Generics}, 23 utils::{generics, variant_data, Generics},
24 AdtId, Binders, CallableDefId, FnPointer, FnSig, Interner, Obligation, Rawness, Scalar, Substs, 24 AdtId, Binders, CallableDefId, FnPointer, FnSig, Interner, Obligation, Rawness, Scalar,
25 TraitRef, Ty, TyKind, 25 Substitution, TraitRef, Ty, TyKind,
26}; 26};
27 27
28use super::{ 28use super::{
@@ -77,7 +77,7 @@ impl<'a> InferenceContext<'a> {
77 return None; 77 return None;
78 } 78 }
79 79
80 let mut param_builder = Substs::builder(num_args); 80 let mut param_builder = Substitution::builder(num_args);
81 let mut arg_tys = vec![]; 81 let mut arg_tys = vec![];
82 for _ in 0..num_args { 82 for _ in 0..num_args {
83 let arg = self.table.new_type_var(); 83 let arg = self.table.new_type_var();
@@ -87,7 +87,7 @@ impl<'a> InferenceContext<'a> {
87 let parameters = param_builder.build(); 87 let parameters = param_builder.build();
88 let arg_ty = TyKind::Tuple(num_args, parameters).intern(&Interner); 88 let arg_ty = TyKind::Tuple(num_args, parameters).intern(&Interner);
89 let substs = 89 let substs =
90 Substs::build_for_generics(&generic_params).push(ty.clone()).push(arg_ty).build(); 90 Substitution::build_for_generics(&generic_params).push(ty.clone()).push(arg_ty).build();
91 91
92 let trait_env = Arc::clone(&self.trait_env); 92 let trait_env = Arc::clone(&self.trait_env);
93 let implements_fn_trait = 93 let implements_fn_trait =
@@ -181,7 +181,7 @@ impl<'a> InferenceContext<'a> {
181 let inner_ty = self.infer_expr(*body, &Expectation::none()); 181 let inner_ty = self.infer_expr(*body, &Expectation::none());
182 let impl_trait_id = crate::ImplTraitId::AsyncBlockTypeImplTrait(self.owner, *body); 182 let impl_trait_id = crate::ImplTraitId::AsyncBlockTypeImplTrait(self.owner, *body);
183 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into(); 183 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
184 TyKind::OpaqueType(opaque_ty_id, Substs::single(inner_ty)).intern(&Interner) 184 TyKind::OpaqueType(opaque_ty_id, Substitution::single(inner_ty)).intern(&Interner)
185 } 185 }
186 Expr::Loop { body, label } => { 186 Expr::Loop { body, label } => {
187 self.breakables.push(BreakableContext { 187 self.breakables.push(BreakableContext {
@@ -262,12 +262,12 @@ impl<'a> InferenceContext<'a> {
262 let sig_ty = TyKind::Function(FnPointer { 262 let sig_ty = TyKind::Function(FnPointer {
263 num_args: sig_tys.len() - 1, 263 num_args: sig_tys.len() - 1,
264 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false }, 264 sig: FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: false },
265 substs: Substs(sig_tys.clone().into()), 265 substs: Substitution(sig_tys.clone().into()),
266 }) 266 })
267 .intern(&Interner); 267 .intern(&Interner);
268 let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into(); 268 let closure_id = self.db.intern_closure((self.owner, tgt_expr)).into();
269 let closure_ty = 269 let closure_ty =
270 TyKind::Closure(closure_id, Substs::single(sig_ty)).intern(&Interner); 270 TyKind::Closure(closure_id, Substitution::single(sig_ty)).intern(&Interner);
271 271
272 // Eagerly try to relate the closure type with the expected 272 // Eagerly try to relate the closure type with the expected
273 // type, otherwise we often won't have enough information to 273 // type, otherwise we often won't have enough information to
@@ -402,7 +402,7 @@ impl<'a> InferenceContext<'a> {
402 402
403 self.unify(&ty, &expected.ty); 403 self.unify(&ty, &expected.ty);
404 404
405 let substs = ty.substs().cloned().unwrap_or_else(Substs::empty); 405 let substs = ty.substs().cloned().unwrap_or_else(Substitution::empty);
406 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default(); 406 let field_types = def_id.map(|it| self.db.field_types(it)).unwrap_or_default();
407 let variant_data = def_id.map(|it| variant_data(self.db.upcast(), it)); 407 let variant_data = def_id.map(|it| variant_data(self.db.upcast(), it));
408 for field in fields.iter() { 408 for field in fields.iter() {
@@ -511,7 +511,8 @@ impl<'a> InferenceContext<'a> {
511 Expr::Box { expr } => { 511 Expr::Box { expr } => {
512 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none()); 512 let inner_ty = self.infer_expr_inner(*expr, &Expectation::none());
513 if let Some(box_) = self.resolve_boxed_box() { 513 if let Some(box_) = self.resolve_boxed_box() {
514 let mut sb = Substs::builder(generics(self.db.upcast(), box_.into()).len()); 514 let mut sb =
515 Substitution::builder(generics(self.db.upcast(), box_.into()).len());
515 sb = sb.push(inner_ty); 516 sb = sb.push(inner_ty);
516 match self.db.generic_defaults(box_.into()).as_ref() { 517 match self.db.generic_defaults(box_.into()).as_ref() {
517 [_, alloc_ty, ..] if !alloc_ty.value.is_unknown() => { 518 [_, alloc_ty, ..] if !alloc_ty.value.is_unknown() => {
@@ -610,31 +611,31 @@ impl<'a> InferenceContext<'a> {
610 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect)); 611 let rhs_ty = rhs.map(|e| self.infer_expr(e, &rhs_expect));
611 match (range_type, lhs_ty, rhs_ty) { 612 match (range_type, lhs_ty, rhs_ty) {
612 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() { 613 (RangeOp::Exclusive, None, None) => match self.resolve_range_full() {
613 Some(adt) => Ty::adt_ty(adt, Substs::empty()), 614 Some(adt) => Ty::adt_ty(adt, Substitution::empty()),
614 None => self.err_ty(), 615 None => self.err_ty(),
615 }, 616 },
616 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() { 617 (RangeOp::Exclusive, None, Some(ty)) => match self.resolve_range_to() {
617 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 618 Some(adt) => Ty::adt_ty(adt, Substitution::single(ty)),
618 None => self.err_ty(), 619 None => self.err_ty(),
619 }, 620 },
620 (RangeOp::Inclusive, None, Some(ty)) => { 621 (RangeOp::Inclusive, None, Some(ty)) => {
621 match self.resolve_range_to_inclusive() { 622 match self.resolve_range_to_inclusive() {
622 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 623 Some(adt) => Ty::adt_ty(adt, Substitution::single(ty)),
623 None => self.err_ty(), 624 None => self.err_ty(),
624 } 625 }
625 } 626 }
626 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() { 627 (RangeOp::Exclusive, Some(_), Some(ty)) => match self.resolve_range() {
627 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 628 Some(adt) => Ty::adt_ty(adt, Substitution::single(ty)),
628 None => self.err_ty(), 629 None => self.err_ty(),
629 }, 630 },
630 (RangeOp::Inclusive, Some(_), Some(ty)) => { 631 (RangeOp::Inclusive, Some(_), Some(ty)) => {
631 match self.resolve_range_inclusive() { 632 match self.resolve_range_inclusive() {
632 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 633 Some(adt) => Ty::adt_ty(adt, Substitution::single(ty)),
633 None => self.err_ty(), 634 None => self.err_ty(),
634 } 635 }
635 } 636 }
636 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() { 637 (RangeOp::Exclusive, Some(ty), None) => match self.resolve_range_from() {
637 Some(adt) => Ty::adt_ty(adt, Substs::single(ty)), 638 Some(adt) => Ty::adt_ty(adt, Substitution::single(ty)),
638 None => self.err_ty(), 639 None => self.err_ty(),
639 }, 640 },
640 (RangeOp::Inclusive, _, None) => self.err_ty(), 641 (RangeOp::Inclusive, _, None) => self.err_ty(),
@@ -681,7 +682,7 @@ impl<'a> InferenceContext<'a> {
681 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone())); 682 self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone()));
682 } 683 }
683 684
684 TyKind::Tuple(tys.len(), Substs(tys.into())).intern(&Interner) 685 TyKind::Tuple(tys.len(), Substitution(tys.into())).intern(&Interner)
685 } 686 }
686 Expr::Array(array) => { 687 Expr::Array(array) => {
687 let elem_ty = match expected.ty.interned(&Interner) { 688 let elem_ty = match expected.ty.interned(&Interner) {
@@ -887,7 +888,7 @@ impl<'a> InferenceContext<'a> {
887 def_generics: Option<Generics>, 888 def_generics: Option<Generics>,
888 generic_args: Option<&GenericArgs>, 889 generic_args: Option<&GenericArgs>,
889 receiver_ty: &Ty, 890 receiver_ty: &Ty,
890 ) -> Substs { 891 ) -> Substitution {
891 let (parent_params, self_params, type_params, impl_trait_params) = 892 let (parent_params, self_params, type_params, impl_trait_params) =
892 def_generics.as_ref().map_or((0, 0, 0, 0), |g| g.provenance_split()); 893 def_generics.as_ref().map_or((0, 0, 0, 0), |g| g.provenance_split());
893 assert_eq!(self_params, 0); // method shouldn't have another Self param 894 assert_eq!(self_params, 0); // method shouldn't have another Self param
@@ -926,7 +927,7 @@ impl<'a> InferenceContext<'a> {
926 substs.push(self.err_ty()); 927 substs.push(self.err_ty());
927 } 928 }
928 assert_eq!(substs.len(), total_len); 929 assert_eq!(substs.len(), total_len);
929 Substs(substs.into()) 930 Substitution(substs.into())
930 } 931 }
931 932
932 fn register_obligations_for_call(&mut self, callable_ty: &Ty) { 933 fn register_obligations_for_call(&mut self, callable_ty: &Ty) {
diff --git a/crates/hir_ty/src/infer/pat.rs b/crates/hir_ty/src/infer/pat.rs
index 9e8ca18ef..befa0d69b 100644
--- a/crates/hir_ty/src/infer/pat.rs
+++ b/crates/hir_ty/src/infer/pat.rs
@@ -12,7 +12,9 @@ use hir_def::{
12use hir_expand::name::Name; 12use hir_expand::name::Name;
13 13
14use super::{BindingMode, Expectation, InferenceContext}; 14use super::{BindingMode, Expectation, InferenceContext};
15use crate::{lower::lower_to_chalk_mutability, utils::variant_data, Interner, Substs, Ty, TyKind}; 15use crate::{
16 lower::lower_to_chalk_mutability, utils::variant_data, Interner, Substitution, Ty, TyKind,
17};
16 18
17impl<'a> InferenceContext<'a> { 19impl<'a> InferenceContext<'a> {
18 fn infer_tuple_struct_pat( 20 fn infer_tuple_struct_pat(
@@ -31,7 +33,7 @@ impl<'a> InferenceContext<'a> {
31 } 33 }
32 self.unify(&ty, expected); 34 self.unify(&ty, expected);
33 35
34 let substs = ty.substs().cloned().unwrap_or_else(Substs::empty); 36 let substs = ty.substs().cloned().unwrap_or_else(Substitution::empty);
35 37
36 let field_tys = def.map(|it| self.db.field_types(it)).unwrap_or_default(); 38 let field_tys = def.map(|it| self.db.field_types(it)).unwrap_or_default();
37 let (pre, post) = match ellipsis { 39 let (pre, post) = match ellipsis {
@@ -70,7 +72,7 @@ impl<'a> InferenceContext<'a> {
70 72
71 self.unify(&ty, expected); 73 self.unify(&ty, expected);
72 74
73 let substs = ty.substs().cloned().unwrap_or_else(Substs::empty); 75 let substs = ty.substs().cloned().unwrap_or_else(Substitution::empty);
74 76
75 let field_tys = def.map(|it| self.db.field_types(it)).unwrap_or_default(); 77 let field_tys = def.map(|it| self.db.field_types(it)).unwrap_or_default();
76 for subpat in subpats { 78 for subpat in subpats {
@@ -138,7 +140,7 @@ impl<'a> InferenceContext<'a> {
138 inner_tys.extend(expectations_iter.by_ref().take(n_uncovered_patterns).cloned()); 140 inner_tys.extend(expectations_iter.by_ref().take(n_uncovered_patterns).cloned());
139 inner_tys.extend(post.iter().zip(expectations_iter).map(infer_pat)); 141 inner_tys.extend(post.iter().zip(expectations_iter).map(infer_pat));
140 142
141 TyKind::Tuple(inner_tys.len(), Substs(inner_tys.into())).intern(&Interner) 143 TyKind::Tuple(inner_tys.len(), Substitution(inner_tys.into())).intern(&Interner)
142 } 144 }
143 Pat::Or(ref pats) => { 145 Pat::Or(ref pats) => {
144 if let Some((first_pat, rest)) = pats.split_first() { 146 if let Some((first_pat, rest)) = pats.split_first() {
@@ -237,7 +239,7 @@ impl<'a> InferenceContext<'a> {
237 }; 239 };
238 240
239 let inner_ty = self.infer_pat(*inner, &inner_expected, default_bm); 241 let inner_ty = self.infer_pat(*inner, &inner_expected, default_bm);
240 Ty::adt_ty(box_adt, Substs::single(inner_ty)) 242 Ty::adt_ty(box_adt, Substitution::single(inner_ty))
241 } 243 }
242 None => self.err_ty(), 244 None => self.err_ty(),
243 }, 245 },
diff --git a/crates/hir_ty/src/infer/path.rs b/crates/hir_ty/src/infer/path.rs
index af108fb6c..ea01d6238 100644
--- a/crates/hir_ty/src/infer/path.rs
+++ b/crates/hir_ty/src/infer/path.rs
@@ -9,7 +9,7 @@ use hir_def::{
9}; 9};
10use hir_expand::name::Name; 10use hir_expand::name::Name;
11 11
12use crate::{method_resolution, Interner, Substs, Ty, TyKind, ValueTyDefId}; 12use crate::{method_resolution, Interner, Substitution, Ty, TyKind, ValueTyDefId};
13 13
14use super::{ExprOrPatId, InferenceContext, TraitRef}; 14use super::{ExprOrPatId, InferenceContext, TraitRef};
15 15
@@ -79,7 +79,7 @@ impl<'a> InferenceContext<'a> {
79 } 79 }
80 ValueNs::ImplSelf(impl_id) => { 80 ValueNs::ImplSelf(impl_id) => {
81 let generics = crate::utils::generics(self.db.upcast(), impl_id.into()); 81 let generics = crate::utils::generics(self.db.upcast(), impl_id.into());
82 let substs = Substs::type_params_for_generics(self.db, &generics); 82 let substs = Substitution::type_params_for_generics(self.db, &generics);
83 let ty = self.db.impl_self_ty(impl_id).subst(&substs); 83 let ty = self.db.impl_self_ty(impl_id).subst(&substs);
84 if let Some((AdtId::StructId(struct_id), substs)) = ty.as_adt() { 84 if let Some((AdtId::StructId(struct_id), substs)) = ty.as_adt() {
85 let ty = self.db.value_ty(struct_id.into()).subst(&substs); 85 let ty = self.db.value_ty(struct_id.into()).subst(&substs);
@@ -94,10 +94,10 @@ impl<'a> InferenceContext<'a> {
94 94
95 let ty = self.db.value_ty(typable); 95 let ty = self.db.value_ty(typable);
96 // self_subst is just for the parent 96 // self_subst is just for the parent
97 let parent_substs = self_subst.unwrap_or_else(Substs::empty); 97 let parent_substs = self_subst.unwrap_or_else(Substitution::empty);
98 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver); 98 let ctx = crate::lower::TyLoweringContext::new(self.db, &self.resolver);
99 let substs = ctx.substs_from_path(path, typable, true); 99 let substs = ctx.substs_from_path(path, typable, true);
100 let full_substs = Substs::builder(substs.len()) 100 let full_substs = Substitution::builder(substs.len())
101 .use_parent_substs(&parent_substs) 101 .use_parent_substs(&parent_substs)
102 .fill(substs.0[parent_substs.len()..].iter().cloned()) 102 .fill(substs.0[parent_substs.len()..].iter().cloned())
103 .build(); 103 .build();
@@ -111,7 +111,7 @@ impl<'a> InferenceContext<'a> {
111 path: &Path, 111 path: &Path,
112 remaining_index: usize, 112 remaining_index: usize,
113 id: ExprOrPatId, 113 id: ExprOrPatId,
114 ) -> Option<(ValueNs, Option<Substs>)> { 114 ) -> Option<(ValueNs, Option<Substitution>)> {
115 assert!(remaining_index < path.segments().len()); 115 assert!(remaining_index < path.segments().len());
116 // there may be more intermediate segments between the resolved one and 116 // there may be more intermediate segments between the resolved one and
117 // the end. Only the last segment needs to be resolved to a value; from 117 // the end. Only the last segment needs to be resolved to a value; from
@@ -164,7 +164,7 @@ impl<'a> InferenceContext<'a> {
164 trait_ref: TraitRef, 164 trait_ref: TraitRef,
165 segment: PathSegment<'_>, 165 segment: PathSegment<'_>,
166 id: ExprOrPatId, 166 id: ExprOrPatId,
167 ) -> Option<(ValueNs, Option<Substs>)> { 167 ) -> Option<(ValueNs, Option<Substitution>)> {
168 let trait_ = trait_ref.trait_; 168 let trait_ = trait_ref.trait_;
169 let item = 169 let item =
170 self.db.trait_data(trait_).items.iter().map(|(_name, id)| (*id)).find_map(|item| { 170 self.db.trait_data(trait_).items.iter().map(|(_name, id)| (*id)).find_map(|item| {
@@ -208,7 +208,7 @@ impl<'a> InferenceContext<'a> {
208 ty: Ty, 208 ty: Ty,
209 name: &Name, 209 name: &Name,
210 id: ExprOrPatId, 210 id: ExprOrPatId,
211 ) -> Option<(ValueNs, Option<Substs>)> { 211 ) -> Option<(ValueNs, Option<Substitution>)> {
212 if let TyKind::Unknown = ty.interned(&Interner) { 212 if let TyKind::Unknown = ty.interned(&Interner) {
213 return None; 213 return None;
214 } 214 }
@@ -241,7 +241,7 @@ impl<'a> InferenceContext<'a> {
241 }; 241 };
242 let substs = match container { 242 let substs = match container {
243 AssocContainerId::ImplId(impl_id) => { 243 AssocContainerId::ImplId(impl_id) => {
244 let impl_substs = Substs::build_for_def(self.db, impl_id) 244 let impl_substs = Substitution::build_for_def(self.db, impl_id)
245 .fill(iter::repeat_with(|| self.table.new_type_var())) 245 .fill(iter::repeat_with(|| self.table.new_type_var()))
246 .build(); 246 .build();
247 let impl_self_ty = self.db.impl_self_ty(impl_id).subst(&impl_substs); 247 let impl_self_ty = self.db.impl_self_ty(impl_id).subst(&impl_substs);
@@ -250,7 +250,7 @@ impl<'a> InferenceContext<'a> {
250 } 250 }
251 AssocContainerId::TraitId(trait_) => { 251 AssocContainerId::TraitId(trait_) => {
252 // we're picking this method 252 // we're picking this method
253 let trait_substs = Substs::build_for_def(self.db, trait_) 253 let trait_substs = Substitution::build_for_def(self.db, trait_)
254 .push(ty.clone()) 254 .push(ty.clone())
255 .fill(std::iter::repeat_with(|| self.table.new_type_var())) 255 .fill(std::iter::repeat_with(|| self.table.new_type_var()))
256 .build(); 256 .build();
@@ -274,7 +274,7 @@ impl<'a> InferenceContext<'a> {
274 ty: &Ty, 274 ty: &Ty,
275 name: &Name, 275 name: &Name,
276 id: ExprOrPatId, 276 id: ExprOrPatId,
277 ) -> Option<(ValueNs, Option<Substs>)> { 277 ) -> Option<(ValueNs, Option<Substitution>)> {
278 let (enum_id, subst) = match ty.as_adt() { 278 let (enum_id, subst) = match ty.as_adt() {
279 Some((AdtId::EnumId(e), subst)) => (e, subst), 279 Some((AdtId::EnumId(e), subst)) => (e, subst),
280 _ => return None, 280 _ => return None,
diff --git a/crates/hir_ty/src/infer/unify.rs b/crates/hir_ty/src/infer/unify.rs
index 7795f446f..b2d4f67b3 100644
--- a/crates/hir_ty/src/infer/unify.rs
+++ b/crates/hir_ty/src/infer/unify.rs
@@ -8,7 +8,7 @@ use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue};
8use super::{InferenceContext, Obligation}; 8use super::{InferenceContext, Obligation};
9use crate::{ 9use crate::{
10 BoundVar, Canonical, DebruijnIndex, FnPointer, GenericPredicate, InEnvironment, InferenceVar, 10 BoundVar, Canonical, DebruijnIndex, FnPointer, GenericPredicate, InEnvironment, InferenceVar,
11 Interner, Scalar, Substs, Ty, TyKind, TypeWalk, 11 Interner, Scalar, Substitution, Ty, TyKind, TypeWalk,
12}; 12};
13 13
14impl<'a> InferenceContext<'a> { 14impl<'a> InferenceContext<'a> {
@@ -123,10 +123,10 @@ impl<T> Canonicalized<T> {
123 pub(super) fn apply_solution( 123 pub(super) fn apply_solution(
124 &self, 124 &self,
125 ctx: &mut InferenceContext<'_>, 125 ctx: &mut InferenceContext<'_>,
126 solution: Canonical<Substs>, 126 solution: Canonical<Substitution>,
127 ) { 127 ) {
128 // the solution may contain new variables, which we need to convert to new inference vars 128 // the solution may contain new variables, which we need to convert to new inference vars
129 let new_vars = Substs( 129 let new_vars = Substitution(
130 solution 130 solution
131 .kinds 131 .kinds
132 .iter() 132 .iter()
@@ -147,9 +147,9 @@ impl<T> Canonicalized<T> {
147 } 147 }
148} 148}
149 149
150pub(crate) fn unify(tys: &Canonical<(Ty, Ty)>) -> Option<Substs> { 150pub(crate) fn unify(tys: &Canonical<(Ty, Ty)>) -> Option<Substitution> {
151 let mut table = InferenceTable::new(); 151 let mut table = InferenceTable::new();
152 let vars = Substs( 152 let vars = Substitution(
153 tys.kinds 153 tys.kinds
154 .iter() 154 .iter()
155 // we always use type vars here because we want everything to 155 // we always use type vars here because we want everything to
@@ -173,7 +173,7 @@ pub(crate) fn unify(tys: &Canonical<(Ty, Ty)>) -> Option<Substs> {
173 } 173 }
174 } 174 }
175 Some( 175 Some(
176 Substs::builder(tys.kinds.len()) 176 Substitution::builder(tys.kinds.len())
177 .fill(vars.iter().map(|v| table.resolve_ty_completely(v.clone()))) 177 .fill(vars.iter().map(|v| table.resolve_ty_completely(v.clone())))
178 .build(), 178 .build(),
179 ) 179 )
@@ -264,8 +264,8 @@ impl InferenceTable {
264 264
265 pub(crate) fn unify_substs( 265 pub(crate) fn unify_substs(
266 &mut self, 266 &mut self,
267 substs1: &Substs, 267 substs1: &Substitution,
268 substs2: &Substs, 268 substs2: &Substitution,
269 depth: usize, 269 depth: usize,
270 ) -> bool { 270 ) -> bool {
271 substs1.0.iter().zip(substs2.0.iter()).all(|(t1, t2)| self.unify_inner(t1, t2, depth)) 271 substs1.0.iter().zip(substs2.0.iter()).all(|(t1, t2)| self.unify_inner(t1, t2, depth))
diff --git a/crates/hir_ty/src/lib.rs b/crates/hir_ty/src/lib.rs
index 850385280..52b498ff7 100644
--- a/crates/hir_ty/src/lib.rs
+++ b/crates/hir_ty/src/lib.rs
@@ -67,7 +67,7 @@ pub enum Lifetime {
67#[derive(Clone, PartialEq, Eq, Debug, Hash)] 67#[derive(Clone, PartialEq, Eq, Debug, Hash)]
68pub struct OpaqueTy { 68pub struct OpaqueTy {
69 pub opaque_ty_id: OpaqueTyId, 69 pub opaque_ty_id: OpaqueTyId,
70 pub substitution: Substs, 70 pub substitution: Substitution,
71} 71}
72 72
73/// A "projection" type corresponds to an (unnormalized) 73/// A "projection" type corresponds to an (unnormalized)
@@ -76,7 +76,7 @@ pub struct OpaqueTy {
76#[derive(Clone, PartialEq, Eq, Debug, Hash)] 76#[derive(Clone, PartialEq, Eq, Debug, Hash)]
77pub struct ProjectionTy { 77pub struct ProjectionTy {
78 pub associated_ty_id: AssocTypeId, 78 pub associated_ty_id: AssocTypeId,
79 pub substitution: Substs, 79 pub substitution: Substitution,
80} 80}
81 81
82impl ProjectionTy { 82impl ProjectionTy {
@@ -112,7 +112,7 @@ pub type FnSig = chalk_ir::FnSig<Interner>;
112pub struct FnPointer { 112pub struct FnPointer {
113 pub num_args: usize, 113 pub num_args: usize,
114 pub sig: FnSig, 114 pub sig: FnSig,
115 pub substs: Substs, 115 pub substs: Substitution,
116} 116}
117 117
118#[derive(Clone, PartialEq, Eq, Debug, Hash)] 118#[derive(Clone, PartialEq, Eq, Debug, Hash)]
@@ -137,19 +137,19 @@ pub enum AliasTy {
137#[derive(Clone, PartialEq, Eq, Debug, Hash)] 137#[derive(Clone, PartialEq, Eq, Debug, Hash)]
138pub enum TyKind { 138pub enum TyKind {
139 /// Structures, enumerations and unions. 139 /// Structures, enumerations and unions.
140 Adt(AdtId<Interner>, Substs), 140 Adt(AdtId<Interner>, Substitution),
141 141
142 /// Represents an associated item like `Iterator::Item`. This is used 142 /// Represents an associated item like `Iterator::Item`. This is used
143 /// when we have tried to normalize a projection like `T::Item` but 143 /// when we have tried to normalize a projection like `T::Item` but
144 /// couldn't find a better representation. In that case, we generate 144 /// couldn't find a better representation. In that case, we generate
145 /// an **application type** like `(Iterator::Item)<T>`. 145 /// an **application type** like `(Iterator::Item)<T>`.
146 AssociatedType(AssocTypeId, Substs), 146 AssociatedType(AssocTypeId, Substitution),
147 147
148 /// a scalar type like `bool` or `u32` 148 /// a scalar type like `bool` or `u32`
149 Scalar(Scalar), 149 Scalar(Scalar),
150 150
151 /// A tuple type. For example, `(i32, bool)`. 151 /// A tuple type. For example, `(i32, bool)`.
152 Tuple(usize, Substs), 152 Tuple(usize, Substitution),
153 153
154 /// An array with the given length. Written as `[T; n]`. 154 /// An array with the given length. Written as `[T; n]`.
155 Array(Ty), 155 Array(Ty),
@@ -169,7 +169,7 @@ pub enum TyKind {
169 /// analogous to the `AssociatedType` type constructor. 169 /// analogous to the `AssociatedType` type constructor.
170 /// It is also used as the type of async block, with one type parameter 170 /// It is also used as the type of async block, with one type parameter
171 /// representing the Future::Output type. 171 /// representing the Future::Output type.
172 OpaqueType(OpaqueTyId, Substs), 172 OpaqueType(OpaqueTyId, Substitution),
173 173
174 /// The anonymous type of a function declaration/definition. Each 174 /// The anonymous type of a function declaration/definition. Each
175 /// function has a unique type, which is output (for a function 175 /// function has a unique type, which is output (for a function
@@ -183,7 +183,7 @@ pub enum TyKind {
183 /// fn foo() -> i32 { 1 } 183 /// fn foo() -> i32 { 1 }
184 /// let bar = foo; // bar: fn() -> i32 {foo} 184 /// let bar = foo; // bar: fn() -> i32 {foo}
185 /// ``` 185 /// ```
186 FnDef(FnDefId, Substs), 186 FnDef(FnDefId, Substitution),
187 187
188 /// The pointee of a string slice. Written as `str`. 188 /// The pointee of a string slice. Written as `str`.
189 Str, 189 Str,
@@ -195,7 +195,7 @@ pub enum TyKind {
195 /// 195 ///
196 /// The closure signature is stored in a `FnPtr` type in the first type 196 /// The closure signature is stored in a `FnPtr` type in the first type
197 /// parameter. 197 /// parameter.
198 Closure(ClosureId, Substs), 198 Closure(ClosureId, Substitution),
199 199
200 /// Represents a foreign type declared in external blocks. 200 /// Represents a foreign type declared in external blocks.
201 ForeignType(ForeignDefId), 201 ForeignType(ForeignDefId),
@@ -273,9 +273,9 @@ impl Ty {
273 273
274/// A list of substitutions for generic parameters. 274/// A list of substitutions for generic parameters.
275#[derive(Clone, PartialEq, Eq, Debug, Hash)] 275#[derive(Clone, PartialEq, Eq, Debug, Hash)]
276pub struct Substs(SmallVec<[Ty; 2]>); 276pub struct Substitution(SmallVec<[Ty; 2]>);
277 277
278impl TypeWalk for Substs { 278impl TypeWalk for Substitution {
279 fn walk(&self, f: &mut impl FnMut(&Ty)) { 279 fn walk(&self, f: &mut impl FnMut(&Ty)) {
280 for t in self.0.iter() { 280 for t in self.0.iter() {
281 t.walk(f); 281 t.walk(f);
@@ -293,29 +293,29 @@ impl TypeWalk for Substs {
293 } 293 }
294} 294}
295 295
296impl Substs { 296impl Substitution {
297 pub fn interned(&self, _: &Interner) -> &[Ty] { 297 pub fn interned(&self, _: &Interner) -> &[Ty] {
298 &self.0 298 &self.0
299 } 299 }
300 300
301 pub fn empty() -> Substs { 301 pub fn empty() -> Substitution {
302 Substs(SmallVec::new()) 302 Substitution(SmallVec::new())
303 } 303 }
304 304
305 pub fn single(ty: Ty) -> Substs { 305 pub fn single(ty: Ty) -> Substitution {
306 Substs({ 306 Substitution({
307 let mut v = SmallVec::new(); 307 let mut v = SmallVec::new();
308 v.push(ty); 308 v.push(ty);
309 v 309 v
310 }) 310 })
311 } 311 }
312 312
313 pub fn prefix(&self, n: usize) -> Substs { 313 pub fn prefix(&self, n: usize) -> Substitution {
314 Substs(self.0[..std::cmp::min(self.0.len(), n)].into()) 314 Substitution(self.0[..std::cmp::min(self.0.len(), n)].into())
315 } 315 }
316 316
317 pub fn suffix(&self, n: usize) -> Substs { 317 pub fn suffix(&self, n: usize) -> Substitution {
318 Substs(self.0[self.0.len() - std::cmp::min(self.0.len(), n)..].into()) 318 Substitution(self.0[self.0.len() - std::cmp::min(self.0.len(), n)..].into())
319 } 319 }
320 320
321 pub fn as_single(&self) -> &Ty { 321 pub fn as_single(&self) -> &Ty {
@@ -326,15 +326,15 @@ impl Substs {
326 } 326 }
327 327
328 pub fn from_iter(_interner: &Interner, elements: impl IntoIterator<Item = Ty>) -> Self { 328 pub fn from_iter(_interner: &Interner, elements: impl IntoIterator<Item = Ty>) -> Self {
329 Substs(elements.into_iter().collect()) 329 Substitution(elements.into_iter().collect())
330 } 330 }
331 331
332 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). 332 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
333 pub(crate) fn type_params_for_generics( 333 pub(crate) fn type_params_for_generics(
334 db: &dyn HirDatabase, 334 db: &dyn HirDatabase,
335 generic_params: &Generics, 335 generic_params: &Generics,
336 ) -> Substs { 336 ) -> Substitution {
337 Substs( 337 Substitution(
338 generic_params 338 generic_params
339 .iter() 339 .iter()
340 .map(|(id, _)| TyKind::Placeholder(to_placeholder_idx(db, id)).intern(&Interner)) 340 .map(|(id, _)| TyKind::Placeholder(to_placeholder_idx(db, id)).intern(&Interner))
@@ -343,14 +343,14 @@ impl Substs {
343 } 343 }
344 344
345 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). 345 /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`).
346 pub fn type_params(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> Substs { 346 pub fn type_params(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> Substitution {
347 let params = generics(db.upcast(), def.into()); 347 let params = generics(db.upcast(), def.into());
348 Substs::type_params_for_generics(db, &params) 348 Substitution::type_params_for_generics(db, &params)
349 } 349 }
350 350
351 /// Return Substs that replace each parameter by a bound variable. 351 /// Return Substs that replace each parameter by a bound variable.
352 pub(crate) fn bound_vars(generic_params: &Generics, debruijn: DebruijnIndex) -> Substs { 352 pub(crate) fn bound_vars(generic_params: &Generics, debruijn: DebruijnIndex) -> Substitution {
353 Substs( 353 Substitution(
354 generic_params 354 generic_params
355 .iter() 355 .iter()
356 .enumerate() 356 .enumerate()
@@ -363,11 +363,11 @@ impl Substs {
363 let def = def.into(); 363 let def = def.into();
364 let params = generics(db.upcast(), def); 364 let params = generics(db.upcast(), def);
365 let param_count = params.len(); 365 let param_count = params.len();
366 Substs::builder(param_count) 366 Substitution::builder(param_count)
367 } 367 }
368 368
369 pub(crate) fn build_for_generics(generic_params: &Generics) -> SubstsBuilder { 369 pub(crate) fn build_for_generics(generic_params: &Generics) -> SubstsBuilder {
370 Substs::builder(generic_params.len()) 370 Substitution::builder(generic_params.len())
371 } 371 }
372 372
373 fn builder(param_count: usize) -> SubstsBuilder { 373 fn builder(param_count: usize) -> SubstsBuilder {
@@ -387,9 +387,9 @@ pub struct SubstsBuilder {
387} 387}
388 388
389impl SubstsBuilder { 389impl SubstsBuilder {
390 pub fn build(self) -> Substs { 390 pub fn build(self) -> Substitution {
391 assert_eq!(self.vec.len(), self.param_count); 391 assert_eq!(self.vec.len(), self.param_count);
392 Substs(self.vec.into()) 392 Substitution(self.vec.into())
393 } 393 }
394 394
395 pub fn push(mut self, ty: Ty) -> Self { 395 pub fn push(mut self, ty: Ty) -> Self {
@@ -418,7 +418,7 @@ impl SubstsBuilder {
418 self 418 self
419 } 419 }
420 420
421 pub fn use_parent_substs(mut self, parent_substs: &Substs) -> Self { 421 pub fn use_parent_substs(mut self, parent_substs: &Substitution) -> Self {
422 assert!(self.vec.is_empty()); 422 assert!(self.vec.is_empty());
423 assert!(parent_substs.len() <= self.param_count); 423 assert!(parent_substs.len() <= self.param_count);
424 self.vec.extend(parent_substs.iter().cloned()); 424 self.vec.extend(parent_substs.iter().cloned());
@@ -426,7 +426,7 @@ impl SubstsBuilder {
426 } 426 }
427} 427}
428 428
429impl Deref for Substs { 429impl Deref for Substitution {
430 type Target = [Ty]; 430 type Target = [Ty];
431 431
432 fn deref(&self) -> &[Ty] { 432 fn deref(&self) -> &[Ty] {
@@ -466,13 +466,13 @@ impl<T: Clone> Binders<&T> {
466 466
467impl<T: TypeWalk> Binders<T> { 467impl<T: TypeWalk> Binders<T> {
468 /// Substitutes all variables. 468 /// Substitutes all variables.
469 pub fn subst(self, subst: &Substs) -> T { 469 pub fn subst(self, subst: &Substitution) -> T {
470 assert_eq!(subst.len(), self.num_binders); 470 assert_eq!(subst.len(), self.num_binders);
471 self.value.subst_bound_vars(subst) 471 self.value.subst_bound_vars(subst)
472 } 472 }
473 473
474 /// Substitutes just a prefix of the variables (shifting the rest). 474 /// Substitutes just a prefix of the variables (shifting the rest).
475 pub fn subst_prefix(self, subst: &Substs) -> Binders<T> { 475 pub fn subst_prefix(self, subst: &Substitution) -> Binders<T> {
476 assert!(subst.len() < self.num_binders); 476 assert!(subst.len() < self.num_binders);
477 Binders::new(self.num_binders - subst.len(), self.value.subst_bound_vars(subst)) 477 Binders::new(self.num_binders - subst.len(), self.value.subst_bound_vars(subst))
478 } 478 }
@@ -498,7 +498,7 @@ impl<T: TypeWalk> TypeWalk for Binders<T> {
498pub struct TraitRef { 498pub struct TraitRef {
499 /// FIXME name? 499 /// FIXME name?
500 pub trait_: TraitId, 500 pub trait_: TraitId,
501 pub substs: Substs, 501 pub substs: Substitution,
502} 502}
503 503
504impl TraitRef { 504impl TraitRef {
@@ -618,7 +618,7 @@ impl CallableSig {
618 } 618 }
619 } 619 }
620 620
621 pub fn from_substs(substs: &Substs) -> CallableSig { 621 pub fn from_substs(substs: &Substitution) -> CallableSig {
622 CallableSig { params_and_return: substs.iter().cloned().collect(), is_varargs: false } 622 CallableSig { params_and_return: substs.iter().cloned().collect(), is_varargs: false }
623 } 623 }
624 624
@@ -651,10 +651,10 @@ impl TypeWalk for CallableSig {
651 651
652impl Ty { 652impl Ty {
653 pub fn unit() -> Self { 653 pub fn unit() -> Self {
654 TyKind::Tuple(0, Substs::empty()).intern(&Interner) 654 TyKind::Tuple(0, Substitution::empty()).intern(&Interner)
655 } 655 }
656 656
657 pub fn adt_ty(adt: hir_def::AdtId, substs: Substs) -> Ty { 657 pub fn adt_ty(adt: hir_def::AdtId, substs: Substitution) -> Ty {
658 TyKind::Adt(AdtId(adt), substs).intern(&Interner) 658 TyKind::Adt(AdtId(adt), substs).intern(&Interner)
659 } 659 }
660 660
@@ -662,7 +662,7 @@ impl Ty {
662 TyKind::Function(FnPointer { 662 TyKind::Function(FnPointer {
663 num_args: sig.params().len(), 663 num_args: sig.params().len(),
664 sig: FnSig { abi: (), safety: Safety::Safe, variadic: sig.is_varargs }, 664 sig: FnSig { abi: (), safety: Safety::Safe, variadic: sig.is_varargs },
665 substs: Substs::from_iter(&Interner, sig.params_and_return.iter().cloned()), 665 substs: Substitution::from_iter(&Interner, sig.params_and_return.iter().cloned()),
666 }) 666 })
667 .intern(&Interner) 667 .intern(&Interner)
668 } 668 }
@@ -709,14 +709,14 @@ impl Ty {
709 t 709 t
710 } 710 }
711 711
712 pub fn as_adt(&self) -> Option<(hir_def::AdtId, &Substs)> { 712 pub fn as_adt(&self) -> Option<(hir_def::AdtId, &Substitution)> {
713 match self.interned(&Interner) { 713 match self.interned(&Interner) {
714 TyKind::Adt(AdtId(adt), parameters) => Some((*adt, parameters)), 714 TyKind::Adt(AdtId(adt), parameters) => Some((*adt, parameters)),
715 _ => None, 715 _ => None,
716 } 716 }
717 } 717 }
718 718
719 pub fn as_tuple(&self) -> Option<&Substs> { 719 pub fn as_tuple(&self) -> Option<&Substitution> {
720 match self.interned(&Interner) { 720 match self.interned(&Interner) {
721 TyKind::Tuple(_, substs) => Some(substs), 721 TyKind::Tuple(_, substs) => Some(substs),
722 _ => None, 722 _ => None,
@@ -828,7 +828,7 @@ impl Ty {
828 828
829 /// Returns the type parameters of this type if it has some (i.e. is an ADT 829 /// Returns the type parameters of this type if it has some (i.e. is an ADT
830 /// or function); so if `self` is `Option<u32>`, this returns the `u32`. 830 /// or function); so if `self` is `Option<u32>`, this returns the `u32`.
831 pub fn substs(&self) -> Option<&Substs> { 831 pub fn substs(&self) -> Option<&Substitution> {
832 match self.interned(&Interner) { 832 match self.interned(&Interner) {
833 TyKind::Adt(_, substs) 833 TyKind::Adt(_, substs)
834 | TyKind::FnDef(_, substs) 834 | TyKind::FnDef(_, substs)
@@ -841,7 +841,7 @@ impl Ty {
841 } 841 }
842 } 842 }
843 843
844 fn substs_mut(&mut self) -> Option<&mut Substs> { 844 fn substs_mut(&mut self) -> Option<&mut Substitution> {
845 match self.interned_mut() { 845 match self.interned_mut() {
846 TyKind::Adt(_, substs) 846 TyKind::Adt(_, substs)
847 | TyKind::FnDef(_, substs) 847 | TyKind::FnDef(_, substs)
@@ -869,7 +869,7 @@ impl Ty {
869 // So just provide the Future trait. 869 // So just provide the Future trait.
870 let impl_bound = GenericPredicate::Implemented(TraitRef { 870 let impl_bound = GenericPredicate::Implemented(TraitRef {
871 trait_: future_trait, 871 trait_: future_trait,
872 substs: Substs::empty(), 872 substs: Substitution::empty(),
873 }); 873 });
874 Some(vec![impl_bound]) 874 Some(vec![impl_bound])
875 } else { 875 } else {
@@ -992,7 +992,7 @@ pub trait TypeWalk {
992 } 992 }
993 993
994 /// Substitutes `TyKind::Bound` vars with the given substitution. 994 /// Substitutes `TyKind::Bound` vars with the given substitution.
995 fn subst_bound_vars(self, substs: &Substs) -> Self 995 fn subst_bound_vars(self, substs: &Substitution) -> Self
996 where 996 where
997 Self: Sized, 997 Self: Sized,
998 { 998 {
@@ -1000,7 +1000,7 @@ pub trait TypeWalk {
1000 } 1000 }
1001 1001
1002 /// Substitutes `TyKind::Bound` vars with the given substitution. 1002 /// Substitutes `TyKind::Bound` vars with the given substitution.
1003 fn subst_bound_vars_at_depth(mut self, substs: &Substs, depth: DebruijnIndex) -> Self 1003 fn subst_bound_vars_at_depth(mut self, substs: &Substitution, depth: DebruijnIndex) -> Self
1004 where 1004 where
1005 Self: Sized, 1005 Self: Sized,
1006 { 1006 {
diff --git a/crates/hir_ty/src/lower.rs b/crates/hir_ty/src/lower.rs
index 6ab757bfc..462882b2b 100644
--- a/crates/hir_ty/src/lower.rs
+++ b/crates/hir_ty/src/lower.rs
@@ -35,7 +35,7 @@ use crate::{
35 }, 35 },
36 AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, FnPointer, FnSig, GenericPredicate, 36 AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, FnPointer, FnSig, GenericPredicate,
37 ImplTraitId, OpaqueTy, PolyFnSig, ProjectionPredicate, ProjectionTy, ReturnTypeImplTrait, 37 ImplTraitId, OpaqueTy, PolyFnSig, ProjectionPredicate, ProjectionTy, ReturnTypeImplTrait,
38 ReturnTypeImplTraits, Substs, TraitEnvironment, TraitRef, Ty, TyKind, TypeWalk, 38 ReturnTypeImplTraits, Substitution, TraitEnvironment, TraitRef, Ty, TyKind, TypeWalk,
39}; 39};
40 40
41#[derive(Debug)] 41#[derive(Debug)]
@@ -151,7 +151,7 @@ impl<'a> TyLoweringContext<'a> {
151 TypeRef::Never => TyKind::Never.intern(&Interner), 151 TypeRef::Never => TyKind::Never.intern(&Interner),
152 TypeRef::Tuple(inner) => { 152 TypeRef::Tuple(inner) => {
153 let inner_tys = inner.iter().map(|tr| self.lower_ty(tr)); 153 let inner_tys = inner.iter().map(|tr| self.lower_ty(tr));
154 TyKind::Tuple(inner_tys.len(), Substs::from_iter(&Interner, inner_tys)) 154 TyKind::Tuple(inner_tys.len(), Substitution::from_iter(&Interner, inner_tys))
155 .intern(&Interner) 155 .intern(&Interner)
156 } 156 }
157 TypeRef::Path(path) => { 157 TypeRef::Path(path) => {
@@ -177,7 +177,7 @@ impl<'a> TyLoweringContext<'a> {
177 } 177 }
178 TypeRef::Placeholder => TyKind::Unknown.intern(&Interner), 178 TypeRef::Placeholder => TyKind::Unknown.intern(&Interner),
179 TypeRef::Fn(params, is_varargs) => { 179 TypeRef::Fn(params, is_varargs) => {
180 let substs = Substs(params.iter().map(|tr| self.lower_ty(tr)).collect()); 180 let substs = Substitution(params.iter().map(|tr| self.lower_ty(tr)).collect());
181 TyKind::Function(FnPointer { 181 TyKind::Function(FnPointer {
182 num_args: substs.len() - 1, 182 num_args: substs.len() - 1,
183 sig: FnSig { abi: (), safety: Safety::Safe, variadic: *is_varargs }, 183 sig: FnSig { abi: (), safety: Safety::Safe, variadic: *is_varargs },
@@ -228,7 +228,7 @@ impl<'a> TyLoweringContext<'a> {
228 let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx); 228 let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx);
229 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into(); 229 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
230 let generics = generics(self.db.upcast(), func.into()); 230 let generics = generics(self.db.upcast(), func.into());
231 let parameters = Substs::bound_vars(&generics, self.in_binders); 231 let parameters = Substitution::bound_vars(&generics, self.in_binders);
232 TyKind::Alias(AliasTy::Opaque(OpaqueTy { 232 TyKind::Alias(AliasTy::Opaque(OpaqueTy {
233 opaque_ty_id, 233 opaque_ty_id,
234 substitution: parameters, 234 substitution: parameters,
@@ -398,10 +398,10 @@ impl<'a> TyLoweringContext<'a> {
398 let generics = generics(self.db.upcast(), impl_id.into()); 398 let generics = generics(self.db.upcast(), impl_id.into());
399 let substs = match self.type_param_mode { 399 let substs = match self.type_param_mode {
400 TypeParamLoweringMode::Placeholder => { 400 TypeParamLoweringMode::Placeholder => {
401 Substs::type_params_for_generics(self.db, &generics) 401 Substitution::type_params_for_generics(self.db, &generics)
402 } 402 }
403 TypeParamLoweringMode::Variable => { 403 TypeParamLoweringMode::Variable => {
404 Substs::bound_vars(&generics, self.in_binders) 404 Substitution::bound_vars(&generics, self.in_binders)
405 } 405 }
406 }; 406 };
407 self.db.impl_self_ty(impl_id).subst(&substs) 407 self.db.impl_self_ty(impl_id).subst(&substs)
@@ -410,10 +410,10 @@ impl<'a> TyLoweringContext<'a> {
410 let generics = generics(self.db.upcast(), adt.into()); 410 let generics = generics(self.db.upcast(), adt.into());
411 let substs = match self.type_param_mode { 411 let substs = match self.type_param_mode {
412 TypeParamLoweringMode::Placeholder => { 412 TypeParamLoweringMode::Placeholder => {
413 Substs::type_params_for_generics(self.db, &generics) 413 Substitution::type_params_for_generics(self.db, &generics)
414 } 414 }
415 TypeParamLoweringMode::Variable => { 415 TypeParamLoweringMode::Variable => {
416 Substs::bound_vars(&generics, self.in_binders) 416 Substitution::bound_vars(&generics, self.in_binders)
417 } 417 }
418 }; 418 };
419 self.db.ty(adt.into()).subst(&substs) 419 self.db.ty(adt.into()).subst(&substs)
@@ -464,7 +464,7 @@ impl<'a> TyLoweringContext<'a> {
464 TypeParamLoweringMode::Placeholder => { 464 TypeParamLoweringMode::Placeholder => {
465 // if we're lowering to placeholders, we have to put 465 // if we're lowering to placeholders, we have to put
466 // them in now 466 // them in now
467 let s = Substs::type_params( 467 let s = Substitution::type_params(
468 self.db, 468 self.db,
469 self.resolver.generic_def().expect( 469 self.resolver.generic_def().expect(
470 "there should be generics if there's a generic param", 470 "there should be generics if there's a generic param",
@@ -522,7 +522,7 @@ impl<'a> TyLoweringContext<'a> {
522 // special-case enum variants 522 // special-case enum variants
523 resolved: ValueTyDefId, 523 resolved: ValueTyDefId,
524 infer_args: bool, 524 infer_args: bool,
525 ) -> Substs { 525 ) -> Substitution {
526 let last = path.segments().last().expect("path should have at least one segment"); 526 let last = path.segments().last().expect("path should have at least one segment");
527 let (segment, generic_def) = match resolved { 527 let (segment, generic_def) = match resolved {
528 ValueTyDefId::FunctionId(it) => (last, Some(it.into())), 528 ValueTyDefId::FunctionId(it) => (last, Some(it.into())),
@@ -553,7 +553,7 @@ impl<'a> TyLoweringContext<'a> {
553 segment: PathSegment<'_>, 553 segment: PathSegment<'_>,
554 def_generic: Option<GenericDefId>, 554 def_generic: Option<GenericDefId>,
555 infer_args: bool, 555 infer_args: bool,
556 ) -> Substs { 556 ) -> Substitution {
557 let mut substs = Vec::new(); 557 let mut substs = Vec::new();
558 let def_generics = def_generic.map(|def| generics(self.db.upcast(), def)); 558 let def_generics = def_generic.map(|def| generics(self.db.upcast(), def));
559 559
@@ -601,7 +601,7 @@ impl<'a> TyLoweringContext<'a> {
601 601
602 for default_ty in defaults.iter().skip(substs.len()) { 602 for default_ty in defaults.iter().skip(substs.len()) {
603 // each default can depend on the previous parameters 603 // each default can depend on the previous parameters
604 let substs_so_far = Substs(substs.clone().into()); 604 let substs_so_far = Substitution(substs.clone().into());
605 substs.push(default_ty.clone().subst(&substs_so_far)); 605 substs.push(default_ty.clone().subst(&substs_so_far));
606 } 606 }
607 } 607 }
@@ -614,7 +614,7 @@ impl<'a> TyLoweringContext<'a> {
614 } 614 }
615 assert_eq!(substs.len(), total_len); 615 assert_eq!(substs.len(), total_len);
616 616
617 Substs(substs.into()) 617 Substitution(substs.into())
618 } 618 }
619 619
620 fn lower_trait_ref_from_path( 620 fn lower_trait_ref_from_path(
@@ -656,7 +656,11 @@ impl<'a> TyLoweringContext<'a> {
656 self.lower_trait_ref_from_path(path, explicit_self_ty) 656 self.lower_trait_ref_from_path(path, explicit_self_ty)
657 } 657 }
658 658
659 fn trait_ref_substs_from_path(&self, segment: PathSegment<'_>, resolved: TraitId) -> Substs { 659 fn trait_ref_substs_from_path(
660 &self,
661 segment: PathSegment<'_>,
662 resolved: TraitId,
663 ) -> Substitution {
660 self.substs_from_path_segment(segment, Some(resolved.into()), false) 664 self.substs_from_path_segment(segment, Some(resolved.into()), false)
661 } 665 }
662 666
@@ -817,7 +821,7 @@ pub fn associated_type_shorthand_candidates<R>(
817 { 821 {
818 let trait_ref = TraitRef { 822 let trait_ref = TraitRef {
819 trait_: trait_id, 823 trait_: trait_id,
820 substs: Substs::bound_vars(&generics, DebruijnIndex::INNERMOST), 824 substs: Substitution::bound_vars(&generics, DebruijnIndex::INNERMOST),
821 }; 825 };
822 traits_.push(trait_ref); 826 traits_.push(trait_ref);
823 } 827 }
@@ -945,7 +949,7 @@ pub(crate) fn trait_environment_query(
945 // function default implementations (and hypothetical code 949 // function default implementations (and hypothetical code
946 // inside consts or type aliases) 950 // inside consts or type aliases)
947 cov_mark::hit!(trait_self_implements_self); 951 cov_mark::hit!(trait_self_implements_self);
948 let substs = Substs::type_params(db, trait_id); 952 let substs = Substitution::type_params(db, trait_id);
949 let trait_ref = TraitRef { trait_: trait_id, substs }; 953 let trait_ref = TraitRef { trait_: trait_id, substs };
950 let pred = GenericPredicate::Implemented(trait_ref); 954 let pred = GenericPredicate::Implemented(trait_ref);
951 let program_clause: chalk_ir::ProgramClause<Interner> = 955 let program_clause: chalk_ir::ProgramClause<Interner> =
@@ -1033,7 +1037,7 @@ fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
1033/// function body. 1037/// function body.
1034fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> { 1038fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
1035 let generics = generics(db.upcast(), def.into()); 1039 let generics = generics(db.upcast(), def.into());
1036 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST); 1040 let substs = Substitution::bound_vars(&generics, DebruijnIndex::INNERMOST);
1037 Binders::new( 1041 Binders::new(
1038 substs.len(), 1042 substs.len(),
1039 TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner), 1043 TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner),
@@ -1078,7 +1082,7 @@ fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<T
1078 return type_for_adt(db, def.into()); 1082 return type_for_adt(db, def.into());
1079 } 1083 }
1080 let generics = generics(db.upcast(), def.into()); 1084 let generics = generics(db.upcast(), def.into());
1081 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST); 1085 let substs = Substitution::bound_vars(&generics, DebruijnIndex::INNERMOST);
1082 Binders::new( 1086 Binders::new(
1083 substs.len(), 1087 substs.len(),
1084 TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(&Interner), 1088 TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(&Interner),
@@ -1105,7 +1109,7 @@ fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -
1105 return type_for_adt(db, def.parent.into()); 1109 return type_for_adt(db, def.parent.into());
1106 } 1110 }
1107 let generics = generics(db.upcast(), def.parent.into()); 1111 let generics = generics(db.upcast(), def.parent.into());
1108 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST); 1112 let substs = Substitution::bound_vars(&generics, DebruijnIndex::INNERMOST);
1109 Binders::new( 1113 Binders::new(
1110 substs.len(), 1114 substs.len(),
1111 TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner), 1115 TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner),
@@ -1114,7 +1118,7 @@ fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -
1114 1118
1115fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> { 1119fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
1116 let generics = generics(db.upcast(), adt.into()); 1120 let generics = generics(db.upcast(), adt.into());
1117 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST); 1121 let substs = Substitution::bound_vars(&generics, DebruijnIndex::INNERMOST);
1118 Binders::new(substs.len(), Ty::adt_ty(adt, substs)) 1122 Binders::new(substs.len(), Ty::adt_ty(adt, substs))
1119} 1123}
1120 1124
@@ -1126,7 +1130,7 @@ fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
1126 if db.type_alias_data(t).is_extern { 1130 if db.type_alias_data(t).is_extern {
1127 Binders::new(0, TyKind::ForeignType(crate::to_foreign_def_id(t)).intern(&Interner)) 1131 Binders::new(0, TyKind::ForeignType(crate::to_foreign_def_id(t)).intern(&Interner))
1128 } else { 1132 } else {
1129 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST); 1133 let substs = Substitution::bound_vars(&generics, DebruijnIndex::INNERMOST);
1130 let type_ref = &db.type_alias_data(t).type_ref; 1134 let type_ref = &db.type_alias_data(t).type_ref;
1131 let inner = ctx.lower_ty(type_ref.as_ref().unwrap_or(&TypeRef::Error)); 1135 let inner = ctx.lower_ty(type_ref.as_ref().unwrap_or(&TypeRef::Error));
1132 Binders::new(substs.len(), inner) 1136 Binders::new(substs.len(), inner)
diff --git a/crates/hir_ty/src/method_resolution.rs b/crates/hir_ty/src/method_resolution.rs
index be72c4a1c..943d3339b 100644
--- a/crates/hir_ty/src/method_resolution.rs
+++ b/crates/hir_ty/src/method_resolution.rs
@@ -21,7 +21,7 @@ use crate::{
21 primitive::{self, FloatTy, IntTy, UintTy}, 21 primitive::{self, FloatTy, IntTy, UintTy},
22 utils::all_super_traits, 22 utils::all_super_traits,
23 AdtId, Canonical, DebruijnIndex, FnPointer, FnSig, ForeignDefId, InEnvironment, Interner, 23 AdtId, Canonical, DebruijnIndex, FnPointer, FnSig, ForeignDefId, InEnvironment, Interner,
24 Scalar, Substs, TraitEnvironment, TraitRef, Ty, TyKind, TypeWalk, 24 Scalar, Substitution, TraitEnvironment, TraitRef, Ty, TyKind, TypeWalk,
25}; 25};
26 26
27/// This is used as a key for indexing impls. 27/// This is used as a key for indexing impls.
@@ -672,10 +672,10 @@ pub(crate) fn inherent_impl_substs(
672 db: &dyn HirDatabase, 672 db: &dyn HirDatabase,
673 impl_id: ImplId, 673 impl_id: ImplId,
674 self_ty: &Canonical<Ty>, 674 self_ty: &Canonical<Ty>,
675) -> Option<Substs> { 675) -> Option<Substitution> {
676 // we create a var for each type parameter of the impl; we need to keep in 676 // we create a var for each type parameter of the impl; we need to keep in
677 // mind here that `self_ty` might have vars of its own 677 // mind here that `self_ty` might have vars of its own
678 let vars = Substs::build_for_def(db, impl_id) 678 let vars = Substitution::build_for_def(db, impl_id)
679 .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty.kinds.len()) 679 .fill_with_bound_vars(DebruijnIndex::INNERMOST, self_ty.kinds.len())
680 .build(); 680 .build();
681 let self_ty_with_vars = db.impl_self_ty(impl_id).subst(&vars); 681 let self_ty_with_vars = db.impl_self_ty(impl_id).subst(&vars);
@@ -693,7 +693,7 @@ pub(crate) fn inherent_impl_substs(
693 693
694/// This replaces any 'free' Bound vars in `s` (i.e. those with indices past 694/// This replaces any 'free' Bound vars in `s` (i.e. those with indices past
695/// num_vars_to_keep) by `TyKind::Unknown`. 695/// num_vars_to_keep) by `TyKind::Unknown`.
696fn fallback_bound_vars(s: Substs, num_vars_to_keep: usize) -> Substs { 696fn fallback_bound_vars(s: Substitution, num_vars_to_keep: usize) -> Substitution {
697 s.fold_binders( 697 s.fold_binders(
698 &mut |ty, binders| { 698 &mut |ty, binders| {
699 if let TyKind::BoundVar(bound) = ty.interned(&Interner) { 699 if let TyKind::BoundVar(bound) = ty.interned(&Interner) {
@@ -716,13 +716,13 @@ fn transform_receiver_ty(
716 self_ty: &Canonical<Ty>, 716 self_ty: &Canonical<Ty>,
717) -> Option<Ty> { 717) -> Option<Ty> {
718 let substs = match function_id.lookup(db.upcast()).container { 718 let substs = match function_id.lookup(db.upcast()).container {
719 AssocContainerId::TraitId(_) => Substs::build_for_def(db, function_id) 719 AssocContainerId::TraitId(_) => Substitution::build_for_def(db, function_id)
720 .push(self_ty.value.clone()) 720 .push(self_ty.value.clone())
721 .fill_with_unknown() 721 .fill_with_unknown()
722 .build(), 722 .build(),
723 AssocContainerId::ImplId(impl_id) => { 723 AssocContainerId::ImplId(impl_id) => {
724 let impl_substs = inherent_impl_substs(db, impl_id, &self_ty)?; 724 let impl_substs = inherent_impl_substs(db, impl_id, &self_ty)?;
725 Substs::build_for_def(db, function_id) 725 Substitution::build_for_def(db, function_id)
726 .use_parent_substs(&impl_substs) 726 .use_parent_substs(&impl_substs)
727 .fill_with_unknown() 727 .fill_with_unknown()
728 .build() 728 .build()
@@ -768,7 +768,7 @@ fn generic_implements_goal(
768 self_ty: Canonical<Ty>, 768 self_ty: Canonical<Ty>,
769) -> Canonical<InEnvironment<super::Obligation>> { 769) -> Canonical<InEnvironment<super::Obligation>> {
770 let mut kinds = self_ty.kinds.to_vec(); 770 let mut kinds = self_ty.kinds.to_vec();
771 let substs = super::Substs::build_for_def(db, trait_) 771 let substs = super::Substitution::build_for_def(db, trait_)
772 .push(self_ty.value) 772 .push(self_ty.value)
773 .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len()) 773 .fill_with_bound_vars(DebruijnIndex::INNERMOST, kinds.len())
774 .build(); 774 .build();
diff --git a/crates/hir_ty/src/tests/macros.rs b/crates/hir_ty/src/tests/macros.rs
index fb3afaedc..af4f8bb11 100644
--- a/crates/hir_ty/src/tests/macros.rs
+++ b/crates/hir_ty/src/tests/macros.rs
@@ -216,6 +216,22 @@ fn expr_macro_expanded_in_various_places() {
216} 216}
217 217
218#[test] 218#[test]
219fn expr_macro_expanded_in_stmts() {
220 check_infer(
221 r#"
222 macro_rules! id { ($($es:tt)*) => { $($es)* } }
223 fn foo() {
224 id! { let a = (); }
225 }
226 "#,
227 expect![[r#"
228 !0..8 'leta=();': ()
229 57..84 '{ ...); } }': ()
230 "#]],
231 );
232}
233
234#[test]
219fn infer_type_value_macro_having_same_name() { 235fn infer_type_value_macro_having_same_name() {
220 check_infer( 236 check_infer(
221 r#" 237 r#"
diff --git a/crates/hir_ty/src/traits.rs b/crates/hir_ty/src/traits.rs
index a6a63c673..40eb1034e 100644
--- a/crates/hir_ty/src/traits.rs
+++ b/crates/hir_ty/src/traits.rs
@@ -8,7 +8,7 @@ use chalk_solve::{logging_db::LoggingRustIrDatabase, Solver};
8use hir_def::{lang_item::LangItemTarget, TraitId}; 8use hir_def::{lang_item::LangItemTarget, TraitId};
9use stdx::panic_context; 9use stdx::panic_context;
10 10
11use crate::{db::HirDatabase, DebruijnIndex, Substs}; 11use crate::{db::HirDatabase, DebruijnIndex, Substitution};
12 12
13use super::{ 13use super::{
14 Canonical, GenericPredicate, HirDisplay, ProjectionTy, TraitRef, Ty, TyKind, TypeWalk, 14 Canonical, GenericPredicate, HirDisplay, ProjectionTy, TraitRef, Ty, TyKind, TypeWalk,
@@ -252,7 +252,7 @@ fn solution_from_chalk(
252} 252}
253 253
254#[derive(Clone, Debug, PartialEq, Eq)] 254#[derive(Clone, Debug, PartialEq, Eq)]
255pub struct SolutionVariables(pub Canonical<Substs>); 255pub struct SolutionVariables(pub Canonical<Substitution>);
256 256
257#[derive(Clone, Debug, PartialEq, Eq)] 257#[derive(Clone, Debug, PartialEq, Eq)]
258/// A (possible) solution for a proposed goal. 258/// A (possible) solution for a proposed goal.
diff --git a/crates/hir_ty/src/traits/chalk.rs b/crates/hir_ty/src/traits/chalk.rs
index 232cf9cd0..bef6e7e9c 100644
--- a/crates/hir_ty/src/traits/chalk.rs
+++ b/crates/hir_ty/src/traits/chalk.rs
@@ -22,7 +22,7 @@ use crate::{
22 to_assoc_type_id, 22 to_assoc_type_id,
23 utils::generics, 23 utils::generics,
24 BoundVar, CallableDefId, CallableSig, DebruijnIndex, FnDefId, GenericPredicate, 24 BoundVar, CallableDefId, CallableSig, DebruijnIndex, FnDefId, GenericPredicate,
25 ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TyKind, 25 ProjectionPredicate, ProjectionTy, Substitution, TraitRef, Ty, TyKind,
26}; 26};
27use mapping::{ 27use mapping::{
28 convert_where_clauses, generic_predicate_to_inline_bound, make_binders, TypeAliasAsValue, 28 convert_where_clauses, generic_predicate_to_inline_bound, make_binders, TypeAliasAsValue,
@@ -221,7 +221,7 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
221 let impl_bound = GenericPredicate::Implemented(TraitRef { 221 let impl_bound = GenericPredicate::Implemented(TraitRef {
222 trait_: future_trait, 222 trait_: future_trait,
223 // Self type as the first parameter. 223 // Self type as the first parameter.
224 substs: Substs::single( 224 substs: Substitution::single(
225 TyKind::BoundVar(BoundVar { 225 TyKind::BoundVar(BoundVar {
226 debruijn: DebruijnIndex::INNERMOST, 226 debruijn: DebruijnIndex::INNERMOST,
227 index: 0, 227 index: 0,
@@ -236,7 +236,7 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
236 projection_ty: ProjectionTy { 236 projection_ty: ProjectionTy {
237 associated_ty_id: to_assoc_type_id(future_output), 237 associated_ty_id: to_assoc_type_id(future_output),
238 // Self type as the first parameter. 238 // Self type as the first parameter.
239 substitution: Substs::single( 239 substitution: Substitution::single(
240 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)) 240 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
241 .intern(&Interner), 241 .intern(&Interner),
242 ), 242 ),
@@ -313,7 +313,7 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
313 _closure_id: chalk_ir::ClosureId<Interner>, 313 _closure_id: chalk_ir::ClosureId<Interner>,
314 _substs: &chalk_ir::Substitution<Interner>, 314 _substs: &chalk_ir::Substitution<Interner>,
315 ) -> chalk_ir::Substitution<Interner> { 315 ) -> chalk_ir::Substitution<Interner> {
316 Substs::empty().to_chalk(self.db) 316 Substitution::empty().to_chalk(self.db)
317 } 317 }
318 318
319 fn trait_name(&self, trait_id: chalk_ir::TraitId<Interner>) -> String { 319 fn trait_name(&self, trait_id: chalk_ir::TraitId<Interner>) -> String {
@@ -392,7 +392,7 @@ pub(crate) fn associated_ty_data_query(
392 // Lower bounds -- we could/should maybe move this to a separate query in `lower` 392 // Lower bounds -- we could/should maybe move this to a separate query in `lower`
393 let type_alias_data = db.type_alias_data(type_alias); 393 let type_alias_data = db.type_alias_data(type_alias);
394 let generic_params = generics(db.upcast(), type_alias.into()); 394 let generic_params = generics(db.upcast(), type_alias.into());
395 let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST); 395 let bound_vars = Substitution::bound_vars(&generic_params, DebruijnIndex::INNERMOST);
396 let resolver = hir_def::resolver::HasResolver::resolver(type_alias, db.upcast()); 396 let resolver = hir_def::resolver::HasResolver::resolver(type_alias, db.upcast());
397 let ctx = crate::TyLoweringContext::new(db, &resolver) 397 let ctx = crate::TyLoweringContext::new(db, &resolver)
398 .with_type_param_mode(crate::lower::TypeParamLoweringMode::Variable); 398 .with_type_param_mode(crate::lower::TypeParamLoweringMode::Variable);
@@ -427,9 +427,9 @@ pub(crate) fn trait_datum_query(
427 let trait_data = db.trait_data(trait_); 427 let trait_data = db.trait_data(trait_);
428 debug!("trait {:?} = {:?}", trait_id, trait_data.name); 428 debug!("trait {:?} = {:?}", trait_id, trait_data.name);
429 let generic_params = generics(db.upcast(), trait_.into()); 429 let generic_params = generics(db.upcast(), trait_.into());
430 let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST); 430 let bound_vars = Substitution::bound_vars(&generic_params, DebruijnIndex::INNERMOST);
431 let flags = rust_ir::TraitFlags { 431 let flags = rust_ir::TraitFlags {
432 auto: trait_data.auto, 432 auto: trait_data.is_auto,
433 upstream: trait_.lookup(db.upcast()).container.krate() != krate, 433 upstream: trait_.lookup(db.upcast()).container.krate() != krate,
434 non_enumerable: true, 434 non_enumerable: true,
435 coinductive: false, // only relevant for Chalk testing 435 coinductive: false, // only relevant for Chalk testing
@@ -496,7 +496,7 @@ pub(crate) fn struct_datum_query(
496 let upstream = adt_id.module(db.upcast()).krate() != krate; 496 let upstream = adt_id.module(db.upcast()).krate() != krate;
497 let where_clauses = { 497 let where_clauses = {
498 let generic_params = generics(db.upcast(), adt_id.into()); 498 let generic_params = generics(db.upcast(), adt_id.into());
499 let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST); 499 let bound_vars = Substitution::bound_vars(&generic_params, DebruijnIndex::INNERMOST);
500 convert_where_clauses(db, adt_id.into(), &bound_vars) 500 convert_where_clauses(db, adt_id.into(), &bound_vars)
501 }; 501 };
502 let flags = rust_ir::AdtFlags { 502 let flags = rust_ir::AdtFlags {
@@ -545,7 +545,7 @@ fn impl_def_datum(
545 let impl_data = db.impl_data(impl_id); 545 let impl_data = db.impl_data(impl_id);
546 546
547 let generic_params = generics(db.upcast(), impl_id.into()); 547 let generic_params = generics(db.upcast(), impl_id.into());
548 let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST); 548 let bound_vars = Substitution::bound_vars(&generic_params, DebruijnIndex::INNERMOST);
549 let trait_ = trait_ref.trait_; 549 let trait_ = trait_ref.trait_;
550 let impl_type = if impl_id.lookup(db.upcast()).container.krate() == krate { 550 let impl_type = if impl_id.lookup(db.upcast()).container.krate() == krate {
551 rust_ir::ImplType::Local 551 rust_ir::ImplType::Local
@@ -635,7 +635,7 @@ pub(crate) fn fn_def_datum_query(
635 let callable_def: CallableDefId = from_chalk(db, fn_def_id); 635 let callable_def: CallableDefId = from_chalk(db, fn_def_id);
636 let generic_params = generics(db.upcast(), callable_def.into()); 636 let generic_params = generics(db.upcast(), callable_def.into());
637 let sig = db.callable_item_signature(callable_def); 637 let sig = db.callable_item_signature(callable_def);
638 let bound_vars = Substs::bound_vars(&generic_params, DebruijnIndex::INNERMOST); 638 let bound_vars = Substitution::bound_vars(&generic_params, DebruijnIndex::INNERMOST);
639 let where_clauses = convert_where_clauses(db, callable_def.into(), &bound_vars); 639 let where_clauses = convert_where_clauses(db, callable_def.into(), &bound_vars);
640 let bound = rust_ir::FnDefDatumBound { 640 let bound = rust_ir::FnDefDatumBound {
641 // Note: Chalk doesn't actually use this information yet as far as I am aware, but we provide it anyway 641 // Note: Chalk doesn't actually use this information yet as far as I am aware, but we provide it anyway
diff --git a/crates/hir_ty/src/traits/chalk/mapping.rs b/crates/hir_ty/src/traits/chalk/mapping.rs
index 6a8b6752e..524814f43 100644
--- a/crates/hir_ty/src/traits/chalk/mapping.rs
+++ b/crates/hir_ty/src/traits/chalk/mapping.rs
@@ -15,7 +15,7 @@ use crate::{
15 primitive::UintTy, 15 primitive::UintTy,
16 traits::{Canonical, Obligation}, 16 traits::{Canonical, Obligation},
17 AliasTy, CallableDefId, FnPointer, GenericPredicate, InEnvironment, OpaqueTy, 17 AliasTy, CallableDefId, FnPointer, GenericPredicate, InEnvironment, OpaqueTy,
18 ProjectionPredicate, ProjectionTy, Scalar, Substs, TraitRef, Ty, 18 ProjectionPredicate, ProjectionTy, Scalar, Substitution, TraitRef, Ty,
19}; 19};
20 20
21use super::interner::*; 21use super::interner::*;
@@ -134,7 +134,7 @@ impl ToChalk for Ty {
134 .. 134 ..
135 }) => { 135 }) => {
136 assert_eq!(num_binders, 0); 136 assert_eq!(num_binders, 0);
137 let substs: Substs = from_chalk( 137 let substs: Substitution = from_chalk(
138 db, 138 db,
139 substitution.0.shifted_out(&Interner).expect("fn ptr should have no binders"), 139 substitution.0.shifted_out(&Interner).expect("fn ptr should have no binders"),
140 ); 140 );
@@ -213,14 +213,17 @@ fn array_to_chalk(db: &dyn HirDatabase, ty: Ty) -> chalk_ir::Ty<Interner> {
213 chalk_ir::TyKind::Array(arg, const_).intern(&Interner) 213 chalk_ir::TyKind::Array(arg, const_).intern(&Interner)
214} 214}
215 215
216impl ToChalk for Substs { 216impl ToChalk for Substitution {
217 type Chalk = chalk_ir::Substitution<Interner>; 217 type Chalk = chalk_ir::Substitution<Interner>;
218 218
219 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Substitution<Interner> { 219 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Substitution<Interner> {
220 chalk_ir::Substitution::from_iter(&Interner, self.iter().map(|ty| ty.clone().to_chalk(db))) 220 chalk_ir::Substitution::from_iter(&Interner, self.iter().map(|ty| ty.clone().to_chalk(db)))
221 } 221 }
222 222
223 fn from_chalk(db: &dyn HirDatabase, parameters: chalk_ir::Substitution<Interner>) -> Substs { 223 fn from_chalk(
224 db: &dyn HirDatabase,
225 parameters: chalk_ir::Substitution<Interner>,
226 ) -> Substitution {
224 let tys = parameters 227 let tys = parameters
225 .iter(&Interner) 228 .iter(&Interner)
226 .map(|p| match p.ty(&Interner) { 229 .map(|p| match p.ty(&Interner) {
@@ -228,7 +231,7 @@ impl ToChalk for Substs {
228 None => unimplemented!(), 231 None => unimplemented!(),
229 }) 232 })
230 .collect(); 233 .collect();
231 Substs(tys) 234 Substitution(tys)
232 } 235 }
233} 236}
234 237
@@ -489,7 +492,7 @@ where
489pub(super) fn convert_where_clauses( 492pub(super) fn convert_where_clauses(
490 db: &dyn HirDatabase, 493 db: &dyn HirDatabase,
491 def: GenericDefId, 494 def: GenericDefId,
492 substs: &Substs, 495 substs: &Substitution,
493) -> Vec<chalk_ir::QuantifiedWhereClause<Interner>> { 496) -> Vec<chalk_ir::QuantifiedWhereClause<Interner>> {
494 let generic_predicates = db.generic_predicates(def); 497 let generic_predicates = db.generic_predicates(def);
495 let mut result = Vec::with_capacity(generic_predicates.len()); 498 let mut result = Vec::with_capacity(generic_predicates.len());
diff --git a/crates/ide/src/call_hierarchy.rs b/crates/ide/src/call_hierarchy.rs
index b848945d7..96021f677 100644
--- a/crates/ide/src/call_hierarchy.rs
+++ b/crates/ide/src/call_hierarchy.rs
@@ -53,10 +53,8 @@ pub(crate) fn incoming_calls(db: &RootDatabase, position: FilePosition) -> Optio
53 for (r_range, _) in references { 53 for (r_range, _) in references {
54 let token = file.token_at_offset(r_range.start()).next()?; 54 let token = file.token_at_offset(r_range.start()).next()?;
55 let token = sema.descend_into_macros(token); 55 let token = sema.descend_into_macros(token);
56 let syntax = token.parent();
57
58 // This target is the containing function 56 // This target is the containing function
59 if let Some(nav) = syntax.ancestors().find_map(|node| { 57 if let Some(nav) = token.ancestors().find_map(|node| {
60 let fn_ = ast::Fn::cast(node)?; 58 let fn_ = ast::Fn::cast(node)?;
61 let def = sema.to_def(&fn_)?; 59 let def = sema.to_def(&fn_)?;
62 def.try_to_nav(sema.db) 60 def.try_to_nav(sema.db)
@@ -77,12 +75,13 @@ pub(crate) fn outgoing_calls(db: &RootDatabase, position: FilePosition) -> Optio
77 let file = file.syntax(); 75 let file = file.syntax();
78 let token = file.token_at_offset(position.offset).next()?; 76 let token = file.token_at_offset(position.offset).next()?;
79 let token = sema.descend_into_macros(token); 77 let token = sema.descend_into_macros(token);
80 let syntax = token.parent();
81 78
82 let mut calls = CallLocations::default(); 79 let mut calls = CallLocations::default();
83 80
84 syntax 81 token
85 .descendants() 82 .parent()
83 .into_iter()
84 .flat_map(|it| it.descendants())
86 .filter_map(|node| FnCallNode::with_node_exact(&node)) 85 .filter_map(|node| FnCallNode::with_node_exact(&node))
87 .filter_map(|call_node| { 86 .filter_map(|call_node| {
88 let name_ref = call_node.name_ref()?; 87 let name_ref = call_node.name_ref()?;
diff --git a/crates/ide/src/display.rs b/crates/ide/src/display.rs
index bae9e40df..71e97d6b4 100644
--- a/crates/ide/src/display.rs
+++ b/crates/ide/src/display.rs
@@ -2,9 +2,7 @@
2//! into types that may be used to render in a UI. 2//! into types that may be used to render in a UI.
3 3
4pub(crate) mod navigation_target; 4pub(crate) mod navigation_target;
5mod short_label;
6 5
7pub(crate) use navigation_target::{ToNav, TryToNav}; 6pub(crate) use navigation_target::{ToNav, TryToNav};
8pub(crate) use short_label::ShortLabel;
9 7
10pub(crate) use syntax::display::{function_declaration, macro_label}; 8pub(crate) use syntax::display::macro_label;
diff --git a/crates/ide/src/display/navigation_target.rs b/crates/ide/src/display/navigation_target.rs
index 198243466..c086de163 100644
--- a/crates/ide/src/display/navigation_target.rs
+++ b/crates/ide/src/display/navigation_target.rs
@@ -3,9 +3,12 @@
3use std::fmt; 3use std::fmt;
4 4
5use either::Either; 5use either::Either;
6use hir::{AssocItem, Documentation, FieldSource, HasAttrs, HasSource, InFile, ModuleSource}; 6use hir::{
7 AssocItem, Documentation, FieldSource, HasAttrs, HasSource, HirDisplay, InFile, ModuleSource,
8 Semantics,
9};
7use ide_db::{ 10use ide_db::{
8 base_db::{FileId, FileRange, SourceDatabase}, 11 base_db::{FileId, FileRange},
9 symbol_index::FileSymbolKind, 12 symbol_index::FileSymbolKind,
10 SymbolKind, 13 SymbolKind,
11}; 14};
@@ -17,8 +20,6 @@ use syntax::{
17 20
18use crate::FileSymbol; 21use crate::FileSymbol;
19 22
20use super::short_label::ShortLabel;
21
22/// `NavigationTarget` represents and element in the editor's UI which you can 23/// `NavigationTarget` represents and element in the editor's UI which you can
23/// click on to navigate to a particular piece of code. 24/// click on to navigate to a particular piece of code.
24/// 25///
@@ -98,7 +99,7 @@ impl NavigationTarget {
98 SymbolKind::Module, 99 SymbolKind::Module,
99 ); 100 );
100 res.docs = module.attrs(db).docs(); 101 res.docs = module.attrs(db).docs();
101 res.description = src.value.short_label(); 102 res.description = Some(module.display(db).to_string());
102 return res; 103 return res;
103 } 104 }
104 module.to_nav(db) 105 module.to_nav(db)
@@ -251,8 +252,8 @@ impl ToNavFromAst for hir::Trait {
251 252
252impl<D> TryToNav for D 253impl<D> TryToNav for D
253where 254where
254 D: HasSource + ToNavFromAst + Copy + HasAttrs, 255 D: HasSource + ToNavFromAst + Copy + HasAttrs + HirDisplay,
255 D::Ast: ast::NameOwner + ShortLabel, 256 D::Ast: ast::NameOwner,
256{ 257{
257 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> { 258 fn try_to_nav(&self, db: &RootDatabase) -> Option<NavigationTarget> {
258 let src = self.source(db)?; 259 let src = self.source(db)?;
@@ -262,7 +263,7 @@ where
262 D::KIND, 263 D::KIND,
263 ); 264 );
264 res.docs = self.docs(db); 265 res.docs = self.docs(db);
265 res.description = src.value.short_label(); 266 res.description = Some(self.display(db).to_string());
266 Some(res) 267 Some(res)
267 } 268 }
268} 269}
@@ -317,7 +318,7 @@ impl TryToNav for hir::Field {
317 let mut res = 318 let mut res =
318 NavigationTarget::from_named(db, src.with_value(it), SymbolKind::Field); 319 NavigationTarget::from_named(db, src.with_value(it), SymbolKind::Field);
319 res.docs = self.docs(db); 320 res.docs = self.docs(db);
320 res.description = it.short_label(); 321 res.description = Some(self.display(db).to_string());
321 res 322 res
322 } 323 }
323 FieldSource::Pos(it) => { 324 FieldSource::Pos(it) => {
@@ -500,21 +501,22 @@ impl TryToNav for hir::ConstParam {
500/// 501///
501/// e.g. `struct Name`, `enum Name`, `fn Name` 502/// e.g. `struct Name`, `enum Name`, `fn Name`
502pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> { 503pub(crate) fn description_from_symbol(db: &RootDatabase, symbol: &FileSymbol) -> Option<String> {
503 let parse = db.parse(symbol.file_id); 504 let sema = Semantics::new(db);
504 let node = symbol.ptr.to_node(parse.tree().syntax()); 505 let parse = sema.parse(symbol.file_id);
506 let node = symbol.ptr.to_node(parse.syntax());
505 507
506 match_ast! { 508 match_ast! {
507 match node { 509 match node {
508 ast::Fn(it) => it.short_label(), 510 ast::Fn(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
509 ast::Struct(it) => it.short_label(), 511 ast::Struct(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
510 ast::Enum(it) => it.short_label(), 512 ast::Enum(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
511 ast::Trait(it) => it.short_label(), 513 ast::Trait(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
512 ast::Module(it) => it.short_label(), 514 ast::Module(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
513 ast::TypeAlias(it) => it.short_label(), 515 ast::TypeAlias(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
514 ast::Const(it) => it.short_label(), 516 ast::Const(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
515 ast::Static(it) => it.short_label(), 517 ast::Static(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
516 ast::RecordField(it) => it.short_label(), 518 ast::RecordField(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
517 ast::Variant(it) => it.short_label(), 519 ast::Variant(it) => sema.to_def(&it).map(|it| it.display(db).to_string()),
518 _ => None, 520 _ => None,
519 } 521 }
520 } 522 }
diff --git a/crates/ide/src/display/short_label.rs b/crates/ide/src/display/short_label.rs
deleted file mode 100644
index 2df9266b4..000000000
--- a/crates/ide/src/display/short_label.rs
+++ /dev/null
@@ -1,128 +0,0 @@
1//! FIXME: write short doc here
2
3use stdx::format_to;
4use syntax::ast::{self, AstNode, NameOwner, VisibilityOwner};
5
6pub(crate) trait ShortLabel {
7 fn short_label(&self) -> Option<String>;
8}
9
10impl ShortLabel for ast::Fn {
11 fn short_label(&self) -> Option<String> {
12 Some(crate::display::function_declaration(self))
13 }
14}
15
16impl ShortLabel for ast::Struct {
17 fn short_label(&self) -> Option<String> {
18 short_label_from_node(self, "struct ")
19 }
20}
21
22impl ShortLabel for ast::Union {
23 fn short_label(&self) -> Option<String> {
24 short_label_from_node(self, "union ")
25 }
26}
27
28impl ShortLabel for ast::Enum {
29 fn short_label(&self) -> Option<String> {
30 short_label_from_node(self, "enum ")
31 }
32}
33
34impl ShortLabel for ast::Trait {
35 fn short_label(&self) -> Option<String> {
36 if self.unsafe_token().is_some() {
37 short_label_from_node(self, "unsafe trait ")
38 } else {
39 short_label_from_node(self, "trait ")
40 }
41 }
42}
43
44impl ShortLabel for ast::Module {
45 fn short_label(&self) -> Option<String> {
46 short_label_from_node(self, "mod ")
47 }
48}
49
50impl ShortLabel for ast::SourceFile {
51 fn short_label(&self) -> Option<String> {
52 None
53 }
54}
55
56impl ShortLabel for ast::BlockExpr {
57 fn short_label(&self) -> Option<String> {
58 None
59 }
60}
61
62impl ShortLabel for ast::TypeAlias {
63 fn short_label(&self) -> Option<String> {
64 let mut buf = short_label_from_node(self, "type ")?;
65 if let Some(type_ref) = self.ty() {
66 format_to!(buf, " = {}", type_ref.syntax());
67 }
68 Some(buf)
69 }
70}
71
72impl ShortLabel for ast::Const {
73 fn short_label(&self) -> Option<String> {
74 short_label_from_ty(self, self.ty(), "const ")
75 }
76}
77
78impl ShortLabel for ast::Static {
79 fn short_label(&self) -> Option<String> {
80 short_label_from_ty(self, self.ty(), "static ")
81 }
82}
83
84impl ShortLabel for ast::RecordField {
85 fn short_label(&self) -> Option<String> {
86 short_label_from_ty(self, self.ty(), "")
87 }
88}
89
90impl ShortLabel for ast::Variant {
91 fn short_label(&self) -> Option<String> {
92 Some(self.name()?.text().to_string())
93 }
94}
95
96impl ShortLabel for ast::ConstParam {
97 fn short_label(&self) -> Option<String> {
98 let mut buf = "const ".to_owned();
99 buf.push_str(self.name()?.text());
100 if let Some(type_ref) = self.ty() {
101 format_to!(buf, ": {}", type_ref.syntax());
102 }
103 Some(buf)
104 }
105}
106
107fn short_label_from_ty<T>(node: &T, ty: Option<ast::Type>, prefix: &str) -> Option<String>
108where
109 T: NameOwner + VisibilityOwner,
110{
111 let mut buf = short_label_from_node(node, prefix)?;
112
113 if let Some(type_ref) = ty {
114 format_to!(buf, ": {}", type_ref.syntax());
115 }
116
117 Some(buf)
118}
119
120fn short_label_from_node<T>(node: &T, label: &str) -> Option<String>
121where
122 T: NameOwner + VisibilityOwner,
123{
124 let mut buf = node.visibility().map(|v| format!("{} ", v.syntax())).unwrap_or_default();
125 buf.push_str(label);
126 buf.push_str(node.name()?.text());
127 Some(buf)
128}
diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs
index 7bdd3cca3..461e11060 100644
--- a/crates/ide/src/doc_links.rs
+++ b/crates/ide/src/doc_links.rs
@@ -279,7 +279,7 @@ pub(crate) fn external_docs(
279 let token = pick_best(file.token_at_offset(position.offset))?; 279 let token = pick_best(file.token_at_offset(position.offset))?;
280 let token = sema.descend_into_macros(token); 280 let token = sema.descend_into_macros(token);
281 281
282 let node = token.parent(); 282 let node = token.parent()?;
283 let definition = match_ast! { 283 let definition = match_ast! {
284 match node { 284 match node {
285 ast::NameRef(name_ref) => NameRefClass::classify(&sema, &name_ref).map(|d| d.referenced(sema.db)), 285 ast::NameRef(name_ref) => NameRefClass::classify(&sema, &name_ref).map(|d| d.referenced(sema.db)),
diff --git a/crates/ide/src/extend_selection.rs b/crates/ide/src/extend_selection.rs
index b540d04fe..e187243cb 100644
--- a/crates/ide/src/extend_selection.rs
+++ b/crates/ide/src/extend_selection.rs
@@ -88,7 +88,7 @@ fn try_extend_selection(
88 return Some(range); 88 return Some(range);
89 } 89 }
90 } 90 }
91 token.parent() 91 token.parent()?
92 } 92 }
93 NodeOrToken::Node(node) => node, 93 NodeOrToken::Node(node) => node,
94 }; 94 };
@@ -142,7 +142,8 @@ fn extend_tokens_from_range(
142 let extended = { 142 let extended = {
143 let fst_expanded = sema.descend_into_macros(first_token.clone()); 143 let fst_expanded = sema.descend_into_macros(first_token.clone());
144 let lst_expanded = sema.descend_into_macros(last_token.clone()); 144 let lst_expanded = sema.descend_into_macros(last_token.clone());
145 let mut lca = algo::least_common_ancestor(&fst_expanded.parent(), &lst_expanded.parent())?; 145 let mut lca =
146 algo::least_common_ancestor(&fst_expanded.parent()?, &lst_expanded.parent()?)?;
146 lca = shallowest_node(&lca); 147 lca = shallowest_node(&lca);
147 if lca.first_token() == Some(fst_expanded) && lca.last_token() == Some(lst_expanded) { 148 if lca.first_token() == Some(fst_expanded) && lca.last_token() == Some(lst_expanded) {
148 lca = lca.parent()?; 149 lca = lca.parent()?;
@@ -151,9 +152,13 @@ fn extend_tokens_from_range(
151 }; 152 };
152 153
153 // Compute parent node range 154 // Compute parent node range
154 let validate = |token: &SyntaxToken| { 155 let validate = |token: &SyntaxToken| -> bool {
155 let expanded = sema.descend_into_macros(token.clone()); 156 let expanded = sema.descend_into_macros(token.clone());
156 algo::least_common_ancestor(&extended, &expanded.parent()).as_ref() == Some(&extended) 157 let parent = match expanded.parent() {
158 Some(it) => it,
159 None => return false,
160 };
161 algo::least_common_ancestor(&extended, &parent).as_ref() == Some(&extended)
157 }; 162 };
158 163
159 // Find the first and last text range under expanded parent 164 // Find the first and last text range under expanded parent
diff --git a/crates/ide/src/goto_definition.rs b/crates/ide/src/goto_definition.rs
index e8f31e4b1..6986477a5 100644
--- a/crates/ide/src/goto_definition.rs
+++ b/crates/ide/src/goto_definition.rs
@@ -30,7 +30,7 @@ pub(crate) fn goto_definition(
30 let file = sema.parse(position.file_id).syntax().clone(); 30 let file = sema.parse(position.file_id).syntax().clone();
31 let original_token = pick_best(file.token_at_offset(position.offset))?; 31 let original_token = pick_best(file.token_at_offset(position.offset))?;
32 let token = sema.descend_into_macros(original_token.clone()); 32 let token = sema.descend_into_macros(original_token.clone());
33 let parent = token.parent(); 33 let parent = token.parent()?;
34 if let Some(comment) = ast::Comment::cast(token) { 34 if let Some(comment) = ast::Comment::cast(token) {
35 let nav = def_for_doc_comment(&sema, position, &comment)?.try_to_nav(db)?; 35 let nav = def_for_doc_comment(&sema, position, &comment)?.try_to_nav(db)?;
36 return Some(RangeInfo::new(original_token.text_range(), vec![nav])); 36 return Some(RangeInfo::new(original_token.text_range(), vec![nav]));
@@ -63,7 +63,7 @@ fn def_for_doc_comment(
63 position: FilePosition, 63 position: FilePosition,
64 doc_comment: &ast::Comment, 64 doc_comment: &ast::Comment,
65) -> Option<hir::ModuleDef> { 65) -> Option<hir::ModuleDef> {
66 let parent = doc_comment.syntax().parent(); 66 let parent = doc_comment.syntax().parent()?;
67 let (link, ns) = extract_positioned_link_from_comment(position, doc_comment)?; 67 let (link, ns) = extract_positioned_link_from_comment(position, doc_comment)?;
68 68
69 let def = doc_owner_to_def(sema, parent)?; 69 let def = doc_owner_to_def(sema, parent)?;
diff --git a/crates/ide/src/goto_type_definition.rs b/crates/ide/src/goto_type_definition.rs
index 369a59820..2d38cb112 100644
--- a/crates/ide/src/goto_type_definition.rs
+++ b/crates/ide/src/goto_type_definition.rs
@@ -22,7 +22,7 @@ pub(crate) fn goto_type_definition(
22 let token: SyntaxToken = pick_best(file.syntax().token_at_offset(position.offset))?; 22 let token: SyntaxToken = pick_best(file.syntax().token_at_offset(position.offset))?;
23 let token: SyntaxToken = sema.descend_into_macros(token); 23 let token: SyntaxToken = sema.descend_into_macros(token);
24 24
25 let (ty, node) = sema.ancestors_with_macros(token.parent()).find_map(|node| { 25 let (ty, node) = sema.token_ancestors_with_macros(token).find_map(|node| {
26 let ty = match_ast! { 26 let ty = match_ast! {
27 match node { 27 match node {
28 ast::Expr(it) => sema.type_of_expr(&it)?, 28 ast::Expr(it) => sema.type_of_expr(&it)?,
diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs
index ea45086ce..325014622 100644
--- a/crates/ide/src/hover.rs
+++ b/crates/ide/src/hover.rs
@@ -1,7 +1,7 @@
1use either::Either; 1use either::Either;
2use hir::{ 2use hir::{
3 Adt, AsAssocItem, AssocItemContainer, FieldSource, GenericParam, HasAttrs, HasSource, 3 AsAssocItem, AssocItemContainer, GenericParam, HasAttrs, HasSource, HirDisplay, Module,
4 HirDisplay, Module, ModuleDef, ModuleSource, Semantics, 4 ModuleDef, Semantics,
5}; 5};
6use ide_db::{ 6use ide_db::{
7 base_db::SourceDatabase, 7 base_db::SourceDatabase,
@@ -14,7 +14,7 @@ use stdx::format_to;
14use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset, T}; 14use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, TokenAtOffset, T};
15 15
16use crate::{ 16use crate::{
17 display::{macro_label, ShortLabel, TryToNav}, 17 display::{macro_label, TryToNav},
18 doc_links::{remove_links, rewrite_links}, 18 doc_links::{remove_links, rewrite_links},
19 markdown_remove::remove_markdown, 19 markdown_remove::remove_markdown,
20 markup::Markup, 20 markup::Markup,
@@ -92,7 +92,7 @@ pub(crate) fn hover(
92 92
93 let mut res = HoverResult::default(); 93 let mut res = HoverResult::default();
94 94
95 let node = token.parent(); 95 let node = token.parent()?;
96 let definition = match_ast! { 96 let definition = match_ast! {
97 match node { 97 match node {
98 // we don't use NameClass::referenced_or_defined here as we do not want to resolve 98 // we don't use NameClass::referenced_or_defined here as we do not want to resolve
@@ -335,61 +335,34 @@ fn hover_for_definition(
335 let label = macro_label(&it.source(db)?.value); 335 let label = macro_label(&it.source(db)?.value);
336 from_def_source_labeled(db, it, Some(label), mod_path) 336 from_def_source_labeled(db, it, Some(label), mod_path)
337 } 337 }
338 Definition::Field(def) => { 338 Definition::Field(def) => from_hir_fmt(db, def, mod_path),
339 let src = def.source(db)?.value;
340 if let FieldSource::Named(it) = src {
341 from_def_source_labeled(db, def, it.short_label(), mod_path)
342 } else {
343 None
344 }
345 }
346 Definition::ModuleDef(it) => match it { 339 Definition::ModuleDef(it) => match it {
347 ModuleDef::Module(it) => from_def_source_labeled( 340 ModuleDef::Module(it) => from_hir_fmt(db, it, mod_path),
348 db, 341 ModuleDef::Function(it) => from_hir_fmt(db, it, mod_path),
349 it, 342 ModuleDef::Adt(it) => from_hir_fmt(db, it, mod_path),
350 match it.definition_source(db).value { 343 ModuleDef::Variant(it) => from_hir_fmt(db, it, mod_path),
351 ModuleSource::Module(it) => it.short_label(), 344 ModuleDef::Const(it) => from_hir_fmt(db, it, mod_path),
352 ModuleSource::SourceFile(it) => it.short_label(), 345 ModuleDef::Static(it) => from_hir_fmt(db, it, mod_path),
353 ModuleSource::BlockExpr(it) => it.short_label(), 346 ModuleDef::Trait(it) => from_hir_fmt(db, it, mod_path),
354 }, 347 ModuleDef::TypeAlias(it) => from_hir_fmt(db, it, mod_path),
355 mod_path,
356 ),
357 ModuleDef::Function(it) => from_def_source(db, it, mod_path),
358 ModuleDef::Adt(Adt::Struct(it)) => from_def_source(db, it, mod_path),
359 ModuleDef::Adt(Adt::Union(it)) => from_def_source(db, it, mod_path),
360 ModuleDef::Adt(Adt::Enum(it)) => from_def_source(db, it, mod_path),
361 ModuleDef::Variant(it) => from_def_source(db, it, mod_path),
362 ModuleDef::Const(it) => from_def_source(db, it, mod_path),
363 ModuleDef::Static(it) => from_def_source(db, it, mod_path),
364 ModuleDef::Trait(it) => from_def_source(db, it, mod_path),
365 ModuleDef::TypeAlias(it) => from_def_source(db, it, mod_path),
366 ModuleDef::BuiltinType(it) => famous_defs 348 ModuleDef::BuiltinType(it) => famous_defs
367 .and_then(|fd| hover_for_builtin(fd, it)) 349 .and_then(|fd| hover_for_builtin(fd, it))
368 .or_else(|| Some(Markup::fenced_block(&it.name()))), 350 .or_else(|| Some(Markup::fenced_block(&it.name()))),
369 }, 351 },
370 Definition::Local(it) => hover_for_local(it, db), 352 Definition::Local(it) => hover_for_local(it, db),
371 Definition::SelfType(impl_def) => { 353 Definition::SelfType(impl_def) => {
372 impl_def.target_ty(db).as_adt().and_then(|adt| match adt { 354 impl_def.target_ty(db).as_adt().and_then(|adt| from_hir_fmt(db, adt, mod_path))
373 Adt::Struct(it) => from_def_source(db, it, mod_path),
374 Adt::Union(it) => from_def_source(db, it, mod_path),
375 Adt::Enum(it) => from_def_source(db, it, mod_path),
376 })
377 } 355 }
356 Definition::GenericParam(it) => from_hir_fmt(db, it, None),
378 Definition::Label(it) => Some(Markup::fenced_block(&it.name(db))), 357 Definition::Label(it) => Some(Markup::fenced_block(&it.name(db))),
379 Definition::GenericParam(it) => match it {
380 GenericParam::TypeParam(it) => Some(Markup::fenced_block(&it.display(db))),
381 GenericParam::LifetimeParam(it) => Some(Markup::fenced_block(&it.name(db))),
382 GenericParam::ConstParam(it) => from_def_source(db, it, None),
383 },
384 }; 358 };
385 359
386 fn from_def_source<A, D>(db: &RootDatabase, def: D, mod_path: Option<String>) -> Option<Markup> 360 fn from_hir_fmt<D>(db: &RootDatabase, def: D, mod_path: Option<String>) -> Option<Markup>
387 where 361 where
388 D: HasSource<Ast = A> + HasAttrs + Copy, 362 D: HasAttrs + HirDisplay,
389 A: ShortLabel,
390 { 363 {
391 let short_label = def.source(db)?.value.short_label(); 364 let label = def.display(db).to_string();
392 from_def_source_labeled(db, def, short_label, mod_path) 365 from_def_source_labeled(db, def, Some(label), mod_path)
393 } 366 }
394 367
395 fn from_def_source_labeled<D>( 368 fn from_def_source_labeled<D>(
@@ -438,7 +411,7 @@ fn hover_for_keyword(
438 if !token.kind().is_keyword() { 411 if !token.kind().is_keyword() {
439 return None; 412 return None;
440 } 413 }
441 let famous_defs = FamousDefs(&sema, sema.scope(&token.parent()).krate()); 414 let famous_defs = FamousDefs(&sema, sema.scope(&token.parent()?).krate());
442 // std exposes {}_keyword modules with docstrings on the root to document keywords 415 // std exposes {}_keyword modules with docstrings on the root to document keywords
443 let keyword_mod = format!("{}_keyword", token.text()); 416 let keyword_mod = format!("{}_keyword", token.text());
444 let doc_owner = find_std_module(&famous_defs, &keyword_mod)?; 417 let doc_owner = find_std_module(&famous_defs, &keyword_mod)?;
@@ -670,7 +643,9 @@ fn main() { let foo_test = fo$0o(); }
670 ``` 643 ```
671 644
672 ```rust 645 ```rust
673 pub fn foo<'a, T: AsRef<str>>(b: &'a T) -> &'a str 646 pub fn foo<'a, T>(b: &'a T) -> &'a str
647 where
648 T: AsRef<str>,
674 ``` 649 ```
675 "#]], 650 "#]],
676 ); 651 );
@@ -878,7 +853,7 @@ fn main() { So$0me(12); }
878 ``` 853 ```
879 854
880 ```rust 855 ```rust
881 Some 856 Some(T)
882 ``` 857 ```
883 "#]], 858 "#]],
884 ); 859 );
@@ -944,7 +919,7 @@ fn main() {
944 ``` 919 ```
945 920
946 ```rust 921 ```rust
947 Some 922 Some(T)
948 ``` 923 ```
949 924
950 --- 925 ---
@@ -1441,13 +1416,14 @@ fn bar() { fo$0o(); }
1441 ``` 1416 ```
1442 "#]], 1417 "#]],
1443 ); 1418 );
1419 // Top level `pub(crate)` will be displayed as no visibility.
1444 check( 1420 check(
1445 r#"pub(crate) async unsafe extern "C" fn foo$0() {}"#, 1421 r#"mod m { pub(crate) async unsafe extern "C" fn foo$0() {} }"#,
1446 expect![[r#" 1422 expect![[r#"
1447 *foo* 1423 *foo*
1448 1424
1449 ```rust 1425 ```rust
1450 test 1426 test::m
1451 ``` 1427 ```
1452 1428
1453 ```rust 1429 ```rust
@@ -1489,11 +1465,18 @@ extern crate st$0d;
1489//! abc123 1465//! abc123
1490 "#, 1466 "#,
1491 expect![[r#" 1467 expect![[r#"
1492 *std* 1468 *std*
1493 Standard library for this test 1469
1470 ```rust
1471 extern crate std
1472 ```
1473
1474 ---
1494 1475
1495 Printed? 1476 Standard library for this test
1496 abc123 1477
1478 Printed?
1479 abc123
1497 "#]], 1480 "#]],
1498 ); 1481 );
1499 check( 1482 check(
@@ -1507,11 +1490,18 @@ extern crate std as ab$0c;
1507//! abc123 1490//! abc123
1508 "#, 1491 "#,
1509 expect![[r#" 1492 expect![[r#"
1510 *abc* 1493 *abc*
1511 Standard library for this test 1494
1495 ```rust
1496 extern crate std
1497 ```
1512 1498
1513 Printed? 1499 ---
1514 abc123 1500
1501 Standard library for this test
1502
1503 Printed?
1504 abc123
1515 "#]], 1505 "#]],
1516 ); 1506 );
1517 } 1507 }
@@ -2021,7 +2011,7 @@ enum E {
2021 ``` 2011 ```
2022 2012
2023 ```rust 2013 ```rust
2024 V 2014 V { field: i32 }
2025 ``` 2015 ```
2026 2016
2027 --- 2017 ---
@@ -2417,7 +2407,7 @@ fn main() { let s$0t = S{ f1:Arg(0) }; }
2417 focus_range: 24..25, 2407 focus_range: 24..25,
2418 name: "S", 2408 name: "S",
2419 kind: Struct, 2409 kind: Struct,
2420 description: "struct S", 2410 description: "struct S<T>",
2421 }, 2411 },
2422 }, 2412 },
2423 HoverGotoTypeData { 2413 HoverGotoTypeData {
@@ -2463,7 +2453,7 @@ fn main() { let s$0t = S{ f1: S{ f1: Arg(0) } }; }
2463 focus_range: 24..25, 2453 focus_range: 24..25,
2464 name: "S", 2454 name: "S",
2465 kind: Struct, 2455 kind: Struct,
2466 description: "struct S", 2456 description: "struct S<T>",
2467 }, 2457 },
2468 }, 2458 },
2469 HoverGotoTypeData { 2459 HoverGotoTypeData {
@@ -2605,7 +2595,7 @@ fn main() { let s$0t = foo(); }
2605 focus_range: 6..9, 2595 focus_range: 6..9,
2606 name: "Foo", 2596 name: "Foo",
2607 kind: Trait, 2597 kind: Trait,
2608 description: "trait Foo", 2598 description: "trait Foo<T>",
2609 }, 2599 },
2610 }, 2600 },
2611 HoverGotoTypeData { 2601 HoverGotoTypeData {
@@ -2702,7 +2692,7 @@ fn main() { let s$0t = foo(); }
2702 focus_range: 6..9, 2692 focus_range: 6..9,
2703 name: "Foo", 2693 name: "Foo",
2704 kind: Trait, 2694 kind: Trait,
2705 description: "trait Foo", 2695 description: "trait Foo<T>",
2706 }, 2696 },
2707 }, 2697 },
2708 HoverGotoTypeData { 2698 HoverGotoTypeData {
@@ -2715,7 +2705,7 @@ fn main() { let s$0t = foo(); }
2715 focus_range: 22..25, 2705 focus_range: 22..25,
2716 name: "Bar", 2706 name: "Bar",
2717 kind: Trait, 2707 kind: Trait,
2718 description: "trait Bar", 2708 description: "trait Bar<T>",
2719 }, 2709 },
2720 }, 2710 },
2721 HoverGotoTypeData { 2711 HoverGotoTypeData {
@@ -2819,7 +2809,7 @@ fn foo(ar$0g: &impl Foo + Bar<S>) {}
2819 focus_range: 19..22, 2809 focus_range: 19..22,
2820 name: "Bar", 2810 name: "Bar",
2821 kind: Trait, 2811 kind: Trait,
2822 description: "trait Bar", 2812 description: "trait Bar<T>",
2823 }, 2813 },
2824 }, 2814 },
2825 HoverGotoTypeData { 2815 HoverGotoTypeData {
@@ -2916,7 +2906,7 @@ fn foo(ar$0g: &impl Foo<S>) {}
2916 focus_range: 6..9, 2906 focus_range: 6..9,
2917 name: "Foo", 2907 name: "Foo",
2918 kind: Trait, 2908 kind: Trait,
2919 description: "trait Foo", 2909 description: "trait Foo<T>",
2920 }, 2910 },
2921 }, 2911 },
2922 HoverGotoTypeData { 2912 HoverGotoTypeData {
@@ -2966,7 +2956,7 @@ fn main() { let s$0t = foo(); }
2966 focus_range: 49..50, 2956 focus_range: 49..50,
2967 name: "B", 2957 name: "B",
2968 kind: Struct, 2958 kind: Struct,
2969 description: "struct B", 2959 description: "struct B<T>",
2970 }, 2960 },
2971 }, 2961 },
2972 HoverGotoTypeData { 2962 HoverGotoTypeData {
@@ -3042,7 +3032,7 @@ fn foo(ar$0g: &dyn Foo<S>) {}
3042 focus_range: 6..9, 3032 focus_range: 6..9,
3043 name: "Foo", 3033 name: "Foo",
3044 kind: Trait, 3034 kind: Trait,
3045 description: "trait Foo", 3035 description: "trait Foo<T>",
3046 }, 3036 },
3047 }, 3037 },
3048 HoverGotoTypeData { 3038 HoverGotoTypeData {
@@ -3090,7 +3080,7 @@ fn foo(a$0rg: &impl ImplTrait<B<dyn DynTrait<B<S>>>>) {}
3090 focus_range: 6..15, 3080 focus_range: 6..15,
3091 name: "ImplTrait", 3081 name: "ImplTrait",
3092 kind: Trait, 3082 kind: Trait,
3093 description: "trait ImplTrait", 3083 description: "trait ImplTrait<T>",
3094 }, 3084 },
3095 }, 3085 },
3096 HoverGotoTypeData { 3086 HoverGotoTypeData {
@@ -3103,7 +3093,7 @@ fn foo(a$0rg: &impl ImplTrait<B<dyn DynTrait<B<S>>>>) {}
3103 focus_range: 50..51, 3093 focus_range: 50..51,
3104 name: "B", 3094 name: "B",
3105 kind: Struct, 3095 kind: Struct,
3106 description: "struct B", 3096 description: "struct B<T>",
3107 }, 3097 },
3108 }, 3098 },
3109 HoverGotoTypeData { 3099 HoverGotoTypeData {
@@ -3116,7 +3106,7 @@ fn foo(a$0rg: &impl ImplTrait<B<dyn DynTrait<B<S>>>>) {}
3116 focus_range: 28..36, 3106 focus_range: 28..36,
3117 name: "DynTrait", 3107 name: "DynTrait",
3118 kind: Trait, 3108 kind: Trait,
3119 description: "trait DynTrait", 3109 description: "trait DynTrait<T>",
3120 }, 3110 },
3121 }, 3111 },
3122 HoverGotoTypeData { 3112 HoverGotoTypeData {
@@ -3582,6 +3572,17 @@ mod foo$0;
3582"#, 3572"#,
3583 expect![[r#" 3573 expect![[r#"
3584 *foo* 3574 *foo*
3575
3576 ```rust
3577 test
3578 ```
3579
3580 ```rust
3581 mod foo
3582 ```
3583
3584 ---
3585
3585 For the horde! 3586 For the horde!
3586 "#]], 3587 "#]],
3587 ); 3588 );
@@ -3606,7 +3607,7 @@ use foo::bar::{self$0};
3606 ``` 3607 ```
3607 3608
3608 ```rust 3609 ```rust
3609 pub mod bar 3610 mod bar
3610 ``` 3611 ```
3611 3612
3612 --- 3613 ---
@@ -3657,4 +3658,43 @@ cosnt _: &str$0 = ""; }"#;
3657 "#]], 3658 "#]],
3658 ); 3659 );
3659 } 3660 }
3661
3662 #[test]
3663 fn hover_macro_expanded_function() {
3664 check(
3665 r#"
3666struct S<'a, T>(&'a T);
3667trait Clone {}
3668macro_rules! foo {
3669 () => {
3670 fn bar<'t, T: Clone + 't>(s: &mut S<'t, T>, t: u32) -> *mut u32 where
3671 't: 't + 't,
3672 for<'a> T: Clone + 'a
3673 { 0 as _ }
3674 };
3675}
3676
3677foo!();
3678
3679fn main() {
3680 bar$0;
3681}
3682"#,
3683 expect![[r#"
3684 *bar*
3685
3686 ```rust
3687 test
3688 ```
3689
3690 ```rust
3691 fn bar<'t, T>(s: &mut S<'t, T>, t: u32) -> *mut u32
3692 where
3693 T: Clone + 't,
3694 't: 't + 't,
3695 for<'a> T: Clone + 'a,
3696 ```
3697 "#]],
3698 )
3699 }
3660} 3700}
diff --git a/crates/ide/src/join_lines.rs b/crates/ide/src/join_lines.rs
index d571ed559..4b25135cd 100644
--- a/crates/ide/src/join_lines.rs
+++ b/crates/ide/src/join_lines.rs
@@ -32,29 +32,35 @@ pub(crate) fn join_lines(file: &SourceFile, range: TextRange) -> TextEdit {
32 range 32 range
33 }; 33 };
34 34
35 let node = match file.syntax().covering_element(range) {
36 NodeOrToken::Node(node) => node,
37 NodeOrToken::Token(token) => token.parent(),
38 };
39 let mut edit = TextEdit::builder(); 35 let mut edit = TextEdit::builder();
40 for token in node.descendants_with_tokens().filter_map(|it| it.into_token()) { 36 match file.syntax().covering_element(range) {
41 let range = match range.intersect(token.text_range()) { 37 NodeOrToken::Node(node) => {
42 Some(range) => range, 38 for token in node.descendants_with_tokens().filter_map(|it| it.into_token()) {
43 None => continue, 39 remove_newlines(&mut edit, &token, range)
44 } - token.text_range().start();
45 let text = token.text();
46 for (pos, _) in text[range].bytes().enumerate().filter(|&(_, b)| b == b'\n') {
47 let pos: TextSize = (pos as u32).into();
48 let offset = token.text_range().start() + range.start() + pos;
49 if !edit.invalidates_offset(offset) {
50 remove_newline(&mut edit, &token, offset);
51 } 40 }
52 } 41 }
53 } 42 NodeOrToken::Token(token) => remove_newlines(&mut edit, &token, range),
54 43 };
55 edit.finish() 44 edit.finish()
56} 45}
57 46
47fn remove_newlines(edit: &mut TextEditBuilder, token: &SyntaxToken, range: TextRange) {
48 let intersection = match range.intersect(token.text_range()) {
49 Some(range) => range,
50 None => return,
51 };
52
53 let range = intersection - token.text_range().start();
54 let text = token.text();
55 for (pos, _) in text[range].bytes().enumerate().filter(|&(_, b)| b == b'\n') {
56 let pos: TextSize = (pos as u32).into();
57 let offset = token.text_range().start() + range.start() + pos;
58 if !edit.invalidates_offset(offset) {
59 remove_newline(edit, &token, offset);
60 }
61 }
62}
63
58fn remove_newline(edit: &mut TextEditBuilder, token: &SyntaxToken, offset: TextSize) { 64fn remove_newline(edit: &mut TextEditBuilder, token: &SyntaxToken, offset: TextSize) {
59 if token.kind() != WHITESPACE || token.text().bytes().filter(|&b| b == b'\n').count() != 1 { 65 if token.kind() != WHITESPACE || token.text().bytes().filter(|&b| b == b'\n').count() != 1 {
60 let mut string_open_quote = false; 66 let mut string_open_quote = false;
@@ -148,7 +154,7 @@ fn has_comma_after(node: &SyntaxNode) -> bool {
148} 154}
149 155
150fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> { 156fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
151 let block_expr = ast::BlockExpr::cast(token.parent())?; 157 let block_expr = ast::BlockExpr::cast(token.parent()?)?;
152 if !block_expr.is_standalone() { 158 if !block_expr.is_standalone() {
153 return None; 159 return None;
154 } 160 }
@@ -170,7 +176,7 @@ fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Op
170} 176}
171 177
172fn join_single_use_tree(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> { 178fn join_single_use_tree(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
173 let use_tree_list = ast::UseTreeList::cast(token.parent())?; 179 let use_tree_list = ast::UseTreeList::cast(token.parent()?)?;
174 let (tree,) = use_tree_list.use_trees().collect_tuple()?; 180 let (tree,) = use_tree_list.use_trees().collect_tuple()?;
175 edit.replace(use_tree_list.syntax().text_range(), tree.syntax().text().to_string()); 181 edit.replace(use_tree_list.syntax().text_range(), tree.syntax().text().to_string());
176 Some(()) 182 Some(())
diff --git a/crates/ide/src/matching_brace.rs b/crates/ide/src/matching_brace.rs
index 000c412d9..4241a6dac 100644
--- a/crates/ide/src/matching_brace.rs
+++ b/crates/ide/src/matching_brace.rs
@@ -25,7 +25,7 @@ pub(crate) fn matching_brace(file: &SourceFile, offset: TextSize) -> Option<Text
25 Some((node, idx)) 25 Some((node, idx))
26 }) 26 })
27 .next()?; 27 .next()?;
28 let parent = brace_token.parent(); 28 let parent = brace_token.parent()?;
29 if brace_token.kind() == T![|] && !ast::ParamList::can_cast(parent.kind()) { 29 if brace_token.kind() == T![|] && !ast::ParamList::can_cast(parent.kind()) {
30 cov_mark::hit!(pipes_not_braces); 30 cov_mark::hit!(pipes_not_braces);
31 return None; 31 return None;
diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs
index ec7c7686d..379674530 100644
--- a/crates/ide/src/references.rs
+++ b/crates/ide/src/references.rs
@@ -148,14 +148,15 @@ fn decl_access(def: &Definition, syntax: &SyntaxNode, range: TextRange) -> Optio
148 148
149fn get_name_of_item_declaration(syntax: &SyntaxNode, position: FilePosition) -> Option<ast::Name> { 149fn get_name_of_item_declaration(syntax: &SyntaxNode, position: FilePosition) -> Option<ast::Name> {
150 let token = syntax.token_at_offset(position.offset).right_biased()?; 150 let token = syntax.token_at_offset(position.offset).right_biased()?;
151 let token_parent = token.parent()?;
151 let kind = token.kind(); 152 let kind = token.kind();
152 if kind == T![;] { 153 if kind == T![;] {
153 ast::Struct::cast(token.parent()) 154 ast::Struct::cast(token_parent)
154 .filter(|struct_| struct_.field_list().is_none()) 155 .filter(|struct_| struct_.field_list().is_none())
155 .and_then(|struct_| struct_.name()) 156 .and_then(|struct_| struct_.name())
156 } else if kind == T!['{'] { 157 } else if kind == T!['{'] {
157 match_ast! { 158 match_ast! {
158 match (token.parent()) { 159 match token_parent {
159 ast::RecordFieldList(rfl) => match_ast! { 160 ast::RecordFieldList(rfl) => match_ast! {
160 match (rfl.syntax().parent()?) { 161 match (rfl.syntax().parent()?) {
161 ast::Variant(it) => it.name(), 162 ast::Variant(it) => it.name(),
@@ -169,7 +170,7 @@ fn get_name_of_item_declaration(syntax: &SyntaxNode, position: FilePosition) ->
169 } 170 }
170 } 171 }
171 } else if kind == T!['('] { 172 } else if kind == T!['('] {
172 let tfl = ast::TupleFieldList::cast(token.parent())?; 173 let tfl = ast::TupleFieldList::cast(token_parent)?;
173 match_ast! { 174 match_ast! {
174 match (tfl.syntax().parent()?) { 175 match (tfl.syntax().parent()?) {
175 ast::Variant(it) => it.name(), 176 ast::Variant(it) => it.name(),
@@ -1270,4 +1271,27 @@ fn foo(_: bool) -> bo$0ol { true }
1270 "#]], 1271 "#]],
1271 ); 1272 );
1272 } 1273 }
1274
1275 #[test]
1276 fn test_transitive() {
1277 check(
1278 r#"
1279//- /level3.rs new_source_root: crate:level3
1280pub struct Fo$0o;
1281//- /level2.rs new_source_root: crate:level2 deps:level3
1282pub use level3::Foo;
1283//- /level1.rs new_source_root: crate:level1 deps:level2
1284pub use level2::Foo;
1285//- /level0.rs new_source_root: crate:level0 deps:level1
1286pub use level1::Foo;
1287"#,
1288 expect![[r#"
1289 Foo Struct FileId(0) 0..15 11..14
1290
1291 FileId(1) 16..19
1292 FileId(2) 16..19
1293 FileId(3) 16..19
1294 "#]],
1295 );
1296 }
1273} 1297}
diff --git a/crates/ide/src/runnables.rs b/crates/ide/src/runnables.rs
index 0c7a8fbf8..397e2126b 100644
--- a/crates/ide/src/runnables.rs
+++ b/crates/ide/src/runnables.rs
@@ -167,8 +167,7 @@ fn find_related_tests(
167 let functions = refs.iter().filter_map(|(range, _)| { 167 let functions = refs.iter().filter_map(|(range, _)| {
168 let token = file.token_at_offset(range.start()).next()?; 168 let token = file.token_at_offset(range.start()).next()?;
169 let token = sema.descend_into_macros(token); 169 let token = sema.descend_into_macros(token);
170 let syntax = token.parent(); 170 token.ancestors().find_map(ast::Fn::cast)
171 syntax.ancestors().find_map(ast::Fn::cast)
172 }); 171 });
173 172
174 for fn_def in functions { 173 for fn_def in functions {
diff --git a/crates/ide/src/syntax_highlighting.rs b/crates/ide/src/syntax_highlighting.rs
index 9bed329d8..870146d24 100644
--- a/crates/ide/src/syntax_highlighting.rs
+++ b/crates/ide/src/syntax_highlighting.rs
@@ -64,7 +64,7 @@ pub(crate) fn highlight(
64 Some(range) => { 64 Some(range) => {
65 let node = match source_file.syntax().covering_element(range) { 65 let node = match source_file.syntax().covering_element(range) {
66 NodeOrToken::Node(it) => it, 66 NodeOrToken::Node(it) => it,
67 NodeOrToken::Token(it) => it.parent(), 67 NodeOrToken::Token(it) => it.parent().unwrap(),
68 }; 68 };
69 (node, range) 69 (node, range)
70 } 70 }
@@ -167,16 +167,19 @@ fn traverse(
167 let element_to_highlight = if current_macro_call.is_some() && element.kind() != COMMENT { 167 let element_to_highlight = if current_macro_call.is_some() && element.kind() != COMMENT {
168 // Inside a macro -- expand it first 168 // Inside a macro -- expand it first
169 let token = match element.clone().into_token() { 169 let token = match element.clone().into_token() {
170 Some(it) if it.parent().kind() == TOKEN_TREE => it, 170 Some(it) if it.parent().map_or(false, |it| it.kind() == TOKEN_TREE) => it,
171 _ => continue, 171 _ => continue,
172 }; 172 };
173 let token = sema.descend_into_macros(token.clone()); 173 let token = sema.descend_into_macros(token.clone());
174 let parent = token.parent(); 174 match token.parent() {
175 175 Some(parent) => {
176 // We only care Name and Name_ref 176 // We only care Name and Name_ref
177 match (token.kind(), parent.kind()) { 177 match (token.kind(), parent.kind()) {
178 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(), 178 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
179 _ => token.into(), 179 _ => token.into(),
180 }
181 }
182 None => token.into(),
180 } 183 }
181 } else { 184 } else {
182 element.clone() 185 element.clone()
diff --git a/crates/ide/src/syntax_highlighting/format.rs b/crates/ide/src/syntax_highlighting/format.rs
index 8c67a0863..e503abc93 100644
--- a/crates/ide/src/syntax_highlighting/format.rs
+++ b/crates/ide/src/syntax_highlighting/format.rs
@@ -28,7 +28,7 @@ pub(super) fn highlight_format_string(
28} 28}
29 29
30fn is_format_string(string: &ast::String) -> Option<()> { 30fn is_format_string(string: &ast::String) -> Option<()> {
31 let parent = string.syntax().parent(); 31 let parent = string.syntax().parent()?;
32 32
33 let name = parent.parent().and_then(ast::MacroCall::cast)?.path()?.segment()?.name_ref()?; 33 let name = parent.parent().and_then(ast::MacroCall::cast)?.path()?.segment()?.name_ref()?;
34 if !matches!(name.text(), "format_args" | "format_args_nl") { 34 if !matches!(name.text(), "format_args" | "format_args_nl") {
diff --git a/crates/ide/src/syntax_tree.rs b/crates/ide/src/syntax_tree.rs
index f979ba434..8979de528 100644
--- a/crates/ide/src/syntax_tree.rs
+++ b/crates/ide/src/syntax_tree.rs
@@ -27,7 +27,7 @@ pub(crate) fn syntax_tree(
27 if let Some(tree) = syntax_tree_for_string(&token, text_range) { 27 if let Some(tree) = syntax_tree_for_string(&token, text_range) {
28 return tree; 28 return tree;
29 } 29 }
30 token.parent() 30 token.parent().unwrap()
31 } 31 }
32 }; 32 };
33 33
diff --git a/crates/ide/src/typing.rs b/crates/ide/src/typing.rs
index a718faf63..e10b7d98e 100644
--- a/crates/ide/src/typing.rs
+++ b/crates/ide/src/typing.rs
@@ -108,7 +108,7 @@ fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
108 }; 108 };
109 let current_indent_len = TextSize::of(current_indent); 109 let current_indent_len = TextSize::of(current_indent);
110 110
111 let parent = whitespace.syntax().parent(); 111 let parent = whitespace.syntax().parent()?;
112 // Make sure dot is a part of call chain 112 // Make sure dot is a part of call chain
113 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) { 113 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) {
114 return None; 114 return None;
diff --git a/crates/ide_assists/src/handlers/add_turbo_fish.rs b/crates/ide_assists/src/handlers/add_turbo_fish.rs
index ee879c151..436767895 100644
--- a/crates/ide_assists/src/handlers/add_turbo_fish.rs
+++ b/crates/ide_assists/src/handlers/add_turbo_fish.rs
@@ -38,7 +38,7 @@ pub(crate) fn add_turbo_fish(acc: &mut Assists, ctx: &AssistContext) -> Option<(
38 cov_mark::hit!(add_turbo_fish_one_fish_is_enough); 38 cov_mark::hit!(add_turbo_fish_one_fish_is_enough);
39 return None; 39 return None;
40 } 40 }
41 let name_ref = ast::NameRef::cast(ident.parent())?; 41 let name_ref = ast::NameRef::cast(ident.parent()?)?;
42 let def = match NameRefClass::classify(&ctx.sema, &name_ref)? { 42 let def = match NameRefClass::classify(&ctx.sema, &name_ref)? {
43 NameRefClass::Definition(def) => def, 43 NameRefClass::Definition(def) => def,
44 NameRefClass::ExternCrate(_) | NameRefClass::FieldShorthand { .. } => return None, 44 NameRefClass::ExternCrate(_) | NameRefClass::FieldShorthand { .. } => return None,
diff --git a/crates/ide_assists/src/handlers/change_visibility.rs b/crates/ide_assists/src/handlers/change_visibility.rs
index ec99a5505..d7e39b2ae 100644
--- a/crates/ide_assists/src/handlers/change_visibility.rs
+++ b/crates/ide_assists/src/handlers/change_visibility.rs
@@ -41,7 +41,7 @@ fn add_vis(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
41 }); 41 });
42 42
43 let (offset, target) = if let Some(keyword) = item_keyword { 43 let (offset, target) = if let Some(keyword) = item_keyword {
44 let parent = keyword.parent(); 44 let parent = keyword.parent()?;
45 let def_kws = vec![CONST, STATIC, TYPE_ALIAS, FN, MODULE, STRUCT, ENUM, TRAIT]; 45 let def_kws = vec![CONST, STATIC, TYPE_ALIAS, FN, MODULE, STRUCT, ENUM, TRAIT];
46 // Parent is not a definition, can't add visibility 46 // Parent is not a definition, can't add visibility
47 if !def_kws.iter().any(|&def_kw| def_kw == parent.kind()) { 47 if !def_kws.iter().any(|&def_kw| def_kw == parent.kind()) {
diff --git a/crates/ide_assists/src/handlers/expand_glob_import.rs b/crates/ide_assists/src/handlers/expand_glob_import.rs
index 5fe617ba4..5b540df5c 100644
--- a/crates/ide_assists/src/handlers/expand_glob_import.rs
+++ b/crates/ide_assists/src/handlers/expand_glob_import.rs
@@ -48,7 +48,7 @@ pub(crate) fn expand_glob_import(acc: &mut Assists, ctx: &AssistContext) -> Opti
48 _ => return None, 48 _ => return None,
49 }; 49 };
50 50
51 let current_scope = ctx.sema.scope(&star.parent()); 51 let current_scope = ctx.sema.scope(&star.parent()?);
52 let current_module = current_scope.module()?; 52 let current_module = current_scope.module()?;
53 53
54 let refs_in_target = find_refs_in_mod(ctx, target_module, Some(current_module))?; 54 let refs_in_target = find_refs_in_mod(ctx, target_module, Some(current_module))?;
diff --git a/crates/ide_assists/src/handlers/extract_function.rs b/crates/ide_assists/src/handlers/extract_function.rs
index dd4501709..5fdc8bf38 100644
--- a/crates/ide_assists/src/handlers/extract_function.rs
+++ b/crates/ide_assists/src/handlers/extract_function.rs
@@ -16,7 +16,6 @@ use syntax::{
16 edit::{AstNodeEdit, IndentLevel}, 16 edit::{AstNodeEdit, IndentLevel},
17 AstNode, 17 AstNode,
18 }, 18 },
19 SyntaxElement,
20 SyntaxKind::{self, BLOCK_EXPR, BREAK_EXPR, COMMENT, PATH_EXPR, RETURN_EXPR}, 19 SyntaxKind::{self, BLOCK_EXPR, BREAK_EXPR, COMMENT, PATH_EXPR, RETURN_EXPR},
21 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T, 20 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T,
22}; 21};
@@ -62,7 +61,10 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option
62 return None; 61 return None;
63 } 62 }
64 63
65 let node = element_to_node(node); 64 let node = match node {
65 syntax::NodeOrToken::Node(n) => n,
66 syntax::NodeOrToken::Token(t) => t.parent()?,
67 };
66 68
67 let body = extraction_target(&node, ctx.frange.range)?; 69 let body = extraction_target(&node, ctx.frange.range)?;
68 70
@@ -560,14 +562,6 @@ impl HasTokenAtOffset for FunctionBody {
560 } 562 }
561} 563}
562 564
563/// node or token's parent
564fn element_to_node(node: SyntaxElement) -> SyntaxNode {
565 match node {
566 syntax::NodeOrToken::Node(n) => n,
567 syntax::NodeOrToken::Token(t) => t.parent(),
568 }
569}
570
571/// Try to guess what user wants to extract 565/// Try to guess what user wants to extract
572/// 566///
573/// We have basically have two cases: 567/// We have basically have two cases:
@@ -1246,7 +1240,7 @@ fn make_body(
1246 }) 1240 })
1247 } 1241 }
1248 FlowHandler::If { .. } => { 1242 FlowHandler::If { .. } => {
1249 let lit_false = ast::Literal::cast(make::tokens::literal("false").parent()).unwrap(); 1243 let lit_false = make::expr_literal("false");
1250 with_tail_expr(block, lit_false.into()) 1244 with_tail_expr(block, lit_false.into())
1251 } 1245 }
1252 FlowHandler::IfOption { .. } => { 1246 FlowHandler::IfOption { .. } => {
@@ -1420,9 +1414,7 @@ fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) -> S
1420fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> { 1414fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1421 let value = match handler { 1415 let value = match handler {
1422 FlowHandler::None | FlowHandler::Try { .. } => return None, 1416 FlowHandler::None | FlowHandler::Try { .. } => return None,
1423 FlowHandler::If { .. } => { 1417 FlowHandler::If { .. } => make::expr_literal("true").into(),
1424 ast::Literal::cast(make::tokens::literal("true").parent()).unwrap().into()
1425 }
1426 FlowHandler::IfOption { .. } => { 1418 FlowHandler::IfOption { .. } => {
1427 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new())); 1419 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1428 let args = make::arg_list(iter::once(expr)); 1420 let args = make::arg_list(iter::once(expr));
diff --git a/crates/ide_assists/src/handlers/flip_trait_bound.rs b/crates/ide_assists/src/handlers/flip_trait_bound.rs
index d419d263e..a868aa43d 100644
--- a/crates/ide_assists/src/handlers/flip_trait_bound.rs
+++ b/crates/ide_assists/src/handlers/flip_trait_bound.rs
@@ -23,7 +23,7 @@ pub(crate) fn flip_trait_bound(acc: &mut Assists, ctx: &AssistContext) -> Option
23 let plus = ctx.find_token_syntax_at_offset(T![+])?; 23 let plus = ctx.find_token_syntax_at_offset(T![+])?;
24 24
25 // Make sure we're in a `TypeBoundList` 25 // Make sure we're in a `TypeBoundList`
26 if ast::TypeBoundList::cast(plus.parent()).is_none() { 26 if ast::TypeBoundList::cast(plus.parent()?).is_none() {
27 return None; 27 return None;
28 } 28 }
29 29
diff --git a/crates/ide_assists/src/handlers/generate_is_empty_from_len.rs b/crates/ide_assists/src/handlers/generate_is_empty_from_len.rs
index aa7072f25..b8834d283 100644
--- a/crates/ide_assists/src/handlers/generate_is_empty_from_len.rs
+++ b/crates/ide_assists/src/handlers/generate_is_empty_from_len.rs
@@ -1,7 +1,7 @@
1use hir::{known, HasSource, Name}; 1use hir::{known, HasSource, Name};
2use syntax::{ 2use syntax::{
3 ast::{self, NameOwner}, 3 ast::{self, NameOwner},
4 AstNode, TextRange, 4 AstNode,
5}; 5};
6 6
7use crate::{ 7use crate::{
@@ -51,12 +51,19 @@ pub(crate) fn generate_is_empty_from_len(acc: &mut Assists, ctx: &AssistContext)
51 } 51 }
52 52
53 let impl_ = fn_node.syntax().ancestors().find_map(ast::Impl::cast)?; 53 let impl_ = fn_node.syntax().ancestors().find_map(ast::Impl::cast)?;
54 let len_fn = get_impl_method(ctx, &impl_, &known::len)?;
55 if !len_fn.ret_type(ctx.sema.db).is_usize() {
56 cov_mark::hit!(len_fn_different_return_type);
57 return None;
58 }
59
54 if get_impl_method(ctx, &impl_, &known::is_empty).is_some() { 60 if get_impl_method(ctx, &impl_, &known::is_empty).is_some() {
55 cov_mark::hit!(is_empty_already_implemented); 61 cov_mark::hit!(is_empty_already_implemented);
56 return None; 62 return None;
57 } 63 }
58 64
59 let range = get_text_range_of_len_function(ctx, &impl_)?; 65 let node = len_fn.source(ctx.sema.db)?;
66 let range = node.syntax().value.text_range();
60 67
61 acc.add( 68 acc.add(
62 AssistId("generate_is_empty_from_len", AssistKind::Generate), 69 AssistId("generate_is_empty_from_len", AssistKind::Generate),
@@ -89,13 +96,6 @@ fn get_impl_method(
89 ty.iterate_method_candidates(db, krate, &traits_in_scope, Some(fn_name), |_, func| Some(func)) 96 ty.iterate_method_candidates(db, krate, &traits_in_scope, Some(fn_name), |_, func| Some(func))
90} 97}
91 98
92fn get_text_range_of_len_function(ctx: &AssistContext, impl_: &ast::Impl) -> Option<TextRange> {
93 let db = ctx.sema.db;
94 let func = get_impl_method(ctx, impl_, &known::len)?;
95 let node = func.source(db)?;
96 Some(node.syntax().value.text_range())
97}
98
99#[cfg(test)] 99#[cfg(test)]
100mod tests { 100mod tests {
101 use crate::tests::{check_assist, check_assist_not_applicable}; 101 use crate::tests::{check_assist, check_assist_not_applicable};
@@ -158,6 +158,23 @@ impl MyStruct {
158 } 158 }
159 159
160 #[test] 160 #[test]
161 fn len_fn_different_return_type() {
162 cov_mark::check!(len_fn_different_return_type);
163 check_assist_not_applicable(
164 generate_is_empty_from_len,
165 r#"
166struct MyStruct { data: Vec<String> }
167
168impl MyStruct {
169 p$0ub fn len(&self) -> u32 {
170 self.data.len()
171 }
172}
173"#,
174 );
175 }
176
177 #[test]
161 fn generate_is_empty() { 178 fn generate_is_empty() {
162 check_assist( 179 check_assist(
163 generate_is_empty_from_len, 180 generate_is_empty_from_len,
diff --git a/crates/ide_assists/src/handlers/invert_if.rs b/crates/ide_assists/src/handlers/invert_if.rs
index b131dc205..53612ec3f 100644
--- a/crates/ide_assists/src/handlers/invert_if.rs
+++ b/crates/ide_assists/src/handlers/invert_if.rs
@@ -30,7 +30,7 @@ use crate::{
30 30
31pub(crate) fn invert_if(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { 31pub(crate) fn invert_if(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
32 let if_keyword = ctx.find_token_syntax_at_offset(T![if])?; 32 let if_keyword = ctx.find_token_syntax_at_offset(T![if])?;
33 let expr = ast::IfExpr::cast(if_keyword.parent())?; 33 let expr = ast::IfExpr::cast(if_keyword.parent()?)?;
34 let if_range = if_keyword.text_range(); 34 let if_range = if_keyword.text_range();
35 let cursor_in_range = if_range.contains_range(ctx.frange.range); 35 let cursor_in_range = if_range.contains_range(ctx.frange.range);
36 if !cursor_in_range { 36 if !cursor_in_range {
diff --git a/crates/ide_assists/src/handlers/move_bounds.rs b/crates/ide_assists/src/handlers/move_bounds.rs
index cf260c6f8..9ad0c9816 100644
--- a/crates/ide_assists/src/handlers/move_bounds.rs
+++ b/crates/ide_assists/src/handlers/move_bounds.rs
@@ -1,8 +1,6 @@
1use syntax::{ 1use syntax::{
2 ast::{self, edit::AstNodeEdit, make, AstNode, NameOwner, TypeBoundsOwner}, 2 ast::{self, edit_in_place::GenericParamsOwnerEdit, make, AstNode, NameOwner, TypeBoundsOwner},
3 match_ast, 3 match_ast,
4 SyntaxKind::*,
5 T,
6}; 4};
7 5
8use crate::{AssistContext, AssistId, AssistKind, Assists}; 6use crate::{AssistContext, AssistId, AssistKind, Assists};
@@ -23,7 +21,7 @@ use crate::{AssistContext, AssistId, AssistKind, Assists};
23// } 21// }
24// ``` 22// ```
25pub(crate) fn move_bounds_to_where_clause(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { 23pub(crate) fn move_bounds_to_where_clause(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
26 let type_param_list = ctx.find_node_at_offset::<ast::GenericParamList>()?; 24 let type_param_list = ctx.find_node_at_offset::<ast::GenericParamList>()?.clone_for_update();
27 25
28 let mut type_params = type_param_list.type_params(); 26 let mut type_params = type_param_list.type_params();
29 if type_params.all(|p| p.type_bound_list().is_none()) { 27 if type_params.all(|p| p.type_bound_list().is_none()) {
@@ -31,23 +29,7 @@ pub(crate) fn move_bounds_to_where_clause(acc: &mut Assists, ctx: &AssistContext
31 } 29 }
32 30
33 let parent = type_param_list.syntax().parent()?; 31 let parent = type_param_list.syntax().parent()?;
34 if parent.children_with_tokens().any(|it| it.kind() == WHERE_CLAUSE) { 32 let original_parent_range = parent.text_range();
35 return None;
36 }
37
38 let anchor = match_ast! {
39 match parent {
40 ast::Fn(it) => it.body()?.syntax().clone().into(),
41 ast::Trait(it) => it.assoc_item_list()?.syntax().clone().into(),
42 ast::Impl(it) => it.assoc_item_list()?.syntax().clone().into(),
43 ast::Enum(it) => it.variant_list()?.syntax().clone().into(),
44 ast::Struct(it) => {
45 it.syntax().children_with_tokens()
46 .find(|it| it.kind() == RECORD_FIELD_LIST || it.kind() == T![;])?
47 },
48 _ => return None
49 }
50 };
51 33
52 let target = type_param_list.syntax().text_range(); 34 let target = type_param_list.syntax().text_range();
53 acc.add( 35 acc.add(
@@ -55,29 +37,27 @@ pub(crate) fn move_bounds_to_where_clause(acc: &mut Assists, ctx: &AssistContext
55 "Move to where clause", 37 "Move to where clause",
56 target, 38 target,
57 |edit| { 39 |edit| {
58 let new_params = type_param_list 40 let where_clause: ast::WhereClause = match_ast! {
59 .type_params() 41 match parent {
60 .filter(|it| it.type_bound_list().is_some()) 42 ast::Fn(it) => it.get_or_create_where_clause(),
61 .map(|type_param| { 43 ast::Trait(it) => it.get_or_create_where_clause(),
62 let without_bounds = type_param.remove_bounds(); 44 ast::Impl(it) => it.get_or_create_where_clause(),
63 (type_param, without_bounds) 45 ast::Enum(it) => it.get_or_create_where_clause(),
64 }); 46 ast::Struct(it) => it.get_or_create_where_clause(),
65 47 _ => return,
66 let new_type_param_list = type_param_list.replace_descendants(new_params); 48 }
67 edit.replace_ast(type_param_list.clone(), new_type_param_list);
68
69 let where_clause = {
70 let predicates = type_param_list.type_params().filter_map(build_predicate);
71 make::where_clause(predicates)
72 }; 49 };
73 50
74 let to_insert = match anchor.prev_sibling_or_token() { 51 for type_param in type_param_list.type_params() {
75 Some(ref elem) if elem.kind() == WHITESPACE => { 52 if let Some(tbl) = type_param.type_bound_list() {
76 format!("{} ", where_clause.syntax()) 53 if let Some(predicate) = build_predicate(type_param.clone()) {
54 where_clause.add_predicate(predicate.clone_for_update())
55 }
56 tbl.remove()
77 } 57 }
78 _ => format!(" {}", where_clause.syntax()), 58 }
79 }; 59
80 edit.insert(anchor.text_range().start(), to_insert); 60 edit.replace(original_parent_range, parent.to_string())
81 }, 61 },
82 ) 62 )
83} 63}
@@ -102,12 +82,8 @@ mod tests {
102 fn move_bounds_to_where_clause_fn() { 82 fn move_bounds_to_where_clause_fn() {
103 check_assist( 83 check_assist(
104 move_bounds_to_where_clause, 84 move_bounds_to_where_clause,
105 r#" 85 r#"fn foo<T: u32, $0F: FnOnce(T) -> T>() {}"#,
106 fn foo<T: u32, $0F: FnOnce(T) -> T>() {} 86 r#"fn foo<T, F>() where T: u32, F: FnOnce(T) -> T {}"#,
107 "#,
108 r#"
109 fn foo<T, F>() where T: u32, F: FnOnce(T) -> T {}
110 "#,
111 ); 87 );
112 } 88 }
113 89
@@ -115,12 +91,8 @@ mod tests {
115 fn move_bounds_to_where_clause_impl() { 91 fn move_bounds_to_where_clause_impl() {
116 check_assist( 92 check_assist(
117 move_bounds_to_where_clause, 93 move_bounds_to_where_clause,
118 r#" 94 r#"impl<U: u32, $0T> A<U, T> {}"#,
119 impl<U: u32, $0T> A<U, T> {} 95 r#"impl<U, T> A<U, T> where U: u32 {}"#,
120 "#,
121 r#"
122 impl<U, T> A<U, T> where U: u32 {}
123 "#,
124 ); 96 );
125 } 97 }
126 98
@@ -128,12 +100,8 @@ mod tests {
128 fn move_bounds_to_where_clause_struct() { 100 fn move_bounds_to_where_clause_struct() {
129 check_assist( 101 check_assist(
130 move_bounds_to_where_clause, 102 move_bounds_to_where_clause,
131 r#" 103 r#"struct A<$0T: Iterator<Item = u32>> {}"#,
132 struct A<$0T: Iterator<Item = u32>> {} 104 r#"struct A<T> where T: Iterator<Item = u32> {}"#,
133 "#,
134 r#"
135 struct A<T> where T: Iterator<Item = u32> {}
136 "#,
137 ); 105 );
138 } 106 }
139 107
@@ -141,12 +109,8 @@ mod tests {
141 fn move_bounds_to_where_clause_tuple_struct() { 109 fn move_bounds_to_where_clause_tuple_struct() {
142 check_assist( 110 check_assist(
143 move_bounds_to_where_clause, 111 move_bounds_to_where_clause,
144 r#" 112 r#"struct Pair<$0T: u32>(T, T);"#,
145 struct Pair<$0T: u32>(T, T); 113 r#"struct Pair<T>(T, T) where T: u32;"#,
146 "#,
147 r#"
148 struct Pair<T>(T, T) where T: u32;
149 "#,
150 ); 114 );
151 } 115 }
152} 116}
diff --git a/crates/ide_assists/src/handlers/split_import.rs b/crates/ide_assists/src/handlers/split_import.rs
index 9319a4267..446f30544 100644
--- a/crates/ide_assists/src/handlers/split_import.rs
+++ b/crates/ide_assists/src/handlers/split_import.rs
@@ -17,7 +17,7 @@ use crate::{AssistContext, AssistId, AssistKind, Assists};
17// ``` 17// ```
18pub(crate) fn split_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { 18pub(crate) fn split_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
19 let colon_colon = ctx.find_token_syntax_at_offset(T![::])?; 19 let colon_colon = ctx.find_token_syntax_at_offset(T![::])?;
20 let path = ast::Path::cast(colon_colon.parent())?.qualifier()?; 20 let path = ast::Path::cast(colon_colon.parent()?)?.qualifier()?;
21 let top_path = successors(Some(path.clone()), |it| it.parent_path()).last()?; 21 let top_path = successors(Some(path.clone()), |it| it.parent_path()).last()?;
22 22
23 let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast)?; 23 let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast)?;
diff --git a/crates/ide_assists/src/handlers/unwrap_block.rs b/crates/ide_assists/src/handlers/unwrap_block.rs
index ed6f6177d..440639322 100644
--- a/crates/ide_assists/src/handlers/unwrap_block.rs
+++ b/crates/ide_assists/src/handlers/unwrap_block.rs
@@ -30,7 +30,7 @@ pub(crate) fn unwrap_block(acc: &mut Assists, ctx: &AssistContext) -> Option<()>
30 let assist_label = "Unwrap block"; 30 let assist_label = "Unwrap block";
31 31
32 let l_curly_token = ctx.find_token_syntax_at_offset(T!['{'])?; 32 let l_curly_token = ctx.find_token_syntax_at_offset(T!['{'])?;
33 let mut block = ast::BlockExpr::cast(l_curly_token.parent())?; 33 let mut block = ast::BlockExpr::cast(l_curly_token.parent()?)?;
34 let target = block.syntax().text_range(); 34 let target = block.syntax().text_range();
35 let mut parent = block.syntax().parent()?; 35 let mut parent = block.syntax().parent()?;
36 if ast::MatchArm::can_cast(parent.kind()) { 36 if ast::MatchArm::can_cast(parent.kind()) {
diff --git a/crates/ide_completion/src/completions/dot.rs b/crates/ide_completion/src/completions/dot.rs
index 5ee9a9f07..cec2d0c3a 100644
--- a/crates/ide_completion/src/completions/dot.rs
+++ b/crates/ide_completion/src/completions/dot.rs
@@ -81,7 +81,7 @@ fn foo(s: S) { s.$0 }
81"#, 81"#,
82 expect![[r#" 82 expect![[r#"
83 fd foo u32 83 fd foo u32
84 me bar() -> () 84 me bar() fn(&self)
85 "#]], 85 "#]],
86 ); 86 );
87 } 87 }
@@ -97,7 +97,7 @@ impl S {
97"#, 97"#,
98 expect![[r#" 98 expect![[r#"
99 fd the_field (u32,) 99 fd the_field (u32,)
100 me foo() -> () 100 me foo() fn(self)
101 "#]], 101 "#]],
102 ) 102 )
103 } 103 }
@@ -113,7 +113,7 @@ impl A {
113"#, 113"#,
114 expect![[r#" 114 expect![[r#"
115 fd the_field (u32, i32) 115 fd the_field (u32, i32)
116 me foo() -> () 116 me foo() fn(&self)
117 "#]], 117 "#]],
118 ) 118 )
119 } 119 }
@@ -163,7 +163,7 @@ mod m {
163fn foo(a: A) { a.$0 } 163fn foo(a: A) { a.$0 }
164"#, 164"#,
165 expect![[r#" 165 expect![[r#"
166 me the_method() -> () 166 me the_method() fn(&self)
167 "#]], 167 "#]],
168 ); 168 );
169 } 169 }
@@ -196,7 +196,7 @@ impl A<i32> {
196fn foo(a: A<u32>) { a.$0 } 196fn foo(a: A<u32>) { a.$0 }
197"#, 197"#,
198 expect![[r#" 198 expect![[r#"
199 me the_method() -> () 199 me the_method() fn(&self)
200 "#]], 200 "#]],
201 ) 201 )
202 } 202 }
@@ -211,7 +211,7 @@ impl Trait for A {}
211fn foo(a: A) { a.$0 } 211fn foo(a: A) { a.$0 }
212"#, 212"#,
213 expect![[r#" 213 expect![[r#"
214 me the_method() -> () 214 me the_method() fn(&self)
215 "#]], 215 "#]],
216 ); 216 );
217 } 217 }
@@ -226,7 +226,7 @@ impl<T> Trait for T {}
226fn foo(a: &A) { a.$0 } 226fn foo(a: &A) { a.$0 }
227", 227",
228 expect![[r#" 228 expect![[r#"
229 me the_method() -> () 229 me the_method() fn(&self)
230 "#]], 230 "#]],
231 ); 231 );
232 } 232 }
@@ -244,7 +244,7 @@ impl Trait for A {}
244fn foo(a: A) { a.$0 } 244fn foo(a: A) { a.$0 }
245", 245",
246 expect![[r#" 246 expect![[r#"
247 me the_method() -> () 247 me the_method() fn(&self)
248 "#]], 248 "#]],
249 ); 249 );
250 } 250 }
@@ -298,7 +298,7 @@ impl T {
298} 298}
299"#, 299"#,
300 expect![[r#" 300 expect![[r#"
301 me blah() -> () 301 me blah() fn(&self)
302 "#]], 302 "#]],
303 ); 303 );
304 } 304 }
@@ -407,7 +407,7 @@ fn foo() {
407} 407}
408"#, 408"#,
409 expect![[r#" 409 expect![[r#"
410 me the_method() -> () 410 me the_method() fn(&self)
411 "#]], 411 "#]],
412 ); 412 );
413 } 413 }
@@ -422,7 +422,7 @@ macro_rules! make_s { () => { S }; }
422fn main() { make_s!().f$0; } 422fn main() { make_s!().f$0; }
423"#, 423"#,
424 expect![[r#" 424 expect![[r#"
425 me foo() -> () 425 me foo() fn(&self)
426 "#]], 426 "#]],
427 ) 427 )
428 } 428 }
@@ -450,7 +450,7 @@ mod foo {
450} 450}
451 "#, 451 "#,
452 expect![[r#" 452 expect![[r#"
453 me private() -> () 453 me private() fn(&self)
454 "#]], 454 "#]],
455 ); 455 );
456 } 456 }
diff --git a/crates/ide_completion/src/completions/flyimport.rs b/crates/ide_completion/src/completions/flyimport.rs
index 391a11c91..08df2df3f 100644
--- a/crates/ide_completion/src/completions/flyimport.rs
+++ b/crates/ide_completion/src/completions/flyimport.rs
@@ -402,7 +402,7 @@ fn main() {
402 check( 402 check(
403 fixture, 403 fixture,
404 expect![[r#" 404 expect![[r#"
405 fn weird_function() (dep::test_mod::TestTrait) -> () 405 fn weird_function() (dep::test_mod::TestTrait) fn()
406 "#]], 406 "#]],
407 ); 407 );
408 408
@@ -495,7 +495,7 @@ fn main() {
495 check( 495 check(
496 fixture, 496 fixture,
497 expect![[r#" 497 expect![[r#"
498 me random_method() (dep::test_mod::TestTrait) -> () 498 me random_method() (dep::test_mod::TestTrait) fn(&self)
499 "#]], 499 "#]],
500 ); 500 );
501 501
@@ -665,7 +665,7 @@ fn main() {
665} 665}
666 "#, 666 "#,
667 expect![[r#" 667 expect![[r#"
668 me random_method() (dep::test_mod::TestTrait) -> () DEPRECATED 668 me random_method() (dep::test_mod::TestTrait) fn(&self) DEPRECATED
669 "#]], 669 "#]],
670 ); 670 );
671 671
@@ -696,7 +696,7 @@ fn main() {
696"#, 696"#,
697 expect![[r#" 697 expect![[r#"
698 ct SPECIAL_CONST (dep::test_mod::TestTrait) DEPRECATED 698 ct SPECIAL_CONST (dep::test_mod::TestTrait) DEPRECATED
699 fn weird_function() (dep::test_mod::TestTrait) -> () DEPRECATED 699 fn weird_function() (dep::test_mod::TestTrait) fn() DEPRECATED
700 "#]], 700 "#]],
701 ); 701 );
702 } 702 }
diff --git a/crates/ide_completion/src/completions/fn_param.rs b/crates/ide_completion/src/completions/fn_param.rs
index 0243dce56..0ea558489 100644
--- a/crates/ide_completion/src/completions/fn_param.rs
+++ b/crates/ide_completion/src/completions/fn_param.rs
@@ -33,7 +33,7 @@ pub(crate) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext)
33 }); 33 });
34 }; 34 };
35 35
36 for node in ctx.token.parent().ancestors() { 36 for node in ctx.token.ancestors() {
37 match_ast! { 37 match_ast! {
38 match node { 38 match node {
39 ast::SourceFile(it) => it.items().filter_map(|item| match item { 39 ast::SourceFile(it) => it.items().filter_map(|item| match item {
diff --git a/crates/ide_completion/src/completions/qualified_path.rs b/crates/ide_completion/src/completions/qualified_path.rs
index df74b739e..105ff6013 100644
--- a/crates/ide_completion/src/completions/qualified_path.rs
+++ b/crates/ide_completion/src/completions/qualified_path.rs
@@ -359,8 +359,8 @@ impl S {
359fn foo() { let _ = S::$0 } 359fn foo() { let _ = S::$0 }
360"#, 360"#,
361 expect![[r#" 361 expect![[r#"
362 fn a() -> () 362 fn a() fn()
363 me b(…) -> () 363 me b(…) fn(&self)
364 ct C const C: i32 = 42; 364 ct C const C: i32 = 42;
365 ta T type T = i32; 365 ta T type T = i32;
366 "#]], 366 "#]],
@@ -387,7 +387,7 @@ mod m {
387fn foo() { let _ = S::$0 } 387fn foo() { let _ = S::$0 }
388"#, 388"#,
389 expect![[r#" 389 expect![[r#"
390 fn public_method() -> () 390 fn public_method() fn()
391 ct PUBLIC_CONST pub(crate) const PUBLIC_CONST: u32 = 1; 391 ct PUBLIC_CONST pub(crate) const PUBLIC_CONST: u32 = 1;
392 ta PublicType pub(crate) type PublicType = u32; 392 ta PublicType pub(crate) type PublicType = u32;
393 "#]], 393 "#]],
@@ -404,7 +404,7 @@ impl E { fn m() { } }
404fn foo() { let _ = E::$0 } 404fn foo() { let _ = E::$0 }
405 "#, 405 "#,
406 expect![[r#" 406 expect![[r#"
407 fn m() -> () 407 fn m() fn()
408 "#]], 408 "#]],
409 ); 409 );
410 } 410 }
@@ -419,7 +419,7 @@ impl U { fn m() { } }
419fn foo() { let _ = U::$0 } 419fn foo() { let _ = U::$0 }
420"#, 420"#,
421 expect![[r#" 421 expect![[r#"
422 fn m() -> () 422 fn m() fn()
423 "#]], 423 "#]],
424 ); 424 );
425 } 425 }
@@ -449,7 +449,7 @@ trait Trait { fn m(); }
449fn foo() { let _ = Trait::$0 } 449fn foo() { let _ = Trait::$0 }
450"#, 450"#,
451 expect![[r#" 451 expect![[r#"
452 fn m() -> () 452 fn m() fn()
453 "#]], 453 "#]],
454 ); 454 );
455 } 455 }
@@ -466,7 +466,7 @@ impl Trait for S {}
466fn foo() { let _ = S::$0 } 466fn foo() { let _ = S::$0 }
467"#, 467"#,
468 expect![[r#" 468 expect![[r#"
469 fn m() -> () 469 fn m() fn()
470 "#]], 470 "#]],
471 ); 471 );
472 } 472 }
@@ -483,7 +483,7 @@ impl Trait for S {}
483fn foo() { let _ = <S as Trait>::$0 } 483fn foo() { let _ = <S as Trait>::$0 }
484"#, 484"#,
485 expect![[r#" 485 expect![[r#"
486 fn m() -> () 486 fn m() fn()
487 "#]], 487 "#]],
488 ); 488 );
489 } 489 }
@@ -512,11 +512,11 @@ fn foo<T: Sub>() { T::$0 }
512 ta SubTy type SubTy; 512 ta SubTy type SubTy;
513 ta Ty type Ty; 513 ta Ty type Ty;
514 ct C2 const C2: (); 514 ct C2 const C2: ();
515 fn subfunc() -> () 515 fn subfunc() fn()
516 me submethod(…) -> () 516 me submethod(…) fn(&self)
517 ct CONST const CONST: u8; 517 ct CONST const CONST: u8;
518 fn func() -> () 518 fn func() fn()
519 me method(…) -> () 519 me method(…) fn(&self)
520 "#]], 520 "#]],
521 ); 521 );
522 } 522 }
@@ -552,11 +552,11 @@ impl<T> Sub for Wrap<T> {
552 ta SubTy type SubTy; 552 ta SubTy type SubTy;
553 ta Ty type Ty; 553 ta Ty type Ty;
554 ct CONST const CONST: u8 = 0; 554 ct CONST const CONST: u8 = 0;
555 fn func() -> () 555 fn func() fn()
556 me method(…) -> () 556 me method(…) fn(&self)
557 ct C2 const C2: () = (); 557 ct C2 const C2: () = ();
558 fn subfunc() -> () 558 fn subfunc() fn()
559 me submethod(…) -> () 559 me submethod(…) fn(&self)
560 "#]], 560 "#]],
561 ); 561 );
562 } 562 }
@@ -573,8 +573,8 @@ impl T { fn bar() {} }
573fn main() { T::$0; } 573fn main() { T::$0; }
574"#, 574"#,
575 expect![[r#" 575 expect![[r#"
576 fn foo() -> () 576 fn foo() fn()
577 fn bar() -> () 577 fn bar() fn()
578 "#]], 578 "#]],
579 ); 579 );
580 } 580 }
@@ -589,7 +589,7 @@ macro_rules! foo { () => {} }
589fn main() { let _ = crate::$0 } 589fn main() { let _ = crate::$0 }
590 "#, 590 "#,
591 expect![[r##" 591 expect![[r##"
592 fn main() -> () 592 fn main() fn()
593 ma foo!(…) #[macro_export] macro_rules! foo 593 ma foo!(…) #[macro_export] macro_rules! foo
594 "##]], 594 "##]],
595 ); 595 );
@@ -633,7 +633,7 @@ mod p {
633"#, 633"#,
634 expect![[r#" 634 expect![[r#"
635 ct RIGHT_CONST 635 ct RIGHT_CONST
636 fn right_fn() -> () 636 fn right_fn() fn()
637 st RightType 637 st RightType
638 "#]], 638 "#]],
639 ); 639 );
@@ -680,8 +680,8 @@ fn main() { m!(self::f$0); }
680fn foo() {} 680fn foo() {}
681"#, 681"#,
682 expect![[r#" 682 expect![[r#"
683 fn main() -> () 683 fn main() fn()
684 fn foo() -> () 684 fn foo() fn()
685 "#]], 685 "#]],
686 ); 686 );
687 } 687 }
@@ -699,7 +699,7 @@ mod m {
699"#, 699"#,
700 expect![[r#" 700 expect![[r#"
701 md z 701 md z
702 fn z() -> () 702 fn z() fn()
703 "#]], 703 "#]],
704 ); 704 );
705 } 705 }
@@ -719,7 +719,7 @@ fn foo() {
719} 719}
720"#, 720"#,
721 expect![[r#" 721 expect![[r#"
722 fn new() -> HashMap<K, V, RandomState> 722 fn new() fn() -> HashMap<K, V, RandomState>
723 "#]], 723 "#]],
724 ); 724 );
725 } 725 }
@@ -752,8 +752,8 @@ fn main() {
752} 752}
753"#, 753"#,
754 expect![[r#" 754 expect![[r#"
755 fn main() -> () 755 fn main() fn()
756 fn foo(…) -> () 756 fn foo(…) fn(i32, i32)
757 "#]], 757 "#]],
758 ); 758 );
759 } 759 }
@@ -776,7 +776,7 @@ impl Foo {
776 expect![[r#" 776 expect![[r#"
777 ev Bar () 777 ev Bar ()
778 ev Baz () 778 ev Baz ()
779 me foo(…) -> () 779 me foo(…) fn(self)
780 "#]], 780 "#]],
781 ); 781 );
782 } 782 }
@@ -800,7 +800,7 @@ impl u8 {
800"#, 800"#,
801 expect![[r#" 801 expect![[r#"
802 ct MAX pub const MAX: Self = 255; 802 ct MAX pub const MAX: Self = 255;
803 me func(…) -> () 803 me func(…) fn(self)
804 "#]], 804 "#]],
805 ); 805 );
806 } 806 }
diff --git a/crates/ide_completion/src/completions/trait_impl.rs b/crates/ide_completion/src/completions/trait_impl.rs
index 5a7361f8e..a26fe7c6c 100644
--- a/crates/ide_completion/src/completions/trait_impl.rs
+++ b/crates/ide_completion/src/completions/trait_impl.rs
@@ -82,13 +82,14 @@ pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext
82 82
83fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, SyntaxNode, Impl)> { 83fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, SyntaxNode, Impl)> {
84 let mut token = ctx.token.clone(); 84 let mut token = ctx.token.clone();
85 // For keywork without name like `impl .. { fn $0 }`, the current position is inside 85 // For keyword without name like `impl .. { fn $0 }`, the current position is inside
86 // the whitespace token, which is outside `FN` syntax node. 86 // the whitespace token, which is outside `FN` syntax node.
87 // We need to follow the previous token in this case. 87 // We need to follow the previous token in this case.
88 if token.kind() == SyntaxKind::WHITESPACE { 88 if token.kind() == SyntaxKind::WHITESPACE {
89 token = token.prev_token()?; 89 token = token.prev_token()?;
90 } 90 }
91 91
92 let parent_kind = token.parent().map_or(SyntaxKind::EOF, |it| it.kind());
92 let impl_item_offset = match token.kind() { 93 let impl_item_offset = match token.kind() {
93 // `impl .. { const $0 }` 94 // `impl .. { const $0 }`
94 // ERROR 0 95 // ERROR 0
@@ -102,14 +103,14 @@ fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, Synt
102 // FN/TYPE_ALIAS/CONST 1 103 // FN/TYPE_ALIAS/CONST 1
103 // NAME 0 104 // NAME 0
104 // IDENT <- * 105 // IDENT <- *
105 SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME => 1, 106 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME => 1,
106 // `impl .. { foo$0 }` 107 // `impl .. { foo$0 }`
107 // MACRO_CALL 3 108 // MACRO_CALL 3
108 // PATH 2 109 // PATH 2
109 // PATH_SEGMENT 1 110 // PATH_SEGMENT 1
110 // NAME_REF 0 111 // NAME_REF 0
111 // IDENT <- * 112 // IDENT <- *
112 SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME_REF => 3, 113 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME_REF => 3,
113 _ => return None, 114 _ => return None,
114 }; 115 };
115 116
diff --git a/crates/ide_completion/src/completions/unqualified_path.rs b/crates/ide_completion/src/completions/unqualified_path.rs
index 5ef80f6a7..1b8b063e7 100644
--- a/crates/ide_completion/src/completions/unqualified_path.rs
+++ b/crates/ide_completion/src/completions/unqualified_path.rs
@@ -135,7 +135,7 @@ fn quux(x: i32) {
135 expect![[r#" 135 expect![[r#"
136 lc y i32 136 lc y i32
137 lc x i32 137 lc x i32
138 fn quux(…) -> () 138 fn quux(…) fn(i32)
139 "#]], 139 "#]],
140 ); 140 );
141 } 141 }
@@ -157,7 +157,7 @@ fn quux() {
157 expect![[r#" 157 expect![[r#"
158 lc b i32 158 lc b i32
159 lc a 159 lc a
160 fn quux() -> () 160 fn quux() fn()
161 "#]], 161 "#]],
162 ); 162 );
163 } 163 }
@@ -172,7 +172,7 @@ fn quux() {
172"#, 172"#,
173 expect![[r#" 173 expect![[r#"
174 lc x 174 lc x
175 fn quux() -> () 175 fn quux() fn()
176 "#]], 176 "#]],
177 ); 177 );
178 } 178 }
@@ -203,14 +203,14 @@ fn main() {
203 r#"fn quux<T>() { $0 }"#, 203 r#"fn quux<T>() { $0 }"#,
204 expect![[r#" 204 expect![[r#"
205 tp T 205 tp T
206 fn quux() -> () 206 fn quux() fn()
207 "#]], 207 "#]],
208 ); 208 );
209 check( 209 check(
210 r#"fn quux<const C: usize>() { $0 }"#, 210 r#"fn quux<const C: usize>() { $0 }"#,
211 expect![[r#" 211 expect![[r#"
212 cp C 212 cp C
213 fn quux() -> () 213 fn quux() fn()
214 "#]], 214 "#]],
215 ); 215 );
216 } 216 }
@@ -221,7 +221,7 @@ fn main() {
221 check( 221 check(
222 r#"fn quux<'a>() { $0 }"#, 222 r#"fn quux<'a>() { $0 }"#,
223 expect![[r#" 223 expect![[r#"
224 fn quux() -> () 224 fn quux() fn()
225 "#]], 225 "#]],
226 ); 226 );
227 } 227 }
@@ -259,7 +259,7 @@ fn quux() { $0 }
259"#, 259"#,
260 expect![[r#" 260 expect![[r#"
261 st S 261 st S
262 fn quux() -> () 262 fn quux() fn()
263 en E 263 en E
264 "#]], 264 "#]],
265 ); 265 );
@@ -312,7 +312,7 @@ mod m {
312} 312}
313"#, 313"#,
314 expect![[r#" 314 expect![[r#"
315 fn quux() -> () 315 fn quux() fn()
316 st Bar 316 st Bar
317 "#]], 317 "#]],
318 ); 318 );
@@ -327,7 +327,7 @@ fn x() -> $0
327"#, 327"#,
328 expect![[r#" 328 expect![[r#"
329 st Foo 329 st Foo
330 fn x() -> () 330 fn x() fn()
331 "#]], 331 "#]],
332 ); 332 );
333 } 333 }
@@ -348,7 +348,7 @@ fn foo() {
348 expect![[r#" 348 expect![[r#"
349 lc bar i32 349 lc bar i32
350 lc bar i32 350 lc bar i32
351 fn foo() -> () 351 fn foo() fn()
352 "#]], 352 "#]],
353 ); 353 );
354 } 354 }
@@ -378,7 +378,7 @@ use prelude::*;
378mod prelude { struct Option; } 378mod prelude { struct Option; }
379"#, 379"#,
380 expect![[r#" 380 expect![[r#"
381 fn foo() -> () 381 fn foo() fn()
382 md std 382 md std
383 st Option 383 st Option
384 "#]], 384 "#]],
@@ -408,7 +408,7 @@ mod macros {
408} 408}
409"#, 409"#,
410 expect![[r##" 410 expect![[r##"
411 fn f() -> () 411 fn f() fn()
412 ma concat!(…) #[macro_export] macro_rules! concat 412 ma concat!(…) #[macro_export] macro_rules! concat
413 md std 413 md std
414 "##]], 414 "##]],
@@ -435,7 +435,7 @@ use prelude::*;
435mod prelude { struct String; } 435mod prelude { struct String; }
436"#, 436"#,
437 expect![[r#" 437 expect![[r#"
438 fn foo() -> () 438 fn foo() fn()
439 md std 439 md std
440 md core 440 md core
441 st String 441 st String
@@ -466,7 +466,7 @@ fn main() { let v = $0 }
466 expect![[r##" 466 expect![[r##"
467 md m1 467 md m1
468 ma baz!(…) #[macro_export] macro_rules! baz 468 ma baz!(…) #[macro_export] macro_rules! baz
469 fn main() -> () 469 fn main() fn()
470 md m2 470 md m2
471 ma bar!(…) macro_rules! bar 471 ma bar!(…) macro_rules! bar
472 ma foo!(…) macro_rules! foo 472 ma foo!(…) macro_rules! foo
@@ -482,7 +482,7 @@ macro_rules! foo { () => {} }
482fn foo() { $0 } 482fn foo() { $0 }
483"#, 483"#,
484 expect![[r#" 484 expect![[r#"
485 fn foo() -> () 485 fn foo() fn()
486 ma foo!(…) macro_rules! foo 486 ma foo!(…) macro_rules! foo
487 "#]], 487 "#]],
488 ); 488 );
@@ -496,7 +496,7 @@ macro_rules! foo { () => {} }
496fn main() { let x: $0 } 496fn main() { let x: $0 }
497"#, 497"#,
498 expect![[r#" 498 expect![[r#"
499 fn main() -> () 499 fn main() fn()
500 ma foo!(…) macro_rules! foo 500 ma foo!(…) macro_rules! foo
501 "#]], 501 "#]],
502 ); 502 );
@@ -510,7 +510,7 @@ macro_rules! foo { () => {} }
510fn main() { $0 } 510fn main() { $0 }
511"#, 511"#,
512 expect![[r#" 512 expect![[r#"
513 fn main() -> () 513 fn main() fn()
514 ma foo!(…) macro_rules! foo 514 ma foo!(…) macro_rules! foo
515 "#]], 515 "#]],
516 ); 516 );
@@ -526,8 +526,8 @@ fn main() {
526} 526}
527"#, 527"#,
528 expect![[r#" 528 expect![[r#"
529 fn frobnicate() -> () 529 fn frobnicate() fn()
530 fn main() -> () 530 fn main() fn()
531 "#]], 531 "#]],
532 ); 532 );
533 } 533 }
@@ -545,7 +545,7 @@ fn quux(x: i32) {
545 expect![[r#" 545 expect![[r#"
546 lc y i32 546 lc y i32
547 lc x i32 547 lc x i32
548 fn quux(…) -> () 548 fn quux(…) fn(i32)
549 ma m!(…) macro_rules! m 549 ma m!(…) macro_rules! m
550 "#]], 550 "#]],
551 ); 551 );
@@ -564,7 +564,7 @@ fn quux(x: i32) {
564 expect![[r#" 564 expect![[r#"
565 lc y i32 565 lc y i32
566 lc x i32 566 lc x i32
567 fn quux(…) -> () 567 fn quux(…) fn(i32)
568 ma m!(…) macro_rules! m 568 ma m!(…) macro_rules! m
569 "#]], 569 "#]],
570 ); 570 );
@@ -583,7 +583,7 @@ fn quux(x: i32) {
583 expect![[r#" 583 expect![[r#"
584 lc y i32 584 lc y i32
585 lc x i32 585 lc x i32
586 fn quux(…) -> () 586 fn quux(…) fn(i32)
587 ma m!(…) macro_rules! m 587 ma m!(…) macro_rules! m
588 "#]], 588 "#]],
589 ); 589 );
@@ -598,7 +598,7 @@ use spam::Quux;
598fn main() { $0 } 598fn main() { $0 }
599"#, 599"#,
600 expect![[r#" 600 expect![[r#"
601 fn main() -> () 601 fn main() fn()
602 ?? Quux 602 ?? Quux
603 "#]], 603 "#]],
604 ); 604 );
@@ -616,7 +616,7 @@ fn main() { let foo: Foo = Q$0 }
616 ev Foo::Baz () 616 ev Foo::Baz ()
617 ev Foo::Quux () 617 ev Foo::Quux ()
618 en Foo 618 en Foo
619 fn main() -> () 619 fn main() fn()
620 "#]], 620 "#]],
621 ) 621 )
622 } 622 }
@@ -631,7 +631,7 @@ fn f() -> m::E { V$0 }
631 expect![[r#" 631 expect![[r#"
632 ev m::E::V () 632 ev m::E::V ()
633 md m 633 md m
634 fn f() -> E 634 fn f() fn() -> E
635 "#]], 635 "#]],
636 ) 636 )
637 } 637 }
diff --git a/crates/ide_completion/src/context.rs b/crates/ide_completion/src/context.rs
index e6cc6329c..6d57da06a 100644
--- a/crates/ide_completion/src/context.rs
+++ b/crates/ide_completion/src/context.rs
@@ -120,7 +120,7 @@ impl<'a> CompletionContext<'a> {
120 let original_token = 120 let original_token =
121 original_file.syntax().token_at_offset(position.offset).left_biased()?; 121 original_file.syntax().token_at_offset(position.offset).left_biased()?;
122 let token = sema.descend_into_macros(original_token.clone()); 122 let token = sema.descend_into_macros(original_token.clone());
123 let scope = sema.scope_at_offset(&token.parent(), position.offset); 123 let scope = sema.scope_at_offset(&token, position.offset);
124 let mut locals = vec![]; 124 let mut locals = vec![];
125 scope.process_all_names(&mut |name, scope| { 125 scope.process_all_names(&mut |name, scope| {
126 if let ScopeDef::Local(local) = scope { 126 if let ScopeDef::Local(local) = scope {
@@ -281,7 +281,7 @@ impl<'a> CompletionContext<'a> {
281 fn fill_impl_def(&mut self) { 281 fn fill_impl_def(&mut self) {
282 self.impl_def = self 282 self.impl_def = self
283 .sema 283 .sema
284 .ancestors_with_macros(self.token.parent()) 284 .token_ancestors_with_macros(self.token.clone())
285 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE) 285 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
286 .find_map(ast::Impl::cast); 286 .find_map(ast::Impl::cast);
287 } 287 }
@@ -293,7 +293,10 @@ impl<'a> CompletionContext<'a> {
293 offset: TextSize, 293 offset: TextSize,
294 ) { 294 ) {
295 let expected = { 295 let expected = {
296 let mut node = self.token.parent(); 296 let mut node = match self.token.parent() {
297 Some(it) => it,
298 None => return,
299 };
297 loop { 300 loop {
298 let ret = match_ast! { 301 let ret = match_ast! {
299 match node { 302 match node {
@@ -310,7 +313,7 @@ impl<'a> CompletionContext<'a> {
310 313
311 (ty, name) 314 (ty, name)
312 }, 315 },
313 ast::ArgList(it) => { 316 ast::ArgList(_it) => {
314 cov_mark::hit!(expected_type_fn_param_with_leading_char); 317 cov_mark::hit!(expected_type_fn_param_with_leading_char);
315 cov_mark::hit!(expected_type_fn_param_without_leading_char); 318 cov_mark::hit!(expected_type_fn_param_without_leading_char);
316 ActiveParameter::at_token( 319 ActiveParameter::at_token(
@@ -319,7 +322,7 @@ impl<'a> CompletionContext<'a> {
319 ).map(|ap| (Some(ap.ty), Some(ap.name))) 322 ).map(|ap| (Some(ap.ty), Some(ap.name)))
320 .unwrap_or((None, None)) 323 .unwrap_or((None, None))
321 }, 324 },
322 ast::RecordExprFieldList(it) => { 325 ast::RecordExprFieldList(_it) => {
323 cov_mark::hit!(expected_type_struct_field_without_leading_char); 326 cov_mark::hit!(expected_type_struct_field_without_leading_char);
324 self.token.prev_sibling_or_token() 327 self.token.prev_sibling_or_token()
325 .and_then(|se| se.into_node()) 328 .and_then(|se| se.into_node())
@@ -355,7 +358,7 @@ impl<'a> CompletionContext<'a> {
355 358
356 (ty, None) 359 (ty, None)
357 }, 360 },
358 ast::Fn(it) => { 361 ast::Fn(_it) => {
359 cov_mark::hit!(expected_type_fn_ret_with_leading_char); 362 cov_mark::hit!(expected_type_fn_ret_with_leading_char);
360 cov_mark::hit!(expected_type_fn_ret_without_leading_char); 363 cov_mark::hit!(expected_type_fn_ret_without_leading_char);
361 let ty = self.token.ancestors() 364 let ty = self.token.ancestors()
@@ -474,17 +477,17 @@ impl<'a> CompletionContext<'a> {
474 } 477 }
475 478
476 self.use_item_syntax = 479 self.use_item_syntax =
477 self.sema.ancestors_with_macros(self.token.parent()).find_map(ast::Use::cast); 480 self.sema.token_ancestors_with_macros(self.token.clone()).find_map(ast::Use::cast);
478 481
479 self.function_syntax = self 482 self.function_syntax = self
480 .sema 483 .sema
481 .ancestors_with_macros(self.token.parent()) 484 .token_ancestors_with_macros(self.token.clone())
482 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE) 485 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
483 .find_map(ast::Fn::cast); 486 .find_map(ast::Fn::cast);
484 487
485 self.record_field_syntax = self 488 self.record_field_syntax = self
486 .sema 489 .sema
487 .ancestors_with_macros(self.token.parent()) 490 .token_ancestors_with_macros(self.token.clone())
488 .take_while(|it| { 491 .take_while(|it| {
489 it.kind() != SOURCE_FILE && it.kind() != MODULE && it.kind() != CALL_EXPR 492 it.kind() != SOURCE_FILE && it.kind() != MODULE && it.kind() != CALL_EXPR
490 }) 493 })
diff --git a/crates/ide_completion/src/lib.rs b/crates/ide_completion/src/lib.rs
index 263554ecf..5b7ad38d5 100644
--- a/crates/ide_completion/src/lib.rs
+++ b/crates/ide_completion/src/lib.rs
@@ -230,7 +230,7 @@ fn foo() {
230 bar.fo$0; 230 bar.fo$0;
231} 231}
232"#, 232"#,
233 DetailAndDocumentation { detail: "-> ()", documentation: "Do the foo" }, 233 DetailAndDocumentation { detail: "fn(&self)", documentation: "Do the foo" },
234 ); 234 );
235 } 235 }
236 236
@@ -255,7 +255,7 @@ fn foo() {
255 bar.fo$0; 255 bar.fo$0;
256} 256}
257"#, 257"#,
258 DetailAndDocumentation { detail: "-> ()", documentation: " Do the foo" }, 258 DetailAndDocumentation { detail: "fn(&self)", documentation: " Do the foo" },
259 ); 259 );
260 } 260 }
261 261
@@ -273,7 +273,7 @@ fn bar() {
273 for c in fo$0 273 for c in fo$0
274} 274}
275"#, 275"#,
276 DetailAndDocumentation { detail: "-> &str", documentation: "Do the foo" }, 276 DetailAndDocumentation { detail: "fn() -> &str", documentation: "Do the foo" },
277 ); 277 );
278 } 278 }
279} 279}
diff --git a/crates/ide_completion/src/patterns.rs b/crates/ide_completion/src/patterns.rs
index f3ce91dd1..cf5ef07b7 100644
--- a/crates/ide_completion/src/patterns.rs
+++ b/crates/ide_completion/src/patterns.rs
@@ -184,11 +184,7 @@ fn test_has_impl_as_prev_sibling() {
184} 184}
185 185
186pub(crate) fn is_in_loop_body(element: SyntaxElement) -> bool { 186pub(crate) fn is_in_loop_body(element: SyntaxElement) -> bool {
187 let leaf = match element { 187 for node in element.ancestors() {
188 NodeOrToken::Node(node) => node,
189 NodeOrToken::Token(token) => token.parent(),
190 };
191 for node in leaf.ancestors() {
192 if node.kind() == FN || node.kind() == CLOSURE_EXPR { 188 if node.kind() == FN || node.kind() == CLOSURE_EXPR {
193 break; 189 break;
194 } 190 }
@@ -201,7 +197,7 @@ pub(crate) fn is_in_loop_body(element: SyntaxElement) -> bool {
201 } 197 }
202 }; 198 };
203 if let Some(body) = loop_body { 199 if let Some(body) = loop_body {
204 if body.syntax().text_range().contains_range(leaf.text_range()) { 200 if body.syntax().text_range().contains_range(element.text_range()) {
205 return true; 201 return true;
206 } 202 }
207 } 203 }
@@ -235,12 +231,8 @@ fn previous_sibling_or_ancestor_sibling(element: SyntaxElement) -> Option<Syntax
235 Some(sibling) 231 Some(sibling)
236 } else { 232 } else {
237 // if not trying to find first ancestor which has such a sibling 233 // if not trying to find first ancestor which has such a sibling
238 let node = match element { 234 let range = element.text_range();
239 NodeOrToken::Node(node) => node, 235 let top_node = element.ancestors().take_while(|it| it.text_range() == range).last()?;
240 NodeOrToken::Token(token) => token.parent(),
241 };
242 let range = node.text_range();
243 let top_node = node.ancestors().take_while(|it| it.text_range() == range).last()?;
244 let prev_sibling_node = top_node.ancestors().find(|it| { 236 let prev_sibling_node = top_node.ancestors().find(|it| {
245 non_trivia_sibling(NodeOrToken::Node(it.to_owned()), Direction::Prev).is_some() 237 non_trivia_sibling(NodeOrToken::Node(it.to_owned()), Direction::Prev).is_some()
246 })?; 238 })?;
diff --git a/crates/ide_completion/src/render.rs b/crates/ide_completion/src/render.rs
index 2514dda7c..4e4923e0d 100644
--- a/crates/ide_completion/src/render.rs
+++ b/crates/ide_completion/src/render.rs
@@ -10,10 +10,8 @@ pub(crate) mod type_alias;
10 10
11mod builder_ext; 11mod builder_ext;
12 12
13use base_db::Upcast;
14use hir::{ 13use hir::{
15 db::HirDatabase, AsAssocItem, Documentation, HasAttrs, HirDisplay, ModuleDef, Mutability, 14 AsAssocItem, Documentation, HasAttrs, HirDisplay, ModuleDef, Mutability, ScopeDef, Type,
16 ScopeDef, Type,
17}; 15};
18use ide_db::{ 16use ide_db::{
19 helpers::{item_name, SnippetCap}, 17 helpers::{item_name, SnippetCap},
@@ -22,8 +20,8 @@ use ide_db::{
22use syntax::TextRange; 20use syntax::TextRange;
23 21
24use crate::{ 22use crate::{
25 item::{CompletionRelevance, ImportEdit}, 23 item::ImportEdit, CompletionContext, CompletionItem, CompletionItemKind, CompletionKind,
26 CompletionContext, CompletionItem, CompletionItemKind, CompletionKind, 24 CompletionRelevance,
27}; 25};
28 26
29use crate::render::{enum_variant::render_variant, function::render_fn, macro_::render_macro}; 27use crate::render::{enum_variant::render_variant, function::render_fn, macro_::render_macro};
@@ -144,7 +142,15 @@ impl<'a> Render<'a> {
144 .set_documentation(field.docs(self.ctx.db())) 142 .set_documentation(field.docs(self.ctx.db()))
145 .set_deprecated(is_deprecated); 143 .set_deprecated(is_deprecated);
146 144
147 item.set_relevance(compute_relevance(&self.ctx, &ty, &name.to_string())); 145 item.set_relevance(CompletionRelevance {
146 exact_type_match: compute_exact_type_match(self.ctx.completion, ty),
147 exact_name_match: compute_exact_name_match(self.ctx.completion, name.to_string()),
148 ..CompletionRelevance::default()
149 });
150
151 if let Some(ref_match) = compute_ref_match(self.ctx.completion, ty) {
152 item.ref_match(ref_match);
153 }
148 154
149 item.build() 155 item.build()
150 } 156 }
@@ -234,31 +240,18 @@ impl<'a> Render<'a> {
234 if !ty.is_unknown() { 240 if !ty.is_unknown() {
235 item.detail(ty.display(self.ctx.db()).to_string()); 241 item.detail(ty.display(self.ctx.db()).to_string());
236 } 242 }
237 };
238 243
239 if let ScopeDef::Local(local) = resolution { 244 item.set_relevance(CompletionRelevance {
240 let ty = local.ty(self.ctx.db()); 245 exact_type_match: compute_exact_type_match(self.ctx.completion, &ty),
246 exact_name_match: compute_exact_name_match(self.ctx.completion, local_name.clone()),
247 is_local: true,
248 ..CompletionRelevance::default()
249 });
241 250
242 let mut relevance = compute_relevance(&self.ctx, &ty, &local_name); 251 if let Some(ref_match) = compute_ref_match(self.ctx.completion, &ty) {
243 relevance.is_local = true; 252 item.ref_match(ref_match);
244 item.set_relevance(relevance);
245
246 if let Some(expected_type) = self.ctx.completion.expected_type.as_ref() {
247 if &ty != expected_type {
248 if let Some(ty_without_ref) = expected_type.remove_ref() {
249 if relevance_type_match(self.ctx.db().upcast(), &ty, &ty_without_ref) {
250 cov_mark::hit!(suggest_ref);
251 let mutability = if expected_type.is_mutable_reference() {
252 Mutability::Mut
253 } else {
254 Mutability::Shared
255 };
256 item.ref_match(mutability);
257 }
258 }
259 }
260 } 253 }
261 } 254 };
262 255
263 // Add `<>` for generic types 256 // Add `<>` for generic types
264 if self.ctx.completion.is_path_type 257 if self.ctx.completion.is_path_type
@@ -313,17 +306,38 @@ impl<'a> Render<'a> {
313 } 306 }
314} 307}
315 308
316fn compute_relevance(ctx: &RenderContext, ty: &Type, name: &str) -> CompletionRelevance { 309fn compute_exact_type_match(ctx: &CompletionContext, completion_ty: &hir::Type) -> bool {
317 let mut res = CompletionRelevance::default(); 310 match ctx.expected_type.as_ref() {
311 Some(expected_type) => {
312 // We don't ever consider unit type to be an exact type match, since
313 // nearly always this is not meaningful to the user.
314 completion_ty == expected_type && !expected_type.is_unit()
315 }
316 None => false,
317 }
318}
318 319
319 res.exact_type_match = Some(ty) == ctx.completion.expected_type.as_ref(); 320fn compute_exact_name_match(ctx: &CompletionContext, completion_name: impl Into<String>) -> bool {
320 res.exact_name_match = Some(name) == ctx.completion.expected_name.as_deref(); 321 let completion_name = completion_name.into();
321 322
322 res 323 Some(&completion_name) == ctx.expected_name.as_ref()
323} 324}
324 325
325fn relevance_type_match(db: &dyn HirDatabase, ty: &Type, expected_type: &Type) -> bool { 326fn compute_ref_match(ctx: &CompletionContext, completion_ty: &hir::Type) -> Option<Mutability> {
326 ty == expected_type || ty.autoderef(db).any(|deref_ty| &deref_ty == expected_type) 327 let expected_type = ctx.expected_type.as_ref()?;
328 if completion_ty != expected_type {
329 let expected_type_without_ref = expected_type.remove_ref()?;
330 if completion_ty.autoderef(ctx.db).any(|deref_ty| deref_ty == expected_type_without_ref) {
331 cov_mark::hit!(suggest_ref);
332 let mutability = if expected_type.is_mutable_reference() {
333 Mutability::Mut
334 } else {
335 Mutability::Shared
336 };
337 return Some(mutability);
338 };
339 }
340 None
327} 341}
328 342
329#[cfg(test)] 343#[cfg(test)]
@@ -432,6 +446,44 @@ fn main() { Foo::Fo$0 }
432 } 446 }
433 447
434 #[test] 448 #[test]
449 fn fn_detail_includes_args_and_return_type() {
450 check(
451 r#"
452fn foo<T>(a: u32, b: u32, t: T) -> (u32, T) { (a, t) }
453
454fn main() { fo$0 }
455"#,
456 expect![[r#"
457 [
458 CompletionItem {
459 label: "foo(…)",
460 source_range: 68..70,
461 delete: 68..70,
462 insert: "foo(${1:a}, ${2:b}, ${3:t})$0",
463 kind: SymbolKind(
464 Function,
465 ),
466 lookup: "foo",
467 detail: "fn(u32, u32, T) -> (u32, T)",
468 trigger_call_info: true,
469 },
470 CompletionItem {
471 label: "main()",
472 source_range: 68..70,
473 delete: 68..70,
474 insert: "main()$0",
475 kind: SymbolKind(
476 Function,
477 ),
478 lookup: "main",
479 detail: "fn()",
480 },
481 ]
482 "#]],
483 );
484 }
485
486 #[test]
435 fn enum_detail_just_parentheses_for_unit() { 487 fn enum_detail_just_parentheses_for_unit() {
436 check( 488 check(
437 r#" 489 r#"
@@ -477,6 +529,11 @@ fn main() { let _: m::Spam = S$0 }
477 ), 529 ),
478 lookup: "Spam::Bar", 530 lookup: "Spam::Bar",
479 detail: "(i32)", 531 detail: "(i32)",
532 relevance: CompletionRelevance {
533 exact_name_match: false,
534 exact_type_match: true,
535 is_local: false,
536 },
480 trigger_call_info: true, 537 trigger_call_info: true,
481 }, 538 },
482 CompletionItem { 539 CompletionItem {
@@ -498,6 +555,11 @@ fn main() { let _: m::Spam = S$0 }
498 ), 555 ),
499 lookup: "Spam::Foo", 556 lookup: "Spam::Foo",
500 detail: "()", 557 detail: "()",
558 relevance: CompletionRelevance {
559 exact_name_match: false,
560 exact_type_match: true,
561 is_local: false,
562 },
501 }, 563 },
502 CompletionItem { 564 CompletionItem {
503 label: "main()", 565 label: "main()",
@@ -508,7 +570,7 @@ fn main() { let _: m::Spam = S$0 }
508 Function, 570 Function,
509 ), 571 ),
510 lookup: "main", 572 lookup: "main",
511 detail: "-> ()", 573 detail: "fn()",
512 }, 574 },
513 ] 575 ]
514 "#]], 576 "#]],
@@ -537,7 +599,7 @@ fn main() { som$0 }
537 Function, 599 Function,
538 ), 600 ),
539 lookup: "main", 601 lookup: "main",
540 detail: "-> ()", 602 detail: "fn()",
541 }, 603 },
542 CompletionItem { 604 CompletionItem {
543 label: "something_deprecated()", 605 label: "something_deprecated()",
@@ -548,7 +610,7 @@ fn main() { som$0 }
548 Function, 610 Function,
549 ), 611 ),
550 lookup: "something_deprecated", 612 lookup: "something_deprecated",
551 detail: "-> ()", 613 detail: "fn()",
552 deprecated: true, 614 deprecated: true,
553 }, 615 },
554 CompletionItem { 616 CompletionItem {
@@ -560,7 +622,7 @@ fn main() { som$0 }
560 Function, 622 Function,
561 ), 623 ),
562 lookup: "something_else_deprecated", 624 lookup: "something_else_deprecated",
563 detail: "-> ()", 625 detail: "fn()",
564 deprecated: true, 626 deprecated: true,
565 }, 627 },
566 ] 628 ]
@@ -611,7 +673,7 @@ impl S {
611 insert: "bar()$0", 673 insert: "bar()$0",
612 kind: Method, 674 kind: Method,
613 lookup: "bar", 675 lookup: "bar",
614 detail: "-> ()", 676 detail: "fn(self)",
615 documentation: Documentation( 677 documentation: Documentation(
616 "Method docs", 678 "Method docs",
617 ), 679 ),
@@ -711,7 +773,7 @@ fn foo(s: S) { s.$0 }
711 insert: "the_method()$0", 773 insert: "the_method()$0",
712 kind: Method, 774 kind: Method,
713 lookup: "the_method", 775 lookup: "the_method",
714 detail: "-> ()", 776 detail: "fn(&self)",
715 }, 777 },
716 ] 778 ]
717 "#]], 779 "#]],
@@ -1019,7 +1081,7 @@ fn main() {
1019 Function, 1081 Function,
1020 ), 1082 ),
1021 lookup: "foo", 1083 lookup: "foo",
1022 detail: "-> ()", 1084 detail: "fn(&mut S)",
1023 trigger_call_info: true, 1085 trigger_call_info: true,
1024 }, 1086 },
1025 CompletionItem { 1087 CompletionItem {
@@ -1031,7 +1093,7 @@ fn main() {
1031 Function, 1093 Function,
1032 ), 1094 ),
1033 lookup: "main", 1095 lookup: "main",
1034 detail: "-> ()", 1096 detail: "fn()",
1035 }, 1097 },
1036 CompletionItem { 1098 CompletionItem {
1037 label: "s", 1099 label: "s",
@@ -1169,4 +1231,86 @@ fn foo(bar: u32) {
1169 "#]], 1231 "#]],
1170 ); 1232 );
1171 } 1233 }
1234
1235 #[test]
1236 fn enum_owned() {
1237 check_relevance(
1238 r#"
1239enum Foo { A, B }
1240fn foo() {
1241 bar($0);
1242}
1243fn bar(t: Foo) {}
1244"#,
1245 expect![[r#"
1246 ev Foo::A [type]
1247 ev Foo::B [type]
1248 en Foo []
1249 fn bar(…) []
1250 fn foo() []
1251 "#]],
1252 );
1253 }
1254
1255 #[test]
1256 fn enum_ref() {
1257 check_relevance(
1258 r#"
1259enum Foo { A, B }
1260fn foo() {
1261 bar($0);
1262}
1263fn bar(t: &Foo) {}
1264"#,
1265 expect![[r#"
1266 ev Foo::A []
1267 ev &Foo::A [type]
1268 ev Foo::B []
1269 ev &Foo::B [type]
1270 en Foo []
1271 fn bar(…) []
1272 fn foo() []
1273 "#]],
1274 );
1275 }
1276
1277 #[test]
1278 fn suggest_deref_fn_ret() {
1279 check_relevance(
1280 r#"
1281#[lang = "deref"]
1282trait Deref {
1283 type Target;
1284 fn deref(&self) -> &Self::Target;
1285}
1286
1287struct S;
1288struct T(S);
1289
1290impl Deref for T {
1291 type Target = S;
1292
1293 fn deref(&self) -> &Self::Target {
1294 &self.0
1295 }
1296}
1297
1298fn foo(s: &S) {}
1299fn bar() -> T {}
1300
1301fn main() {
1302 foo($0);
1303}
1304 "#,
1305 expect![[r#"
1306 tt Deref []
1307 fn bar() []
1308 fn &bar() [type]
1309 fn foo(…) []
1310 st T []
1311 st S []
1312 fn main() []
1313 "#]],
1314 )
1315 }
1172} 1316}
diff --git a/crates/ide_completion/src/render/enum_variant.rs b/crates/ide_completion/src/render/enum_variant.rs
index e8cfcc0c7..374247b05 100644
--- a/crates/ide_completion/src/render/enum_variant.rs
+++ b/crates/ide_completion/src/render/enum_variant.rs
@@ -6,7 +6,8 @@ use itertools::Itertools;
6 6
7use crate::{ 7use crate::{
8 item::{CompletionItem, CompletionKind, ImportEdit}, 8 item::{CompletionItem, CompletionKind, ImportEdit},
9 render::{builder_ext::Params, RenderContext}, 9 render::{builder_ext::Params, compute_exact_type_match, compute_ref_match, RenderContext},
10 CompletionRelevance,
10}; 11};
11 12
12pub(crate) fn render_variant<'a>( 13pub(crate) fn render_variant<'a>(
@@ -74,6 +75,16 @@ impl<'a> EnumRender<'a> {
74 item.lookup_by(self.short_qualified_name); 75 item.lookup_by(self.short_qualified_name);
75 } 76 }
76 77
78 let ty = self.variant.parent_enum(self.ctx.completion.db).ty(self.ctx.completion.db);
79 item.set_relevance(CompletionRelevance {
80 exact_type_match: compute_exact_type_match(self.ctx.completion, &ty),
81 ..CompletionRelevance::default()
82 });
83
84 if let Some(ref_match) = compute_ref_match(self.ctx.completion, &ty) {
85 item.ref_match(ref_match);
86 }
87
77 item.build() 88 item.build()
78 } 89 }
79 90
diff --git a/crates/ide_completion/src/render/function.rs b/crates/ide_completion/src/render/function.rs
index 47e26a5d8..010303182 100644
--- a/crates/ide_completion/src/render/function.rs
+++ b/crates/ide_completion/src/render/function.rs
@@ -2,11 +2,15 @@
2 2
3use hir::{HasSource, HirDisplay, Type}; 3use hir::{HasSource, HirDisplay, Type};
4use ide_db::SymbolKind; 4use ide_db::SymbolKind;
5use itertools::Itertools;
5use syntax::ast::Fn; 6use syntax::ast::Fn;
6 7
7use crate::{ 8use crate::{
8 item::{CompletionItem, CompletionItemKind, CompletionKind, CompletionRelevance, ImportEdit}, 9 item::{CompletionItem, CompletionItemKind, CompletionKind, CompletionRelevance, ImportEdit},
9 render::{builder_ext::Params, RenderContext}, 10 render::{
11 builder_ext::Params, compute_exact_name_match, compute_exact_type_match, compute_ref_match,
12 RenderContext,
13 },
10}; 14};
11 15
12pub(crate) fn render_fn<'a>( 16pub(crate) fn render_fn<'a>(
@@ -52,30 +56,60 @@ impl<'a> FunctionRender<'a> {
52 self.ctx.is_deprecated(self.func) || self.ctx.is_deprecated_assoc_item(self.func), 56 self.ctx.is_deprecated(self.func) || self.ctx.is_deprecated_assoc_item(self.func),
53 ) 57 )
54 .detail(self.detail()) 58 .detail(self.detail())
55 .add_call_parens(self.ctx.completion, self.name, params) 59 .add_call_parens(self.ctx.completion, self.name.clone(), params)
56 .add_import(import_to_add); 60 .add_import(import_to_add);
57 61
58 let mut relevance = CompletionRelevance::default(); 62 let ret_type = self.func.ret_type(self.ctx.db());
59 if let Some(expected_type) = &self.ctx.completion.expected_type { 63 item.set_relevance(CompletionRelevance {
60 let ret_ty = self.func.ret_type(self.ctx.db()); 64 exact_type_match: compute_exact_type_match(self.ctx.completion, &ret_type),
65 exact_name_match: compute_exact_name_match(self.ctx.completion, self.name.clone()),
66 ..CompletionRelevance::default()
67 });
61 68
62 // We don't ever consider a function which returns unit type to be an 69 if let Some(ref_match) = compute_ref_match(self.ctx.completion, &ret_type) {
63 // exact type match, since nearly always this is not meaningful to the 70 item.ref_match(ref_match);
64 // user.
65 relevance.exact_type_match = &ret_ty == expected_type && !ret_ty.is_unit();
66 } 71 }
67 if let Some(expected_name) = &self.ctx.completion.expected_name {
68 relevance.exact_name_match =
69 expected_name == &self.func.name(self.ctx.db()).to_string();
70 }
71 item.set_relevance(relevance);
72 72
73 item.build() 73 item.build()
74 } 74 }
75 75
76 fn detail(&self) -> String { 76 fn detail(&self) -> String {
77 let ty = self.func.ret_type(self.ctx.db()); 77 let ret_ty = self.func.ret_type(self.ctx.db());
78 format!("-> {}", ty.display(self.ctx.db())) 78 let ret = if ret_ty.is_unit() {
79 // Omit the return type if it is the unit type
80 String::new()
81 } else {
82 format!(" {}", self.ty_display())
83 };
84
85 format!("fn({}){}", self.params_display(), ret)
86 }
87
88 fn params_display(&self) -> String {
89 if let Some(self_param) = self.func.self_param(self.ctx.db()) {
90 let params = self
91 .func
92 .assoc_fn_params(self.ctx.db())
93 .into_iter()
94 .skip(1) // skip the self param because we are manually handling that
95 .map(|p| p.ty().display(self.ctx.db()).to_string());
96
97 std::iter::once(self_param.display(self.ctx.db()).to_owned()).chain(params).join(", ")
98 } else {
99 let params = self
100 .func
101 .assoc_fn_params(self.ctx.db())
102 .into_iter()
103 .map(|p| p.ty().display(self.ctx.db()).to_string())
104 .join(", ");
105 params
106 }
107 }
108
109 fn ty_display(&self) -> String {
110 let ret_ty = self.func.ret_type(self.ctx.db());
111
112 format!("-> {}", ret_ty.display(self.ctx.db()))
79 } 113 }
80 114
81 fn add_arg(&self, arg: &str, ty: &Type) -> String { 115 fn add_arg(&self, arg: &str, ty: &Type) -> String {
diff --git a/crates/ide_db/src/call_info.rs b/crates/ide_db/src/call_info.rs
index d8878aa91..d4016973c 100644
--- a/crates/ide_db/src/call_info.rs
+++ b/crates/ide_db/src/call_info.rs
@@ -109,7 +109,7 @@ fn call_info_impl(
109 token: SyntaxToken, 109 token: SyntaxToken,
110) -> Option<(hir::Callable, Option<usize>)> { 110) -> Option<(hir::Callable, Option<usize>)> {
111 // Find the calling expression and it's NameRef 111 // Find the calling expression and it's NameRef
112 let calling_node = FnCallNode::with_node(&token.parent())?; 112 let calling_node = FnCallNode::with_node(&token.parent()?)?;
113 113
114 let callable = match &calling_node { 114 let callable = match &calling_node {
115 FnCallNode::CallExpr(call) => sema.type_of_expr(&call.expr()?)?.as_callable(sema.db)?, 115 FnCallNode::CallExpr(call) => sema.type_of_expr(&call.expr()?)?.as_callable(sema.db)?,
diff --git a/crates/ide_db/src/search.rs b/crates/ide_db/src/search.rs
index d00a8b6e7..f56221a6c 100644
--- a/crates/ide_db/src/search.rs
+++ b/crates/ide_db/src/search.rs
@@ -260,7 +260,7 @@ impl Definition {
260 let mut res = source_root.iter().map(|id| (id, None)).collect::<FxHashMap<_, _>>(); 260 let mut res = source_root.iter().map(|id| (id, None)).collect::<FxHashMap<_, _>>();
261 261
262 let krate = module.krate(); 262 let krate = module.krate();
263 for rev_dep in krate.reverse_dependencies(db) { 263 for rev_dep in krate.transitive_reverse_dependencies(db) {
264 let root_file = rev_dep.root_file(db); 264 let root_file = rev_dep.root_file(db);
265 let source_root_id = db.file_source_root(root_file); 265 let source_root_id = db.file_source_root(root_file);
266 let source_root = db.source_root(source_root_id); 266 let source_root = db.source_root(source_root_id);
diff --git a/crates/ide_ssr/src/resolving.rs b/crates/ide_ssr/src/resolving.rs
index af94c7bb1..dc7835473 100644
--- a/crates/ide_ssr/src/resolving.rs
+++ b/crates/ide_ssr/src/resolving.rs
@@ -195,7 +195,7 @@ impl<'db> ResolutionScope<'db> {
195 .syntax() 195 .syntax()
196 .token_at_offset(resolve_context.offset) 196 .token_at_offset(resolve_context.offset)
197 .left_biased() 197 .left_biased()
198 .map(|token| token.parent()) 198 .and_then(|token| token.parent())
199 .unwrap_or_else(|| file.syntax().clone()); 199 .unwrap_or_else(|| file.syntax().clone());
200 let node = pick_node_for_resolution(node); 200 let node = pick_node_for_resolution(node);
201 let scope = sema.scope(&node); 201 let scope = sema.scope(&node);
diff --git a/crates/mbe/src/tests.rs b/crates/mbe/src/tests.rs
index 3a168bb4b..eca0bcc18 100644
--- a/crates/mbe/src/tests.rs
+++ b/crates/mbe/src/tests.rs
@@ -662,12 +662,11 @@ fn test_tt_to_stmts() {
662 [email protected] 662 [email protected]
663 [email protected] "1" 663 [email protected] "1"
664 [email protected] ";" 664 [email protected] ";"
665 [email protected] 665 [email protected]
666 [email protected] 666 [email protected]
667 [email protected] 667 [email protected]
668 [email protected] 668 [email protected]
669 [email protected] 669 [email protected] "a""#,
670 [email protected] "a""#,
671 ); 670 );
672} 671}
673 672
diff --git a/crates/parser/src/grammar.rs b/crates/parser/src/grammar.rs
index 6c0e22722..cebb8f400 100644
--- a/crates/parser/src/grammar.rs
+++ b/crates/parser/src/grammar.rs
@@ -63,11 +63,11 @@ pub(crate) mod fragments {
63 } 63 }
64 64
65 pub(crate) fn stmt(p: &mut Parser) { 65 pub(crate) fn stmt(p: &mut Parser) {
66 expressions::stmt(p, expressions::StmtWithSemi::No) 66 expressions::stmt(p, expressions::StmtWithSemi::No, true)
67 } 67 }
68 68
69 pub(crate) fn stmt_optional_semi(p: &mut Parser) { 69 pub(crate) fn stmt_optional_semi(p: &mut Parser) {
70 expressions::stmt(p, expressions::StmtWithSemi::Optional) 70 expressions::stmt(p, expressions::StmtWithSemi::Optional, false)
71 } 71 }
72 72
73 pub(crate) fn opt_visibility(p: &mut Parser) { 73 pub(crate) fn opt_visibility(p: &mut Parser) {
@@ -133,7 +133,7 @@ pub(crate) mod fragments {
133 continue; 133 continue;
134 } 134 }
135 135
136 expressions::stmt(p, expressions::StmtWithSemi::Optional); 136 expressions::stmt(p, expressions::StmtWithSemi::Optional, true);
137 } 137 }
138 138
139 m.complete(p, MACRO_STMTS); 139 m.complete(p, MACRO_STMTS);
diff --git a/crates/parser/src/grammar/expressions.rs b/crates/parser/src/grammar/expressions.rs
index 5f885edfd..0d9dc9348 100644
--- a/crates/parser/src/grammar/expressions.rs
+++ b/crates/parser/src/grammar/expressions.rs
@@ -54,7 +54,7 @@ fn is_expr_stmt_attr_allowed(kind: SyntaxKind) -> bool {
54 !forbid 54 !forbid
55} 55}
56 56
57pub(super) fn stmt(p: &mut Parser, with_semi: StmtWithSemi) { 57pub(super) fn stmt(p: &mut Parser, with_semi: StmtWithSemi, prefer_expr: bool) {
58 let m = p.start(); 58 let m = p.start();
59 // test attr_on_expr_stmt 59 // test attr_on_expr_stmt
60 // fn foo() { 60 // fn foo() {
@@ -90,7 +90,7 @@ pub(super) fn stmt(p: &mut Parser, with_semi: StmtWithSemi) {
90 p.error(format!("attributes are not allowed on {:?}", kind)); 90 p.error(format!("attributes are not allowed on {:?}", kind));
91 } 91 }
92 92
93 if p.at(T!['}']) { 93 if p.at(T!['}']) || (prefer_expr && p.at(EOF)) {
94 // test attr_on_last_expr_in_block 94 // test attr_on_last_expr_in_block
95 // fn foo() { 95 // fn foo() {
96 // { #[A] bar!()? } 96 // { #[A] bar!()? }
@@ -198,7 +198,7 @@ pub(super) fn expr_block_contents(p: &mut Parser) {
198 continue; 198 continue;
199 } 199 }
200 200
201 stmt(p, StmtWithSemi::Yes) 201 stmt(p, StmtWithSemi::Yes, false)
202 } 202 }
203} 203}
204 204
diff --git a/crates/syntax/Cargo.toml b/crates/syntax/Cargo.toml
index c0fd894b0..74cafaa8d 100644
--- a/crates/syntax/Cargo.toml
+++ b/crates/syntax/Cargo.toml
@@ -13,7 +13,7 @@ doctest = false
13[dependencies] 13[dependencies]
14cov-mark = { version = "1.1", features = ["thread-local"] } 14cov-mark = { version = "1.1", features = ["thread-local"] }
15itertools = "0.10.0" 15itertools = "0.10.0"
16rowan = "0.12.2" 16rowan = "0.13.0-pre.2"
17rustc_lexer = { version = "710.0.0", package = "rustc-ap-rustc_lexer" } 17rustc_lexer = { version = "710.0.0", package = "rustc-ap-rustc_lexer" }
18rustc-hash = "1.1.0" 18rustc-hash = "1.1.0"
19arrayvec = "0.5.1" 19arrayvec = "0.5.1"
diff --git a/crates/syntax/src/algo.rs b/crates/syntax/src/algo.rs
index b13252eec..82ebf9037 100644
--- a/crates/syntax/src/algo.rs
+++ b/crates/syntax/src/algo.rs
@@ -4,7 +4,6 @@ use std::{
4 fmt, 4 fmt,
5 hash::BuildHasherDefault, 5 hash::BuildHasherDefault,
6 ops::{self, RangeInclusive}, 6 ops::{self, RangeInclusive},
7 ptr,
8}; 7};
9 8
10use indexmap::IndexMap; 9use indexmap::IndexMap;
@@ -27,7 +26,7 @@ pub fn ancestors_at_offset(
27 offset: TextSize, 26 offset: TextSize,
28) -> impl Iterator<Item = SyntaxNode> { 27) -> impl Iterator<Item = SyntaxNode> {
29 node.token_at_offset(offset) 28 node.token_at_offset(offset)
30 .map(|token| token.parent().ancestors()) 29 .map(|token| token.ancestors())
31 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len()) 30 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
32} 31}
33 32
@@ -171,7 +170,7 @@ pub fn diff(from: &SyntaxNode, to: &SyntaxNode) -> TreeDiff {
171 && lhs.text_range().len() == rhs.text_range().len() 170 && lhs.text_range().len() == rhs.text_range().len()
172 && match (&lhs, &rhs) { 171 && match (&lhs, &rhs) {
173 (NodeOrToken::Node(lhs), NodeOrToken::Node(rhs)) => { 172 (NodeOrToken::Node(lhs), NodeOrToken::Node(rhs)) => {
174 ptr::eq(lhs.green(), rhs.green()) || lhs.text() == rhs.text() 173 lhs == rhs || lhs.text() == rhs.text()
175 } 174 }
176 (NodeOrToken::Token(lhs), NodeOrToken::Token(rhs)) => lhs.text() == rhs.text(), 175 (NodeOrToken::Token(lhs), NodeOrToken::Token(rhs)) => lhs.text() == rhs.text(),
177 _ => false, 176 _ => false,
@@ -280,9 +279,10 @@ fn _insert_children(
280 to_green_element(element) 279 to_green_element(element)
281 }); 280 });
282 281
283 let mut old_children = parent.green().children().map(|it| match it { 282 let parent_green = parent.green();
284 NodeOrToken::Token(it) => NodeOrToken::Token(it.clone()), 283 let mut old_children = parent_green.children().map(|it| match it {
285 NodeOrToken::Node(it) => NodeOrToken::Node(it.clone()), 284 NodeOrToken::Token(it) => NodeOrToken::Token(it.to_owned()),
285 NodeOrToken::Node(it) => NodeOrToken::Node(it.to_owned()),
286 }); 286 });
287 287
288 let new_children = match &position { 288 let new_children = match &position {
@@ -319,9 +319,10 @@ fn _replace_children(
319) -> SyntaxNode { 319) -> SyntaxNode {
320 let start = position_of_child(parent, to_delete.start().clone()); 320 let start = position_of_child(parent, to_delete.start().clone());
321 let end = position_of_child(parent, to_delete.end().clone()); 321 let end = position_of_child(parent, to_delete.end().clone());
322 let mut old_children = parent.green().children().map(|it| match it { 322 let parent_green = parent.green();
323 NodeOrToken::Token(it) => NodeOrToken::Token(it.clone()), 323 let mut old_children = parent_green.children().map(|it| match it {
324 NodeOrToken::Node(it) => NodeOrToken::Node(it.clone()), 324 NodeOrToken::Token(it) => NodeOrToken::Token(it.to_owned()),
325 NodeOrToken::Node(it) => NodeOrToken::Node(it.to_owned()),
325 }); 326 });
326 327
327 let before = old_children.by_ref().take(start).collect::<Vec<_>>(); 328 let before = old_children.by_ref().take(start).collect::<Vec<_>>();
@@ -487,9 +488,9 @@ impl<'a> SyntaxRewriter<'a> {
487 /// Returns `None` when there are no replacements. 488 /// Returns `None` when there are no replacements.
488 pub fn rewrite_root(&self) -> Option<SyntaxNode> { 489 pub fn rewrite_root(&self) -> Option<SyntaxNode> {
489 let _p = profile::span("rewrite_root"); 490 let _p = profile::span("rewrite_root");
490 fn element_to_node_or_parent(element: &SyntaxElement) -> SyntaxNode { 491 fn element_to_node_or_parent(element: &SyntaxElement) -> Option<SyntaxNode> {
491 match element { 492 match element {
492 SyntaxElement::Node(it) => it.clone(), 493 SyntaxElement::Node(it) => Some(it.clone()),
493 SyntaxElement::Token(it) => it.parent(), 494 SyntaxElement::Token(it) => it.parent(),
494 } 495 }
495 } 496 }
@@ -497,9 +498,9 @@ impl<'a> SyntaxRewriter<'a> {
497 assert!(self.f.is_none()); 498 assert!(self.f.is_none());
498 self.replacements 499 self.replacements
499 .keys() 500 .keys()
500 .map(element_to_node_or_parent) 501 .filter_map(element_to_node_or_parent)
501 .chain(self.insertions.keys().map(|pos| match pos { 502 .chain(self.insertions.keys().filter_map(|pos| match pos {
502 InsertPos::FirstChildOf(it) => it.clone(), 503 InsertPos::FirstChildOf(it) => Some(it.clone()),
503 InsertPos::After(it) => element_to_node_or_parent(it), 504 InsertPos::After(it) => element_to_node_or_parent(it),
504 })) 505 }))
505 // If we only have one replacement/insertion, we must return its parent node, since `rewrite` does 506 // If we only have one replacement/insertion, we must return its parent node, since `rewrite` does
@@ -552,7 +553,7 @@ impl<'a> SyntaxRewriter<'a> {
552 }; 553 };
553 } else { 554 } else {
554 match element { 555 match element {
555 NodeOrToken::Token(it) => acc.push(NodeOrToken::Token(it.green().clone())), 556 NodeOrToken::Token(it) => acc.push(NodeOrToken::Token(it.green().to_owned())),
556 NodeOrToken::Node(it) => { 557 NodeOrToken::Node(it) => {
557 acc.push(NodeOrToken::Node(self.rewrite_children(it))); 558 acc.push(NodeOrToken::Node(self.rewrite_children(it)));
558 } 559 }
@@ -567,7 +568,7 @@ impl<'a> SyntaxRewriter<'a> {
567fn element_to_green(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> { 568fn element_to_green(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> {
568 match element { 569 match element {
569 NodeOrToken::Node(it) => NodeOrToken::Node(it.green().to_owned()), 570 NodeOrToken::Node(it) => NodeOrToken::Node(it.green().to_owned()),
570 NodeOrToken::Token(it) => NodeOrToken::Token(it.green().clone()), 571 NodeOrToken::Token(it) => NodeOrToken::Token(it.green().to_owned()),
571 } 572 }
572} 573}
573 574
@@ -625,7 +626,7 @@ fn position_of_child(parent: &SyntaxNode, child: SyntaxElement) -> usize {
625fn to_green_element(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> { 626fn to_green_element(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> {
626 match element { 627 match element {
627 NodeOrToken::Node(it) => it.green().to_owned().into(), 628 NodeOrToken::Node(it) => it.green().to_owned().into(),
628 NodeOrToken::Token(it) => it.green().clone().into(), 629 NodeOrToken::Token(it) => it.green().to_owned().into(),
629 } 630 }
630} 631}
631 632
diff --git a/crates/syntax/src/ast.rs b/crates/syntax/src/ast.rs
index b3a24d39d..19261686c 100644
--- a/crates/syntax/src/ast.rs
+++ b/crates/syntax/src/ast.rs
@@ -6,6 +6,7 @@ mod token_ext;
6mod node_ext; 6mod node_ext;
7mod expr_ext; 7mod expr_ext;
8pub mod edit; 8pub mod edit;
9pub mod edit_in_place;
9pub mod make; 10pub mod make;
10 11
11use std::marker::PhantomData; 12use std::marker::PhantomData;
@@ -40,6 +41,12 @@ pub trait AstNode {
40 Self: Sized; 41 Self: Sized;
41 42
42 fn syntax(&self) -> &SyntaxNode; 43 fn syntax(&self) -> &SyntaxNode;
44 fn clone_for_update(&self) -> Self
45 where
46 Self: Sized,
47 {
48 Self::cast(self.syntax().clone_for_update()).unwrap()
49 }
43} 50}
44 51
45/// Like `AstNode`, but wraps tokens rather than interior nodes. 52/// Like `AstNode`, but wraps tokens rather than interior nodes.
diff --git a/crates/syntax/src/ast/edit_in_place.rs b/crates/syntax/src/ast/edit_in_place.rs
new file mode 100644
index 000000000..1788f2a40
--- /dev/null
+++ b/crates/syntax/src/ast/edit_in_place.rs
@@ -0,0 +1,139 @@
1//! Structural editing for ast.
2
3use std::iter::empty;
4
5use ast::{edit::AstNodeEdit, make, GenericParamsOwner, WhereClause};
6use parser::T;
7
8use crate::{
9 ast,
10 ted::{self, Position},
11 AstNode, Direction, SyntaxKind,
12};
13
14use super::NameOwner;
15
16pub trait GenericParamsOwnerEdit: ast::GenericParamsOwner + AstNodeEdit {
17 fn get_or_create_where_clause(&self) -> ast::WhereClause;
18}
19
20impl GenericParamsOwnerEdit for ast::Fn {
21 fn get_or_create_where_clause(&self) -> WhereClause {
22 if self.where_clause().is_none() {
23 let position = if let Some(ty) = self.ret_type() {
24 Position::after(ty.syntax().clone())
25 } else if let Some(param_list) = self.param_list() {
26 Position::after(param_list.syntax().clone())
27 } else {
28 Position::last_child_of(self.syntax().clone())
29 };
30 create_where_clause(position, true)
31 }
32 self.where_clause().unwrap()
33 }
34}
35
36impl GenericParamsOwnerEdit for ast::Impl {
37 fn get_or_create_where_clause(&self) -> WhereClause {
38 if self.where_clause().is_none() {
39 let position = if let Some(items) = self.assoc_item_list() {
40 Position::before(items.syntax().clone())
41 } else {
42 Position::last_child_of(self.syntax().clone())
43 };
44 create_where_clause(position, false)
45 }
46 self.where_clause().unwrap()
47 }
48}
49
50impl GenericParamsOwnerEdit for ast::Trait {
51 fn get_or_create_where_clause(&self) -> WhereClause {
52 if self.where_clause().is_none() {
53 let position = if let Some(items) = self.assoc_item_list() {
54 Position::before(items.syntax().clone())
55 } else {
56 Position::last_child_of(self.syntax().clone())
57 };
58 create_where_clause(position, false)
59 }
60 self.where_clause().unwrap()
61 }
62}
63
64impl GenericParamsOwnerEdit for ast::Struct {
65 fn get_or_create_where_clause(&self) -> WhereClause {
66 if self.where_clause().is_none() {
67 let tfl = self.field_list().and_then(|fl| match fl {
68 ast::FieldList::RecordFieldList(_) => None,
69 ast::FieldList::TupleFieldList(it) => Some(it),
70 });
71 let position = if let Some(tfl) = tfl {
72 Position::after(tfl.syntax().clone())
73 } else if let Some(gpl) = self.generic_param_list() {
74 Position::after(gpl.syntax().clone())
75 } else if let Some(name) = self.name() {
76 Position::after(name.syntax().clone())
77 } else {
78 Position::last_child_of(self.syntax().clone())
79 };
80 create_where_clause(position, true)
81 }
82 self.where_clause().unwrap()
83 }
84}
85
86impl GenericParamsOwnerEdit for ast::Enum {
87 fn get_or_create_where_clause(&self) -> WhereClause {
88 if self.where_clause().is_none() {
89 let position = if let Some(gpl) = self.generic_param_list() {
90 Position::after(gpl.syntax().clone())
91 } else if let Some(name) = self.name() {
92 Position::after(name.syntax().clone())
93 } else {
94 Position::last_child_of(self.syntax().clone())
95 };
96 create_where_clause(position, true)
97 }
98 self.where_clause().unwrap()
99 }
100}
101
102fn create_where_clause(position: Position, after: bool) {
103 let mut elements = vec![make::where_clause(empty()).clone_for_update().syntax().clone().into()];
104 let ws = make::tokens::single_space().into();
105 if after {
106 elements.insert(0, ws)
107 } else {
108 elements.push(ws)
109 }
110 ted::insert_all(position, elements);
111}
112
113impl ast::WhereClause {
114 pub fn add_predicate(&self, predicate: ast::WherePred) {
115 if let Some(pred) = self.predicates().last() {
116 if !pred.syntax().siblings_with_tokens(Direction::Next).any(|it| it.kind() == T![,]) {
117 ted::append_child(self.syntax().clone(), make::token(T![,]));
118 }
119 }
120 if self.syntax().children_with_tokens().last().map(|it| it.kind())
121 != Some(SyntaxKind::WHITESPACE)
122 {
123 ted::append_child(self.syntax().clone(), make::tokens::single_space());
124 }
125 ted::append_child(self.syntax().clone(), predicate.syntax().clone())
126 }
127}
128
129impl ast::TypeBoundList {
130 pub fn remove(&self) {
131 if let Some(colon) =
132 self.syntax().siblings_with_tokens(Direction::Prev).find(|it| it.kind() == T![:])
133 {
134 ted::remove_all(colon..=self.syntax().clone().into())
135 } else {
136 ted::remove(self.syntax().clone())
137 }
138 }
139}
diff --git a/crates/syntax/src/ast/generated/nodes.rs b/crates/syntax/src/ast/generated/nodes.rs
index 064931aec..6097178b6 100644
--- a/crates/syntax/src/ast/generated/nodes.rs
+++ b/crates/syntax/src/ast/generated/nodes.rs
@@ -1336,6 +1336,7 @@ pub enum Expr {
1336 Literal(Literal), 1336 Literal(Literal),
1337 LoopExpr(LoopExpr), 1337 LoopExpr(LoopExpr),
1338 MacroCall(MacroCall), 1338 MacroCall(MacroCall),
1339 MacroStmts(MacroStmts),
1339 MatchExpr(MatchExpr), 1340 MatchExpr(MatchExpr),
1340 MethodCallExpr(MethodCallExpr), 1341 MethodCallExpr(MethodCallExpr),
1341 ParenExpr(ParenExpr), 1342 ParenExpr(ParenExpr),
@@ -3034,6 +3035,9 @@ impl From<LoopExpr> for Expr {
3034impl From<MacroCall> for Expr { 3035impl From<MacroCall> for Expr {
3035 fn from(node: MacroCall) -> Expr { Expr::MacroCall(node) } 3036 fn from(node: MacroCall) -> Expr { Expr::MacroCall(node) }
3036} 3037}
3038impl From<MacroStmts> for Expr {
3039 fn from(node: MacroStmts) -> Expr { Expr::MacroStmts(node) }
3040}
3037impl From<MatchExpr> for Expr { 3041impl From<MatchExpr> for Expr {
3038 fn from(node: MatchExpr) -> Expr { Expr::MatchExpr(node) } 3042 fn from(node: MatchExpr) -> Expr { Expr::MatchExpr(node) }
3039} 3043}
@@ -3078,8 +3082,8 @@ impl AstNode for Expr {
3078 match kind { 3082 match kind {
3079 ARRAY_EXPR | AWAIT_EXPR | BIN_EXPR | BLOCK_EXPR | BOX_EXPR | BREAK_EXPR | CALL_EXPR 3083 ARRAY_EXPR | AWAIT_EXPR | BIN_EXPR | BLOCK_EXPR | BOX_EXPR | BREAK_EXPR | CALL_EXPR
3080 | CAST_EXPR | CLOSURE_EXPR | CONTINUE_EXPR | EFFECT_EXPR | FIELD_EXPR | FOR_EXPR 3084 | CAST_EXPR | CLOSURE_EXPR | CONTINUE_EXPR | EFFECT_EXPR | FIELD_EXPR | FOR_EXPR
3081 | IF_EXPR | INDEX_EXPR | LITERAL | LOOP_EXPR | MACRO_CALL | MATCH_EXPR 3085 | IF_EXPR | INDEX_EXPR | LITERAL | LOOP_EXPR | MACRO_CALL | MACRO_STMTS
3082 | METHOD_CALL_EXPR | PAREN_EXPR | PATH_EXPR | PREFIX_EXPR | RANGE_EXPR 3086 | MATCH_EXPR | METHOD_CALL_EXPR | PAREN_EXPR | PATH_EXPR | PREFIX_EXPR | RANGE_EXPR
3083 | RECORD_EXPR | REF_EXPR | RETURN_EXPR | TRY_EXPR | TUPLE_EXPR | WHILE_EXPR 3087 | RECORD_EXPR | REF_EXPR | RETURN_EXPR | TRY_EXPR | TUPLE_EXPR | WHILE_EXPR
3084 | YIELD_EXPR => true, 3088 | YIELD_EXPR => true,
3085 _ => false, 3089 _ => false,
@@ -3105,6 +3109,7 @@ impl AstNode for Expr {
3105 LITERAL => Expr::Literal(Literal { syntax }), 3109 LITERAL => Expr::Literal(Literal { syntax }),
3106 LOOP_EXPR => Expr::LoopExpr(LoopExpr { syntax }), 3110 LOOP_EXPR => Expr::LoopExpr(LoopExpr { syntax }),
3107 MACRO_CALL => Expr::MacroCall(MacroCall { syntax }), 3111 MACRO_CALL => Expr::MacroCall(MacroCall { syntax }),
3112 MACRO_STMTS => Expr::MacroStmts(MacroStmts { syntax }),
3108 MATCH_EXPR => Expr::MatchExpr(MatchExpr { syntax }), 3113 MATCH_EXPR => Expr::MatchExpr(MatchExpr { syntax }),
3109 METHOD_CALL_EXPR => Expr::MethodCallExpr(MethodCallExpr { syntax }), 3114 METHOD_CALL_EXPR => Expr::MethodCallExpr(MethodCallExpr { syntax }),
3110 PAREN_EXPR => Expr::ParenExpr(ParenExpr { syntax }), 3115 PAREN_EXPR => Expr::ParenExpr(ParenExpr { syntax }),
@@ -3142,6 +3147,7 @@ impl AstNode for Expr {
3142 Expr::Literal(it) => &it.syntax, 3147 Expr::Literal(it) => &it.syntax,
3143 Expr::LoopExpr(it) => &it.syntax, 3148 Expr::LoopExpr(it) => &it.syntax,
3144 Expr::MacroCall(it) => &it.syntax, 3149 Expr::MacroCall(it) => &it.syntax,
3150 Expr::MacroStmts(it) => &it.syntax,
3145 Expr::MatchExpr(it) => &it.syntax, 3151 Expr::MatchExpr(it) => &it.syntax,
3146 Expr::MethodCallExpr(it) => &it.syntax, 3152 Expr::MethodCallExpr(it) => &it.syntax,
3147 Expr::ParenExpr(it) => &it.syntax, 3153 Expr::ParenExpr(it) => &it.syntax,
diff --git a/crates/syntax/src/ast/make.rs b/crates/syntax/src/ast/make.rs
index 05a6b0b25..810c8d4c8 100644
--- a/crates/syntax/src/ast/make.rs
+++ b/crates/syntax/src/ast/make.rs
@@ -174,6 +174,11 @@ pub fn block_expr(
174pub fn expr_unit() -> ast::Expr { 174pub fn expr_unit() -> ast::Expr {
175 expr_from_text("()") 175 expr_from_text("()")
176} 176}
177pub fn expr_literal(text: &str) -> ast::Literal {
178 assert_eq!(text.trim(), text);
179 ast_from_text(&format!("fn f() {{ let _ = {}; }}", text))
180}
181
177pub fn expr_empty_block() -> ast::Expr { 182pub fn expr_empty_block() -> ast::Expr {
178 expr_from_text("{}") 183 expr_from_text("{}")
179} 184}
@@ -390,6 +395,7 @@ pub fn token(kind: SyntaxKind) -> SyntaxToken {
390 tokens::SOURCE_FILE 395 tokens::SOURCE_FILE
391 .tree() 396 .tree()
392 .syntax() 397 .syntax()
398 .clone_for_update()
393 .descendants_with_tokens() 399 .descendants_with_tokens()
394 .filter_map(|it| it.into_token()) 400 .filter_map(|it| it.into_token())
395 .find(|it| it.kind() == kind) 401 .find(|it| it.kind() == kind)
@@ -544,6 +550,7 @@ pub mod tokens {
544 SOURCE_FILE 550 SOURCE_FILE
545 .tree() 551 .tree()
546 .syntax() 552 .syntax()
553 .clone_for_update()
547 .descendants_with_tokens() 554 .descendants_with_tokens()
548 .filter_map(|it| it.into_token()) 555 .filter_map(|it| it.into_token())
549 .find(|it| it.kind() == WHITESPACE && it.text() == " ") 556 .find(|it| it.kind() == WHITESPACE && it.text() == " ")
@@ -569,13 +576,16 @@ pub mod tokens {
569 } 576 }
570 577
571 pub fn single_newline() -> SyntaxToken { 578 pub fn single_newline() -> SyntaxToken {
572 SOURCE_FILE 579 let res = SOURCE_FILE
573 .tree() 580 .tree()
574 .syntax() 581 .syntax()
582 .clone_for_update()
575 .descendants_with_tokens() 583 .descendants_with_tokens()
576 .filter_map(|it| it.into_token()) 584 .filter_map(|it| it.into_token())
577 .find(|it| it.kind() == WHITESPACE && it.text() == "\n") 585 .find(|it| it.kind() == WHITESPACE && it.text() == "\n")
578 .unwrap() 586 .unwrap();
587 res.detach();
588 res
579 } 589 }
580 590
581 pub fn blank_line() -> SyntaxToken { 591 pub fn blank_line() -> SyntaxToken {
diff --git a/crates/syntax/src/ast/node_ext.rs b/crates/syntax/src/ast/node_ext.rs
index 52ac97c84..0b0d39a75 100644
--- a/crates/syntax/src/ast/node_ext.rs
+++ b/crates/syntax/src/ast/node_ext.rs
@@ -34,7 +34,9 @@ impl ast::NameRef {
34} 34}
35 35
36fn text_of_first_token(node: &SyntaxNode) -> &str { 36fn text_of_first_token(node: &SyntaxNode) -> &str {
37 node.green().children().next().and_then(|it| it.into_token()).unwrap().text() 37 let t =
38 node.green().children().next().and_then(|it| it.into_token()).unwrap().text().to_string();
39 Box::leak(Box::new(t))
38} 40}
39 41
40pub enum Macro { 42pub enum Macro {
diff --git a/crates/syntax/src/lib.rs b/crates/syntax/src/lib.rs
index 09e212e8c..2a5c61171 100644
--- a/crates/syntax/src/lib.rs
+++ b/crates/syntax/src/lib.rs
@@ -38,6 +38,7 @@ pub mod ast;
38#[doc(hidden)] 38#[doc(hidden)]
39pub mod fuzz; 39pub mod fuzz;
40pub mod utils; 40pub mod utils;
41pub mod ted;
41 42
42use std::{marker::PhantomData, sync::Arc}; 43use std::{marker::PhantomData, sync::Arc};
43 44
diff --git a/crates/syntax/src/parsing/reparsing.rs b/crates/syntax/src/parsing/reparsing.rs
index 3d637bf91..4ad50ab72 100644
--- a/crates/syntax/src/parsing/reparsing.rs
+++ b/crates/syntax/src/parsing/reparsing.rs
@@ -124,11 +124,7 @@ fn is_contextual_kw(text: &str) -> bool {
124fn find_reparsable_node(node: &SyntaxNode, range: TextRange) -> Option<(SyntaxNode, Reparser)> { 124fn find_reparsable_node(node: &SyntaxNode, range: TextRange) -> Option<(SyntaxNode, Reparser)> {
125 let node = node.covering_element(range); 125 let node = node.covering_element(range);
126 126
127 let mut ancestors = match node { 127 node.ancestors().find_map(|node| {
128 NodeOrToken::Token(it) => it.parent().ancestors(),
129 NodeOrToken::Node(it) => it.ancestors(),
130 };
131 ancestors.find_map(|node| {
132 let first_child = node.first_child_or_token().map(|it| it.kind()); 128 let first_child = node.first_child_or_token().map(|it| it.kind());
133 let parent = node.parent().map(|it| it.kind()); 129 let parent = node.parent().map(|it| it.kind());
134 Reparser::for_node(node.kind(), first_child, parent).map(|r| (node, r)) 130 Reparser::for_node(node.kind(), first_child, parent).map(|r| (node, r))
diff --git a/crates/syntax/src/ted.rs b/crates/syntax/src/ted.rs
new file mode 100644
index 000000000..8d6175ed9
--- /dev/null
+++ b/crates/syntax/src/ted.rs
@@ -0,0 +1,78 @@
1//! Primitive tree editor, ed for trees
2#![allow(unused)]
3use std::ops::RangeInclusive;
4
5use crate::{SyntaxElement, SyntaxNode};
6
7#[derive(Debug)]
8pub struct Position {
9 repr: PositionRepr,
10}
11
12#[derive(Debug)]
13enum PositionRepr {
14 FirstChild(SyntaxNode),
15 After(SyntaxElement),
16}
17
18impl Position {
19 pub fn after(elem: impl Into<SyntaxElement>) -> Position {
20 let repr = PositionRepr::After(elem.into());
21 Position { repr }
22 }
23 pub fn before(elem: impl Into<SyntaxElement>) -> Position {
24 let elem = elem.into();
25 let repr = match elem.prev_sibling_or_token() {
26 Some(it) => PositionRepr::After(it),
27 None => PositionRepr::FirstChild(elem.parent().unwrap()),
28 };
29 Position { repr }
30 }
31 pub fn first_child_of(node: impl Into<SyntaxNode>) -> Position {
32 let repr = PositionRepr::FirstChild(node.into());
33 Position { repr }
34 }
35 pub fn last_child_of(node: impl Into<SyntaxNode>) -> Position {
36 let node = node.into();
37 let repr = match node.last_child_or_token() {
38 Some(it) => PositionRepr::After(it),
39 None => PositionRepr::FirstChild(node),
40 };
41 Position { repr }
42 }
43}
44
45pub fn insert(position: Position, elem: impl Into<SyntaxElement>) {
46 insert_all(position, vec![elem.into()])
47}
48pub fn insert_all(position: Position, elements: Vec<SyntaxElement>) {
49 let (parent, index) = match position.repr {
50 PositionRepr::FirstChild(parent) => (parent, 0),
51 PositionRepr::After(child) => (child.parent().unwrap(), child.index() + 1),
52 };
53 parent.splice_children(index..index, elements);
54}
55
56pub fn remove(elem: impl Into<SyntaxElement>) {
57 let elem = elem.into();
58 remove_all(elem.clone()..=elem)
59}
60pub fn remove_all(range: RangeInclusive<SyntaxElement>) {
61 replace_all(range, Vec::new())
62}
63
64pub fn replace(old: impl Into<SyntaxElement>, new: impl Into<SyntaxElement>) {
65 let old = old.into();
66 replace_all(old.clone()..=old, vec![new.into()])
67}
68pub fn replace_all(range: RangeInclusive<SyntaxElement>, new: Vec<SyntaxElement>) {
69 let start = range.start().index();
70 let end = range.end().index();
71 let parent = range.start().parent().unwrap();
72 parent.splice_children(start..end + 1, new)
73}
74
75pub fn append_child(node: impl Into<SyntaxNode>, child: impl Into<SyntaxElement>) {
76 let position = Position::last_child_of(node);
77 insert(position, child)
78}
diff --git a/crates/test_utils/src/fixture.rs b/crates/test_utils/src/fixture.rs
index e3f57f3b2..6bc824e94 100644
--- a/crates/test_utils/src/fixture.rs
+++ b/crates/test_utils/src/fixture.rs
@@ -14,6 +14,7 @@ pub struct Fixture {
14 pub cfg_key_values: Vec<(String, String)>, 14 pub cfg_key_values: Vec<(String, String)>,
15 pub edition: Option<String>, 15 pub edition: Option<String>,
16 pub env: FxHashMap<String, String>, 16 pub env: FxHashMap<String, String>,
17 pub introduce_new_source_root: bool,
17} 18}
18 19
19impl Fixture { 20impl Fixture {
@@ -70,6 +71,7 @@ impl Fixture {
70 let mut cfg_atoms = Vec::new(); 71 let mut cfg_atoms = Vec::new();
71 let mut cfg_key_values = Vec::new(); 72 let mut cfg_key_values = Vec::new();
72 let mut env = FxHashMap::default(); 73 let mut env = FxHashMap::default();
74 let mut introduce_new_source_root = false;
73 for component in components[1..].iter() { 75 for component in components[1..].iter() {
74 let (key, value) = split_once(component, ':').unwrap(); 76 let (key, value) = split_once(component, ':').unwrap();
75 match key { 77 match key {
@@ -91,11 +93,22 @@ impl Fixture {
91 } 93 }
92 } 94 }
93 } 95 }
96 "new_source_root" => introduce_new_source_root = true,
94 _ => panic!("bad component: {:?}", component), 97 _ => panic!("bad component: {:?}", component),
95 } 98 }
96 } 99 }
97 100
98 Fixture { path, text: String::new(), krate, deps, cfg_atoms, cfg_key_values, edition, env } 101 Fixture {
102 path,
103 text: String::new(),
104 krate,
105 deps,
106 cfg_atoms,
107 cfg_key_values,
108 edition,
109 env,
110 introduce_new_source_root,
111 }
99 } 112 }
100} 113}
101 114