diff options
Diffstat (limited to 'crates/ra_hir')
31 files changed, 414 insertions, 12609 deletions
diff --git a/crates/ra_hir/Cargo.toml b/crates/ra_hir/Cargo.toml index 42ddfecc9..e79361e7c 100644 --- a/crates/ra_hir/Cargo.toml +++ b/crates/ra_hir/Cargo.toml | |||
@@ -8,28 +8,11 @@ authors = ["rust-analyzer developers"] | |||
8 | doctest = false | 8 | doctest = false |
9 | 9 | ||
10 | [dependencies] | 10 | [dependencies] |
11 | arrayvec = "0.5.1" | ||
12 | log = "0.4.5" | 11 | log = "0.4.5" |
13 | rustc-hash = "1.0" | 12 | rustc-hash = "1.0" |
14 | parking_lot = "0.9.0" | ||
15 | ena = "0.13" | ||
16 | once_cell = "1.0.1" | ||
17 | 13 | ||
18 | ra_syntax = { path = "../ra_syntax" } | 14 | ra_syntax = { path = "../ra_syntax" } |
19 | ra_arena = { path = "../ra_arena" } | ||
20 | ra_cfg = { path = "../ra_cfg" } | ||
21 | ra_db = { path = "../ra_db" } | 15 | ra_db = { path = "../ra_db" } |
22 | mbe = { path = "../ra_mbe", package = "ra_mbe" } | ||
23 | tt = { path = "../ra_tt", package = "ra_tt" } | ||
24 | hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" } | 16 | hir_expand = { path = "../ra_hir_expand", package = "ra_hir_expand" } |
25 | hir_def = { path = "../ra_hir_def", package = "ra_hir_def" } | 17 | hir_def = { path = "../ra_hir_def", package = "ra_hir_def" } |
26 | test_utils = { path = "../test_utils" } | 18 | hir_ty = { path = "../ra_hir_ty", package = "ra_hir_ty" } |
27 | ra_prof = { path = "../ra_prof" } | ||
28 | |||
29 | chalk-solve = { git = "https://github.com/rust-lang/chalk.git", rev = "a88cad7f0a69e05ba8f40b74c58a1c229c1b2478" } | ||
30 | chalk-rust-ir = { git = "https://github.com/rust-lang/chalk.git", rev = "a88cad7f0a69e05ba8f40b74c58a1c229c1b2478" } | ||
31 | chalk-ir = { git = "https://github.com/rust-lang/chalk.git", rev = "a88cad7f0a69e05ba8f40b74c58a1c229c1b2478" } | ||
32 | lalrpop-intern = "0.15.1" | ||
33 | |||
34 | [dev-dependencies] | ||
35 | insta = "0.12.0" | ||
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs index 3f44a50c4..38d66c2a7 100644 --- a/crates/ra_hir/src/code_model.rs +++ b/crates/ra_hir/src/code_model.rs | |||
@@ -6,28 +6,31 @@ use std::sync::Arc; | |||
6 | 6 | ||
7 | use hir_def::{ | 7 | use hir_def::{ |
8 | adt::VariantData, | 8 | adt::VariantData, |
9 | body::{Body, BodySourceMap}, | ||
9 | builtin_type::BuiltinType, | 10 | builtin_type::BuiltinType, |
10 | docs::Documentation, | 11 | docs::Documentation, |
12 | expr::{BindingAnnotation, Pat, PatId}, | ||
11 | per_ns::PerNs, | 13 | per_ns::PerNs, |
12 | resolver::{HasResolver, TypeNs}, | 14 | resolver::HasResolver, |
13 | type_ref::TypeRef, | 15 | type_ref::{Mutability, TypeRef}, |
14 | AstItemDef, ConstId, ContainerId, EnumId, FunctionId, HasModule, ImplId, LocalEnumVariantId, | 16 | AdtId, AstItemDef, ConstId, ContainerId, DefWithBodyId, EnumId, FunctionId, GenericDefId, |
15 | LocalImportId, LocalModuleId, LocalStructFieldId, Lookup, ModuleId, StaticId, StructId, | 17 | HasModule, ImplId, LocalEnumVariantId, LocalImportId, LocalModuleId, LocalStructFieldId, |
16 | TraitId, TypeAliasId, UnionId, | 18 | Lookup, ModuleId, StaticId, StructId, TraitId, TypeAliasId, UnionId, |
17 | }; | 19 | }; |
18 | use hir_expand::{ | 20 | use hir_expand::{ |
19 | diagnostics::DiagnosticSink, | 21 | diagnostics::DiagnosticSink, |
20 | name::{self, AsName}, | 22 | name::{self, AsName}, |
21 | AstId, MacroDefId, | 23 | AstId, MacroDefId, |
22 | }; | 24 | }; |
25 | use hir_ty::expr::ExprValidator; | ||
23 | use ra_db::{CrateId, Edition, FileId, FilePosition}; | 26 | use ra_db::{CrateId, Edition, FileId, FilePosition}; |
24 | use ra_syntax::{ast, AstNode, SyntaxNode}; | 27 | use ra_syntax::{ast, AstNode, SyntaxNode}; |
25 | 28 | ||
26 | use crate::{ | 29 | use crate::{ |
27 | db::{DefDatabase, HirDatabase}, | 30 | db::{DefDatabase, HirDatabase}, |
28 | expr::{BindingAnnotation, Body, BodySourceMap, ExprValidator, Pat, PatId}, | 31 | ty::display::HirFormatter, |
29 | ty::{InferenceResult, Namespace, TraitRef}, | 32 | ty::{self, InEnvironment, InferenceResult, TraitEnvironment, Ty, TyDefId, TypeCtor, TypeWalk}, |
30 | Either, Name, Source, Ty, | 33 | CallableDef, Either, HirDisplay, Name, Source, |
31 | }; | 34 | }; |
32 | 35 | ||
33 | /// hir::Crate describes a single crate. It's the main interface with which | 36 | /// hir::Crate describes a single crate. It's the main interface with which |
@@ -168,15 +171,15 @@ pub use hir_def::attr::Attrs; | |||
168 | 171 | ||
169 | impl Module { | 172 | impl Module { |
170 | pub(crate) fn new(krate: Crate, crate_module_id: LocalModuleId) -> Module { | 173 | pub(crate) fn new(krate: Crate, crate_module_id: LocalModuleId) -> Module { |
171 | Module { id: ModuleId { krate: krate.crate_id, module_id: crate_module_id } } | 174 | Module { id: ModuleId { krate: krate.crate_id, local_id: crate_module_id } } |
172 | } | 175 | } |
173 | 176 | ||
174 | /// Name of this module. | 177 | /// Name of this module. |
175 | pub fn name(self, db: &impl DefDatabase) -> Option<Name> { | 178 | pub fn name(self, db: &impl DefDatabase) -> Option<Name> { |
176 | let def_map = db.crate_def_map(self.id.krate); | 179 | let def_map = db.crate_def_map(self.id.krate); |
177 | let parent = def_map[self.id.module_id].parent?; | 180 | let parent = def_map[self.id.local_id].parent?; |
178 | def_map[parent].children.iter().find_map(|(name, module_id)| { | 181 | def_map[parent].children.iter().find_map(|(name, module_id)| { |
179 | if *module_id == self.id.module_id { | 182 | if *module_id == self.id.local_id { |
180 | Some(name.clone()) | 183 | Some(name.clone()) |
181 | } else { | 184 | } else { |
182 | None | 185 | None |
@@ -200,14 +203,14 @@ impl Module { | |||
200 | /// Finds a child module with the specified name. | 203 | /// Finds a child module with the specified name. |
201 | pub fn child(self, db: &impl DefDatabase, name: &Name) -> Option<Module> { | 204 | pub fn child(self, db: &impl DefDatabase, name: &Name) -> Option<Module> { |
202 | let def_map = db.crate_def_map(self.id.krate); | 205 | let def_map = db.crate_def_map(self.id.krate); |
203 | let child_id = def_map[self.id.module_id].children.get(name)?; | 206 | let child_id = def_map[self.id.local_id].children.get(name)?; |
204 | Some(self.with_module_id(*child_id)) | 207 | Some(self.with_module_id(*child_id)) |
205 | } | 208 | } |
206 | 209 | ||
207 | /// Iterates over all child modules. | 210 | /// Iterates over all child modules. |
208 | pub fn children(self, db: &impl DefDatabase) -> impl Iterator<Item = Module> { | 211 | pub fn children(self, db: &impl DefDatabase) -> impl Iterator<Item = Module> { |
209 | let def_map = db.crate_def_map(self.id.krate); | 212 | let def_map = db.crate_def_map(self.id.krate); |
210 | let children = def_map[self.id.module_id] | 213 | let children = def_map[self.id.local_id] |
211 | .children | 214 | .children |
212 | .iter() | 215 | .iter() |
213 | .map(|(_, module_id)| self.with_module_id(*module_id)) | 216 | .map(|(_, module_id)| self.with_module_id(*module_id)) |
@@ -218,7 +221,7 @@ impl Module { | |||
218 | /// Finds a parent module. | 221 | /// Finds a parent module. |
219 | pub fn parent(self, db: &impl DefDatabase) -> Option<Module> { | 222 | pub fn parent(self, db: &impl DefDatabase) -> Option<Module> { |
220 | let def_map = db.crate_def_map(self.id.krate); | 223 | let def_map = db.crate_def_map(self.id.krate); |
221 | let parent_id = def_map[self.id.module_id].parent?; | 224 | let parent_id = def_map[self.id.local_id].parent?; |
222 | Some(self.with_module_id(parent_id)) | 225 | Some(self.with_module_id(parent_id)) |
223 | } | 226 | } |
224 | 227 | ||
@@ -234,7 +237,7 @@ impl Module { | |||
234 | 237 | ||
235 | /// Returns a `ModuleScope`: a set of items, visible in this module. | 238 | /// Returns a `ModuleScope`: a set of items, visible in this module. |
236 | pub fn scope(self, db: &impl HirDatabase) -> Vec<(Name, ScopeDef, Option<Import>)> { | 239 | pub fn scope(self, db: &impl HirDatabase) -> Vec<(Name, ScopeDef, Option<Import>)> { |
237 | db.crate_def_map(self.id.krate)[self.id.module_id] | 240 | db.crate_def_map(self.id.krate)[self.id.local_id] |
238 | .scope | 241 | .scope |
239 | .entries() | 242 | .entries() |
240 | .map(|(name, res)| { | 243 | .map(|(name, res)| { |
@@ -244,7 +247,7 @@ impl Module { | |||
244 | } | 247 | } |
245 | 248 | ||
246 | pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { | 249 | pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { |
247 | db.crate_def_map(self.id.krate).add_diagnostics(db, self.id.module_id, sink); | 250 | db.crate_def_map(self.id.krate).add_diagnostics(db, self.id.local_id, sink); |
248 | for decl in self.declarations(db) { | 251 | for decl in self.declarations(db) { |
249 | match decl { | 252 | match decl { |
250 | crate::ModuleDef::Function(f) => f.diagnostics(db, sink), | 253 | crate::ModuleDef::Function(f) => f.diagnostics(db, sink), |
@@ -269,12 +272,12 @@ impl Module { | |||
269 | 272 | ||
270 | pub fn declarations(self, db: &impl DefDatabase) -> Vec<ModuleDef> { | 273 | pub fn declarations(self, db: &impl DefDatabase) -> Vec<ModuleDef> { |
271 | let def_map = db.crate_def_map(self.id.krate); | 274 | let def_map = db.crate_def_map(self.id.krate); |
272 | def_map[self.id.module_id].scope.declarations().map(ModuleDef::from).collect() | 275 | def_map[self.id.local_id].scope.declarations().map(ModuleDef::from).collect() |
273 | } | 276 | } |
274 | 277 | ||
275 | pub fn impl_blocks(self, db: &impl DefDatabase) -> Vec<ImplBlock> { | 278 | pub fn impl_blocks(self, db: &impl DefDatabase) -> Vec<ImplBlock> { |
276 | let def_map = db.crate_def_map(self.id.krate); | 279 | let def_map = db.crate_def_map(self.id.krate); |
277 | def_map[self.id.module_id].impls.iter().copied().map(ImplBlock::from).collect() | 280 | def_map[self.id.local_id].impls.iter().copied().map(ImplBlock::from).collect() |
278 | } | 281 | } |
279 | 282 | ||
280 | fn with_module_id(self, module_id: LocalModuleId) -> Module { | 283 | fn with_module_id(self, module_id: LocalModuleId) -> Module { |
@@ -320,14 +323,14 @@ pub struct Struct { | |||
320 | 323 | ||
321 | impl Struct { | 324 | impl Struct { |
322 | pub fn module(self, db: &impl DefDatabase) -> Module { | 325 | pub fn module(self, db: &impl DefDatabase) -> Module { |
323 | Module { id: self.id.0.module(db) } | 326 | Module { id: self.id.module(db) } |
324 | } | 327 | } |
325 | 328 | ||
326 | pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { | 329 | pub fn krate(self, db: &impl DefDatabase) -> Option<Crate> { |
327 | Some(self.module(db).krate()) | 330 | Some(self.module(db).krate()) |
328 | } | 331 | } |
329 | 332 | ||
330 | pub fn name(self, db: &impl DefDatabase) -> Option<Name> { | 333 | pub fn name(self, db: &impl DefDatabase) -> Name { |
331 | db.struct_data(self.id.into()).name.clone() | 334 | db.struct_data(self.id.into()).name.clone() |
332 | } | 335 | } |
333 | 336 | ||
@@ -349,12 +352,12 @@ impl Struct { | |||
349 | .map(|(id, _)| StructField { parent: self.into(), id }) | 352 | .map(|(id, _)| StructField { parent: self.into(), id }) |
350 | } | 353 | } |
351 | 354 | ||
352 | pub fn ty(self, db: &impl HirDatabase) -> Ty { | 355 | pub fn ty(self, db: &impl HirDatabase) -> Type { |
353 | db.type_for_def(self.into(), Namespace::Types) | 356 | Type::from_def(db, self.id.module(db).krate, self.id) |
354 | } | 357 | } |
355 | 358 | ||
356 | pub fn constructor_ty(self, db: &impl HirDatabase) -> Ty { | 359 | pub fn constructor_ty(self, db: &impl HirDatabase) -> Ty { |
357 | db.type_for_def(self.into(), Namespace::Values) | 360 | db.value_ty(self.id.into()) |
358 | } | 361 | } |
359 | 362 | ||
360 | fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { | 363 | fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { |
@@ -368,16 +371,38 @@ pub struct Union { | |||
368 | } | 371 | } |
369 | 372 | ||
370 | impl Union { | 373 | impl Union { |
371 | pub fn name(self, db: &impl DefDatabase) -> Option<Name> { | 374 | pub fn name(self, db: &impl DefDatabase) -> Name { |
372 | db.struct_data(self.id.into()).name.clone() | 375 | db.union_data(self.id).name.clone() |
373 | } | 376 | } |
374 | 377 | ||
375 | pub fn module(self, db: &impl DefDatabase) -> Module { | 378 | pub fn module(self, db: &impl DefDatabase) -> Module { |
376 | Module { id: self.id.0.module(db) } | 379 | Module { id: self.id.module(db) } |
377 | } | 380 | } |
378 | 381 | ||
379 | pub fn ty(self, db: &impl HirDatabase) -> Ty { | 382 | pub fn ty(self, db: &impl HirDatabase) -> Type { |
380 | db.type_for_def(self.into(), Namespace::Types) | 383 | Type::from_def(db, self.id.module(db).krate, self.id) |
384 | } | ||
385 | |||
386 | pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> { | ||
387 | db.union_data(self.id) | ||
388 | .variant_data | ||
389 | .fields() | ||
390 | .iter() | ||
391 | .map(|(id, _)| StructField { parent: self.into(), id }) | ||
392 | .collect() | ||
393 | } | ||
394 | |||
395 | pub fn field(self, db: &impl HirDatabase, name: &Name) -> Option<StructField> { | ||
396 | db.union_data(self.id) | ||
397 | .variant_data | ||
398 | .fields() | ||
399 | .iter() | ||
400 | .find(|(_id, data)| data.name == *name) | ||
401 | .map(|(id, _)| StructField { parent: self.into(), id }) | ||
402 | } | ||
403 | |||
404 | fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { | ||
405 | db.union_data(self.id).variant_data.clone() | ||
381 | } | 406 | } |
382 | } | 407 | } |
383 | 408 | ||
@@ -395,7 +420,7 @@ impl Enum { | |||
395 | Some(self.module(db).krate()) | 420 | Some(self.module(db).krate()) |
396 | } | 421 | } |
397 | 422 | ||
398 | pub fn name(self, db: &impl DefDatabase) -> Option<Name> { | 423 | pub fn name(self, db: &impl DefDatabase) -> Name { |
399 | db.enum_data(self.id).name.clone() | 424 | db.enum_data(self.id).name.clone() |
400 | } | 425 | } |
401 | 426 | ||
@@ -408,15 +433,12 @@ impl Enum { | |||
408 | } | 433 | } |
409 | 434 | ||
410 | pub fn variant(self, db: &impl DefDatabase, name: &Name) -> Option<EnumVariant> { | 435 | pub fn variant(self, db: &impl DefDatabase, name: &Name) -> Option<EnumVariant> { |
411 | db.enum_data(self.id) | 436 | let id = db.enum_data(self.id).variant(name)?; |
412 | .variants | 437 | Some(EnumVariant { parent: self, id }) |
413 | .iter() | ||
414 | .find(|(_id, data)| data.name.as_ref() == Some(name)) | ||
415 | .map(|(id, _)| EnumVariant { parent: self, id }) | ||
416 | } | 438 | } |
417 | 439 | ||
418 | pub fn ty(self, db: &impl HirDatabase) -> Ty { | 440 | pub fn ty(self, db: &impl HirDatabase) -> Type { |
419 | db.type_for_def(self.into(), Namespace::Types) | 441 | Type::from_def(db, self.id.module(db).krate, self.id) |
420 | } | 442 | } |
421 | } | 443 | } |
422 | 444 | ||
@@ -434,7 +456,7 @@ impl EnumVariant { | |||
434 | self.parent | 456 | self.parent |
435 | } | 457 | } |
436 | 458 | ||
437 | pub fn name(self, db: &impl DefDatabase) -> Option<Name> { | 459 | pub fn name(self, db: &impl DefDatabase) -> Name { |
438 | db.enum_data(self.parent.id).variants[self.id].name.clone() | 460 | db.enum_data(self.parent.id).variants[self.id].name.clone() |
439 | } | 461 | } |
440 | 462 | ||
@@ -469,12 +491,13 @@ pub enum Adt { | |||
469 | impl_froms!(Adt: Struct, Union, Enum); | 491 | impl_froms!(Adt: Struct, Union, Enum); |
470 | 492 | ||
471 | impl Adt { | 493 | impl Adt { |
472 | pub fn ty(self, db: &impl HirDatabase) -> Ty { | 494 | pub fn has_non_default_type_params(self, db: &impl HirDatabase) -> bool { |
473 | match self { | 495 | let subst = db.generic_defaults(self.into()); |
474 | Adt::Struct(it) => it.ty(db), | 496 | subst.iter().any(|ty| ty == &Ty::Unknown) |
475 | Adt::Union(it) => it.ty(db), | 497 | } |
476 | Adt::Enum(it) => it.ty(db), | 498 | pub fn ty(self, db: &impl HirDatabase) -> Type { |
477 | } | 499 | let id = AdtId::from(self); |
500 | Type::from_def(db, id.module(db).krate, id) | ||
478 | } | 501 | } |
479 | 502 | ||
480 | pub fn module(self, db: &impl DefDatabase) -> Module { | 503 | pub fn module(self, db: &impl DefDatabase) -> Module { |
@@ -493,28 +516,24 @@ impl Adt { | |||
493 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | 516 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
494 | pub enum VariantDef { | 517 | pub enum VariantDef { |
495 | Struct(Struct), | 518 | Struct(Struct), |
519 | Union(Union), | ||
496 | EnumVariant(EnumVariant), | 520 | EnumVariant(EnumVariant), |
497 | } | 521 | } |
498 | impl_froms!(VariantDef: Struct, EnumVariant); | 522 | impl_froms!(VariantDef: Struct, Union, EnumVariant); |
499 | 523 | ||
500 | impl VariantDef { | 524 | impl VariantDef { |
501 | pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> { | 525 | pub fn fields(self, db: &impl HirDatabase) -> Vec<StructField> { |
502 | match self { | 526 | match self { |
503 | VariantDef::Struct(it) => it.fields(db), | 527 | VariantDef::Struct(it) => it.fields(db), |
528 | VariantDef::Union(it) => it.fields(db), | ||
504 | VariantDef::EnumVariant(it) => it.fields(db), | 529 | VariantDef::EnumVariant(it) => it.fields(db), |
505 | } | 530 | } |
506 | } | 531 | } |
507 | 532 | ||
508 | pub(crate) fn field(self, db: &impl HirDatabase, name: &Name) -> Option<StructField> { | ||
509 | match self { | ||
510 | VariantDef::Struct(it) => it.field(db, name), | ||
511 | VariantDef::EnumVariant(it) => it.field(db, name), | ||
512 | } | ||
513 | } | ||
514 | |||
515 | pub fn module(self, db: &impl HirDatabase) -> Module { | 533 | pub fn module(self, db: &impl HirDatabase) -> Module { |
516 | match self { | 534 | match self { |
517 | VariantDef::Struct(it) => it.module(db), | 535 | VariantDef::Struct(it) => it.module(db), |
536 | VariantDef::Union(it) => it.module(db), | ||
518 | VariantDef::EnumVariant(it) => it.module(db), | 537 | VariantDef::EnumVariant(it) => it.module(db), |
519 | } | 538 | } |
520 | } | 539 | } |
@@ -522,6 +541,7 @@ impl VariantDef { | |||
522 | pub(crate) fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { | 541 | pub(crate) fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { |
523 | match self { | 542 | match self { |
524 | VariantDef::Struct(it) => it.variant_data(db), | 543 | VariantDef::Struct(it) => it.variant_data(db), |
544 | VariantDef::Union(it) => it.variant_data(db), | ||
525 | VariantDef::EnumVariant(it) => it.variant_data(db), | 545 | VariantDef::EnumVariant(it) => it.variant_data(db), |
526 | } | 546 | } |
527 | } | 547 | } |
@@ -538,14 +558,6 @@ pub enum DefWithBody { | |||
538 | impl_froms!(DefWithBody: Function, Const, Static); | 558 | impl_froms!(DefWithBody: Function, Const, Static); |
539 | 559 | ||
540 | impl DefWithBody { | 560 | impl DefWithBody { |
541 | pub(crate) fn krate(self, db: &impl HirDatabase) -> Option<Crate> { | ||
542 | match self { | ||
543 | DefWithBody::Const(c) => c.krate(db), | ||
544 | DefWithBody::Function(f) => f.krate(db), | ||
545 | DefWithBody::Static(s) => s.krate(db), | ||
546 | } | ||
547 | } | ||
548 | |||
549 | pub fn module(self, db: &impl HirDatabase) -> Module { | 561 | pub fn module(self, db: &impl HirDatabase) -> Module { |
550 | match self { | 562 | match self { |
551 | DefWithBody::Const(c) => c.module(db), | 563 | DefWithBody::Const(c) => c.module(db), |
@@ -590,11 +602,11 @@ impl Function { | |||
590 | } | 602 | } |
591 | 603 | ||
592 | pub fn ty(self, db: &impl HirDatabase) -> Ty { | 604 | pub fn ty(self, db: &impl HirDatabase) -> Ty { |
593 | db.type_for_def(self.into(), Namespace::Values) | 605 | db.value_ty(self.id.into()) |
594 | } | 606 | } |
595 | 607 | ||
596 | pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> { | 608 | pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> { |
597 | db.infer(self.into()) | 609 | db.infer(self.id.into()) |
598 | } | 610 | } |
599 | 611 | ||
600 | /// The containing impl block, if this is a method. | 612 | /// The containing impl block, if this is a method. |
@@ -623,8 +635,8 @@ impl Function { | |||
623 | 635 | ||
624 | pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { | 636 | pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { |
625 | let infer = self.infer(db); | 637 | let infer = self.infer(db); |
626 | infer.add_diagnostics(db, self, sink); | 638 | infer.add_diagnostics(db, self.id, sink); |
627 | let mut validator = ExprValidator::new(self, infer, sink); | 639 | let mut validator = ExprValidator::new(self.id, infer, sink); |
628 | validator.validate_body(db); | 640 | validator.validate_body(db); |
629 | } | 641 | } |
630 | } | 642 | } |
@@ -648,7 +660,7 @@ impl Const { | |||
648 | } | 660 | } |
649 | 661 | ||
650 | pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> { | 662 | pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> { |
651 | db.infer(self.into()) | 663 | db.infer(self.id.into()) |
652 | } | 664 | } |
653 | 665 | ||
654 | /// The containing impl block, if this is a type alias. | 666 | /// The containing impl block, if this is a type alias. |
@@ -691,7 +703,7 @@ impl Static { | |||
691 | } | 703 | } |
692 | 704 | ||
693 | pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> { | 705 | pub fn infer(self, db: &impl HirDatabase) -> Arc<InferenceResult> { |
694 | db.infer(self.into()) | 706 | db.infer(self.id.into()) |
695 | } | 707 | } |
696 | } | 708 | } |
697 | 709 | ||
@@ -705,73 +717,12 @@ impl Trait { | |||
705 | Module { id: self.id.module(db) } | 717 | Module { id: self.id.module(db) } |
706 | } | 718 | } |
707 | 719 | ||
708 | pub fn name(self, db: &impl DefDatabase) -> Option<Name> { | 720 | pub fn name(self, db: &impl DefDatabase) -> Name { |
709 | db.trait_data(self.id).name.clone() | 721 | db.trait_data(self.id).name.clone() |
710 | } | 722 | } |
711 | 723 | ||
712 | pub fn items(self, db: &impl DefDatabase) -> Vec<AssocItem> { | 724 | pub fn items(self, db: &impl DefDatabase) -> Vec<AssocItem> { |
713 | db.trait_data(self.id).items.iter().map(|it| (*it).into()).collect() | 725 | db.trait_data(self.id).items.iter().map(|(_name, it)| (*it).into()).collect() |
714 | } | ||
715 | |||
716 | fn direct_super_traits(self, db: &impl HirDatabase) -> Vec<Trait> { | ||
717 | let resolver = self.id.resolver(db); | ||
718 | // returning the iterator directly doesn't easily work because of | ||
719 | // lifetime problems, but since there usually shouldn't be more than a | ||
720 | // few direct traits this should be fine (we could even use some kind of | ||
721 | // SmallVec if performance is a concern) | ||
722 | db.generic_params(self.id.into()) | ||
723 | .where_predicates | ||
724 | .iter() | ||
725 | .filter_map(|pred| match &pred.type_ref { | ||
726 | TypeRef::Path(p) if p.as_ident() == Some(&name::SELF_TYPE) => pred.bound.as_path(), | ||
727 | _ => None, | ||
728 | }) | ||
729 | .filter_map(|path| match resolver.resolve_path_in_type_ns_fully(db, path) { | ||
730 | Some(TypeNs::TraitId(t)) => Some(t), | ||
731 | _ => None, | ||
732 | }) | ||
733 | .map(Trait::from) | ||
734 | .collect() | ||
735 | } | ||
736 | |||
737 | /// Returns an iterator over the whole super trait hierarchy (including the | ||
738 | /// trait itself). | ||
739 | pub fn all_super_traits(self, db: &impl HirDatabase) -> Vec<Trait> { | ||
740 | // we need to take care a bit here to avoid infinite loops in case of cycles | ||
741 | // (i.e. if we have `trait A: B; trait B: A;`) | ||
742 | let mut result = vec![self]; | ||
743 | let mut i = 0; | ||
744 | while i < result.len() { | ||
745 | let t = result[i]; | ||
746 | // yeah this is quadratic, but trait hierarchies should be flat | ||
747 | // enough that this doesn't matter | ||
748 | for tt in t.direct_super_traits(db) { | ||
749 | if !result.contains(&tt) { | ||
750 | result.push(tt); | ||
751 | } | ||
752 | } | ||
753 | i += 1; | ||
754 | } | ||
755 | result | ||
756 | } | ||
757 | |||
758 | pub fn associated_type_by_name(self, db: &impl DefDatabase, name: &Name) -> Option<TypeAlias> { | ||
759 | let trait_data = db.trait_data(self.id); | ||
760 | let res = | ||
761 | trait_data.associated_types().map(TypeAlias::from).find(|t| &t.name(db) == name)?; | ||
762 | Some(res) | ||
763 | } | ||
764 | |||
765 | pub fn associated_type_by_name_including_super_traits( | ||
766 | self, | ||
767 | db: &impl HirDatabase, | ||
768 | name: &Name, | ||
769 | ) -> Option<TypeAlias> { | ||
770 | self.all_super_traits(db).into_iter().find_map(|t| t.associated_type_by_name(db, name)) | ||
771 | } | ||
772 | |||
773 | pub fn trait_ref(self, db: &impl HirDatabase) -> TraitRef { | ||
774 | TraitRef::for_trait(db, self) | ||
775 | } | 726 | } |
776 | 727 | ||
777 | pub fn is_auto(self, db: &impl DefDatabase) -> bool { | 728 | pub fn is_auto(self, db: &impl DefDatabase) -> bool { |
@@ -785,6 +736,11 @@ pub struct TypeAlias { | |||
785 | } | 736 | } |
786 | 737 | ||
787 | impl TypeAlias { | 738 | impl TypeAlias { |
739 | pub fn has_non_default_type_params(self, db: &impl HirDatabase) -> bool { | ||
740 | let subst = db.generic_defaults(self.id.into()); | ||
741 | subst.iter().any(|ty| ty == &Ty::Unknown) | ||
742 | } | ||
743 | |||
788 | pub fn module(self, db: &impl DefDatabase) -> Module { | 744 | pub fn module(self, db: &impl DefDatabase) -> Module { |
789 | Module { id: self.id.lookup(db).module(db) } | 745 | Module { id: self.id.lookup(db).module(db) } |
790 | } | 746 | } |
@@ -821,8 +777,8 @@ impl TypeAlias { | |||
821 | db.type_alias_data(self.id).type_ref.clone() | 777 | db.type_alias_data(self.id).type_ref.clone() |
822 | } | 778 | } |
823 | 779 | ||
824 | pub fn ty(self, db: &impl HirDatabase) -> Ty { | 780 | pub fn ty(self, db: &impl HirDatabase) -> Type { |
825 | db.type_for_def(self.into(), Namespace::Types) | 781 | Type::from_def(db, self.id.lookup(db).module(db).krate, self.id) |
826 | } | 782 | } |
827 | 783 | ||
828 | pub fn name(self, db: &impl DefDatabase) -> Name { | 784 | pub fn name(self, db: &impl DefDatabase) -> Name { |
@@ -897,16 +853,6 @@ impl_froms!( | |||
897 | Const | 853 | Const |
898 | ); | 854 | ); |
899 | 855 | ||
900 | impl From<AssocItem> for GenericDef { | ||
901 | fn from(item: AssocItem) -> Self { | ||
902 | match item { | ||
903 | AssocItem::Function(f) => f.into(), | ||
904 | AssocItem::Const(c) => c.into(), | ||
905 | AssocItem::TypeAlias(t) => t.into(), | ||
906 | } | ||
907 | } | ||
908 | } | ||
909 | |||
910 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | 856 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
911 | pub struct Local { | 857 | pub struct Local { |
912 | pub(crate) parent: DefWithBody, | 858 | pub(crate) parent: DefWithBody, |
@@ -945,9 +891,14 @@ impl Local { | |||
945 | self.parent.module(db) | 891 | self.parent.module(db) |
946 | } | 892 | } |
947 | 893 | ||
948 | pub fn ty(self, db: &impl HirDatabase) -> Ty { | 894 | pub fn ty(self, db: &impl HirDatabase) -> Type { |
949 | let infer = db.infer(self.parent); | 895 | let def = DefWithBodyId::from(self.parent); |
950 | infer[self.pat_id].clone() | 896 | let infer = db.infer(def); |
897 | let ty = infer[self.pat_id].clone(); | ||
898 | let resolver = def.resolver(db); | ||
899 | let krate = def.module(db).krate; | ||
900 | let environment = TraitEnvironment::lower(db, &resolver); | ||
901 | Type { krate, ty: InEnvironment { value: ty, environment } } | ||
951 | } | 902 | } |
952 | 903 | ||
953 | pub fn source(self, db: &impl HirDatabase) -> Source<Either<ast::BindPat, ast::SelfParam>> { | 904 | pub fn source(self, db: &impl HirDatabase) -> Source<Either<ast::BindPat, ast::SelfParam>> { |
@@ -960,7 +911,7 @@ impl Local { | |||
960 | 911 | ||
961 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | 912 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
962 | pub struct GenericParam { | 913 | pub struct GenericParam { |
963 | pub(crate) parent: GenericDef, | 914 | pub(crate) parent: GenericDefId, |
964 | pub(crate) idx: u32, | 915 | pub(crate) idx: u32, |
965 | } | 916 | } |
966 | 917 | ||
@@ -970,6 +921,15 @@ pub struct ImplBlock { | |||
970 | } | 921 | } |
971 | 922 | ||
972 | impl ImplBlock { | 923 | impl ImplBlock { |
924 | pub fn all_in_crate(db: &impl HirDatabase, krate: Crate) -> Vec<ImplBlock> { | ||
925 | let impls = db.impls_in_crate(krate.crate_id); | ||
926 | impls.all_impls().map(Self::from).collect() | ||
927 | } | ||
928 | pub fn for_trait(db: &impl HirDatabase, krate: Crate, trait_: Trait) -> Vec<ImplBlock> { | ||
929 | let impls = db.impls_in_crate(krate.crate_id); | ||
930 | impls.lookup_impl_blocks_for_trait(trait_.id).map(Self::from).collect() | ||
931 | } | ||
932 | |||
973 | pub fn target_trait(&self, db: &impl DefDatabase) -> Option<TypeRef> { | 933 | pub fn target_trait(&self, db: &impl DefDatabase) -> Option<TypeRef> { |
974 | db.impl_data(self.id).target_trait.clone() | 934 | db.impl_data(self.id).target_trait.clone() |
975 | } | 935 | } |
@@ -978,13 +938,12 @@ impl ImplBlock { | |||
978 | db.impl_data(self.id).target_type.clone() | 938 | db.impl_data(self.id).target_type.clone() |
979 | } | 939 | } |
980 | 940 | ||
981 | pub fn target_ty(&self, db: &impl HirDatabase) -> Ty { | 941 | pub fn target_ty(&self, db: &impl HirDatabase) -> Type { |
982 | Ty::from_hir(db, &self.id.resolver(db), &self.target_type(db)) | 942 | let impl_data = db.impl_data(self.id); |
983 | } | 943 | let resolver = self.id.resolver(db); |
984 | 944 | let environment = TraitEnvironment::lower(db, &resolver); | |
985 | pub fn target_trait_ref(&self, db: &impl HirDatabase) -> Option<TraitRef> { | 945 | let ty = Ty::from_hir(db, &resolver, &impl_data.target_type); |
986 | let target_ty = self.target_ty(db); | 946 | Type { krate: self.id.module(db).krate, ty: InEnvironment { value: ty, environment } } |
987 | TraitRef::from_hir(db, &self.id.resolver(db), &self.target_trait(db)?, Some(target_ty)) | ||
988 | } | 947 | } |
989 | 948 | ||
990 | pub fn items(&self, db: &impl DefDatabase) -> Vec<AssocItem> { | 949 | pub fn items(&self, db: &impl DefDatabase) -> Vec<AssocItem> { |
@@ -1004,6 +963,194 @@ impl ImplBlock { | |||
1004 | } | 963 | } |
1005 | } | 964 | } |
1006 | 965 | ||
966 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
967 | pub struct Type { | ||
968 | pub(crate) krate: CrateId, | ||
969 | pub(crate) ty: InEnvironment<Ty>, | ||
970 | } | ||
971 | |||
972 | impl Type { | ||
973 | fn from_def( | ||
974 | db: &impl HirDatabase, | ||
975 | krate: CrateId, | ||
976 | def: impl HasResolver + Into<TyDefId>, | ||
977 | ) -> Type { | ||
978 | let resolver = def.resolver(db); | ||
979 | let environment = TraitEnvironment::lower(db, &resolver); | ||
980 | let ty = db.ty(def.into()); | ||
981 | Type { krate, ty: InEnvironment { value: ty, environment } } | ||
982 | } | ||
983 | |||
984 | pub fn is_bool(&self) -> bool { | ||
985 | match &self.ty.value { | ||
986 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
987 | TypeCtor::Bool => true, | ||
988 | _ => false, | ||
989 | }, | ||
990 | _ => false, | ||
991 | } | ||
992 | } | ||
993 | |||
994 | pub fn is_mutable_reference(&self) -> bool { | ||
995 | match &self.ty.value { | ||
996 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
997 | TypeCtor::Ref(Mutability::Mut) => true, | ||
998 | _ => false, | ||
999 | }, | ||
1000 | _ => false, | ||
1001 | } | ||
1002 | } | ||
1003 | |||
1004 | pub fn is_unknown(&self) -> bool { | ||
1005 | match &self.ty.value { | ||
1006 | Ty::Unknown => true, | ||
1007 | _ => false, | ||
1008 | } | ||
1009 | } | ||
1010 | |||
1011 | // FIXME: this method is broken, as it doesn't take closures into account. | ||
1012 | pub fn as_callable(&self) -> Option<CallableDef> { | ||
1013 | Some(self.ty.value.as_callable()?.0) | ||
1014 | } | ||
1015 | |||
1016 | pub fn contains_unknown(&self) -> bool { | ||
1017 | return go(&self.ty.value); | ||
1018 | |||
1019 | fn go(ty: &Ty) -> bool { | ||
1020 | match ty { | ||
1021 | Ty::Unknown => true, | ||
1022 | Ty::Apply(a_ty) => a_ty.parameters.iter().any(go), | ||
1023 | _ => false, | ||
1024 | } | ||
1025 | } | ||
1026 | } | ||
1027 | |||
1028 | pub fn fields(&self, db: &impl HirDatabase) -> Vec<(StructField, Type)> { | ||
1029 | if let Ty::Apply(a_ty) = &self.ty.value { | ||
1030 | match a_ty.ctor { | ||
1031 | ty::TypeCtor::Adt(AdtId::StructId(s)) => { | ||
1032 | let var_def = s.into(); | ||
1033 | return db | ||
1034 | .field_types(var_def) | ||
1035 | .iter() | ||
1036 | .map(|(local_id, ty)| { | ||
1037 | let def = StructField { parent: var_def.into(), id: local_id }; | ||
1038 | let ty = ty.clone().subst(&a_ty.parameters); | ||
1039 | (def, self.derived(ty)) | ||
1040 | }) | ||
1041 | .collect(); | ||
1042 | } | ||
1043 | _ => {} | ||
1044 | } | ||
1045 | }; | ||
1046 | Vec::new() | ||
1047 | } | ||
1048 | |||
1049 | pub fn tuple_fields(&self, _db: &impl HirDatabase) -> Vec<Type> { | ||
1050 | let mut res = Vec::new(); | ||
1051 | if let Ty::Apply(a_ty) = &self.ty.value { | ||
1052 | match a_ty.ctor { | ||
1053 | ty::TypeCtor::Tuple { .. } => { | ||
1054 | for ty in a_ty.parameters.iter() { | ||
1055 | let ty = ty.clone().subst(&a_ty.parameters); | ||
1056 | res.push(self.derived(ty)); | ||
1057 | } | ||
1058 | } | ||
1059 | _ => {} | ||
1060 | } | ||
1061 | }; | ||
1062 | res | ||
1063 | } | ||
1064 | |||
1065 | pub fn variant_fields( | ||
1066 | &self, | ||
1067 | db: &impl HirDatabase, | ||
1068 | def: VariantDef, | ||
1069 | ) -> Vec<(StructField, Type)> { | ||
1070 | // FIXME: check that ty and def match | ||
1071 | match &self.ty.value { | ||
1072 | Ty::Apply(a_ty) => def | ||
1073 | .fields(db) | ||
1074 | .into_iter() | ||
1075 | .map(|it| (it, self.derived(it.ty(db).subst(&a_ty.parameters)))) | ||
1076 | .collect(), | ||
1077 | _ => Vec::new(), | ||
1078 | } | ||
1079 | } | ||
1080 | |||
1081 | pub fn autoderef<'a>(&'a self, db: &'a impl HirDatabase) -> impl Iterator<Item = Type> + 'a { | ||
1082 | // There should be no inference vars in types passed here | ||
1083 | // FIXME check that? | ||
1084 | let canonical = crate::ty::Canonical { value: self.ty.value.clone(), num_vars: 0 }; | ||
1085 | let environment = self.ty.environment.clone(); | ||
1086 | let ty = InEnvironment { value: canonical, environment: environment.clone() }; | ||
1087 | ty::autoderef(db, Some(self.krate), ty) | ||
1088 | .map(|canonical| canonical.value) | ||
1089 | .map(move |ty| self.derived(ty)) | ||
1090 | } | ||
1091 | |||
1092 | // This would be nicer if it just returned an iterator, but that runs into | ||
1093 | // lifetime problems, because we need to borrow temp `CrateImplBlocks`. | ||
1094 | pub fn iterate_impl_items<T>( | ||
1095 | self, | ||
1096 | db: &impl HirDatabase, | ||
1097 | krate: Crate, | ||
1098 | mut callback: impl FnMut(AssocItem) -> Option<T>, | ||
1099 | ) -> Option<T> { | ||
1100 | for krate in self.ty.value.def_crates(db, krate.crate_id)? { | ||
1101 | let impls = db.impls_in_crate(krate); | ||
1102 | |||
1103 | for impl_block in impls.lookup_impl_blocks(&self.ty.value) { | ||
1104 | for &item in db.impl_data(impl_block).items.iter() { | ||
1105 | if let Some(result) = callback(item.into()) { | ||
1106 | return Some(result); | ||
1107 | } | ||
1108 | } | ||
1109 | } | ||
1110 | } | ||
1111 | None | ||
1112 | } | ||
1113 | |||
1114 | // FIXME: remove | ||
1115 | pub fn into_ty(self) -> Ty { | ||
1116 | self.ty.value | ||
1117 | } | ||
1118 | |||
1119 | pub fn as_adt(&self) -> Option<Adt> { | ||
1120 | let (adt, _subst) = self.ty.value.as_adt()?; | ||
1121 | Some(adt.into()) | ||
1122 | } | ||
1123 | |||
1124 | // FIXME: provide required accessors such that it becomes implementable from outside. | ||
1125 | pub fn is_equal_for_find_impls(&self, other: &Type) -> bool { | ||
1126 | match (&self.ty.value, &other.ty.value) { | ||
1127 | (Ty::Apply(a_original_ty), Ty::Apply(ty::ApplicationTy { ctor, parameters })) => { | ||
1128 | match ctor { | ||
1129 | TypeCtor::Ref(..) => match parameters.as_single() { | ||
1130 | Ty::Apply(a_ty) => a_original_ty.ctor == a_ty.ctor, | ||
1131 | _ => false, | ||
1132 | }, | ||
1133 | _ => a_original_ty.ctor == *ctor, | ||
1134 | } | ||
1135 | } | ||
1136 | _ => false, | ||
1137 | } | ||
1138 | } | ||
1139 | |||
1140 | fn derived(&self, ty: Ty) -> Type { | ||
1141 | Type { | ||
1142 | krate: self.krate, | ||
1143 | ty: InEnvironment { value: ty, environment: self.ty.environment.clone() }, | ||
1144 | } | ||
1145 | } | ||
1146 | } | ||
1147 | |||
1148 | impl HirDisplay for Type { | ||
1149 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> std::fmt::Result { | ||
1150 | self.ty.value.hir_fmt(f) | ||
1151 | } | ||
1152 | } | ||
1153 | |||
1007 | /// For IDE only | 1154 | /// For IDE only |
1008 | pub enum ScopeDef { | 1155 | pub enum ScopeDef { |
1009 | ModuleDef(ModuleDef), | 1156 | ModuleDef(ModuleDef), |
diff --git a/crates/ra_hir/src/code_model/src.rs b/crates/ra_hir/src/code_model/src.rs index a4e317c20..bf3ee0834 100644 --- a/crates/ra_hir/src/code_model/src.rs +++ b/crates/ra_hir/src/code_model/src.rs | |||
@@ -22,7 +22,7 @@ impl Module { | |||
22 | /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items. | 22 | /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items. |
23 | pub fn definition_source(self, db: &impl DefDatabase) -> Source<ModuleSource> { | 23 | pub fn definition_source(self, db: &impl DefDatabase) -> Source<ModuleSource> { |
24 | let def_map = db.crate_def_map(self.id.krate); | 24 | let def_map = db.crate_def_map(self.id.krate); |
25 | let src = def_map[self.id.module_id].definition_source(db); | 25 | let src = def_map[self.id.local_id].definition_source(db); |
26 | src.map(|it| match it { | 26 | src.map(|it| match it { |
27 | Either::A(it) => ModuleSource::SourceFile(it), | 27 | Either::A(it) => ModuleSource::SourceFile(it), |
28 | Either::B(it) => ModuleSource::Module(it), | 28 | Either::B(it) => ModuleSource::Module(it), |
@@ -33,7 +33,7 @@ impl Module { | |||
33 | /// `None` for the crate root. | 33 | /// `None` for the crate root. |
34 | pub fn declaration_source(self, db: &impl DefDatabase) -> Option<Source<ast::Module>> { | 34 | pub fn declaration_source(self, db: &impl DefDatabase) -> Option<Source<ast::Module>> { |
35 | let def_map = db.crate_def_map(self.id.krate); | 35 | let def_map = db.crate_def_map(self.id.krate); |
36 | def_map[self.id.module_id].declaration_source(db) | 36 | def_map[self.id.local_id].declaration_source(db) |
37 | } | 37 | } |
38 | } | 38 | } |
39 | 39 | ||
@@ -51,13 +51,13 @@ impl HasSource for StructField { | |||
51 | impl HasSource for Struct { | 51 | impl HasSource for Struct { |
52 | type Ast = ast::StructDef; | 52 | type Ast = ast::StructDef; |
53 | fn source(self, db: &impl DefDatabase) -> Source<ast::StructDef> { | 53 | fn source(self, db: &impl DefDatabase) -> Source<ast::StructDef> { |
54 | self.id.0.source(db) | 54 | self.id.source(db) |
55 | } | 55 | } |
56 | } | 56 | } |
57 | impl HasSource for Union { | 57 | impl HasSource for Union { |
58 | type Ast = ast::StructDef; | 58 | type Ast = ast::UnionDef; |
59 | fn source(self, db: &impl DefDatabase) -> Source<ast::StructDef> { | 59 | fn source(self, db: &impl DefDatabase) -> Source<ast::UnionDef> { |
60 | self.id.0.source(db) | 60 | self.id.source(db) |
61 | } | 61 | } |
62 | } | 62 | } |
63 | impl HasSource for Enum { | 63 | impl HasSource for Enum { |
diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index 5084bbacf..bfae3660b 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs | |||
@@ -1,130 +1,22 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | use std::sync::Arc; | 3 | pub use hir_def::db::{ |
4 | 4 | BodyQuery, BodyWithSourceMapQuery, ConstDataQuery, CrateDefMapQuery, CrateLangItemsQuery, | |
5 | use ra_arena::map::ArenaMap; | 5 | DefDatabase, DefDatabaseStorage, DocumentationQuery, EnumDataQuery, ExprScopesQuery, |
6 | use ra_db::salsa; | 6 | FunctionDataQuery, GenericParamsQuery, ImplDataQuery, InternDatabase, InternDatabaseStorage, |
7 | 7 | LangItemQuery, ModuleLangItemsQuery, RawItemsQuery, RawItemsWithSourceMapQuery, | |
8 | use crate::{ | 8 | StaticDataQuery, StructDataQuery, TraitDataQuery, TypeAliasDataQuery, |
9 | ty::{ | ||
10 | method_resolution::CrateImplBlocks, | ||
11 | traits::{AssocTyValue, Impl}, | ||
12 | CallableDef, FnSig, GenericPredicate, InferenceResult, Namespace, Substs, Ty, TypableDef, | ||
13 | TypeCtor, | ||
14 | }, | ||
15 | Crate, DefWithBody, GenericDef, ImplBlock, Trait, | ||
16 | }; | ||
17 | |||
18 | pub use hir_def::{ | ||
19 | db::{ | ||
20 | BodyQuery, BodyWithSourceMapQuery, ConstDataQuery, CrateDefMapQuery, CrateLangItemsQuery, | ||
21 | DefDatabase, DefDatabaseStorage, DocumentationQuery, EnumDataQuery, ExprScopesQuery, | ||
22 | FunctionDataQuery, GenericParamsQuery, ImplDataQuery, InternDatabase, | ||
23 | InternDatabaseStorage, LangItemQuery, ModuleLangItemsQuery, RawItemsQuery, | ||
24 | RawItemsWithSourceMapQuery, StaticDataQuery, StructDataQuery, TraitDataQuery, | ||
25 | TypeAliasDataQuery, | ||
26 | }, | ||
27 | LocalStructFieldId, VariantId, | ||
28 | }; | 9 | }; |
29 | pub use hir_expand::db::{ | 10 | pub use hir_expand::db::{ |
30 | AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery, | 11 | AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery, |
31 | ParseMacroQuery, | 12 | ParseMacroQuery, |
32 | }; | 13 | }; |
33 | 14 | pub use hir_ty::db::{ | |
34 | #[salsa::query_group(HirDatabaseStorage)] | 15 | AssociatedTyDataQuery, CallableItemSignatureQuery, FieldTypesQuery, GenericDefaultsQuery, |
35 | #[salsa::requires(salsa::Database)] | 16 | GenericPredicatesQuery, HirDatabase, HirDatabaseStorage, ImplDatumQuery, ImplsForTraitQuery, |
36 | pub trait HirDatabase: DefDatabase { | 17 | ImplsInCrateQuery, InferQuery, StructDatumQuery, TraitDatumQuery, TraitSolveQuery, TyQuery, |
37 | #[salsa::invoke(crate::ty::infer_query)] | 18 | ValueTyQuery, |
38 | fn infer(&self, def: DefWithBody) -> Arc<InferenceResult>; | 19 | }; |
39 | |||
40 | #[salsa::invoke(crate::ty::type_for_def)] | ||
41 | fn type_for_def(&self, def: TypableDef, ns: Namespace) -> Ty; | ||
42 | |||
43 | #[salsa::invoke(crate::ty::field_types_query)] | ||
44 | fn field_types(&self, var: VariantId) -> Arc<ArenaMap<LocalStructFieldId, Ty>>; | ||
45 | |||
46 | #[salsa::invoke(crate::ty::callable_item_sig)] | ||
47 | fn callable_item_signature(&self, def: CallableDef) -> FnSig; | ||
48 | |||
49 | #[salsa::invoke(crate::ty::generic_predicates_for_param_query)] | ||
50 | fn generic_predicates_for_param( | ||
51 | &self, | ||
52 | def: GenericDef, | ||
53 | param_idx: u32, | ||
54 | ) -> Arc<[GenericPredicate]>; | ||
55 | |||
56 | #[salsa::invoke(crate::ty::generic_predicates_query)] | ||
57 | fn generic_predicates(&self, def: GenericDef) -> Arc<[GenericPredicate]>; | ||
58 | |||
59 | #[salsa::invoke(crate::ty::generic_defaults_query)] | ||
60 | fn generic_defaults(&self, def: GenericDef) -> Substs; | ||
61 | |||
62 | #[salsa::invoke(crate::ty::method_resolution::CrateImplBlocks::impls_in_crate_query)] | ||
63 | fn impls_in_crate(&self, krate: Crate) -> Arc<CrateImplBlocks>; | ||
64 | |||
65 | #[salsa::invoke(crate::ty::traits::impls_for_trait_query)] | ||
66 | fn impls_for_trait(&self, krate: Crate, trait_: Trait) -> Arc<[ImplBlock]>; | ||
67 | |||
68 | /// This provides the Chalk trait solver instance. Because Chalk always | ||
69 | /// works from a specific crate, this query is keyed on the crate; and | ||
70 | /// because Chalk does its own internal caching, the solver is wrapped in a | ||
71 | /// Mutex and the query does an untracked read internally, to make sure the | ||
72 | /// cached state is thrown away when input facts change. | ||
73 | #[salsa::invoke(crate::ty::traits::trait_solver_query)] | ||
74 | fn trait_solver(&self, krate: Crate) -> crate::ty::traits::TraitSolver; | ||
75 | |||
76 | // Interned IDs for Chalk integration | ||
77 | #[salsa::interned] | ||
78 | fn intern_type_ctor(&self, type_ctor: TypeCtor) -> crate::ty::TypeCtorId; | ||
79 | #[salsa::interned] | ||
80 | fn intern_chalk_impl(&self, impl_: Impl) -> crate::ty::traits::GlobalImplId; | ||
81 | #[salsa::interned] | ||
82 | fn intern_assoc_ty_value( | ||
83 | &self, | ||
84 | assoc_ty_value: AssocTyValue, | ||
85 | ) -> crate::ty::traits::AssocTyValueId; | ||
86 | |||
87 | #[salsa::invoke(crate::ty::traits::chalk::associated_ty_data_query)] | ||
88 | fn associated_ty_data( | ||
89 | &self, | ||
90 | id: chalk_ir::TypeId, | ||
91 | ) -> Arc<chalk_rust_ir::AssociatedTyDatum<chalk_ir::family::ChalkIr>>; | ||
92 | |||
93 | #[salsa::invoke(crate::ty::traits::chalk::trait_datum_query)] | ||
94 | fn trait_datum( | ||
95 | &self, | ||
96 | krate: Crate, | ||
97 | trait_id: chalk_ir::TraitId, | ||
98 | ) -> Arc<chalk_rust_ir::TraitDatum<chalk_ir::family::ChalkIr>>; | ||
99 | |||
100 | #[salsa::invoke(crate::ty::traits::chalk::struct_datum_query)] | ||
101 | fn struct_datum( | ||
102 | &self, | ||
103 | krate: Crate, | ||
104 | struct_id: chalk_ir::StructId, | ||
105 | ) -> Arc<chalk_rust_ir::StructDatum<chalk_ir::family::ChalkIr>>; | ||
106 | |||
107 | #[salsa::invoke(crate::ty::traits::chalk::impl_datum_query)] | ||
108 | fn impl_datum( | ||
109 | &self, | ||
110 | krate: Crate, | ||
111 | impl_id: chalk_ir::ImplId, | ||
112 | ) -> Arc<chalk_rust_ir::ImplDatum<chalk_ir::family::ChalkIr>>; | ||
113 | |||
114 | #[salsa::invoke(crate::ty::traits::chalk::associated_ty_value_query)] | ||
115 | fn associated_ty_value( | ||
116 | &self, | ||
117 | krate: Crate, | ||
118 | id: chalk_rust_ir::AssociatedTyValueId, | ||
119 | ) -> Arc<chalk_rust_ir::AssociatedTyValue<chalk_ir::family::ChalkIr>>; | ||
120 | |||
121 | #[salsa::invoke(crate::ty::traits::trait_solve_query)] | ||
122 | fn trait_solve( | ||
123 | &self, | ||
124 | krate: Crate, | ||
125 | goal: crate::ty::Canonical<crate::ty::InEnvironment<crate::ty::Obligation>>, | ||
126 | ) -> Option<crate::ty::traits::Solution>; | ||
127 | } | ||
128 | 20 | ||
129 | #[test] | 21 | #[test] |
130 | fn hir_database_is_object_safe() { | 22 | fn hir_database_is_object_safe() { |
diff --git a/crates/ra_hir/src/diagnostics.rs b/crates/ra_hir/src/diagnostics.rs index dafacba70..a9040ea3d 100644 --- a/crates/ra_hir/src/diagnostics.rs +++ b/crates/ra_hir/src/diagnostics.rs | |||
@@ -1,88 +1,4 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | |||
3 | use std::any::Any; | ||
4 | |||
5 | use hir_expand::HirFileId; | ||
6 | use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr}; | ||
7 | |||
8 | use crate::{db::AstDatabase, Name, Source}; | ||
9 | |||
10 | pub use hir_def::diagnostics::UnresolvedModule; | 2 | pub use hir_def::diagnostics::UnresolvedModule; |
11 | pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink}; | 3 | pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink}; |
12 | 4 | pub use hir_ty::diagnostics::{MissingFields, MissingOkInTailExpr, NoSuchField}; | |
13 | #[derive(Debug)] | ||
14 | pub struct NoSuchField { | ||
15 | pub file: HirFileId, | ||
16 | pub field: AstPtr<ast::RecordField>, | ||
17 | } | ||
18 | |||
19 | impl Diagnostic for NoSuchField { | ||
20 | fn message(&self) -> String { | ||
21 | "no such field".to_string() | ||
22 | } | ||
23 | |||
24 | fn source(&self) -> Source<SyntaxNodePtr> { | ||
25 | Source { file_id: self.file, value: self.field.into() } | ||
26 | } | ||
27 | |||
28 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | ||
29 | self | ||
30 | } | ||
31 | } | ||
32 | |||
33 | #[derive(Debug)] | ||
34 | pub struct MissingFields { | ||
35 | pub file: HirFileId, | ||
36 | pub field_list: AstPtr<ast::RecordFieldList>, | ||
37 | pub missed_fields: Vec<Name>, | ||
38 | } | ||
39 | |||
40 | impl Diagnostic for MissingFields { | ||
41 | fn message(&self) -> String { | ||
42 | "fill structure fields".to_string() | ||
43 | } | ||
44 | fn source(&self) -> Source<SyntaxNodePtr> { | ||
45 | Source { file_id: self.file, value: self.field_list.into() } | ||
46 | } | ||
47 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | ||
48 | self | ||
49 | } | ||
50 | } | ||
51 | |||
52 | impl AstDiagnostic for MissingFields { | ||
53 | type AST = ast::RecordFieldList; | ||
54 | |||
55 | fn ast(&self, db: &impl AstDatabase) -> Self::AST { | ||
56 | let root = db.parse_or_expand(self.source().file_id).unwrap(); | ||
57 | let node = self.source().value.to_node(&root); | ||
58 | ast::RecordFieldList::cast(node).unwrap() | ||
59 | } | ||
60 | } | ||
61 | |||
62 | #[derive(Debug)] | ||
63 | pub struct MissingOkInTailExpr { | ||
64 | pub file: HirFileId, | ||
65 | pub expr: AstPtr<ast::Expr>, | ||
66 | } | ||
67 | |||
68 | impl Diagnostic for MissingOkInTailExpr { | ||
69 | fn message(&self) -> String { | ||
70 | "wrap return expression in Ok".to_string() | ||
71 | } | ||
72 | fn source(&self) -> Source<SyntaxNodePtr> { | ||
73 | Source { file_id: self.file, value: self.expr.into() } | ||
74 | } | ||
75 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | ||
76 | self | ||
77 | } | ||
78 | } | ||
79 | |||
80 | impl AstDiagnostic for MissingOkInTailExpr { | ||
81 | type AST = ast::Expr; | ||
82 | |||
83 | fn ast(&self, db: &impl AstDatabase) -> Self::AST { | ||
84 | let root = db.parse_or_expand(self.file).unwrap(); | ||
85 | let node = self.source().value.to_node(&root); | ||
86 | ast::Expr::cast(node).unwrap() | ||
87 | } | ||
88 | } | ||
diff --git a/crates/ra_hir/src/expr.rs b/crates/ra_hir/src/expr.rs deleted file mode 100644 index 43fedde7a..000000000 --- a/crates/ra_hir/src/expr.rs +++ /dev/null | |||
@@ -1,146 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::sync::Arc; | ||
4 | |||
5 | use hir_def::{path::known, resolver::HasResolver}; | ||
6 | use hir_expand::diagnostics::DiagnosticSink; | ||
7 | use ra_syntax::ast; | ||
8 | use ra_syntax::AstPtr; | ||
9 | use rustc_hash::FxHashSet; | ||
10 | |||
11 | use crate::{ | ||
12 | db::HirDatabase, | ||
13 | diagnostics::{MissingFields, MissingOkInTailExpr}, | ||
14 | ty::{ApplicationTy, InferenceResult, Ty, TypeCtor}, | ||
15 | Adt, Function, Name, Path, | ||
16 | }; | ||
17 | |||
18 | pub use hir_def::{ | ||
19 | body::{ | ||
20 | scope::{ExprScopes, ScopeEntry, ScopeId}, | ||
21 | Body, BodySourceMap, ExprPtr, ExprSource, PatPtr, PatSource, | ||
22 | }, | ||
23 | expr::{ | ||
24 | ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Literal, LogicOp, | ||
25 | MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField, Statement, UnaryOp, | ||
26 | }, | ||
27 | }; | ||
28 | |||
29 | pub(crate) struct ExprValidator<'a, 'b: 'a> { | ||
30 | func: Function, | ||
31 | infer: Arc<InferenceResult>, | ||
32 | sink: &'a mut DiagnosticSink<'b>, | ||
33 | } | ||
34 | |||
35 | impl<'a, 'b> ExprValidator<'a, 'b> { | ||
36 | pub(crate) fn new( | ||
37 | func: Function, | ||
38 | infer: Arc<InferenceResult>, | ||
39 | sink: &'a mut DiagnosticSink<'b>, | ||
40 | ) -> ExprValidator<'a, 'b> { | ||
41 | ExprValidator { func, infer, sink } | ||
42 | } | ||
43 | |||
44 | pub(crate) fn validate_body(&mut self, db: &impl HirDatabase) { | ||
45 | let body = self.func.body(db); | ||
46 | |||
47 | for e in body.exprs.iter() { | ||
48 | if let (id, Expr::RecordLit { path, fields, spread }) = e { | ||
49 | self.validate_record_literal(id, path, fields, *spread, db); | ||
50 | } | ||
51 | } | ||
52 | |||
53 | let body_expr = &body[body.body_expr]; | ||
54 | if let Expr::Block { statements: _, tail: Some(t) } = body_expr { | ||
55 | self.validate_results_in_tail_expr(body.body_expr, *t, db); | ||
56 | } | ||
57 | } | ||
58 | |||
59 | fn validate_record_literal( | ||
60 | &mut self, | ||
61 | id: ExprId, | ||
62 | _path: &Option<Path>, | ||
63 | fields: &[RecordLitField], | ||
64 | spread: Option<ExprId>, | ||
65 | db: &impl HirDatabase, | ||
66 | ) { | ||
67 | if spread.is_some() { | ||
68 | return; | ||
69 | } | ||
70 | |||
71 | let struct_def = match self.infer[id].as_adt() { | ||
72 | Some((Adt::Struct(s), _)) => s, | ||
73 | _ => return, | ||
74 | }; | ||
75 | |||
76 | let lit_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect(); | ||
77 | let missed_fields: Vec<Name> = struct_def | ||
78 | .fields(db) | ||
79 | .iter() | ||
80 | .filter_map(|f| { | ||
81 | let name = f.name(db); | ||
82 | if lit_fields.contains(&name) { | ||
83 | None | ||
84 | } else { | ||
85 | Some(name) | ||
86 | } | ||
87 | }) | ||
88 | .collect(); | ||
89 | if missed_fields.is_empty() { | ||
90 | return; | ||
91 | } | ||
92 | let source_map = self.func.body_source_map(db); | ||
93 | |||
94 | if let Some(source_ptr) = source_map.expr_syntax(id) { | ||
95 | if let Some(expr) = source_ptr.value.a() { | ||
96 | let root = source_ptr.file_syntax(db); | ||
97 | if let ast::Expr::RecordLit(record_lit) = expr.to_node(&root) { | ||
98 | if let Some(field_list) = record_lit.record_field_list() { | ||
99 | self.sink.push(MissingFields { | ||
100 | file: source_ptr.file_id, | ||
101 | field_list: AstPtr::new(&field_list), | ||
102 | missed_fields, | ||
103 | }) | ||
104 | } | ||
105 | } | ||
106 | } | ||
107 | } | ||
108 | } | ||
109 | |||
110 | fn validate_results_in_tail_expr( | ||
111 | &mut self, | ||
112 | body_id: ExprId, | ||
113 | id: ExprId, | ||
114 | db: &impl HirDatabase, | ||
115 | ) { | ||
116 | // the mismatch will be on the whole block currently | ||
117 | let mismatch = match self.infer.type_mismatch_for_expr(body_id) { | ||
118 | Some(m) => m, | ||
119 | None => return, | ||
120 | }; | ||
121 | |||
122 | let std_result_path = known::std_result_result(); | ||
123 | |||
124 | let resolver = self.func.id.resolver(db); | ||
125 | let std_result_enum = match resolver.resolve_known_enum(db, &std_result_path) { | ||
126 | Some(it) => it, | ||
127 | _ => return, | ||
128 | }; | ||
129 | |||
130 | let std_result_ctor = TypeCtor::Adt(Adt::Enum(std_result_enum.into())); | ||
131 | let params = match &mismatch.expected { | ||
132 | Ty::Apply(ApplicationTy { ctor, parameters }) if ctor == &std_result_ctor => parameters, | ||
133 | _ => return, | ||
134 | }; | ||
135 | |||
136 | if params.len() == 2 && ¶ms[0] == &mismatch.actual { | ||
137 | let source_map = self.func.body_source_map(db); | ||
138 | |||
139 | if let Some(source_ptr) = source_map.expr_syntax(id) { | ||
140 | if let Some(expr) = source_ptr.value.a() { | ||
141 | self.sink.push(MissingOkInTailExpr { file: source_ptr.file_id, expr }); | ||
142 | } | ||
143 | } | ||
144 | } | ||
145 | } | ||
146 | } | ||
diff --git a/crates/ra_hir/src/from_id.rs b/crates/ra_hir/src/from_id.rs index 529ac8251..e96a18d12 100644 --- a/crates/ra_hir/src/from_id.rs +++ b/crates/ra_hir/src/from_id.rs | |||
@@ -4,14 +4,13 @@ | |||
4 | //! are splitting the hir. | 4 | //! are splitting the hir. |
5 | 5 | ||
6 | use hir_def::{ | 6 | use hir_def::{ |
7 | AdtId, AssocItemId, AttrDefId, ConstId, DefWithBodyId, EnumId, EnumVariantId, FunctionId, | 7 | AdtId, AssocItemId, AttrDefId, DefWithBodyId, EnumVariantId, GenericDefId, ModuleDefId, |
8 | GenericDefId, ModuleDefId, StaticId, StructFieldId, StructId, TypeAliasId, UnionId, VariantId, | 8 | StructFieldId, VariantId, |
9 | }; | 9 | }; |
10 | 10 | ||
11 | use crate::{ | 11 | use crate::{ |
12 | ty::{CallableDef, TypableDef}, | 12 | Adt, AssocItem, AttrDef, Crate, DefWithBody, EnumVariant, GenericDef, ModuleDef, StructField, |
13 | Adt, AssocItem, AttrDef, Const, Crate, DefWithBody, EnumVariant, Function, GenericDef, | 13 | VariantDef, |
14 | ModuleDef, Static, StructField, TypeAlias, VariantDef, | ||
15 | }; | 14 | }; |
16 | 15 | ||
17 | impl From<ra_db::CrateId> for Crate { | 16 | impl From<ra_db::CrateId> for Crate { |
@@ -138,72 +137,6 @@ impl From<GenericDef> for GenericDefId { | |||
138 | } | 137 | } |
139 | } | 138 | } |
140 | 139 | ||
141 | impl From<GenericDefId> for GenericDef { | ||
142 | fn from(def: GenericDefId) -> Self { | ||
143 | match def { | ||
144 | GenericDefId::FunctionId(it) => GenericDef::Function(it.into()), | ||
145 | GenericDefId::AdtId(it) => GenericDef::Adt(it.into()), | ||
146 | GenericDefId::TraitId(it) => GenericDef::Trait(it.into()), | ||
147 | GenericDefId::TypeAliasId(it) => GenericDef::TypeAlias(it.into()), | ||
148 | GenericDefId::ImplId(it) => GenericDef::ImplBlock(it.into()), | ||
149 | GenericDefId::EnumVariantId(it) => GenericDef::EnumVariant(it.into()), | ||
150 | GenericDefId::ConstId(it) => GenericDef::Const(it.into()), | ||
151 | } | ||
152 | } | ||
153 | } | ||
154 | |||
155 | impl From<AdtId> for TypableDef { | ||
156 | fn from(id: AdtId) -> Self { | ||
157 | Adt::from(id).into() | ||
158 | } | ||
159 | } | ||
160 | |||
161 | impl From<StructId> for TypableDef { | ||
162 | fn from(id: StructId) -> Self { | ||
163 | AdtId::StructId(id).into() | ||
164 | } | ||
165 | } | ||
166 | |||
167 | impl From<UnionId> for TypableDef { | ||
168 | fn from(id: UnionId) -> Self { | ||
169 | AdtId::UnionId(id).into() | ||
170 | } | ||
171 | } | ||
172 | |||
173 | impl From<EnumId> for TypableDef { | ||
174 | fn from(id: EnumId) -> Self { | ||
175 | AdtId::EnumId(id).into() | ||
176 | } | ||
177 | } | ||
178 | |||
179 | impl From<EnumVariantId> for TypableDef { | ||
180 | fn from(id: EnumVariantId) -> Self { | ||
181 | EnumVariant::from(id).into() | ||
182 | } | ||
183 | } | ||
184 | |||
185 | impl From<TypeAliasId> for TypableDef { | ||
186 | fn from(id: TypeAliasId) -> Self { | ||
187 | TypeAlias::from(id).into() | ||
188 | } | ||
189 | } | ||
190 | |||
191 | impl From<FunctionId> for TypableDef { | ||
192 | fn from(id: FunctionId) -> Self { | ||
193 | Function::from(id).into() | ||
194 | } | ||
195 | } | ||
196 | impl From<ConstId> for TypableDef { | ||
197 | fn from(id: ConstId) -> Self { | ||
198 | Const::from(id).into() | ||
199 | } | ||
200 | } | ||
201 | impl From<StaticId> for TypableDef { | ||
202 | fn from(id: StaticId) -> Self { | ||
203 | Static::from(id).into() | ||
204 | } | ||
205 | } | ||
206 | |||
207 | impl From<Adt> for GenericDefId { | 140 | impl From<Adt> for GenericDefId { |
208 | fn from(id: Adt) -> Self { | 141 | fn from(id: Adt) -> Self { |
209 | match id { | 142 | match id { |
@@ -214,14 +147,12 @@ impl From<Adt> for GenericDefId { | |||
214 | } | 147 | } |
215 | } | 148 | } |
216 | 149 | ||
217 | impl From<CallableDef> for GenericDefId { | 150 | impl From<VariantId> for VariantDef { |
218 | fn from(def: CallableDef) -> Self { | 151 | fn from(def: VariantId) -> Self { |
219 | match def { | 152 | match def { |
220 | CallableDef::Function(it) => it.id.into(), | 153 | VariantId::StructId(it) => VariantDef::Struct(it.into()), |
221 | CallableDef::Struct(it) => it.id.into(), | 154 | VariantId::EnumVariantId(it) => VariantDef::EnumVariant(it.into()), |
222 | CallableDef::EnumVariant(it) => { | 155 | VariantId::UnionId(it) => VariantDef::Union(it.into()), |
223 | EnumVariantId { parent: it.parent.id, local_id: it.id }.into() | ||
224 | } | ||
225 | } | 156 | } |
226 | } | 157 | } |
227 | } | 158 | } |
@@ -231,6 +162,7 @@ impl From<VariantDef> for VariantId { | |||
231 | match def { | 162 | match def { |
232 | VariantDef::Struct(it) => VariantId::StructId(it.id), | 163 | VariantDef::Struct(it) => VariantId::StructId(it.id), |
233 | VariantDef::EnumVariant(it) => VariantId::EnumVariantId(it.into()), | 164 | VariantDef::EnumVariant(it) => VariantId::EnumVariantId(it.into()), |
165 | VariantDef::Union(it) => VariantId::UnionId(it.id), | ||
234 | } | 166 | } |
235 | } | 167 | } |
236 | } | 168 | } |
@@ -241,6 +173,12 @@ impl From<StructField> for StructFieldId { | |||
241 | } | 173 | } |
242 | } | 174 | } |
243 | 175 | ||
176 | impl From<StructFieldId> for StructField { | ||
177 | fn from(def: StructFieldId) -> Self { | ||
178 | StructField { parent: def.parent.into(), id: def.local_id } | ||
179 | } | ||
180 | } | ||
181 | |||
244 | impl From<AttrDef> for AttrDefId { | 182 | impl From<AttrDef> for AttrDefId { |
245 | fn from(def: AttrDef) -> Self { | 183 | fn from(def: AttrDef) -> Self { |
246 | match def { | 184 | match def { |
@@ -257,3 +195,13 @@ impl From<AttrDef> for AttrDefId { | |||
257 | } | 195 | } |
258 | } | 196 | } |
259 | } | 197 | } |
198 | |||
199 | impl From<AssocItem> for GenericDefId { | ||
200 | fn from(item: AssocItem) -> Self { | ||
201 | match item { | ||
202 | AssocItem::Function(f) => f.id.into(), | ||
203 | AssocItem::Const(c) => c.id.into(), | ||
204 | AssocItem::TypeAlias(t) => t.id.into(), | ||
205 | } | ||
206 | } | ||
207 | } | ||
diff --git a/crates/ra_hir/src/from_source.rs b/crates/ra_hir/src/from_source.rs index 1e7c22774..9f7c22b21 100644 --- a/crates/ra_hir/src/from_source.rs +++ b/crates/ra_hir/src/from_source.rs | |||
@@ -1,6 +1,6 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! FIXME: write short doc here |
2 | 2 | ||
3 | use hir_def::{AstItemDef, LocationCtx, ModuleId, StructId, StructOrUnionId, UnionId}; | 3 | use hir_def::{AstItemDef, LocationCtx, ModuleId}; |
4 | use hir_expand::{name::AsName, AstId, MacroDefId, MacroDefKind}; | 4 | use hir_expand::{name::AsName, AstId, MacroDefId, MacroDefKind}; |
5 | use ra_syntax::{ | 5 | use ra_syntax::{ |
6 | ast::{self, AstNode, NameOwner}, | 6 | ast::{self, AstNode, NameOwner}, |
@@ -19,19 +19,18 @@ pub trait FromSource: Sized { | |||
19 | fn from_source(db: &(impl DefDatabase + AstDatabase), src: Source<Self::Ast>) -> Option<Self>; | 19 | fn from_source(db: &(impl DefDatabase + AstDatabase), src: Source<Self::Ast>) -> Option<Self>; |
20 | } | 20 | } |
21 | 21 | ||
22 | // FIXIME: these two impls are wrong, `ast::StructDef` might produce either a struct or a union | ||
23 | impl FromSource for Struct { | 22 | impl FromSource for Struct { |
24 | type Ast = ast::StructDef; | 23 | type Ast = ast::StructDef; |
25 | fn from_source(db: &(impl DefDatabase + AstDatabase), src: Source<Self::Ast>) -> Option<Self> { | 24 | fn from_source(db: &(impl DefDatabase + AstDatabase), src: Source<Self::Ast>) -> Option<Self> { |
26 | let id: StructOrUnionId = from_source(db, src)?; | 25 | let id = from_source(db, src)?; |
27 | Some(Struct { id: StructId(id) }) | 26 | Some(Struct { id }) |
28 | } | 27 | } |
29 | } | 28 | } |
30 | impl FromSource for Union { | 29 | impl FromSource for Union { |
31 | type Ast = ast::StructDef; | 30 | type Ast = ast::UnionDef; |
32 | fn from_source(db: &(impl DefDatabase + AstDatabase), src: Source<Self::Ast>) -> Option<Self> { | 31 | fn from_source(db: &(impl DefDatabase + AstDatabase), src: Source<Self::Ast>) -> Option<Self> { |
33 | let id: StructOrUnionId = from_source(db, src)?; | 32 | let id = from_source(db, src)?; |
34 | Some(Union { id: UnionId(id) }) | 33 | Some(Union { id }) |
35 | } | 34 | } |
36 | } | 35 | } |
37 | impl FromSource for Enum { | 36 | impl FromSource for Enum { |
@@ -263,13 +262,12 @@ impl Module { | |||
263 | 262 | ||
264 | let original_file = src.file_id.original_file(db); | 263 | let original_file = src.file_id.original_file(db); |
265 | 264 | ||
266 | let (krate, module_id) = | 265 | let (krate, local_id) = db.relevant_crates(original_file).iter().find_map(|&crate_id| { |
267 | db.relevant_crates(original_file).iter().find_map(|&crate_id| { | 266 | let crate_def_map = db.crate_def_map(crate_id); |
268 | let crate_def_map = db.crate_def_map(crate_id); | 267 | let local_id = crate_def_map.modules_for_file(original_file).next()?; |
269 | let local_module_id = crate_def_map.modules_for_file(original_file).next()?; | 268 | Some((crate_id, local_id)) |
270 | Some((crate_id, local_module_id)) | 269 | })?; |
271 | })?; | 270 | Some(Module { id: ModuleId { krate, local_id } }) |
272 | Some(Module { id: ModuleId { krate, module_id } }) | ||
273 | } | 271 | } |
274 | } | 272 | } |
275 | 273 | ||
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs index 843ce6a88..3c12c61f0 100644 --- a/crates/ra_hir/src/lib.rs +++ b/crates/ra_hir/src/lib.rs | |||
@@ -32,28 +32,20 @@ pub mod db; | |||
32 | pub mod source_binder; | 32 | pub mod source_binder; |
33 | 33 | ||
34 | mod ty; | 34 | mod ty; |
35 | mod expr; | ||
36 | pub mod diagnostics; | 35 | pub mod diagnostics; |
37 | mod util; | ||
38 | 36 | ||
39 | mod from_id; | 37 | mod from_id; |
40 | mod code_model; | 38 | mod code_model; |
41 | 39 | ||
42 | pub mod from_source; | 40 | pub mod from_source; |
43 | 41 | ||
44 | #[cfg(test)] | ||
45 | mod test_db; | ||
46 | #[cfg(test)] | ||
47 | mod marks; | ||
48 | |||
49 | pub use crate::{ | 42 | pub use crate::{ |
50 | code_model::{ | 43 | code_model::{ |
51 | src::HasSource, Adt, AssocItem, AttrDef, Const, Container, Crate, CrateDependency, | 44 | src::HasSource, Adt, AssocItem, AttrDef, Const, Container, Crate, CrateDependency, |
52 | DefWithBody, Docs, Enum, EnumVariant, FieldSource, Function, GenericDef, GenericParam, | 45 | DefWithBody, Docs, Enum, EnumVariant, FieldSource, Function, GenericDef, GenericParam, |
53 | HasAttrs, ImplBlock, Import, Local, MacroDef, Module, ModuleDef, ModuleSource, ScopeDef, | 46 | HasAttrs, ImplBlock, Import, Local, MacroDef, Module, ModuleDef, ModuleSource, ScopeDef, |
54 | Static, Struct, StructField, Trait, TypeAlias, Union, VariantDef, | 47 | Static, Struct, StructField, Trait, Type, TypeAlias, Union, VariantDef, |
55 | }, | 48 | }, |
56 | expr::ExprScopes, | ||
57 | from_source::FromSource, | 49 | from_source::FromSource, |
58 | source_binder::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer}, | 50 | source_binder::{PathResolution, ScopeEntryWithSyntax, SourceAnalyzer}, |
59 | ty::{ | 51 | ty::{ |
@@ -64,6 +56,7 @@ pub use crate::{ | |||
64 | }; | 56 | }; |
65 | 57 | ||
66 | pub use hir_def::{ | 58 | pub use hir_def::{ |
59 | body::scope::ExprScopes, | ||
67 | builtin_type::BuiltinType, | 60 | builtin_type::BuiltinType, |
68 | docs::Documentation, | 61 | docs::Documentation, |
69 | path::{Path, PathKind}, | 62 | path::{Path, PathKind}, |
diff --git a/crates/ra_hir/src/marks.rs b/crates/ra_hir/src/marks.rs deleted file mode 100644 index 0f754eb9c..000000000 --- a/crates/ra_hir/src/marks.rs +++ /dev/null | |||
@@ -1,9 +0,0 @@ | |||
1 | //! See test_utils/src/marks.rs | ||
2 | |||
3 | test_utils::marks!( | ||
4 | type_var_cycles_resolve_completely | ||
5 | type_var_cycles_resolve_as_possible | ||
6 | type_var_resolves_to_int_var | ||
7 | match_ergonomics_ref | ||
8 | coerce_merge_fail_fallback | ||
9 | ); | ||
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 31390bb7f..76c493f1a 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs | |||
@@ -8,13 +8,17 @@ | |||
8 | use std::sync::Arc; | 8 | use std::sync::Arc; |
9 | 9 | ||
10 | use hir_def::{ | 10 | use hir_def::{ |
11 | body::{ | ||
12 | scope::{ExprScopes, ScopeId}, | ||
13 | BodySourceMap, | ||
14 | }, | ||
11 | expr::{ExprId, PatId}, | 15 | expr::{ExprId, PatId}, |
12 | path::known, | 16 | path::known, |
13 | resolver::{self, resolver_for_scope, HasResolver, Resolver, TypeNs, ValueNs}, | 17 | resolver::{self, resolver_for_scope, HasResolver, Resolver, TypeNs, ValueNs}, |
14 | DefWithBodyId, | 18 | AssocItemId, DefWithBodyId, |
15 | }; | 19 | }; |
16 | use hir_expand::{ | 20 | use hir_expand::{ |
17 | name::AsName, AstId, HirFileId, MacroCallId, MacroCallLoc, MacroFileKind, Source, | 21 | hygiene::Hygiene, name::AsName, AstId, HirFileId, MacroCallId, MacroFileKind, Source, |
18 | }; | 22 | }; |
19 | use ra_syntax::{ | 23 | use ra_syntax::{ |
20 | ast::{self, AstNode}, | 24 | ast::{self, AstNode}, |
@@ -25,10 +29,12 @@ use ra_syntax::{ | |||
25 | 29 | ||
26 | use crate::{ | 30 | use crate::{ |
27 | db::HirDatabase, | 31 | db::HirDatabase, |
28 | expr::{BodySourceMap, ExprScopes, ScopeId}, | 32 | ty::{ |
29 | ty::method_resolution::{self, implements_trait}, | 33 | method_resolution::{self, implements_trait}, |
34 | InEnvironment, TraitEnvironment, Ty, | ||
35 | }, | ||
30 | Adt, AssocItem, Const, DefWithBody, Either, Enum, EnumVariant, FromSource, Function, | 36 | Adt, AssocItem, Const, DefWithBody, Either, Enum, EnumVariant, FromSource, Function, |
31 | GenericParam, Local, MacroDef, Name, Path, ScopeDef, Static, Struct, Trait, Ty, TypeAlias, | 37 | GenericParam, Local, MacroDef, Name, Path, ScopeDef, Static, Struct, Trait, Type, TypeAlias, |
32 | }; | 38 | }; |
33 | 39 | ||
34 | fn try_get_resolver_for_node(db: &impl HirDatabase, node: Source<&SyntaxNode>) -> Option<Resolver> { | 40 | fn try_get_resolver_for_node(db: &impl HirDatabase, node: Source<&SyntaxNode>) -> Option<Resolver> { |
@@ -88,7 +94,7 @@ pub struct SourceAnalyzer { | |||
88 | body_owner: Option<DefWithBody>, | 94 | body_owner: Option<DefWithBody>, |
89 | body_source_map: Option<Arc<BodySourceMap>>, | 95 | body_source_map: Option<Arc<BodySourceMap>>, |
90 | infer: Option<Arc<crate::ty::InferenceResult>>, | 96 | infer: Option<Arc<crate::ty::InferenceResult>>, |
91 | scopes: Option<Arc<crate::expr::ExprScopes>>, | 97 | scopes: Option<Arc<ExprScopes>>, |
92 | } | 98 | } |
93 | 99 | ||
94 | #[derive(Debug, Clone, PartialEq, Eq)] | 100 | #[derive(Debug, Clone, PartialEq, Eq)] |
@@ -165,7 +171,7 @@ impl SourceAnalyzer { | |||
165 | resolver, | 171 | resolver, |
166 | body_owner: Some(def), | 172 | body_owner: Some(def), |
167 | body_source_map: Some(source_map), | 173 | body_source_map: Some(source_map), |
168 | infer: Some(db.infer(def)), | 174 | infer: Some(db.infer(def.into())), |
169 | scopes: Some(scopes), | 175 | scopes: Some(scopes), |
170 | file_id: node.file_id, | 176 | file_id: node.file_id, |
171 | } | 177 | } |
@@ -195,48 +201,52 @@ impl SourceAnalyzer { | |||
195 | self.body_source_map.as_ref()?.node_pat(src) | 201 | self.body_source_map.as_ref()?.node_pat(src) |
196 | } | 202 | } |
197 | 203 | ||
198 | pub fn type_of(&self, _db: &impl HirDatabase, expr: &ast::Expr) -> Option<crate::Ty> { | 204 | pub fn type_of(&self, db: &impl HirDatabase, expr: &ast::Expr) -> Option<Type> { |
199 | let expr_id = self.expr_id(expr)?; | 205 | let expr_id = self.expr_id(expr)?; |
200 | Some(self.infer.as_ref()?[expr_id].clone()) | 206 | let ty = self.infer.as_ref()?[expr_id].clone(); |
207 | let environment = TraitEnvironment::lower(db, &self.resolver); | ||
208 | Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } }) | ||
201 | } | 209 | } |
202 | 210 | ||
203 | pub fn type_of_pat(&self, _db: &impl HirDatabase, pat: &ast::Pat) -> Option<crate::Ty> { | 211 | pub fn type_of_pat(&self, db: &impl HirDatabase, pat: &ast::Pat) -> Option<Type> { |
204 | let pat_id = self.pat_id(pat)?; | 212 | let pat_id = self.pat_id(pat)?; |
205 | Some(self.infer.as_ref()?[pat_id].clone()) | 213 | let ty = self.infer.as_ref()?[pat_id].clone(); |
214 | let environment = TraitEnvironment::lower(db, &self.resolver); | ||
215 | Some(Type { krate: self.resolver.krate()?, ty: InEnvironment { value: ty, environment } }) | ||
206 | } | 216 | } |
207 | 217 | ||
208 | pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> { | 218 | pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option<Function> { |
209 | let expr_id = self.expr_id(&call.clone().into())?; | 219 | let expr_id = self.expr_id(&call.clone().into())?; |
210 | self.infer.as_ref()?.method_resolution(expr_id) | 220 | self.infer.as_ref()?.method_resolution(expr_id).map(Function::from) |
211 | } | 221 | } |
212 | 222 | ||
213 | pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<crate::StructField> { | 223 | pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<crate::StructField> { |
214 | let expr_id = self.expr_id(&field.clone().into())?; | 224 | let expr_id = self.expr_id(&field.clone().into())?; |
215 | self.infer.as_ref()?.field_resolution(expr_id) | 225 | self.infer.as_ref()?.field_resolution(expr_id).map(|it| it.into()) |
216 | } | 226 | } |
217 | 227 | ||
218 | pub fn resolve_record_field(&self, field: &ast::RecordField) -> Option<crate::StructField> { | 228 | pub fn resolve_record_field(&self, field: &ast::RecordField) -> Option<crate::StructField> { |
219 | let expr_id = self.expr_id(&field.expr()?)?; | 229 | let expr_id = self.expr_id(&field.expr()?)?; |
220 | self.infer.as_ref()?.record_field_resolution(expr_id) | 230 | self.infer.as_ref()?.record_field_resolution(expr_id).map(|it| it.into()) |
221 | } | 231 | } |
222 | 232 | ||
223 | pub fn resolve_record_literal(&self, record_lit: &ast::RecordLit) -> Option<crate::VariantDef> { | 233 | pub fn resolve_record_literal(&self, record_lit: &ast::RecordLit) -> Option<crate::VariantDef> { |
224 | let expr_id = self.expr_id(&record_lit.clone().into())?; | 234 | let expr_id = self.expr_id(&record_lit.clone().into())?; |
225 | self.infer.as_ref()?.variant_resolution_for_expr(expr_id) | 235 | self.infer.as_ref()?.variant_resolution_for_expr(expr_id).map(|it| it.into()) |
226 | } | 236 | } |
227 | 237 | ||
228 | pub fn resolve_record_pattern(&self, record_pat: &ast::RecordPat) -> Option<crate::VariantDef> { | 238 | pub fn resolve_record_pattern(&self, record_pat: &ast::RecordPat) -> Option<crate::VariantDef> { |
229 | let pat_id = self.pat_id(&record_pat.clone().into())?; | 239 | let pat_id = self.pat_id(&record_pat.clone().into())?; |
230 | self.infer.as_ref()?.variant_resolution_for_pat(pat_id) | 240 | self.infer.as_ref()?.variant_resolution_for_pat(pat_id).map(|it| it.into()) |
231 | } | 241 | } |
232 | 242 | ||
233 | pub fn resolve_macro_call( | 243 | pub fn resolve_macro_call( |
234 | &self, | 244 | &self, |
235 | db: &impl HirDatabase, | 245 | db: &impl HirDatabase, |
236 | macro_call: &ast::MacroCall, | 246 | macro_call: Source<&ast::MacroCall>, |
237 | ) -> Option<MacroDef> { | 247 | ) -> Option<MacroDef> { |
238 | // This must be a normal source file rather than macro file. | 248 | let hygiene = Hygiene::new(db, macro_call.file_id); |
239 | let path = macro_call.path().and_then(Path::from_ast)?; | 249 | let path = macro_call.value.path().and_then(|ast| Path::from_src(ast, &hygiene))?; |
240 | self.resolver.resolve_path_as_macro(db, &path).map(|it| it.into()) | 250 | self.resolver.resolve_path_as_macro(db, &path).map(|it| it.into()) |
241 | } | 251 | } |
242 | 252 | ||
@@ -248,7 +258,7 @@ impl SourceAnalyzer { | |||
248 | let types = self.resolver.resolve_path_in_type_ns_fully(db, &path).map(|ty| match ty { | 258 | let types = self.resolver.resolve_path_in_type_ns_fully(db, &path).map(|ty| match ty { |
249 | TypeNs::SelfType(it) => PathResolution::SelfType(it.into()), | 259 | TypeNs::SelfType(it) => PathResolution::SelfType(it.into()), |
250 | TypeNs::GenericParam(idx) => PathResolution::GenericParam(GenericParam { | 260 | TypeNs::GenericParam(idx) => PathResolution::GenericParam(GenericParam { |
251 | parent: self.resolver.generic_def().unwrap().into(), | 261 | parent: self.resolver.generic_def().unwrap(), |
252 | idx, | 262 | idx, |
253 | }), | 263 | }), |
254 | TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => { | 264 | TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => { |
@@ -290,13 +300,13 @@ impl SourceAnalyzer { | |||
290 | if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) { | 300 | if let Some(path_expr) = path.syntax().parent().and_then(ast::PathExpr::cast) { |
291 | let expr_id = self.expr_id(&path_expr.into())?; | 301 | let expr_id = self.expr_id(&path_expr.into())?; |
292 | if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_expr(expr_id) { | 302 | if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_expr(expr_id) { |
293 | return Some(PathResolution::AssocItem(assoc)); | 303 | return Some(PathResolution::AssocItem(assoc.into())); |
294 | } | 304 | } |
295 | } | 305 | } |
296 | if let Some(path_pat) = path.syntax().parent().and_then(ast::PathPat::cast) { | 306 | if let Some(path_pat) = path.syntax().parent().and_then(ast::PathPat::cast) { |
297 | let pat_id = self.pat_id(&path_pat.into())?; | 307 | let pat_id = self.pat_id(&path_pat.into())?; |
298 | if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) { | 308 | if let Some(assoc) = self.infer.as_ref()?.assoc_resolutions_for_pat(pat_id) { |
299 | return Some(PathResolution::AssocItem(assoc)); | 309 | return Some(PathResolution::AssocItem(assoc.into())); |
300 | } | 310 | } |
301 | } | 311 | } |
302 | // This must be a normal source file rather than macro file. | 312 | // This must be a normal source file rather than macro file. |
@@ -323,7 +333,7 @@ impl SourceAnalyzer { | |||
323 | resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()), | 333 | resolver::ScopeDef::ImplSelfType(it) => ScopeDef::ImplSelfType(it.into()), |
324 | resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()), | 334 | resolver::ScopeDef::AdtSelfType(it) => ScopeDef::AdtSelfType(it.into()), |
325 | resolver::ScopeDef::GenericParam(idx) => { | 335 | resolver::ScopeDef::GenericParam(idx) => { |
326 | let parent = self.resolver.generic_def().unwrap().into(); | 336 | let parent = self.resolver.generic_def().unwrap(); |
327 | ScopeDef::GenericParam(GenericParam { parent, idx }) | 337 | ScopeDef::GenericParam(GenericParam { parent, idx }) |
328 | } | 338 | } |
329 | resolver::ScopeDef::Local(pat_id) => { | 339 | resolver::ScopeDef::Local(pat_id) => { |
@@ -358,14 +368,14 @@ impl SourceAnalyzer { | |||
358 | pub fn iterate_method_candidates<T>( | 368 | pub fn iterate_method_candidates<T>( |
359 | &self, | 369 | &self, |
360 | db: &impl HirDatabase, | 370 | db: &impl HirDatabase, |
361 | ty: Ty, | 371 | ty: &Type, |
362 | name: Option<&Name>, | 372 | name: Option<&Name>, |
363 | mut callback: impl FnMut(&Ty, Function) -> Option<T>, | 373 | mut callback: impl FnMut(&Ty, Function) -> Option<T>, |
364 | ) -> Option<T> { | 374 | ) -> Option<T> { |
365 | // There should be no inference vars in types passed here | 375 | // There should be no inference vars in types passed here |
366 | // FIXME check that? | 376 | // FIXME check that? |
367 | // FIXME replace Unknown by bound vars here | 377 | // FIXME replace Unknown by bound vars here |
368 | let canonical = crate::ty::Canonical { value: ty, num_vars: 0 }; | 378 | let canonical = crate::ty::Canonical { value: ty.ty.value.clone(), num_vars: 0 }; |
369 | method_resolution::iterate_method_candidates( | 379 | method_resolution::iterate_method_candidates( |
370 | &canonical, | 380 | &canonical, |
371 | db, | 381 | db, |
@@ -373,7 +383,7 @@ impl SourceAnalyzer { | |||
373 | name, | 383 | name, |
374 | method_resolution::LookupMode::MethodCall, | 384 | method_resolution::LookupMode::MethodCall, |
375 | |ty, it| match it { | 385 | |ty, it| match it { |
376 | AssocItem::Function(f) => callback(ty, f), | 386 | AssocItemId::FunctionId(f) => callback(ty, f.into()), |
377 | _ => None, | 387 | _ => None, |
378 | }, | 388 | }, |
379 | ) | 389 | ) |
@@ -382,34 +392,37 @@ impl SourceAnalyzer { | |||
382 | pub fn iterate_path_candidates<T>( | 392 | pub fn iterate_path_candidates<T>( |
383 | &self, | 393 | &self, |
384 | db: &impl HirDatabase, | 394 | db: &impl HirDatabase, |
385 | ty: Ty, | 395 | ty: &Type, |
386 | name: Option<&Name>, | 396 | name: Option<&Name>, |
387 | callback: impl FnMut(&Ty, AssocItem) -> Option<T>, | 397 | mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>, |
388 | ) -> Option<T> { | 398 | ) -> Option<T> { |
389 | // There should be no inference vars in types passed here | 399 | // There should be no inference vars in types passed here |
390 | // FIXME check that? | 400 | // FIXME check that? |
391 | // FIXME replace Unknown by bound vars here | 401 | // FIXME replace Unknown by bound vars here |
392 | let canonical = crate::ty::Canonical { value: ty, num_vars: 0 }; | 402 | let canonical = crate::ty::Canonical { value: ty.ty.value.clone(), num_vars: 0 }; |
393 | method_resolution::iterate_method_candidates( | 403 | method_resolution::iterate_method_candidates( |
394 | &canonical, | 404 | &canonical, |
395 | db, | 405 | db, |
396 | &self.resolver, | 406 | &self.resolver, |
397 | name, | 407 | name, |
398 | method_resolution::LookupMode::Path, | 408 | method_resolution::LookupMode::Path, |
399 | callback, | 409 | |ty, it| callback(ty, it.into()), |
400 | ) | 410 | ) |
401 | } | 411 | } |
402 | 412 | ||
403 | pub fn autoderef<'a>( | 413 | // pub fn autoderef<'a>( |
404 | &'a self, | 414 | // &'a self, |
405 | db: &'a impl HirDatabase, | 415 | // db: &'a impl HirDatabase, |
406 | ty: Ty, | 416 | // ty: Ty, |
407 | ) -> impl Iterator<Item = Ty> + 'a { | 417 | // ) -> impl Iterator<Item = Ty> + 'a { |
408 | // There should be no inference vars in types passed here | 418 | // // There should be no inference vars in types passed here |
409 | // FIXME check that? | 419 | // // FIXME check that? |
410 | let canonical = crate::ty::Canonical { value: ty, num_vars: 0 }; | 420 | // let canonical = crate::ty::Canonical { value: ty, num_vars: 0 }; |
411 | crate::ty::autoderef(db, &self.resolver, canonical).map(|canonical| canonical.value) | 421 | // let krate = self.resolver.krate(); |
412 | } | 422 | // let environment = TraitEnvironment::lower(db, &self.resolver); |
423 | // let ty = crate::ty::InEnvironment { value: canonical, environment }; | ||
424 | // crate::ty::autoderef(db, krate, ty).map(|canonical| canonical.value) | ||
425 | // } | ||
413 | 426 | ||
414 | /// Checks that particular type `ty` implements `std::future::Future`. | 427 | /// Checks that particular type `ty` implements `std::future::Future`. |
415 | /// This function is used in `.await` syntax completion. | 428 | /// This function is used in `.await` syntax completion. |
@@ -435,32 +448,16 @@ impl SourceAnalyzer { | |||
435 | db: &impl HirDatabase, | 448 | db: &impl HirDatabase, |
436 | macro_call: Source<&ast::MacroCall>, | 449 | macro_call: Source<&ast::MacroCall>, |
437 | ) -> Option<Expansion> { | 450 | ) -> Option<Expansion> { |
438 | let def = self.resolve_macro_call(db, macro_call.value)?.id; | 451 | let def = self.resolve_macro_call(db, macro_call)?.id; |
439 | let ast_id = AstId::new( | 452 | let ast_id = AstId::new( |
440 | macro_call.file_id, | 453 | macro_call.file_id, |
441 | db.ast_id_map(macro_call.file_id).ast_id(macro_call.value), | 454 | db.ast_id_map(macro_call.file_id).ast_id(macro_call.value), |
442 | ); | 455 | ); |
443 | let macro_call_loc = MacroCallLoc { def, ast_id }; | ||
444 | Some(Expansion { | 456 | Some(Expansion { |
445 | macro_call_id: db.intern_macro(macro_call_loc), | 457 | macro_call_id: def.as_call_id(db, ast_id), |
446 | macro_file_kind: to_macro_file_kind(macro_call.value), | 458 | macro_file_kind: to_macro_file_kind(macro_call.value), |
447 | }) | 459 | }) |
448 | } | 460 | } |
449 | |||
450 | #[cfg(test)] | ||
451 | pub(crate) fn body_source_map(&self) -> Arc<BodySourceMap> { | ||
452 | self.body_source_map.clone().unwrap() | ||
453 | } | ||
454 | |||
455 | #[cfg(test)] | ||
456 | pub(crate) fn inference_result(&self) -> Arc<crate::ty::InferenceResult> { | ||
457 | self.infer.clone().unwrap() | ||
458 | } | ||
459 | |||
460 | #[cfg(test)] | ||
461 | pub(crate) fn analyzed_declaration(&self) -> Option<DefWithBody> { | ||
462 | self.body_owner | ||
463 | } | ||
464 | } | 461 | } |
465 | 462 | ||
466 | fn scope_for( | 463 | fn scope_for( |
diff --git a/crates/ra_hir/src/test_db.rs b/crates/ra_hir/src/test_db.rs deleted file mode 100644 index efee2f658..000000000 --- a/crates/ra_hir/src/test_db.rs +++ /dev/null | |||
@@ -1,119 +0,0 @@ | |||
1 | //! Database used for testing `hir`. | ||
2 | |||
3 | use std::{panic, sync::Arc}; | ||
4 | |||
5 | use hir_def::{db::DefDatabase, ModuleId}; | ||
6 | use hir_expand::diagnostics::DiagnosticSink; | ||
7 | use parking_lot::Mutex; | ||
8 | use ra_db::{salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, RelativePath, SourceDatabase}; | ||
9 | |||
10 | use crate::{db, debug::HirDebugHelper}; | ||
11 | |||
12 | #[salsa::database( | ||
13 | ra_db::SourceDatabaseExtStorage, | ||
14 | ra_db::SourceDatabaseStorage, | ||
15 | db::InternDatabaseStorage, | ||
16 | db::AstDatabaseStorage, | ||
17 | db::DefDatabaseStorage, | ||
18 | db::HirDatabaseStorage | ||
19 | )] | ||
20 | #[derive(Debug, Default)] | ||
21 | pub struct TestDB { | ||
22 | events: Mutex<Option<Vec<salsa::Event<TestDB>>>>, | ||
23 | runtime: salsa::Runtime<TestDB>, | ||
24 | } | ||
25 | |||
26 | impl salsa::Database for TestDB { | ||
27 | fn salsa_runtime(&self) -> &salsa::Runtime<TestDB> { | ||
28 | &self.runtime | ||
29 | } | ||
30 | |||
31 | fn salsa_event(&self, event: impl Fn() -> salsa::Event<TestDB>) { | ||
32 | let mut events = self.events.lock(); | ||
33 | if let Some(events) = &mut *events { | ||
34 | events.push(event()); | ||
35 | } | ||
36 | } | ||
37 | } | ||
38 | |||
39 | impl salsa::ParallelDatabase for TestDB { | ||
40 | fn snapshot(&self) -> salsa::Snapshot<TestDB> { | ||
41 | salsa::Snapshot::new(TestDB { | ||
42 | events: Default::default(), | ||
43 | runtime: self.runtime.snapshot(self), | ||
44 | }) | ||
45 | } | ||
46 | } | ||
47 | |||
48 | impl panic::RefUnwindSafe for TestDB {} | ||
49 | |||
50 | impl FileLoader for TestDB { | ||
51 | fn file_text(&self, file_id: FileId) -> Arc<String> { | ||
52 | FileLoaderDelegate(self).file_text(file_id) | ||
53 | } | ||
54 | fn resolve_relative_path( | ||
55 | &self, | ||
56 | anchor: FileId, | ||
57 | relative_path: &RelativePath, | ||
58 | ) -> Option<FileId> { | ||
59 | FileLoaderDelegate(self).resolve_relative_path(anchor, relative_path) | ||
60 | } | ||
61 | fn relevant_crates(&self, file_id: FileId) -> Arc<Vec<CrateId>> { | ||
62 | FileLoaderDelegate(self).relevant_crates(file_id) | ||
63 | } | ||
64 | } | ||
65 | |||
66 | // FIXME: improve `WithFixture` to bring useful hir debugging back | ||
67 | impl HirDebugHelper for TestDB { | ||
68 | fn crate_name(&self, _krate: CrateId) -> Option<String> { | ||
69 | None | ||
70 | } | ||
71 | |||
72 | fn file_path(&self, _file_id: FileId) -> Option<String> { | ||
73 | None | ||
74 | } | ||
75 | } | ||
76 | |||
77 | impl TestDB { | ||
78 | pub fn diagnostics(&self) -> String { | ||
79 | let mut buf = String::new(); | ||
80 | let crate_graph = self.crate_graph(); | ||
81 | for krate in crate_graph.iter().next() { | ||
82 | let crate_def_map = self.crate_def_map(krate); | ||
83 | for (module_id, _) in crate_def_map.modules.iter() { | ||
84 | let module_id = ModuleId { krate, module_id }; | ||
85 | let module = crate::Module::from(module_id); | ||
86 | module.diagnostics( | ||
87 | self, | ||
88 | &mut DiagnosticSink::new(|d| { | ||
89 | buf += &format!("{:?}: {}\n", d.syntax_node(self).text(), d.message()); | ||
90 | }), | ||
91 | ) | ||
92 | } | ||
93 | } | ||
94 | buf | ||
95 | } | ||
96 | } | ||
97 | |||
98 | impl TestDB { | ||
99 | pub fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event<TestDB>> { | ||
100 | *self.events.lock() = Some(Vec::new()); | ||
101 | f(); | ||
102 | self.events.lock().take().unwrap() | ||
103 | } | ||
104 | |||
105 | pub fn log_executed(&self, f: impl FnOnce()) -> Vec<String> { | ||
106 | let events = self.log(f); | ||
107 | events | ||
108 | .into_iter() | ||
109 | .filter_map(|e| match e.kind { | ||
110 | // This pretty horrible, but `Debug` is the only way to inspect | ||
111 | // QueryDescriptor at the moment. | ||
112 | salsa::EventKind::WillExecute { database_key } => { | ||
113 | Some(format!("{:?}", database_key)) | ||
114 | } | ||
115 | _ => None, | ||
116 | }) | ||
117 | .collect() | ||
118 | } | ||
119 | } | ||
diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index f62316c1f..4ed69c00d 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs | |||
@@ -1,1094 +1,4 @@ | |||
1 | //! The type system. We currently use this to infer types for completion, hover | 1 | //! The type system. We currently use this to infer types for completion, hover |
2 | //! information and various assists. | 2 | //! information and various assists. |
3 | 3 | ||
4 | mod autoderef; | 4 | pub use hir_ty::*; |
5 | pub(crate) mod primitive; | ||
6 | pub(crate) mod traits; | ||
7 | pub(crate) mod method_resolution; | ||
8 | mod op; | ||
9 | mod lower; | ||
10 | mod infer; | ||
11 | pub(crate) mod display; | ||
12 | |||
13 | #[cfg(test)] | ||
14 | mod tests; | ||
15 | |||
16 | use std::ops::Deref; | ||
17 | use std::sync::Arc; | ||
18 | use std::{fmt, iter, mem}; | ||
19 | |||
20 | use hir_def::{generics::GenericParams, AdtId}; | ||
21 | use ra_db::{impl_intern_key, salsa}; | ||
22 | |||
23 | use crate::{ | ||
24 | db::HirDatabase, expr::ExprId, util::make_mut_slice, Adt, Crate, DefWithBody, FloatTy, | ||
25 | GenericDef, IntTy, Mutability, Name, Trait, TypeAlias, Uncertain, | ||
26 | }; | ||
27 | use display::{HirDisplay, HirFormatter}; | ||
28 | |||
29 | pub(crate) use autoderef::autoderef; | ||
30 | pub(crate) use infer::{infer_query, InferTy, InferenceResult}; | ||
31 | pub use lower::CallableDef; | ||
32 | pub(crate) use lower::{ | ||
33 | callable_item_sig, field_types_query, generic_defaults_query, | ||
34 | generic_predicates_for_param_query, generic_predicates_query, type_for_def, Namespace, | ||
35 | TypableDef, | ||
36 | }; | ||
37 | pub(crate) use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment}; | ||
38 | |||
39 | /// A type constructor or type name: this might be something like the primitive | ||
40 | /// type `bool`, a struct like `Vec`, or things like function pointers or | ||
41 | /// tuples. | ||
42 | #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] | ||
43 | pub enum TypeCtor { | ||
44 | /// The primitive boolean type. Written as `bool`. | ||
45 | Bool, | ||
46 | |||
47 | /// The primitive character type; holds a Unicode scalar value | ||
48 | /// (a non-surrogate code point). Written as `char`. | ||
49 | Char, | ||
50 | |||
51 | /// A primitive integer type. For example, `i32`. | ||
52 | Int(Uncertain<IntTy>), | ||
53 | |||
54 | /// A primitive floating-point type. For example, `f64`. | ||
55 | Float(Uncertain<FloatTy>), | ||
56 | |||
57 | /// Structures, enumerations and unions. | ||
58 | Adt(Adt), | ||
59 | |||
60 | /// The pointee of a string slice. Written as `str`. | ||
61 | Str, | ||
62 | |||
63 | /// The pointee of an array slice. Written as `[T]`. | ||
64 | Slice, | ||
65 | |||
66 | /// An array with the given length. Written as `[T; n]`. | ||
67 | Array, | ||
68 | |||
69 | /// A raw pointer. Written as `*mut T` or `*const T` | ||
70 | RawPtr(Mutability), | ||
71 | |||
72 | /// A reference; a pointer with an associated lifetime. Written as | ||
73 | /// `&'a mut T` or `&'a T`. | ||
74 | Ref(Mutability), | ||
75 | |||
76 | /// The anonymous type of a function declaration/definition. Each | ||
77 | /// function has a unique type, which is output (for a function | ||
78 | /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`. | ||
79 | /// | ||
80 | /// This includes tuple struct / enum variant constructors as well. | ||
81 | /// | ||
82 | /// For example the type of `bar` here: | ||
83 | /// | ||
84 | /// ``` | ||
85 | /// fn foo() -> i32 { 1 } | ||
86 | /// let bar = foo; // bar: fn() -> i32 {foo} | ||
87 | /// ``` | ||
88 | FnDef(CallableDef), | ||
89 | |||
90 | /// A pointer to a function. Written as `fn() -> i32`. | ||
91 | /// | ||
92 | /// For example the type of `bar` here: | ||
93 | /// | ||
94 | /// ``` | ||
95 | /// fn foo() -> i32 { 1 } | ||
96 | /// let bar: fn() -> i32 = foo; | ||
97 | /// ``` | ||
98 | FnPtr { num_args: u16 }, | ||
99 | |||
100 | /// The never type `!`. | ||
101 | Never, | ||
102 | |||
103 | /// A tuple type. For example, `(i32, bool)`. | ||
104 | Tuple { cardinality: u16 }, | ||
105 | |||
106 | /// Represents an associated item like `Iterator::Item`. This is used | ||
107 | /// when we have tried to normalize a projection like `T::Item` but | ||
108 | /// couldn't find a better representation. In that case, we generate | ||
109 | /// an **application type** like `(Iterator::Item)<T>`. | ||
110 | AssociatedType(TypeAlias), | ||
111 | |||
112 | /// The type of a specific closure. | ||
113 | /// | ||
114 | /// The closure signature is stored in a `FnPtr` type in the first type | ||
115 | /// parameter. | ||
116 | Closure { def: DefWithBody, expr: ExprId }, | ||
117 | } | ||
118 | |||
119 | /// This exists just for Chalk, because Chalk just has a single `StructId` where | ||
120 | /// we have different kinds of ADTs, primitive types and special type | ||
121 | /// constructors like tuples and function pointers. | ||
122 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
123 | pub struct TypeCtorId(salsa::InternId); | ||
124 | impl_intern_key!(TypeCtorId); | ||
125 | |||
126 | impl TypeCtor { | ||
127 | pub fn num_ty_params(self, db: &impl HirDatabase) -> usize { | ||
128 | match self { | ||
129 | TypeCtor::Bool | ||
130 | | TypeCtor::Char | ||
131 | | TypeCtor::Int(_) | ||
132 | | TypeCtor::Float(_) | ||
133 | | TypeCtor::Str | ||
134 | | TypeCtor::Never => 0, | ||
135 | TypeCtor::Slice | ||
136 | | TypeCtor::Array | ||
137 | | TypeCtor::RawPtr(_) | ||
138 | | TypeCtor::Ref(_) | ||
139 | | TypeCtor::Closure { .. } // 1 param representing the signature of the closure | ||
140 | => 1, | ||
141 | TypeCtor::Adt(adt) => { | ||
142 | let generic_params = db.generic_params(AdtId::from(adt).into()); | ||
143 | generic_params.count_params_including_parent() | ||
144 | } | ||
145 | TypeCtor::FnDef(callable) => { | ||
146 | let generic_params = db.generic_params(callable.into()); | ||
147 | generic_params.count_params_including_parent() | ||
148 | } | ||
149 | TypeCtor::AssociatedType(type_alias) => { | ||
150 | let generic_params = db.generic_params(type_alias.id.into()); | ||
151 | generic_params.count_params_including_parent() | ||
152 | } | ||
153 | TypeCtor::FnPtr { num_args } => num_args as usize + 1, | ||
154 | TypeCtor::Tuple { cardinality } => cardinality as usize, | ||
155 | } | ||
156 | } | ||
157 | |||
158 | pub fn krate(self, db: &impl HirDatabase) -> Option<Crate> { | ||
159 | match self { | ||
160 | TypeCtor::Bool | ||
161 | | TypeCtor::Char | ||
162 | | TypeCtor::Int(_) | ||
163 | | TypeCtor::Float(_) | ||
164 | | TypeCtor::Str | ||
165 | | TypeCtor::Never | ||
166 | | TypeCtor::Slice | ||
167 | | TypeCtor::Array | ||
168 | | TypeCtor::RawPtr(_) | ||
169 | | TypeCtor::Ref(_) | ||
170 | | TypeCtor::FnPtr { .. } | ||
171 | | TypeCtor::Tuple { .. } => None, | ||
172 | TypeCtor::Closure { def, .. } => def.krate(db), | ||
173 | TypeCtor::Adt(adt) => adt.krate(db), | ||
174 | TypeCtor::FnDef(callable) => callable.krate(db), | ||
175 | TypeCtor::AssociatedType(type_alias) => type_alias.krate(db), | ||
176 | } | ||
177 | } | ||
178 | |||
179 | pub fn as_generic_def(self) -> Option<crate::GenericDef> { | ||
180 | match self { | ||
181 | TypeCtor::Bool | ||
182 | | TypeCtor::Char | ||
183 | | TypeCtor::Int(_) | ||
184 | | TypeCtor::Float(_) | ||
185 | | TypeCtor::Str | ||
186 | | TypeCtor::Never | ||
187 | | TypeCtor::Slice | ||
188 | | TypeCtor::Array | ||
189 | | TypeCtor::RawPtr(_) | ||
190 | | TypeCtor::Ref(_) | ||
191 | | TypeCtor::FnPtr { .. } | ||
192 | | TypeCtor::Tuple { .. } | ||
193 | | TypeCtor::Closure { .. } => None, | ||
194 | TypeCtor::Adt(adt) => Some(adt.into()), | ||
195 | TypeCtor::FnDef(callable) => Some(callable.into()), | ||
196 | TypeCtor::AssociatedType(type_alias) => Some(type_alias.into()), | ||
197 | } | ||
198 | } | ||
199 | } | ||
200 | |||
201 | /// A nominal type with (maybe 0) type parameters. This might be a primitive | ||
202 | /// type like `bool`, a struct, tuple, function pointer, reference or | ||
203 | /// several other things. | ||
204 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
205 | pub struct ApplicationTy { | ||
206 | pub ctor: TypeCtor, | ||
207 | pub parameters: Substs, | ||
208 | } | ||
209 | |||
210 | /// A "projection" type corresponds to an (unnormalized) | ||
211 | /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the | ||
212 | /// trait and all its parameters are fully known. | ||
213 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
214 | pub struct ProjectionTy { | ||
215 | pub associated_ty: TypeAlias, | ||
216 | pub parameters: Substs, | ||
217 | } | ||
218 | |||
219 | impl ProjectionTy { | ||
220 | pub fn trait_ref(&self, db: &impl HirDatabase) -> TraitRef { | ||
221 | TraitRef { | ||
222 | trait_: self | ||
223 | .associated_ty | ||
224 | .parent_trait(db) | ||
225 | .expect("projection ty without parent trait"), | ||
226 | substs: self.parameters.clone(), | ||
227 | } | ||
228 | } | ||
229 | } | ||
230 | |||
231 | impl TypeWalk for ProjectionTy { | ||
232 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
233 | self.parameters.walk(f); | ||
234 | } | ||
235 | |||
236 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
237 | self.parameters.walk_mut_binders(f, binders); | ||
238 | } | ||
239 | } | ||
240 | |||
241 | /// A type. | ||
242 | /// | ||
243 | /// See also the `TyKind` enum in rustc (librustc/ty/sty.rs), which represents | ||
244 | /// the same thing (but in a different way). | ||
245 | /// | ||
246 | /// This should be cheap to clone. | ||
247 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
248 | pub enum Ty { | ||
249 | /// A nominal type with (maybe 0) type parameters. This might be a primitive | ||
250 | /// type like `bool`, a struct, tuple, function pointer, reference or | ||
251 | /// several other things. | ||
252 | Apply(ApplicationTy), | ||
253 | |||
254 | /// A "projection" type corresponds to an (unnormalized) | ||
255 | /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the | ||
256 | /// trait and all its parameters are fully known. | ||
257 | Projection(ProjectionTy), | ||
258 | |||
259 | /// A type parameter; for example, `T` in `fn f<T>(x: T) {} | ||
260 | Param { | ||
261 | /// The index of the parameter (starting with parameters from the | ||
262 | /// surrounding impl, then the current function). | ||
263 | idx: u32, | ||
264 | /// The name of the parameter, for displaying. | ||
265 | // FIXME get rid of this | ||
266 | name: Name, | ||
267 | }, | ||
268 | |||
269 | /// A bound type variable. Used during trait resolution to represent Chalk | ||
270 | /// variables, and in `Dyn` and `Opaque` bounds to represent the `Self` type. | ||
271 | Bound(u32), | ||
272 | |||
273 | /// A type variable used during type checking. Not to be confused with a | ||
274 | /// type parameter. | ||
275 | Infer(InferTy), | ||
276 | |||
277 | /// A trait object (`dyn Trait` or bare `Trait` in pre-2018 Rust). | ||
278 | /// | ||
279 | /// The predicates are quantified over the `Self` type, i.e. `Ty::Bound(0)` | ||
280 | /// represents the `Self` type inside the bounds. This is currently | ||
281 | /// implicit; Chalk has the `Binders` struct to make it explicit, but it | ||
282 | /// didn't seem worth the overhead yet. | ||
283 | Dyn(Arc<[GenericPredicate]>), | ||
284 | |||
285 | /// An opaque type (`impl Trait`). | ||
286 | /// | ||
287 | /// The predicates are quantified over the `Self` type; see `Ty::Dyn` for | ||
288 | /// more. | ||
289 | Opaque(Arc<[GenericPredicate]>), | ||
290 | |||
291 | /// A placeholder for a type which could not be computed; this is propagated | ||
292 | /// to avoid useless error messages. Doubles as a placeholder where type | ||
293 | /// variables are inserted before type checking, since we want to try to | ||
294 | /// infer a better type here anyway -- for the IDE use case, we want to try | ||
295 | /// to infer as much as possible even in the presence of type errors. | ||
296 | Unknown, | ||
297 | } | ||
298 | |||
299 | /// A list of substitutions for generic parameters. | ||
300 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
301 | pub struct Substs(Arc<[Ty]>); | ||
302 | |||
303 | impl TypeWalk for Substs { | ||
304 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
305 | for t in self.0.iter() { | ||
306 | t.walk(f); | ||
307 | } | ||
308 | } | ||
309 | |||
310 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
311 | for t in make_mut_slice(&mut self.0) { | ||
312 | t.walk_mut_binders(f, binders); | ||
313 | } | ||
314 | } | ||
315 | } | ||
316 | |||
317 | impl Substs { | ||
318 | pub fn empty() -> Substs { | ||
319 | Substs(Arc::new([])) | ||
320 | } | ||
321 | |||
322 | pub fn single(ty: Ty) -> Substs { | ||
323 | Substs(Arc::new([ty])) | ||
324 | } | ||
325 | |||
326 | pub fn prefix(&self, n: usize) -> Substs { | ||
327 | Substs(self.0[..std::cmp::min(self.0.len(), n)].into()) | ||
328 | } | ||
329 | |||
330 | pub fn as_single(&self) -> &Ty { | ||
331 | if self.0.len() != 1 { | ||
332 | panic!("expected substs of len 1, got {:?}", self); | ||
333 | } | ||
334 | &self.0[0] | ||
335 | } | ||
336 | |||
337 | /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). | ||
338 | pub fn identity(generic_params: &GenericParams) -> Substs { | ||
339 | Substs( | ||
340 | generic_params | ||
341 | .params_including_parent() | ||
342 | .into_iter() | ||
343 | .map(|p| Ty::Param { idx: p.idx, name: p.name.clone() }) | ||
344 | .collect(), | ||
345 | ) | ||
346 | } | ||
347 | |||
348 | /// Return Substs that replace each parameter by a bound variable. | ||
349 | pub fn bound_vars(generic_params: &GenericParams) -> Substs { | ||
350 | Substs( | ||
351 | generic_params | ||
352 | .params_including_parent() | ||
353 | .into_iter() | ||
354 | .map(|p| Ty::Bound(p.idx)) | ||
355 | .collect(), | ||
356 | ) | ||
357 | } | ||
358 | |||
359 | pub fn build_for_def(db: &impl HirDatabase, def: impl Into<GenericDef>) -> SubstsBuilder { | ||
360 | let def = def.into(); | ||
361 | let params = db.generic_params(def.into()); | ||
362 | let param_count = params.count_params_including_parent(); | ||
363 | Substs::builder(param_count) | ||
364 | } | ||
365 | |||
366 | pub fn build_for_generics(generic_params: &GenericParams) -> SubstsBuilder { | ||
367 | Substs::builder(generic_params.count_params_including_parent()) | ||
368 | } | ||
369 | |||
370 | pub fn build_for_type_ctor(db: &impl HirDatabase, type_ctor: TypeCtor) -> SubstsBuilder { | ||
371 | Substs::builder(type_ctor.num_ty_params(db)) | ||
372 | } | ||
373 | |||
374 | fn builder(param_count: usize) -> SubstsBuilder { | ||
375 | SubstsBuilder { vec: Vec::with_capacity(param_count), param_count } | ||
376 | } | ||
377 | } | ||
378 | |||
379 | #[derive(Debug, Clone)] | ||
380 | pub struct SubstsBuilder { | ||
381 | vec: Vec<Ty>, | ||
382 | param_count: usize, | ||
383 | } | ||
384 | |||
385 | impl SubstsBuilder { | ||
386 | pub fn build(self) -> Substs { | ||
387 | assert_eq!(self.vec.len(), self.param_count); | ||
388 | Substs(self.vec.into()) | ||
389 | } | ||
390 | |||
391 | pub fn push(mut self, ty: Ty) -> Self { | ||
392 | self.vec.push(ty); | ||
393 | self | ||
394 | } | ||
395 | |||
396 | fn remaining(&self) -> usize { | ||
397 | self.param_count - self.vec.len() | ||
398 | } | ||
399 | |||
400 | pub fn fill_with_bound_vars(self, starting_from: u32) -> Self { | ||
401 | self.fill((starting_from..).map(Ty::Bound)) | ||
402 | } | ||
403 | |||
404 | pub fn fill_with_params(self) -> Self { | ||
405 | let start = self.vec.len() as u32; | ||
406 | self.fill((start..).map(|idx| Ty::Param { idx, name: Name::missing() })) | ||
407 | } | ||
408 | |||
409 | pub fn fill_with_unknown(self) -> Self { | ||
410 | self.fill(iter::repeat(Ty::Unknown)) | ||
411 | } | ||
412 | |||
413 | pub fn fill(mut self, filler: impl Iterator<Item = Ty>) -> Self { | ||
414 | self.vec.extend(filler.take(self.remaining())); | ||
415 | assert_eq!(self.remaining(), 0); | ||
416 | self | ||
417 | } | ||
418 | |||
419 | pub fn use_parent_substs(mut self, parent_substs: &Substs) -> Self { | ||
420 | assert!(self.vec.is_empty()); | ||
421 | assert!(parent_substs.len() <= self.param_count); | ||
422 | self.vec.extend(parent_substs.iter().cloned()); | ||
423 | self | ||
424 | } | ||
425 | } | ||
426 | |||
427 | impl Deref for Substs { | ||
428 | type Target = [Ty]; | ||
429 | |||
430 | fn deref(&self) -> &[Ty] { | ||
431 | &self.0 | ||
432 | } | ||
433 | } | ||
434 | |||
435 | /// A trait with type parameters. This includes the `Self`, so this represents a concrete type implementing the trait. | ||
436 | /// Name to be bikeshedded: TraitBound? TraitImplements? | ||
437 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
438 | pub struct TraitRef { | ||
439 | /// FIXME name? | ||
440 | pub trait_: Trait, | ||
441 | pub substs: Substs, | ||
442 | } | ||
443 | |||
444 | impl TraitRef { | ||
445 | pub fn self_ty(&self) -> &Ty { | ||
446 | &self.substs[0] | ||
447 | } | ||
448 | } | ||
449 | |||
450 | impl TypeWalk for TraitRef { | ||
451 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
452 | self.substs.walk(f); | ||
453 | } | ||
454 | |||
455 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
456 | self.substs.walk_mut_binders(f, binders); | ||
457 | } | ||
458 | } | ||
459 | |||
460 | /// Like `generics::WherePredicate`, but with resolved types: A condition on the | ||
461 | /// parameters of a generic item. | ||
462 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
463 | pub enum GenericPredicate { | ||
464 | /// The given trait needs to be implemented for its type parameters. | ||
465 | Implemented(TraitRef), | ||
466 | /// An associated type bindings like in `Iterator<Item = T>`. | ||
467 | Projection(ProjectionPredicate), | ||
468 | /// We couldn't resolve the trait reference. (If some type parameters can't | ||
469 | /// be resolved, they will just be Unknown). | ||
470 | Error, | ||
471 | } | ||
472 | |||
473 | impl GenericPredicate { | ||
474 | pub fn is_error(&self) -> bool { | ||
475 | match self { | ||
476 | GenericPredicate::Error => true, | ||
477 | _ => false, | ||
478 | } | ||
479 | } | ||
480 | |||
481 | pub fn is_implemented(&self) -> bool { | ||
482 | match self { | ||
483 | GenericPredicate::Implemented(_) => true, | ||
484 | _ => false, | ||
485 | } | ||
486 | } | ||
487 | |||
488 | pub fn trait_ref(&self, db: &impl HirDatabase) -> Option<TraitRef> { | ||
489 | match self { | ||
490 | GenericPredicate::Implemented(tr) => Some(tr.clone()), | ||
491 | GenericPredicate::Projection(proj) => Some(proj.projection_ty.trait_ref(db)), | ||
492 | GenericPredicate::Error => None, | ||
493 | } | ||
494 | } | ||
495 | } | ||
496 | |||
497 | impl TypeWalk for GenericPredicate { | ||
498 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
499 | match self { | ||
500 | GenericPredicate::Implemented(trait_ref) => trait_ref.walk(f), | ||
501 | GenericPredicate::Projection(projection_pred) => projection_pred.walk(f), | ||
502 | GenericPredicate::Error => {} | ||
503 | } | ||
504 | } | ||
505 | |||
506 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
507 | match self { | ||
508 | GenericPredicate::Implemented(trait_ref) => trait_ref.walk_mut_binders(f, binders), | ||
509 | GenericPredicate::Projection(projection_pred) => { | ||
510 | projection_pred.walk_mut_binders(f, binders) | ||
511 | } | ||
512 | GenericPredicate::Error => {} | ||
513 | } | ||
514 | } | ||
515 | } | ||
516 | |||
517 | /// Basically a claim (currently not validated / checked) that the contained | ||
518 | /// type / trait ref contains no inference variables; any inference variables it | ||
519 | /// contained have been replaced by bound variables, and `num_vars` tells us how | ||
520 | /// many there are. This is used to erase irrelevant differences between types | ||
521 | /// before using them in queries. | ||
522 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
523 | pub struct Canonical<T> { | ||
524 | pub value: T, | ||
525 | pub num_vars: usize, | ||
526 | } | ||
527 | |||
528 | /// A function signature as seen by type inference: Several parameter types and | ||
529 | /// one return type. | ||
530 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
531 | pub struct FnSig { | ||
532 | params_and_return: Arc<[Ty]>, | ||
533 | } | ||
534 | |||
535 | impl FnSig { | ||
536 | pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty) -> FnSig { | ||
537 | params.push(ret); | ||
538 | FnSig { params_and_return: params.into() } | ||
539 | } | ||
540 | |||
541 | pub fn from_fn_ptr_substs(substs: &Substs) -> FnSig { | ||
542 | FnSig { params_and_return: Arc::clone(&substs.0) } | ||
543 | } | ||
544 | |||
545 | pub fn params(&self) -> &[Ty] { | ||
546 | &self.params_and_return[0..self.params_and_return.len() - 1] | ||
547 | } | ||
548 | |||
549 | pub fn ret(&self) -> &Ty { | ||
550 | &self.params_and_return[self.params_and_return.len() - 1] | ||
551 | } | ||
552 | } | ||
553 | |||
554 | impl TypeWalk for FnSig { | ||
555 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
556 | for t in self.params_and_return.iter() { | ||
557 | t.walk(f); | ||
558 | } | ||
559 | } | ||
560 | |||
561 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
562 | for t in make_mut_slice(&mut self.params_and_return) { | ||
563 | t.walk_mut_binders(f, binders); | ||
564 | } | ||
565 | } | ||
566 | } | ||
567 | |||
568 | impl Ty { | ||
569 | pub fn simple(ctor: TypeCtor) -> Ty { | ||
570 | Ty::Apply(ApplicationTy { ctor, parameters: Substs::empty() }) | ||
571 | } | ||
572 | pub fn apply_one(ctor: TypeCtor, param: Ty) -> Ty { | ||
573 | Ty::Apply(ApplicationTy { ctor, parameters: Substs::single(param) }) | ||
574 | } | ||
575 | pub fn apply(ctor: TypeCtor, parameters: Substs) -> Ty { | ||
576 | Ty::Apply(ApplicationTy { ctor, parameters }) | ||
577 | } | ||
578 | pub fn unit() -> Self { | ||
579 | Ty::apply(TypeCtor::Tuple { cardinality: 0 }, Substs::empty()) | ||
580 | } | ||
581 | |||
582 | pub fn as_reference(&self) -> Option<(&Ty, Mutability)> { | ||
583 | match self { | ||
584 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(mutability), parameters }) => { | ||
585 | Some((parameters.as_single(), *mutability)) | ||
586 | } | ||
587 | _ => None, | ||
588 | } | ||
589 | } | ||
590 | |||
591 | pub fn as_adt(&self) -> Option<(Adt, &Substs)> { | ||
592 | match self { | ||
593 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_def), parameters }) => { | ||
594 | Some((*adt_def, parameters)) | ||
595 | } | ||
596 | _ => None, | ||
597 | } | ||
598 | } | ||
599 | |||
600 | pub fn as_tuple(&self) -> Option<&Substs> { | ||
601 | match self { | ||
602 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { .. }, parameters }) => { | ||
603 | Some(parameters) | ||
604 | } | ||
605 | _ => None, | ||
606 | } | ||
607 | } | ||
608 | |||
609 | pub fn as_callable(&self) -> Option<(CallableDef, &Substs)> { | ||
610 | match self { | ||
611 | Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(callable_def), parameters }) => { | ||
612 | Some((*callable_def, parameters)) | ||
613 | } | ||
614 | _ => None, | ||
615 | } | ||
616 | } | ||
617 | |||
618 | fn builtin_deref(&self) -> Option<Ty> { | ||
619 | match self { | ||
620 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
621 | TypeCtor::Ref(..) => Some(Ty::clone(a_ty.parameters.as_single())), | ||
622 | TypeCtor::RawPtr(..) => Some(Ty::clone(a_ty.parameters.as_single())), | ||
623 | _ => None, | ||
624 | }, | ||
625 | _ => None, | ||
626 | } | ||
627 | } | ||
628 | |||
629 | fn callable_sig(&self, db: &impl HirDatabase) -> Option<FnSig> { | ||
630 | match self { | ||
631 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
632 | TypeCtor::FnPtr { .. } => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)), | ||
633 | TypeCtor::FnDef(def) => { | ||
634 | let sig = db.callable_item_signature(def); | ||
635 | Some(sig.subst(&a_ty.parameters)) | ||
636 | } | ||
637 | TypeCtor::Closure { .. } => { | ||
638 | let sig_param = &a_ty.parameters[0]; | ||
639 | sig_param.callable_sig(db) | ||
640 | } | ||
641 | _ => None, | ||
642 | }, | ||
643 | _ => None, | ||
644 | } | ||
645 | } | ||
646 | |||
647 | /// If this is a type with type parameters (an ADT or function), replaces | ||
648 | /// the `Substs` for these type parameters with the given ones. (So e.g. if | ||
649 | /// `self` is `Option<_>` and the substs contain `u32`, we'll have | ||
650 | /// `Option<u32>` afterwards.) | ||
651 | pub fn apply_substs(self, substs: Substs) -> Ty { | ||
652 | match self { | ||
653 | Ty::Apply(ApplicationTy { ctor, parameters: previous_substs }) => { | ||
654 | assert_eq!(previous_substs.len(), substs.len()); | ||
655 | Ty::Apply(ApplicationTy { ctor, parameters: substs }) | ||
656 | } | ||
657 | _ => self, | ||
658 | } | ||
659 | } | ||
660 | |||
661 | /// Returns the type parameters of this type if it has some (i.e. is an ADT | ||
662 | /// or function); so if `self` is `Option<u32>`, this returns the `u32`. | ||
663 | pub fn substs(&self) -> Option<Substs> { | ||
664 | match self { | ||
665 | Ty::Apply(ApplicationTy { parameters, .. }) => Some(parameters.clone()), | ||
666 | _ => None, | ||
667 | } | ||
668 | } | ||
669 | |||
670 | /// If this is an `impl Trait` or `dyn Trait`, returns that trait. | ||
671 | pub fn inherent_trait(&self) -> Option<Trait> { | ||
672 | match self { | ||
673 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | ||
674 | predicates.iter().find_map(|pred| match pred { | ||
675 | GenericPredicate::Implemented(tr) => Some(tr.trait_), | ||
676 | _ => None, | ||
677 | }) | ||
678 | } | ||
679 | _ => None, | ||
680 | } | ||
681 | } | ||
682 | } | ||
683 | |||
684 | /// This allows walking structures that contain types to do something with those | ||
685 | /// types, similar to Chalk's `Fold` trait. | ||
686 | pub trait TypeWalk { | ||
687 | fn walk(&self, f: &mut impl FnMut(&Ty)); | ||
688 | fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { | ||
689 | self.walk_mut_binders(&mut |ty, _binders| f(ty), 0); | ||
690 | } | ||
691 | /// Walk the type, counting entered binders. | ||
692 | /// | ||
693 | /// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers | ||
694 | /// to the innermost binder, 1 to the next, etc.. So when we want to | ||
695 | /// substitute a certain bound variable, we can't just walk the whole type | ||
696 | /// and blindly replace each instance of a certain index; when we 'enter' | ||
697 | /// things that introduce new bound variables, we have to keep track of | ||
698 | /// that. Currently, the only thing that introduces bound variables on our | ||
699 | /// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound | ||
700 | /// variable for the self type. | ||
701 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize); | ||
702 | |||
703 | fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Self | ||
704 | where | ||
705 | Self: Sized, | ||
706 | { | ||
707 | self.walk_mut(&mut |ty_mut| { | ||
708 | let ty = mem::replace(ty_mut, Ty::Unknown); | ||
709 | *ty_mut = f(ty); | ||
710 | }); | ||
711 | self | ||
712 | } | ||
713 | |||
714 | /// Replaces type parameters in this type using the given `Substs`. (So e.g. | ||
715 | /// if `self` is `&[T]`, where type parameter T has index 0, and the | ||
716 | /// `Substs` contain `u32` at index 0, we'll have `&[u32]` afterwards.) | ||
717 | fn subst(self, substs: &Substs) -> Self | ||
718 | where | ||
719 | Self: Sized, | ||
720 | { | ||
721 | self.fold(&mut |ty| match ty { | ||
722 | Ty::Param { idx, name } => { | ||
723 | substs.get(idx as usize).cloned().unwrap_or(Ty::Param { idx, name }) | ||
724 | } | ||
725 | ty => ty, | ||
726 | }) | ||
727 | } | ||
728 | |||
729 | /// Substitutes `Ty::Bound` vars (as opposed to type parameters). | ||
730 | fn subst_bound_vars(mut self, substs: &Substs) -> Self | ||
731 | where | ||
732 | Self: Sized, | ||
733 | { | ||
734 | self.walk_mut_binders( | ||
735 | &mut |ty, binders| match ty { | ||
736 | &mut Ty::Bound(idx) => { | ||
737 | if idx as usize >= binders && (idx as usize - binders) < substs.len() { | ||
738 | *ty = substs.0[idx as usize - binders].clone(); | ||
739 | } | ||
740 | } | ||
741 | _ => {} | ||
742 | }, | ||
743 | 0, | ||
744 | ); | ||
745 | self | ||
746 | } | ||
747 | |||
748 | /// Shifts up `Ty::Bound` vars by `n`. | ||
749 | fn shift_bound_vars(self, n: i32) -> Self | ||
750 | where | ||
751 | Self: Sized, | ||
752 | { | ||
753 | self.fold(&mut |ty| match ty { | ||
754 | Ty::Bound(idx) => { | ||
755 | assert!(idx as i32 >= -n); | ||
756 | Ty::Bound((idx as i32 + n) as u32) | ||
757 | } | ||
758 | ty => ty, | ||
759 | }) | ||
760 | } | ||
761 | } | ||
762 | |||
763 | impl TypeWalk for Ty { | ||
764 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
765 | match self { | ||
766 | Ty::Apply(a_ty) => { | ||
767 | for t in a_ty.parameters.iter() { | ||
768 | t.walk(f); | ||
769 | } | ||
770 | } | ||
771 | Ty::Projection(p_ty) => { | ||
772 | for t in p_ty.parameters.iter() { | ||
773 | t.walk(f); | ||
774 | } | ||
775 | } | ||
776 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | ||
777 | for p in predicates.iter() { | ||
778 | p.walk(f); | ||
779 | } | ||
780 | } | ||
781 | Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} | ||
782 | } | ||
783 | f(self); | ||
784 | } | ||
785 | |||
786 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
787 | match self { | ||
788 | Ty::Apply(a_ty) => { | ||
789 | a_ty.parameters.walk_mut_binders(f, binders); | ||
790 | } | ||
791 | Ty::Projection(p_ty) => { | ||
792 | p_ty.parameters.walk_mut_binders(f, binders); | ||
793 | } | ||
794 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | ||
795 | for p in make_mut_slice(predicates) { | ||
796 | p.walk_mut_binders(f, binders + 1); | ||
797 | } | ||
798 | } | ||
799 | Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} | ||
800 | } | ||
801 | f(self, binders); | ||
802 | } | ||
803 | } | ||
804 | |||
805 | impl HirDisplay for &Ty { | ||
806 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
807 | HirDisplay::hir_fmt(*self, f) | ||
808 | } | ||
809 | } | ||
810 | |||
811 | impl HirDisplay for ApplicationTy { | ||
812 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
813 | if f.should_truncate() { | ||
814 | return write!(f, "…"); | ||
815 | } | ||
816 | |||
817 | match self.ctor { | ||
818 | TypeCtor::Bool => write!(f, "bool")?, | ||
819 | TypeCtor::Char => write!(f, "char")?, | ||
820 | TypeCtor::Int(t) => write!(f, "{}", t)?, | ||
821 | TypeCtor::Float(t) => write!(f, "{}", t)?, | ||
822 | TypeCtor::Str => write!(f, "str")?, | ||
823 | TypeCtor::Slice => { | ||
824 | let t = self.parameters.as_single(); | ||
825 | write!(f, "[{}]", t.display(f.db))?; | ||
826 | } | ||
827 | TypeCtor::Array => { | ||
828 | let t = self.parameters.as_single(); | ||
829 | write!(f, "[{};_]", t.display(f.db))?; | ||
830 | } | ||
831 | TypeCtor::RawPtr(m) => { | ||
832 | let t = self.parameters.as_single(); | ||
833 | write!(f, "*{}{}", m.as_keyword_for_ptr(), t.display(f.db))?; | ||
834 | } | ||
835 | TypeCtor::Ref(m) => { | ||
836 | let t = self.parameters.as_single(); | ||
837 | write!(f, "&{}{}", m.as_keyword_for_ref(), t.display(f.db))?; | ||
838 | } | ||
839 | TypeCtor::Never => write!(f, "!")?, | ||
840 | TypeCtor::Tuple { .. } => { | ||
841 | let ts = &self.parameters; | ||
842 | if ts.len() == 1 { | ||
843 | write!(f, "({},)", ts[0].display(f.db))?; | ||
844 | } else { | ||
845 | write!(f, "(")?; | ||
846 | f.write_joined(&*ts.0, ", ")?; | ||
847 | write!(f, ")")?; | ||
848 | } | ||
849 | } | ||
850 | TypeCtor::FnPtr { .. } => { | ||
851 | let sig = FnSig::from_fn_ptr_substs(&self.parameters); | ||
852 | write!(f, "fn(")?; | ||
853 | f.write_joined(sig.params(), ", ")?; | ||
854 | write!(f, ") -> {}", sig.ret().display(f.db))?; | ||
855 | } | ||
856 | TypeCtor::FnDef(def) => { | ||
857 | let sig = f.db.callable_item_signature(def); | ||
858 | let name = match def { | ||
859 | CallableDef::Function(ff) => ff.name(f.db), | ||
860 | CallableDef::Struct(s) => s.name(f.db).unwrap_or_else(Name::missing), | ||
861 | CallableDef::EnumVariant(e) => e.name(f.db).unwrap_or_else(Name::missing), | ||
862 | }; | ||
863 | match def { | ||
864 | CallableDef::Function(_) => write!(f, "fn {}", name)?, | ||
865 | CallableDef::Struct(_) | CallableDef::EnumVariant(_) => write!(f, "{}", name)?, | ||
866 | } | ||
867 | if self.parameters.len() > 0 { | ||
868 | write!(f, "<")?; | ||
869 | f.write_joined(&*self.parameters.0, ", ")?; | ||
870 | write!(f, ">")?; | ||
871 | } | ||
872 | write!(f, "(")?; | ||
873 | f.write_joined(sig.params(), ", ")?; | ||
874 | write!(f, ") -> {}", sig.ret().display(f.db))?; | ||
875 | } | ||
876 | TypeCtor::Adt(def_id) => { | ||
877 | let name = match def_id { | ||
878 | Adt::Struct(s) => s.name(f.db), | ||
879 | Adt::Union(u) => u.name(f.db), | ||
880 | Adt::Enum(e) => e.name(f.db), | ||
881 | } | ||
882 | .unwrap_or_else(Name::missing); | ||
883 | write!(f, "{}", name)?; | ||
884 | if self.parameters.len() > 0 { | ||
885 | write!(f, "<")?; | ||
886 | f.write_joined(&*self.parameters.0, ", ")?; | ||
887 | write!(f, ">")?; | ||
888 | } | ||
889 | } | ||
890 | TypeCtor::AssociatedType(type_alias) => { | ||
891 | let trait_name = type_alias | ||
892 | .parent_trait(f.db) | ||
893 | .and_then(|t| t.name(f.db)) | ||
894 | .unwrap_or_else(Name::missing); | ||
895 | let name = type_alias.name(f.db); | ||
896 | write!(f, "{}::{}", trait_name, name)?; | ||
897 | if self.parameters.len() > 0 { | ||
898 | write!(f, "<")?; | ||
899 | f.write_joined(&*self.parameters.0, ", ")?; | ||
900 | write!(f, ">")?; | ||
901 | } | ||
902 | } | ||
903 | TypeCtor::Closure { .. } => { | ||
904 | let sig = self.parameters[0] | ||
905 | .callable_sig(f.db) | ||
906 | .expect("first closure parameter should contain signature"); | ||
907 | write!(f, "|")?; | ||
908 | f.write_joined(sig.params(), ", ")?; | ||
909 | write!(f, "| -> {}", sig.ret().display(f.db))?; | ||
910 | } | ||
911 | } | ||
912 | Ok(()) | ||
913 | } | ||
914 | } | ||
915 | |||
916 | impl HirDisplay for ProjectionTy { | ||
917 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
918 | if f.should_truncate() { | ||
919 | return write!(f, "…"); | ||
920 | } | ||
921 | |||
922 | let trait_name = self | ||
923 | .associated_ty | ||
924 | .parent_trait(f.db) | ||
925 | .and_then(|t| t.name(f.db)) | ||
926 | .unwrap_or_else(Name::missing); | ||
927 | write!(f, "<{} as {}", self.parameters[0].display(f.db), trait_name,)?; | ||
928 | if self.parameters.len() > 1 { | ||
929 | write!(f, "<")?; | ||
930 | f.write_joined(&self.parameters[1..], ", ")?; | ||
931 | write!(f, ">")?; | ||
932 | } | ||
933 | write!(f, ">::{}", self.associated_ty.name(f.db))?; | ||
934 | Ok(()) | ||
935 | } | ||
936 | } | ||
937 | |||
938 | impl HirDisplay for Ty { | ||
939 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
940 | if f.should_truncate() { | ||
941 | return write!(f, "…"); | ||
942 | } | ||
943 | |||
944 | match self { | ||
945 | Ty::Apply(a_ty) => a_ty.hir_fmt(f)?, | ||
946 | Ty::Projection(p_ty) => p_ty.hir_fmt(f)?, | ||
947 | Ty::Param { name, .. } => write!(f, "{}", name)?, | ||
948 | Ty::Bound(idx) => write!(f, "?{}", idx)?, | ||
949 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | ||
950 | match self { | ||
951 | Ty::Dyn(_) => write!(f, "dyn ")?, | ||
952 | Ty::Opaque(_) => write!(f, "impl ")?, | ||
953 | _ => unreachable!(), | ||
954 | }; | ||
955 | // Note: This code is written to produce nice results (i.e. | ||
956 | // corresponding to surface Rust) for types that can occur in | ||
957 | // actual Rust. It will have weird results if the predicates | ||
958 | // aren't as expected (i.e. self types = $0, projection | ||
959 | // predicates for a certain trait come after the Implemented | ||
960 | // predicate for that trait). | ||
961 | let mut first = true; | ||
962 | let mut angle_open = false; | ||
963 | for p in predicates.iter() { | ||
964 | match p { | ||
965 | GenericPredicate::Implemented(trait_ref) => { | ||
966 | if angle_open { | ||
967 | write!(f, ">")?; | ||
968 | } | ||
969 | if !first { | ||
970 | write!(f, " + ")?; | ||
971 | } | ||
972 | // We assume that the self type is $0 (i.e. the | ||
973 | // existential) here, which is the only thing that's | ||
974 | // possible in actual Rust, and hence don't print it | ||
975 | write!( | ||
976 | f, | ||
977 | "{}", | ||
978 | trait_ref.trait_.name(f.db).unwrap_or_else(Name::missing) | ||
979 | )?; | ||
980 | if trait_ref.substs.len() > 1 { | ||
981 | write!(f, "<")?; | ||
982 | f.write_joined(&trait_ref.substs[1..], ", ")?; | ||
983 | // there might be assoc type bindings, so we leave the angle brackets open | ||
984 | angle_open = true; | ||
985 | } | ||
986 | } | ||
987 | GenericPredicate::Projection(projection_pred) => { | ||
988 | // in types in actual Rust, these will always come | ||
989 | // after the corresponding Implemented predicate | ||
990 | if angle_open { | ||
991 | write!(f, ", ")?; | ||
992 | } else { | ||
993 | write!(f, "<")?; | ||
994 | angle_open = true; | ||
995 | } | ||
996 | let name = projection_pred.projection_ty.associated_ty.name(f.db); | ||
997 | write!(f, "{} = ", name)?; | ||
998 | projection_pred.ty.hir_fmt(f)?; | ||
999 | } | ||
1000 | GenericPredicate::Error => { | ||
1001 | if angle_open { | ||
1002 | // impl Trait<X, {error}> | ||
1003 | write!(f, ", ")?; | ||
1004 | } else if !first { | ||
1005 | // impl Trait + {error} | ||
1006 | write!(f, " + ")?; | ||
1007 | } | ||
1008 | p.hir_fmt(f)?; | ||
1009 | } | ||
1010 | } | ||
1011 | first = false; | ||
1012 | } | ||
1013 | if angle_open { | ||
1014 | write!(f, ">")?; | ||
1015 | } | ||
1016 | } | ||
1017 | Ty::Unknown => write!(f, "{{unknown}}")?, | ||
1018 | Ty::Infer(..) => write!(f, "_")?, | ||
1019 | } | ||
1020 | Ok(()) | ||
1021 | } | ||
1022 | } | ||
1023 | |||
1024 | impl TraitRef { | ||
1025 | fn hir_fmt_ext(&self, f: &mut HirFormatter<impl HirDatabase>, use_as: bool) -> fmt::Result { | ||
1026 | if f.should_truncate() { | ||
1027 | return write!(f, "…"); | ||
1028 | } | ||
1029 | |||
1030 | self.substs[0].hir_fmt(f)?; | ||
1031 | if use_as { | ||
1032 | write!(f, " as ")?; | ||
1033 | } else { | ||
1034 | write!(f, ": ")?; | ||
1035 | } | ||
1036 | write!(f, "{}", self.trait_.name(f.db).unwrap_or_else(Name::missing))?; | ||
1037 | if self.substs.len() > 1 { | ||
1038 | write!(f, "<")?; | ||
1039 | f.write_joined(&self.substs[1..], ", ")?; | ||
1040 | write!(f, ">")?; | ||
1041 | } | ||
1042 | Ok(()) | ||
1043 | } | ||
1044 | } | ||
1045 | |||
1046 | impl HirDisplay for TraitRef { | ||
1047 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
1048 | self.hir_fmt_ext(f, false) | ||
1049 | } | ||
1050 | } | ||
1051 | |||
1052 | impl HirDisplay for &GenericPredicate { | ||
1053 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
1054 | HirDisplay::hir_fmt(*self, f) | ||
1055 | } | ||
1056 | } | ||
1057 | |||
1058 | impl HirDisplay for GenericPredicate { | ||
1059 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
1060 | if f.should_truncate() { | ||
1061 | return write!(f, "…"); | ||
1062 | } | ||
1063 | |||
1064 | match self { | ||
1065 | GenericPredicate::Implemented(trait_ref) => trait_ref.hir_fmt(f)?, | ||
1066 | GenericPredicate::Projection(projection_pred) => { | ||
1067 | write!(f, "<")?; | ||
1068 | projection_pred.projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?; | ||
1069 | write!( | ||
1070 | f, | ||
1071 | ">::{} = {}", | ||
1072 | projection_pred.projection_ty.associated_ty.name(f.db), | ||
1073 | projection_pred.ty.display(f.db) | ||
1074 | )?; | ||
1075 | } | ||
1076 | GenericPredicate::Error => write!(f, "{{error}}")?, | ||
1077 | } | ||
1078 | Ok(()) | ||
1079 | } | ||
1080 | } | ||
1081 | |||
1082 | impl HirDisplay for Obligation { | ||
1083 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { | ||
1084 | match self { | ||
1085 | Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)), | ||
1086 | Obligation::Projection(proj) => write!( | ||
1087 | f, | ||
1088 | "Normalize({} => {})", | ||
1089 | proj.projection_ty.display(f.db), | ||
1090 | proj.ty.display(f.db) | ||
1091 | ), | ||
1092 | } | ||
1093 | } | ||
1094 | } | ||
diff --git a/crates/ra_hir/src/ty/autoderef.rs b/crates/ra_hir/src/ty/autoderef.rs deleted file mode 100644 index 41c99d227..000000000 --- a/crates/ra_hir/src/ty/autoderef.rs +++ /dev/null | |||
@@ -1,103 +0,0 @@ | |||
1 | //! In certain situations, rust automatically inserts derefs as necessary: for | ||
2 | //! example, field accesses `foo.bar` still work when `foo` is actually a | ||
3 | //! reference to a type with the field `bar`. This is an approximation of the | ||
4 | //! logic in rustc (which lives in librustc_typeck/check/autoderef.rs). | ||
5 | |||
6 | use std::iter::successors; | ||
7 | |||
8 | use hir_def::{lang_item::LangItemTarget, resolver::Resolver}; | ||
9 | use hir_expand::name; | ||
10 | use log::{info, warn}; | ||
11 | |||
12 | use crate::{db::HirDatabase, Trait}; | ||
13 | |||
14 | use super::{traits::Solution, Canonical, Substs, Ty, TypeWalk}; | ||
15 | |||
16 | const AUTODEREF_RECURSION_LIMIT: usize = 10; | ||
17 | |||
18 | pub(crate) fn autoderef<'a>( | ||
19 | db: &'a impl HirDatabase, | ||
20 | resolver: &'a Resolver, | ||
21 | ty: Canonical<Ty>, | ||
22 | ) -> impl Iterator<Item = Canonical<Ty>> + 'a { | ||
23 | successors(Some(ty), move |ty| deref(db, resolver, ty)).take(AUTODEREF_RECURSION_LIMIT) | ||
24 | } | ||
25 | |||
26 | pub(crate) fn deref( | ||
27 | db: &impl HirDatabase, | ||
28 | resolver: &Resolver, | ||
29 | ty: &Canonical<Ty>, | ||
30 | ) -> Option<Canonical<Ty>> { | ||
31 | if let Some(derefed) = ty.value.builtin_deref() { | ||
32 | Some(Canonical { value: derefed, num_vars: ty.num_vars }) | ||
33 | } else { | ||
34 | deref_by_trait(db, resolver, ty) | ||
35 | } | ||
36 | } | ||
37 | |||
38 | fn deref_by_trait( | ||
39 | db: &impl HirDatabase, | ||
40 | resolver: &Resolver, | ||
41 | ty: &Canonical<Ty>, | ||
42 | ) -> Option<Canonical<Ty>> { | ||
43 | let krate = resolver.krate()?; | ||
44 | let deref_trait = match db.lang_item(krate.into(), "deref".into())? { | ||
45 | LangItemTarget::TraitId(t) => Trait::from(t), | ||
46 | _ => return None, | ||
47 | }; | ||
48 | let target = deref_trait.associated_type_by_name(db, &name::TARGET_TYPE)?; | ||
49 | |||
50 | let generic_params = db.generic_params(target.id.into()); | ||
51 | if generic_params.count_params_including_parent() != 1 { | ||
52 | // the Target type + Deref trait should only have one generic parameter, | ||
53 | // namely Deref's Self type | ||
54 | return None; | ||
55 | } | ||
56 | |||
57 | // FIXME make the Canonical handling nicer | ||
58 | |||
59 | let env = super::lower::trait_env(db, resolver); | ||
60 | |||
61 | let parameters = Substs::build_for_generics(&generic_params) | ||
62 | .push(ty.value.clone().shift_bound_vars(1)) | ||
63 | .build(); | ||
64 | |||
65 | let projection = super::traits::ProjectionPredicate { | ||
66 | ty: Ty::Bound(0), | ||
67 | projection_ty: super::ProjectionTy { associated_ty: target, parameters }, | ||
68 | }; | ||
69 | |||
70 | let obligation = super::Obligation::Projection(projection); | ||
71 | |||
72 | let in_env = super::traits::InEnvironment { value: obligation, environment: env }; | ||
73 | |||
74 | let canonical = super::Canonical { num_vars: 1 + ty.num_vars, value: in_env }; | ||
75 | |||
76 | let solution = db.trait_solve(krate.into(), canonical)?; | ||
77 | |||
78 | match &solution { | ||
79 | Solution::Unique(vars) => { | ||
80 | // FIXME: vars may contain solutions for any inference variables | ||
81 | // that happened to be inside ty. To correctly handle these, we | ||
82 | // would have to pass the solution up to the inference context, but | ||
83 | // that requires a larger refactoring (especially if the deref | ||
84 | // happens during method resolution). So for the moment, we just | ||
85 | // check that we're not in the situation we're we would actually | ||
86 | // need to handle the values of the additional variables, i.e. | ||
87 | // they're just being 'passed through'. In the 'standard' case where | ||
88 | // we have `impl<T> Deref for Foo<T> { Target = T }`, that should be | ||
89 | // the case. | ||
90 | for i in 1..vars.0.num_vars { | ||
91 | if vars.0.value[i] != Ty::Bound((i - 1) as u32) { | ||
92 | warn!("complex solution for derefing {:?}: {:?}, ignoring", ty, solution); | ||
93 | return None; | ||
94 | } | ||
95 | } | ||
96 | Some(Canonical { value: vars.0.value[0].clone(), num_vars: vars.0.num_vars }) | ||
97 | } | ||
98 | Solution::Ambig(_) => { | ||
99 | info!("Ambiguous solution for derefing {:?}: {:?}", ty, solution); | ||
100 | None | ||
101 | } | ||
102 | } | ||
103 | } | ||
diff --git a/crates/ra_hir/src/ty/display.rs b/crates/ra_hir/src/ty/display.rs deleted file mode 100644 index 9bb3ece6c..000000000 --- a/crates/ra_hir/src/ty/display.rs +++ /dev/null | |||
@@ -1,93 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::fmt; | ||
4 | |||
5 | use crate::db::HirDatabase; | ||
6 | |||
7 | pub struct HirFormatter<'a, 'b, DB> { | ||
8 | pub db: &'a DB, | ||
9 | fmt: &'a mut fmt::Formatter<'b>, | ||
10 | buf: String, | ||
11 | curr_size: usize, | ||
12 | max_size: Option<usize>, | ||
13 | } | ||
14 | |||
15 | pub trait HirDisplay { | ||
16 | fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result; | ||
17 | |||
18 | fn display<'a, DB>(&'a self, db: &'a DB) -> HirDisplayWrapper<'a, DB, Self> | ||
19 | where | ||
20 | Self: Sized, | ||
21 | { | ||
22 | HirDisplayWrapper(db, self, None) | ||
23 | } | ||
24 | |||
25 | fn display_truncated<'a, DB>( | ||
26 | &'a self, | ||
27 | db: &'a DB, | ||
28 | max_size: Option<usize>, | ||
29 | ) -> HirDisplayWrapper<'a, DB, Self> | ||
30 | where | ||
31 | Self: Sized, | ||
32 | { | ||
33 | HirDisplayWrapper(db, self, max_size) | ||
34 | } | ||
35 | } | ||
36 | |||
37 | impl<'a, 'b, DB> HirFormatter<'a, 'b, DB> | ||
38 | where | ||
39 | DB: HirDatabase, | ||
40 | { | ||
41 | pub fn write_joined<T: HirDisplay>( | ||
42 | &mut self, | ||
43 | iter: impl IntoIterator<Item = T>, | ||
44 | sep: &str, | ||
45 | ) -> fmt::Result { | ||
46 | let mut first = true; | ||
47 | for e in iter { | ||
48 | if !first { | ||
49 | write!(self, "{}", sep)?; | ||
50 | } | ||
51 | first = false; | ||
52 | e.hir_fmt(self)?; | ||
53 | } | ||
54 | Ok(()) | ||
55 | } | ||
56 | |||
57 | /// This allows using the `write!` macro directly with a `HirFormatter`. | ||
58 | pub fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result { | ||
59 | // We write to a buffer first to track output size | ||
60 | self.buf.clear(); | ||
61 | fmt::write(&mut self.buf, args)?; | ||
62 | self.curr_size += self.buf.len(); | ||
63 | |||
64 | // Then we write to the internal formatter from the buffer | ||
65 | self.fmt.write_str(&self.buf) | ||
66 | } | ||
67 | |||
68 | pub fn should_truncate(&self) -> bool { | ||
69 | if let Some(max_size) = self.max_size { | ||
70 | self.curr_size >= max_size | ||
71 | } else { | ||
72 | false | ||
73 | } | ||
74 | } | ||
75 | } | ||
76 | |||
77 | pub struct HirDisplayWrapper<'a, DB, T>(&'a DB, &'a T, Option<usize>); | ||
78 | |||
79 | impl<'a, DB, T> fmt::Display for HirDisplayWrapper<'a, DB, T> | ||
80 | where | ||
81 | DB: HirDatabase, | ||
82 | T: HirDisplay, | ||
83 | { | ||
84 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
85 | self.1.hir_fmt(&mut HirFormatter { | ||
86 | db: self.0, | ||
87 | fmt: f, | ||
88 | buf: String::with_capacity(20), | ||
89 | curr_size: 0, | ||
90 | max_size: self.2, | ||
91 | }) | ||
92 | } | ||
93 | } | ||
diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs deleted file mode 100644 index ddc7d262a..000000000 --- a/crates/ra_hir/src/ty/infer.rs +++ /dev/null | |||
@@ -1,748 +0,0 @@ | |||
1 | //! Type inference, i.e. the process of walking through the code and determining | ||
2 | //! the type of each expression and pattern. | ||
3 | //! | ||
4 | //! For type inference, compare the implementations in rustc (the various | ||
5 | //! check_* methods in librustc_typeck/check/mod.rs are a good entry point) and | ||
6 | //! IntelliJ-Rust (org.rust.lang.core.types.infer). Our entry point for | ||
7 | //! inference here is the `infer` function, which infers the types of all | ||
8 | //! expressions in a given function. | ||
9 | //! | ||
10 | //! During inference, types (i.e. the `Ty` struct) can contain type 'variables' | ||
11 | //! which represent currently unknown types; as we walk through the expressions, | ||
12 | //! we might determine that certain variables need to be equal to each other, or | ||
13 | //! to certain types. To record this, we use the union-find implementation from | ||
14 | //! the `ena` crate, which is extracted from rustc. | ||
15 | |||
16 | use std::borrow::Cow; | ||
17 | use std::mem; | ||
18 | use std::ops::Index; | ||
19 | use std::sync::Arc; | ||
20 | |||
21 | use ena::unify::{InPlaceUnificationTable, NoError, UnifyKey, UnifyValue}; | ||
22 | use rustc_hash::FxHashMap; | ||
23 | |||
24 | use hir_def::{ | ||
25 | data::{ConstData, FunctionData}, | ||
26 | path::known, | ||
27 | resolver::{HasResolver, Resolver, TypeNs}, | ||
28 | type_ref::{Mutability, TypeRef}, | ||
29 | AdtId, DefWithBodyId, | ||
30 | }; | ||
31 | use hir_expand::{diagnostics::DiagnosticSink, name}; | ||
32 | use ra_arena::map::ArenaMap; | ||
33 | use ra_prof::profile; | ||
34 | use test_utils::tested_by; | ||
35 | |||
36 | use super::{ | ||
37 | lower, | ||
38 | traits::{Guidance, Obligation, ProjectionPredicate, Solution}, | ||
39 | ApplicationTy, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypableDef, | ||
40 | TypeCtor, TypeWalk, Uncertain, | ||
41 | }; | ||
42 | use crate::{ | ||
43 | code_model::TypeAlias, | ||
44 | db::HirDatabase, | ||
45 | expr::{BindingAnnotation, Body, ExprId, PatId}, | ||
46 | ty::infer::diagnostics::InferenceDiagnostic, | ||
47 | Adt, AssocItem, DefWithBody, FloatTy, Function, IntTy, Path, StructField, Trait, VariantDef, | ||
48 | }; | ||
49 | |||
50 | macro_rules! ty_app { | ||
51 | ($ctor:pat, $param:pat) => { | ||
52 | crate::ty::Ty::Apply(crate::ty::ApplicationTy { ctor: $ctor, parameters: $param }) | ||
53 | }; | ||
54 | ($ctor:pat) => { | ||
55 | ty_app!($ctor, _) | ||
56 | }; | ||
57 | } | ||
58 | |||
59 | mod unify; | ||
60 | mod path; | ||
61 | mod expr; | ||
62 | mod pat; | ||
63 | mod coerce; | ||
64 | |||
65 | /// The entry point of type inference. | ||
66 | pub fn infer_query(db: &impl HirDatabase, def: DefWithBody) -> Arc<InferenceResult> { | ||
67 | let _p = profile("infer_query"); | ||
68 | let resolver = DefWithBodyId::from(def).resolver(db); | ||
69 | let mut ctx = InferenceContext::new(db, def, resolver); | ||
70 | |||
71 | match &def { | ||
72 | DefWithBody::Const(c) => ctx.collect_const(&db.const_data(c.id)), | ||
73 | DefWithBody::Function(f) => ctx.collect_fn(&db.function_data(f.id)), | ||
74 | DefWithBody::Static(s) => ctx.collect_const(&db.static_data(s.id)), | ||
75 | } | ||
76 | |||
77 | ctx.infer_body(); | ||
78 | |||
79 | Arc::new(ctx.resolve_all()) | ||
80 | } | ||
81 | |||
82 | #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] | ||
83 | enum ExprOrPatId { | ||
84 | ExprId(ExprId), | ||
85 | PatId(PatId), | ||
86 | } | ||
87 | |||
88 | impl_froms!(ExprOrPatId: ExprId, PatId); | ||
89 | |||
90 | /// Binding modes inferred for patterns. | ||
91 | /// https://doc.rust-lang.org/reference/patterns.html#binding-modes | ||
92 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] | ||
93 | enum BindingMode { | ||
94 | Move, | ||
95 | Ref(Mutability), | ||
96 | } | ||
97 | |||
98 | impl BindingMode { | ||
99 | pub fn convert(annotation: BindingAnnotation) -> BindingMode { | ||
100 | match annotation { | ||
101 | BindingAnnotation::Unannotated | BindingAnnotation::Mutable => BindingMode::Move, | ||
102 | BindingAnnotation::Ref => BindingMode::Ref(Mutability::Shared), | ||
103 | BindingAnnotation::RefMut => BindingMode::Ref(Mutability::Mut), | ||
104 | } | ||
105 | } | ||
106 | } | ||
107 | |||
108 | impl Default for BindingMode { | ||
109 | fn default() -> Self { | ||
110 | BindingMode::Move | ||
111 | } | ||
112 | } | ||
113 | |||
114 | /// A mismatch between an expected and an inferred type. | ||
115 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | ||
116 | pub struct TypeMismatch { | ||
117 | pub expected: Ty, | ||
118 | pub actual: Ty, | ||
119 | } | ||
120 | |||
121 | /// The result of type inference: A mapping from expressions and patterns to types. | ||
122 | #[derive(Clone, PartialEq, Eq, Debug, Default)] | ||
123 | pub struct InferenceResult { | ||
124 | /// For each method call expr, records the function it resolves to. | ||
125 | method_resolutions: FxHashMap<ExprId, Function>, | ||
126 | /// For each field access expr, records the field it resolves to. | ||
127 | field_resolutions: FxHashMap<ExprId, StructField>, | ||
128 | /// For each field in record literal, records the field it resolves to. | ||
129 | record_field_resolutions: FxHashMap<ExprId, StructField>, | ||
130 | /// For each struct literal, records the variant it resolves to. | ||
131 | variant_resolutions: FxHashMap<ExprOrPatId, VariantDef>, | ||
132 | /// For each associated item record what it resolves to | ||
133 | assoc_resolutions: FxHashMap<ExprOrPatId, AssocItem>, | ||
134 | diagnostics: Vec<InferenceDiagnostic>, | ||
135 | pub(super) type_of_expr: ArenaMap<ExprId, Ty>, | ||
136 | pub(super) type_of_pat: ArenaMap<PatId, Ty>, | ||
137 | pub(super) type_mismatches: ArenaMap<ExprId, TypeMismatch>, | ||
138 | } | ||
139 | |||
140 | impl InferenceResult { | ||
141 | pub fn method_resolution(&self, expr: ExprId) -> Option<Function> { | ||
142 | self.method_resolutions.get(&expr).copied() | ||
143 | } | ||
144 | pub fn field_resolution(&self, expr: ExprId) -> Option<StructField> { | ||
145 | self.field_resolutions.get(&expr).copied() | ||
146 | } | ||
147 | pub fn record_field_resolution(&self, expr: ExprId) -> Option<StructField> { | ||
148 | self.record_field_resolutions.get(&expr).copied() | ||
149 | } | ||
150 | pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantDef> { | ||
151 | self.variant_resolutions.get(&id.into()).copied() | ||
152 | } | ||
153 | pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantDef> { | ||
154 | self.variant_resolutions.get(&id.into()).copied() | ||
155 | } | ||
156 | pub fn assoc_resolutions_for_expr(&self, id: ExprId) -> Option<AssocItem> { | ||
157 | self.assoc_resolutions.get(&id.into()).copied() | ||
158 | } | ||
159 | pub fn assoc_resolutions_for_pat(&self, id: PatId) -> Option<AssocItem> { | ||
160 | self.assoc_resolutions.get(&id.into()).copied() | ||
161 | } | ||
162 | pub fn type_mismatch_for_expr(&self, expr: ExprId) -> Option<&TypeMismatch> { | ||
163 | self.type_mismatches.get(expr) | ||
164 | } | ||
165 | pub(crate) fn add_diagnostics( | ||
166 | &self, | ||
167 | db: &impl HirDatabase, | ||
168 | owner: Function, | ||
169 | sink: &mut DiagnosticSink, | ||
170 | ) { | ||
171 | self.diagnostics.iter().for_each(|it| it.add_to(db, owner, sink)) | ||
172 | } | ||
173 | } | ||
174 | |||
175 | impl Index<ExprId> for InferenceResult { | ||
176 | type Output = Ty; | ||
177 | |||
178 | fn index(&self, expr: ExprId) -> &Ty { | ||
179 | self.type_of_expr.get(expr).unwrap_or(&Ty::Unknown) | ||
180 | } | ||
181 | } | ||
182 | |||
183 | impl Index<PatId> for InferenceResult { | ||
184 | type Output = Ty; | ||
185 | |||
186 | fn index(&self, pat: PatId) -> &Ty { | ||
187 | self.type_of_pat.get(pat).unwrap_or(&Ty::Unknown) | ||
188 | } | ||
189 | } | ||
190 | |||
191 | /// The inference context contains all information needed during type inference. | ||
192 | #[derive(Clone, Debug)] | ||
193 | struct InferenceContext<'a, D: HirDatabase> { | ||
194 | db: &'a D, | ||
195 | owner: DefWithBody, | ||
196 | body: Arc<Body>, | ||
197 | resolver: Resolver, | ||
198 | var_unification_table: InPlaceUnificationTable<TypeVarId>, | ||
199 | trait_env: Arc<TraitEnvironment>, | ||
200 | obligations: Vec<Obligation>, | ||
201 | result: InferenceResult, | ||
202 | /// The return type of the function being inferred. | ||
203 | return_ty: Ty, | ||
204 | |||
205 | /// Impls of `CoerceUnsized` used in coercion. | ||
206 | /// (from_ty_ctor, to_ty_ctor) => coerce_generic_index | ||
207 | // FIXME: Use trait solver for this. | ||
208 | // Chalk seems unable to work well with builtin impl of `Unsize` now. | ||
209 | coerce_unsized_map: FxHashMap<(TypeCtor, TypeCtor), usize>, | ||
210 | } | ||
211 | |||
212 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
213 | fn new(db: &'a D, owner: DefWithBody, resolver: Resolver) -> Self { | ||
214 | InferenceContext { | ||
215 | result: InferenceResult::default(), | ||
216 | var_unification_table: InPlaceUnificationTable::new(), | ||
217 | obligations: Vec::default(), | ||
218 | return_ty: Ty::Unknown, // set in collect_fn_signature | ||
219 | trait_env: lower::trait_env(db, &resolver), | ||
220 | coerce_unsized_map: Self::init_coerce_unsized_map(db, &resolver), | ||
221 | db, | ||
222 | owner, | ||
223 | body: db.body(owner.into()), | ||
224 | resolver, | ||
225 | } | ||
226 | } | ||
227 | |||
228 | fn resolve_all(mut self) -> InferenceResult { | ||
229 | // FIXME resolve obligations as well (use Guidance if necessary) | ||
230 | let mut result = mem::replace(&mut self.result, InferenceResult::default()); | ||
231 | let mut tv_stack = Vec::new(); | ||
232 | for ty in result.type_of_expr.values_mut() { | ||
233 | let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown)); | ||
234 | *ty = resolved; | ||
235 | } | ||
236 | for ty in result.type_of_pat.values_mut() { | ||
237 | let resolved = self.resolve_ty_completely(&mut tv_stack, mem::replace(ty, Ty::Unknown)); | ||
238 | *ty = resolved; | ||
239 | } | ||
240 | result | ||
241 | } | ||
242 | |||
243 | fn write_expr_ty(&mut self, expr: ExprId, ty: Ty) { | ||
244 | self.result.type_of_expr.insert(expr, ty); | ||
245 | } | ||
246 | |||
247 | fn write_method_resolution(&mut self, expr: ExprId, func: Function) { | ||
248 | self.result.method_resolutions.insert(expr, func); | ||
249 | } | ||
250 | |||
251 | fn write_field_resolution(&mut self, expr: ExprId, field: StructField) { | ||
252 | self.result.field_resolutions.insert(expr, field); | ||
253 | } | ||
254 | |||
255 | fn write_variant_resolution(&mut self, id: ExprOrPatId, variant: VariantDef) { | ||
256 | self.result.variant_resolutions.insert(id, variant); | ||
257 | } | ||
258 | |||
259 | fn write_assoc_resolution(&mut self, id: ExprOrPatId, item: AssocItem) { | ||
260 | self.result.assoc_resolutions.insert(id, item); | ||
261 | } | ||
262 | |||
263 | fn write_pat_ty(&mut self, pat: PatId, ty: Ty) { | ||
264 | self.result.type_of_pat.insert(pat, ty); | ||
265 | } | ||
266 | |||
267 | fn push_diagnostic(&mut self, diagnostic: InferenceDiagnostic) { | ||
268 | self.result.diagnostics.push(diagnostic); | ||
269 | } | ||
270 | |||
271 | fn make_ty(&mut self, type_ref: &TypeRef) -> Ty { | ||
272 | let ty = Ty::from_hir( | ||
273 | self.db, | ||
274 | // FIXME use right resolver for block | ||
275 | &self.resolver, | ||
276 | type_ref, | ||
277 | ); | ||
278 | let ty = self.insert_type_vars(ty); | ||
279 | self.normalize_associated_types_in(ty) | ||
280 | } | ||
281 | |||
282 | fn unify_substs(&mut self, substs1: &Substs, substs2: &Substs, depth: usize) -> bool { | ||
283 | substs1.0.iter().zip(substs2.0.iter()).all(|(t1, t2)| self.unify_inner(t1, t2, depth)) | ||
284 | } | ||
285 | |||
286 | fn unify(&mut self, ty1: &Ty, ty2: &Ty) -> bool { | ||
287 | self.unify_inner(ty1, ty2, 0) | ||
288 | } | ||
289 | |||
290 | fn unify_inner(&mut self, ty1: &Ty, ty2: &Ty, depth: usize) -> bool { | ||
291 | if depth > 1000 { | ||
292 | // prevent stackoverflows | ||
293 | panic!("infinite recursion in unification"); | ||
294 | } | ||
295 | if ty1 == ty2 { | ||
296 | return true; | ||
297 | } | ||
298 | // try to resolve type vars first | ||
299 | let ty1 = self.resolve_ty_shallow(ty1); | ||
300 | let ty2 = self.resolve_ty_shallow(ty2); | ||
301 | match (&*ty1, &*ty2) { | ||
302 | (Ty::Apply(a_ty1), Ty::Apply(a_ty2)) if a_ty1.ctor == a_ty2.ctor => { | ||
303 | self.unify_substs(&a_ty1.parameters, &a_ty2.parameters, depth + 1) | ||
304 | } | ||
305 | _ => self.unify_inner_trivial(&ty1, &ty2), | ||
306 | } | ||
307 | } | ||
308 | |||
309 | fn unify_inner_trivial(&mut self, ty1: &Ty, ty2: &Ty) -> bool { | ||
310 | match (ty1, ty2) { | ||
311 | (Ty::Unknown, _) | (_, Ty::Unknown) => true, | ||
312 | |||
313 | (Ty::Infer(InferTy::TypeVar(tv1)), Ty::Infer(InferTy::TypeVar(tv2))) | ||
314 | | (Ty::Infer(InferTy::IntVar(tv1)), Ty::Infer(InferTy::IntVar(tv2))) | ||
315 | | (Ty::Infer(InferTy::FloatVar(tv1)), Ty::Infer(InferTy::FloatVar(tv2))) | ||
316 | | ( | ||
317 | Ty::Infer(InferTy::MaybeNeverTypeVar(tv1)), | ||
318 | Ty::Infer(InferTy::MaybeNeverTypeVar(tv2)), | ||
319 | ) => { | ||
320 | // both type vars are unknown since we tried to resolve them | ||
321 | self.var_unification_table.union(*tv1, *tv2); | ||
322 | true | ||
323 | } | ||
324 | |||
325 | // The order of MaybeNeverTypeVar matters here. | ||
326 | // Unifying MaybeNeverTypeVar and TypeVar will let the latter become MaybeNeverTypeVar. | ||
327 | // Unifying MaybeNeverTypeVar and other concrete type will let the former become it. | ||
328 | (Ty::Infer(InferTy::TypeVar(tv)), other) | ||
329 | | (other, Ty::Infer(InferTy::TypeVar(tv))) | ||
330 | | (Ty::Infer(InferTy::MaybeNeverTypeVar(tv)), other) | ||
331 | | (other, Ty::Infer(InferTy::MaybeNeverTypeVar(tv))) | ||
332 | | (Ty::Infer(InferTy::IntVar(tv)), other @ ty_app!(TypeCtor::Int(_))) | ||
333 | | (other @ ty_app!(TypeCtor::Int(_)), Ty::Infer(InferTy::IntVar(tv))) | ||
334 | | (Ty::Infer(InferTy::FloatVar(tv)), other @ ty_app!(TypeCtor::Float(_))) | ||
335 | | (other @ ty_app!(TypeCtor::Float(_)), Ty::Infer(InferTy::FloatVar(tv))) => { | ||
336 | // the type var is unknown since we tried to resolve it | ||
337 | self.var_unification_table.union_value(*tv, TypeVarValue::Known(other.clone())); | ||
338 | true | ||
339 | } | ||
340 | |||
341 | _ => false, | ||
342 | } | ||
343 | } | ||
344 | |||
345 | fn new_type_var(&mut self) -> Ty { | ||
346 | Ty::Infer(InferTy::TypeVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) | ||
347 | } | ||
348 | |||
349 | fn new_integer_var(&mut self) -> Ty { | ||
350 | Ty::Infer(InferTy::IntVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) | ||
351 | } | ||
352 | |||
353 | fn new_float_var(&mut self) -> Ty { | ||
354 | Ty::Infer(InferTy::FloatVar(self.var_unification_table.new_key(TypeVarValue::Unknown))) | ||
355 | } | ||
356 | |||
357 | fn new_maybe_never_type_var(&mut self) -> Ty { | ||
358 | Ty::Infer(InferTy::MaybeNeverTypeVar( | ||
359 | self.var_unification_table.new_key(TypeVarValue::Unknown), | ||
360 | )) | ||
361 | } | ||
362 | |||
363 | /// Replaces Ty::Unknown by a new type var, so we can maybe still infer it. | ||
364 | fn insert_type_vars_shallow(&mut self, ty: Ty) -> Ty { | ||
365 | match ty { | ||
366 | Ty::Unknown => self.new_type_var(), | ||
367 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Int(Uncertain::Unknown), .. }) => { | ||
368 | self.new_integer_var() | ||
369 | } | ||
370 | Ty::Apply(ApplicationTy { ctor: TypeCtor::Float(Uncertain::Unknown), .. }) => { | ||
371 | self.new_float_var() | ||
372 | } | ||
373 | _ => ty, | ||
374 | } | ||
375 | } | ||
376 | |||
377 | fn insert_type_vars(&mut self, ty: Ty) -> Ty { | ||
378 | ty.fold(&mut |ty| self.insert_type_vars_shallow(ty)) | ||
379 | } | ||
380 | |||
381 | fn resolve_obligations_as_possible(&mut self) { | ||
382 | let obligations = mem::replace(&mut self.obligations, Vec::new()); | ||
383 | for obligation in obligations { | ||
384 | let in_env = InEnvironment::new(self.trait_env.clone(), obligation.clone()); | ||
385 | let canonicalized = self.canonicalizer().canonicalize_obligation(in_env); | ||
386 | let solution = self | ||
387 | .db | ||
388 | .trait_solve(self.resolver.krate().unwrap().into(), canonicalized.value.clone()); | ||
389 | |||
390 | match solution { | ||
391 | Some(Solution::Unique(substs)) => { | ||
392 | canonicalized.apply_solution(self, substs.0); | ||
393 | } | ||
394 | Some(Solution::Ambig(Guidance::Definite(substs))) => { | ||
395 | canonicalized.apply_solution(self, substs.0); | ||
396 | self.obligations.push(obligation); | ||
397 | } | ||
398 | Some(_) => { | ||
399 | // FIXME use this when trying to resolve everything at the end | ||
400 | self.obligations.push(obligation); | ||
401 | } | ||
402 | None => { | ||
403 | // FIXME obligation cannot be fulfilled => diagnostic | ||
404 | } | ||
405 | }; | ||
406 | } | ||
407 | } | ||
408 | |||
409 | /// Resolves the type as far as currently possible, replacing type variables | ||
410 | /// by their known types. All types returned by the infer_* functions should | ||
411 | /// be resolved as far as possible, i.e. contain no type variables with | ||
412 | /// known type. | ||
413 | fn resolve_ty_as_possible(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { | ||
414 | self.resolve_obligations_as_possible(); | ||
415 | |||
416 | ty.fold(&mut |ty| match ty { | ||
417 | Ty::Infer(tv) => { | ||
418 | let inner = tv.to_inner(); | ||
419 | if tv_stack.contains(&inner) { | ||
420 | tested_by!(type_var_cycles_resolve_as_possible); | ||
421 | // recursive type | ||
422 | return tv.fallback_value(); | ||
423 | } | ||
424 | if let Some(known_ty) = | ||
425 | self.var_unification_table.inlined_probe_value(inner).known() | ||
426 | { | ||
427 | // known_ty may contain other variables that are known by now | ||
428 | tv_stack.push(inner); | ||
429 | let result = self.resolve_ty_as_possible(tv_stack, known_ty.clone()); | ||
430 | tv_stack.pop(); | ||
431 | result | ||
432 | } else { | ||
433 | ty | ||
434 | } | ||
435 | } | ||
436 | _ => ty, | ||
437 | }) | ||
438 | } | ||
439 | |||
440 | /// If `ty` is a type variable with known type, returns that type; | ||
441 | /// otherwise, return ty. | ||
442 | fn resolve_ty_shallow<'b>(&mut self, ty: &'b Ty) -> Cow<'b, Ty> { | ||
443 | let mut ty = Cow::Borrowed(ty); | ||
444 | // The type variable could resolve to a int/float variable. Hence try | ||
445 | // resolving up to three times; each type of variable shouldn't occur | ||
446 | // more than once | ||
447 | for i in 0..3 { | ||
448 | if i > 0 { | ||
449 | tested_by!(type_var_resolves_to_int_var); | ||
450 | } | ||
451 | match &*ty { | ||
452 | Ty::Infer(tv) => { | ||
453 | let inner = tv.to_inner(); | ||
454 | match self.var_unification_table.inlined_probe_value(inner).known() { | ||
455 | Some(known_ty) => { | ||
456 | // The known_ty can't be a type var itself | ||
457 | ty = Cow::Owned(known_ty.clone()); | ||
458 | } | ||
459 | _ => return ty, | ||
460 | } | ||
461 | } | ||
462 | _ => return ty, | ||
463 | } | ||
464 | } | ||
465 | log::error!("Inference variable still not resolved: {:?}", ty); | ||
466 | ty | ||
467 | } | ||
468 | |||
469 | /// Recurses through the given type, normalizing associated types mentioned | ||
470 | /// in it by replacing them by type variables and registering obligations to | ||
471 | /// resolve later. This should be done once for every type we get from some | ||
472 | /// type annotation (e.g. from a let type annotation, field type or function | ||
473 | /// call). `make_ty` handles this already, but e.g. for field types we need | ||
474 | /// to do it as well. | ||
475 | fn normalize_associated_types_in(&mut self, ty: Ty) -> Ty { | ||
476 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
477 | ty.fold(&mut |ty| match ty { | ||
478 | Ty::Projection(proj_ty) => self.normalize_projection_ty(proj_ty), | ||
479 | _ => ty, | ||
480 | }) | ||
481 | } | ||
482 | |||
483 | fn normalize_projection_ty(&mut self, proj_ty: ProjectionTy) -> Ty { | ||
484 | let var = self.new_type_var(); | ||
485 | let predicate = ProjectionPredicate { projection_ty: proj_ty, ty: var.clone() }; | ||
486 | let obligation = Obligation::Projection(predicate); | ||
487 | self.obligations.push(obligation); | ||
488 | var | ||
489 | } | ||
490 | |||
491 | /// Resolves the type completely; type variables without known type are | ||
492 | /// replaced by Ty::Unknown. | ||
493 | fn resolve_ty_completely(&mut self, tv_stack: &mut Vec<TypeVarId>, ty: Ty) -> Ty { | ||
494 | ty.fold(&mut |ty| match ty { | ||
495 | Ty::Infer(tv) => { | ||
496 | let inner = tv.to_inner(); | ||
497 | if tv_stack.contains(&inner) { | ||
498 | tested_by!(type_var_cycles_resolve_completely); | ||
499 | // recursive type | ||
500 | return tv.fallback_value(); | ||
501 | } | ||
502 | if let Some(known_ty) = | ||
503 | self.var_unification_table.inlined_probe_value(inner).known() | ||
504 | { | ||
505 | // known_ty may contain other variables that are known by now | ||
506 | tv_stack.push(inner); | ||
507 | let result = self.resolve_ty_completely(tv_stack, known_ty.clone()); | ||
508 | tv_stack.pop(); | ||
509 | result | ||
510 | } else { | ||
511 | tv.fallback_value() | ||
512 | } | ||
513 | } | ||
514 | _ => ty, | ||
515 | }) | ||
516 | } | ||
517 | |||
518 | fn resolve_variant(&mut self, path: Option<&Path>) -> (Ty, Option<VariantDef>) { | ||
519 | let path = match path { | ||
520 | Some(path) => path, | ||
521 | None => return (Ty::Unknown, None), | ||
522 | }; | ||
523 | let resolver = &self.resolver; | ||
524 | let def: TypableDef = | ||
525 | // FIXME: this should resolve assoc items as well, see this example: | ||
526 | // https://play.rust-lang.org/?gist=087992e9e22495446c01c0d4e2d69521 | ||
527 | match resolver.resolve_path_in_type_ns_fully(self.db, &path) { | ||
528 | Some(TypeNs::AdtId(AdtId::StructId(it))) => it.into(), | ||
529 | Some(TypeNs::AdtId(AdtId::UnionId(it))) => it.into(), | ||
530 | Some(TypeNs::AdtSelfType(adt)) => adt.into(), | ||
531 | Some(TypeNs::EnumVariantId(it)) => it.into(), | ||
532 | Some(TypeNs::TypeAliasId(it)) => it.into(), | ||
533 | |||
534 | Some(TypeNs::SelfType(_)) | | ||
535 | Some(TypeNs::GenericParam(_)) | | ||
536 | Some(TypeNs::BuiltinType(_)) | | ||
537 | Some(TypeNs::TraitId(_)) | | ||
538 | Some(TypeNs::AdtId(AdtId::EnumId(_))) | | ||
539 | None => { | ||
540 | return (Ty::Unknown, None) | ||
541 | } | ||
542 | }; | ||
543 | // FIXME remove the duplication between here and `Ty::from_path`? | ||
544 | let substs = Ty::substs_from_path(self.db, resolver, path, def); | ||
545 | match def { | ||
546 | TypableDef::Adt(Adt::Struct(s)) => { | ||
547 | let ty = s.ty(self.db); | ||
548 | let ty = self.insert_type_vars(ty.apply_substs(substs)); | ||
549 | (ty, Some(s.into())) | ||
550 | } | ||
551 | TypableDef::EnumVariant(var) => { | ||
552 | let ty = var.parent_enum(self.db).ty(self.db); | ||
553 | let ty = self.insert_type_vars(ty.apply_substs(substs)); | ||
554 | (ty, Some(var.into())) | ||
555 | } | ||
556 | TypableDef::Adt(Adt::Enum(_)) | ||
557 | | TypableDef::Adt(Adt::Union(_)) | ||
558 | | TypableDef::TypeAlias(_) | ||
559 | | TypableDef::Function(_) | ||
560 | | TypableDef::Const(_) | ||
561 | | TypableDef::Static(_) | ||
562 | | TypableDef::BuiltinType(_) => (Ty::Unknown, None), | ||
563 | } | ||
564 | } | ||
565 | |||
566 | fn collect_const(&mut self, data: &ConstData) { | ||
567 | self.return_ty = self.make_ty(&data.type_ref); | ||
568 | } | ||
569 | |||
570 | fn collect_fn(&mut self, data: &FunctionData) { | ||
571 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
572 | for (type_ref, pat) in data.params.iter().zip(body.params.iter()) { | ||
573 | let ty = self.make_ty(type_ref); | ||
574 | |||
575 | self.infer_pat(*pat, &ty, BindingMode::default()); | ||
576 | } | ||
577 | self.return_ty = self.make_ty(&data.ret_type); | ||
578 | } | ||
579 | |||
580 | fn infer_body(&mut self) { | ||
581 | self.infer_expr(self.body.body_expr, &Expectation::has_type(self.return_ty.clone())); | ||
582 | } | ||
583 | |||
584 | fn resolve_into_iter_item(&self) -> Option<TypeAlias> { | ||
585 | let path = known::std_iter_into_iterator(); | ||
586 | let trait_: Trait = self.resolver.resolve_known_trait(self.db, &path)?.into(); | ||
587 | trait_.associated_type_by_name(self.db, &name::ITEM_TYPE) | ||
588 | } | ||
589 | |||
590 | fn resolve_ops_try_ok(&self) -> Option<TypeAlias> { | ||
591 | let path = known::std_ops_try(); | ||
592 | let trait_: Trait = self.resolver.resolve_known_trait(self.db, &path)?.into(); | ||
593 | trait_.associated_type_by_name(self.db, &name::OK_TYPE) | ||
594 | } | ||
595 | |||
596 | fn resolve_future_future_output(&self) -> Option<TypeAlias> { | ||
597 | let path = known::std_future_future(); | ||
598 | let trait_: Trait = self.resolver.resolve_known_trait(self.db, &path)?.into(); | ||
599 | trait_.associated_type_by_name(self.db, &name::OUTPUT_TYPE) | ||
600 | } | ||
601 | |||
602 | fn resolve_boxed_box(&self) -> Option<Adt> { | ||
603 | let path = known::std_boxed_box(); | ||
604 | let struct_ = self.resolver.resolve_known_struct(self.db, &path)?; | ||
605 | Some(Adt::Struct(struct_.into())) | ||
606 | } | ||
607 | } | ||
608 | |||
609 | /// The ID of a type variable. | ||
610 | #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] | ||
611 | pub struct TypeVarId(pub(super) u32); | ||
612 | |||
613 | impl UnifyKey for TypeVarId { | ||
614 | type Value = TypeVarValue; | ||
615 | |||
616 | fn index(&self) -> u32 { | ||
617 | self.0 | ||
618 | } | ||
619 | |||
620 | fn from_index(i: u32) -> Self { | ||
621 | TypeVarId(i) | ||
622 | } | ||
623 | |||
624 | fn tag() -> &'static str { | ||
625 | "TypeVarId" | ||
626 | } | ||
627 | } | ||
628 | |||
629 | /// The value of a type variable: either we already know the type, or we don't | ||
630 | /// know it yet. | ||
631 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
632 | pub enum TypeVarValue { | ||
633 | Known(Ty), | ||
634 | Unknown, | ||
635 | } | ||
636 | |||
637 | impl TypeVarValue { | ||
638 | fn known(&self) -> Option<&Ty> { | ||
639 | match self { | ||
640 | TypeVarValue::Known(ty) => Some(ty), | ||
641 | TypeVarValue::Unknown => None, | ||
642 | } | ||
643 | } | ||
644 | } | ||
645 | |||
646 | impl UnifyValue for TypeVarValue { | ||
647 | type Error = NoError; | ||
648 | |||
649 | fn unify_values(value1: &Self, value2: &Self) -> Result<Self, NoError> { | ||
650 | match (value1, value2) { | ||
651 | // We should never equate two type variables, both of which have | ||
652 | // known types. Instead, we recursively equate those types. | ||
653 | (TypeVarValue::Known(t1), TypeVarValue::Known(t2)) => panic!( | ||
654 | "equating two type variables, both of which have known types: {:?} and {:?}", | ||
655 | t1, t2 | ||
656 | ), | ||
657 | |||
658 | // If one side is known, prefer that one. | ||
659 | (TypeVarValue::Known(..), TypeVarValue::Unknown) => Ok(value1.clone()), | ||
660 | (TypeVarValue::Unknown, TypeVarValue::Known(..)) => Ok(value2.clone()), | ||
661 | |||
662 | (TypeVarValue::Unknown, TypeVarValue::Unknown) => Ok(TypeVarValue::Unknown), | ||
663 | } | ||
664 | } | ||
665 | } | ||
666 | |||
667 | /// The kinds of placeholders we need during type inference. There's separate | ||
668 | /// values for general types, and for integer and float variables. The latter | ||
669 | /// two are used for inference of literal values (e.g. `100` could be one of | ||
670 | /// several integer types). | ||
671 | #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] | ||
672 | pub enum InferTy { | ||
673 | TypeVar(TypeVarId), | ||
674 | IntVar(TypeVarId), | ||
675 | FloatVar(TypeVarId), | ||
676 | MaybeNeverTypeVar(TypeVarId), | ||
677 | } | ||
678 | |||
679 | impl InferTy { | ||
680 | fn to_inner(self) -> TypeVarId { | ||
681 | match self { | ||
682 | InferTy::TypeVar(ty) | ||
683 | | InferTy::IntVar(ty) | ||
684 | | InferTy::FloatVar(ty) | ||
685 | | InferTy::MaybeNeverTypeVar(ty) => ty, | ||
686 | } | ||
687 | } | ||
688 | |||
689 | fn fallback_value(self) -> Ty { | ||
690 | match self { | ||
691 | InferTy::TypeVar(..) => Ty::Unknown, | ||
692 | InferTy::IntVar(..) => Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::i32()))), | ||
693 | InferTy::FloatVar(..) => Ty::simple(TypeCtor::Float(Uncertain::Known(FloatTy::f64()))), | ||
694 | InferTy::MaybeNeverTypeVar(..) => Ty::simple(TypeCtor::Never), | ||
695 | } | ||
696 | } | ||
697 | } | ||
698 | |||
699 | /// When inferring an expression, we propagate downward whatever type hint we | ||
700 | /// are able in the form of an `Expectation`. | ||
701 | #[derive(Clone, PartialEq, Eq, Debug)] | ||
702 | struct Expectation { | ||
703 | ty: Ty, | ||
704 | // FIXME: In some cases, we need to be aware whether the expectation is that | ||
705 | // the type match exactly what we passed, or whether it just needs to be | ||
706 | // coercible to the expected type. See Expectation::rvalue_hint in rustc. | ||
707 | } | ||
708 | |||
709 | impl Expectation { | ||
710 | /// The expectation that the type of the expression needs to equal the given | ||
711 | /// type. | ||
712 | fn has_type(ty: Ty) -> Self { | ||
713 | Expectation { ty } | ||
714 | } | ||
715 | |||
716 | /// This expresses no expectation on the type. | ||
717 | fn none() -> Self { | ||
718 | Expectation { ty: Ty::Unknown } | ||
719 | } | ||
720 | } | ||
721 | |||
722 | mod diagnostics { | ||
723 | use hir_expand::diagnostics::DiagnosticSink; | ||
724 | |||
725 | use crate::{db::HirDatabase, diagnostics::NoSuchField, expr::ExprId, Function, HasSource}; | ||
726 | |||
727 | #[derive(Debug, PartialEq, Eq, Clone)] | ||
728 | pub(super) enum InferenceDiagnostic { | ||
729 | NoSuchField { expr: ExprId, field: usize }, | ||
730 | } | ||
731 | |||
732 | impl InferenceDiagnostic { | ||
733 | pub(super) fn add_to( | ||
734 | &self, | ||
735 | db: &impl HirDatabase, | ||
736 | owner: Function, | ||
737 | sink: &mut DiagnosticSink, | ||
738 | ) { | ||
739 | match self { | ||
740 | InferenceDiagnostic::NoSuchField { expr, field } => { | ||
741 | let file = owner.source(db).file_id; | ||
742 | let field = owner.body_source_map(db).field_syntax(*expr, *field); | ||
743 | sink.push(NoSuchField { file, field }) | ||
744 | } | ||
745 | } | ||
746 | } | ||
747 | } | ||
748 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/coerce.rs b/crates/ra_hir/src/ty/infer/coerce.rs deleted file mode 100644 index 54765da35..000000000 --- a/crates/ra_hir/src/ty/infer/coerce.rs +++ /dev/null | |||
@@ -1,339 +0,0 @@ | |||
1 | //! Coercion logic. Coercions are certain type conversions that can implicitly | ||
2 | //! happen in certain places, e.g. weakening `&mut` to `&` or deref coercions | ||
3 | //! like going from `&Vec<T>` to `&[T]`. | ||
4 | //! | ||
5 | //! See: https://doc.rust-lang.org/nomicon/coercions.html | ||
6 | |||
7 | use hir_def::{lang_item::LangItemTarget, resolver::Resolver}; | ||
8 | use rustc_hash::FxHashMap; | ||
9 | use test_utils::tested_by; | ||
10 | |||
11 | use crate::{ | ||
12 | db::HirDatabase, | ||
13 | ty::{autoderef, Substs, Ty, TypeCtor, TypeWalk}, | ||
14 | Adt, Mutability, | ||
15 | }; | ||
16 | |||
17 | use super::{InferTy, InferenceContext, TypeVarValue}; | ||
18 | |||
19 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
20 | /// Unify two types, but may coerce the first one to the second one | ||
21 | /// using "implicit coercion rules" if needed. | ||
22 | pub(super) fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
23 | let from_ty = self.resolve_ty_shallow(from_ty).into_owned(); | ||
24 | let to_ty = self.resolve_ty_shallow(to_ty); | ||
25 | self.coerce_inner(from_ty, &to_ty) | ||
26 | } | ||
27 | |||
28 | /// Merge two types from different branches, with possible implicit coerce. | ||
29 | /// | ||
30 | /// Note that it is only possible that one type are coerced to another. | ||
31 | /// Coercing both types to another least upper bound type is not possible in rustc, | ||
32 | /// which will simply result in "incompatible types" error. | ||
33 | pub(super) fn coerce_merge_branch<'t>(&mut self, ty1: &Ty, ty2: &Ty) -> Ty { | ||
34 | if self.coerce(ty1, ty2) { | ||
35 | ty2.clone() | ||
36 | } else if self.coerce(ty2, ty1) { | ||
37 | ty1.clone() | ||
38 | } else { | ||
39 | tested_by!(coerce_merge_fail_fallback); | ||
40 | // For incompatible types, we use the latter one as result | ||
41 | // to be better recovery for `if` without `else`. | ||
42 | ty2.clone() | ||
43 | } | ||
44 | } | ||
45 | |||
46 | pub(super) fn init_coerce_unsized_map( | ||
47 | db: &'a D, | ||
48 | resolver: &Resolver, | ||
49 | ) -> FxHashMap<(TypeCtor, TypeCtor), usize> { | ||
50 | let krate = resolver.krate().unwrap(); | ||
51 | let impls = match db.lang_item(krate.into(), "coerce_unsized".into()) { | ||
52 | Some(LangItemTarget::TraitId(trait_)) => { | ||
53 | db.impls_for_trait(krate.into(), trait_.into()) | ||
54 | } | ||
55 | _ => return FxHashMap::default(), | ||
56 | }; | ||
57 | |||
58 | impls | ||
59 | .iter() | ||
60 | .filter_map(|impl_block| { | ||
61 | // `CoerseUnsized` has one generic parameter for the target type. | ||
62 | let trait_ref = impl_block.target_trait_ref(db)?; | ||
63 | let cur_from_ty = trait_ref.substs.0.get(0)?; | ||
64 | let cur_to_ty = trait_ref.substs.0.get(1)?; | ||
65 | |||
66 | match (&cur_from_ty, cur_to_ty) { | ||
67 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => { | ||
68 | // FIXME: We return the first non-equal bound as the type parameter to coerce to unsized type. | ||
69 | // This works for smart-pointer-like coercion, which covers all impls from std. | ||
70 | st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| { | ||
71 | match (ty1, ty2) { | ||
72 | (Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. }) | ||
73 | if p1 != p2 => | ||
74 | { | ||
75 | Some(((*ctor1, *ctor2), i)) | ||
76 | } | ||
77 | _ => None, | ||
78 | } | ||
79 | }) | ||
80 | } | ||
81 | _ => None, | ||
82 | } | ||
83 | }) | ||
84 | .collect() | ||
85 | } | ||
86 | |||
87 | fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool { | ||
88 | match (&from_ty, to_ty) { | ||
89 | // Never type will make type variable to fallback to Never Type instead of Unknown. | ||
90 | (ty_app!(TypeCtor::Never), Ty::Infer(InferTy::TypeVar(tv))) => { | ||
91 | let var = self.new_maybe_never_type_var(); | ||
92 | self.var_unification_table.union_value(*tv, TypeVarValue::Known(var)); | ||
93 | return true; | ||
94 | } | ||
95 | (ty_app!(TypeCtor::Never), _) => return true, | ||
96 | |||
97 | // Trivial cases, this should go after `never` check to | ||
98 | // avoid infer result type to be never | ||
99 | _ => { | ||
100 | if self.unify_inner_trivial(&from_ty, &to_ty) { | ||
101 | return true; | ||
102 | } | ||
103 | } | ||
104 | } | ||
105 | |||
106 | // Pointer weakening and function to pointer | ||
107 | match (&mut from_ty, to_ty) { | ||
108 | // `*mut T`, `&mut T, `&T`` -> `*const T` | ||
109 | // `&mut T` -> `&T` | ||
110 | // `&mut T` -> `*mut T` | ||
111 | (ty_app!(c1@TypeCtor::RawPtr(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
112 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
113 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::Ref(Mutability::Shared))) | ||
114 | | (ty_app!(c1@TypeCtor::Ref(Mutability::Mut)), ty_app!(c2@TypeCtor::RawPtr(_))) => { | ||
115 | *c1 = *c2; | ||
116 | } | ||
117 | |||
118 | // Illegal mutablity conversion | ||
119 | ( | ||
120 | ty_app!(TypeCtor::RawPtr(Mutability::Shared)), | ||
121 | ty_app!(TypeCtor::RawPtr(Mutability::Mut)), | ||
122 | ) | ||
123 | | ( | ||
124 | ty_app!(TypeCtor::Ref(Mutability::Shared)), | ||
125 | ty_app!(TypeCtor::Ref(Mutability::Mut)), | ||
126 | ) => return false, | ||
127 | |||
128 | // `{function_type}` -> `fn()` | ||
129 | (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnPtr { .. })) => { | ||
130 | match from_ty.callable_sig(self.db) { | ||
131 | None => return false, | ||
132 | Some(sig) => { | ||
133 | let num_args = sig.params_and_return.len() as u16 - 1; | ||
134 | from_ty = | ||
135 | Ty::apply(TypeCtor::FnPtr { num_args }, Substs(sig.params_and_return)); | ||
136 | } | ||
137 | } | ||
138 | } | ||
139 | |||
140 | _ => {} | ||
141 | } | ||
142 | |||
143 | if let Some(ret) = self.try_coerce_unsized(&from_ty, &to_ty) { | ||
144 | return ret; | ||
145 | } | ||
146 | |||
147 | // Auto Deref if cannot coerce | ||
148 | match (&from_ty, to_ty) { | ||
149 | // FIXME: DerefMut | ||
150 | (ty_app!(TypeCtor::Ref(_), st1), ty_app!(TypeCtor::Ref(_), st2)) => { | ||
151 | self.unify_autoderef_behind_ref(&st1[0], &st2[0]) | ||
152 | } | ||
153 | |||
154 | // Otherwise, normal unify | ||
155 | _ => self.unify(&from_ty, to_ty), | ||
156 | } | ||
157 | } | ||
158 | |||
159 | /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>` | ||
160 | /// | ||
161 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html | ||
162 | fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> Option<bool> { | ||
163 | let (ctor1, st1, ctor2, st2) = match (from_ty, to_ty) { | ||
164 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => (ctor1, st1, ctor2, st2), | ||
165 | _ => return None, | ||
166 | }; | ||
167 | |||
168 | let coerce_generic_index = *self.coerce_unsized_map.get(&(*ctor1, *ctor2))?; | ||
169 | |||
170 | // Check `Unsize` first | ||
171 | match self.check_unsize_and_coerce( | ||
172 | st1.0.get(coerce_generic_index)?, | ||
173 | st2.0.get(coerce_generic_index)?, | ||
174 | 0, | ||
175 | ) { | ||
176 | Some(true) => {} | ||
177 | ret => return ret, | ||
178 | } | ||
179 | |||
180 | let ret = st1 | ||
181 | .iter() | ||
182 | .zip(st2.iter()) | ||
183 | .enumerate() | ||
184 | .filter(|&(idx, _)| idx != coerce_generic_index) | ||
185 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
186 | |||
187 | Some(ret) | ||
188 | } | ||
189 | |||
190 | /// Check if `from_ty: Unsize<to_ty>`, and coerce to `to_ty` if it holds. | ||
191 | /// | ||
192 | /// It should not be directly called. It is only used by `try_coerce_unsized`. | ||
193 | /// | ||
194 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.Unsize.html | ||
195 | fn check_unsize_and_coerce(&mut self, from_ty: &Ty, to_ty: &Ty, depth: usize) -> Option<bool> { | ||
196 | if depth > 1000 { | ||
197 | panic!("Infinite recursion in coercion"); | ||
198 | } | ||
199 | |||
200 | match (&from_ty, &to_ty) { | ||
201 | // `[T; N]` -> `[T]` | ||
202 | (ty_app!(TypeCtor::Array, st1), ty_app!(TypeCtor::Slice, st2)) => { | ||
203 | Some(self.unify(&st1[0], &st2[0])) | ||
204 | } | ||
205 | |||
206 | // `T` -> `dyn Trait` when `T: Trait` | ||
207 | (_, Ty::Dyn(_)) => { | ||
208 | // FIXME: Check predicates | ||
209 | Some(true) | ||
210 | } | ||
211 | |||
212 | // `(..., T)` -> `(..., U)` when `T: Unsize<U>` | ||
213 | ( | ||
214 | ty_app!(TypeCtor::Tuple { cardinality: len1 }, st1), | ||
215 | ty_app!(TypeCtor::Tuple { cardinality: len2 }, st2), | ||
216 | ) => { | ||
217 | if len1 != len2 || *len1 == 0 { | ||
218 | return None; | ||
219 | } | ||
220 | |||
221 | match self.check_unsize_and_coerce( | ||
222 | st1.last().unwrap(), | ||
223 | st2.last().unwrap(), | ||
224 | depth + 1, | ||
225 | ) { | ||
226 | Some(true) => {} | ||
227 | ret => return ret, | ||
228 | } | ||
229 | |||
230 | let ret = st1[..st1.len() - 1] | ||
231 | .iter() | ||
232 | .zip(&st2[..st2.len() - 1]) | ||
233 | .all(|(ty1, ty2)| self.unify(ty1, ty2)); | ||
234 | |||
235 | Some(ret) | ||
236 | } | ||
237 | |||
238 | // Foo<..., T, ...> is Unsize<Foo<..., U, ...>> if: | ||
239 | // - T: Unsize<U> | ||
240 | // - Foo is a struct | ||
241 | // - Only the last field of Foo has a type involving T | ||
242 | // - T is not part of the type of any other fields | ||
243 | // - Bar<T>: Unsize<Bar<U>>, if the last field of Foo has type Bar<T> | ||
244 | ( | ||
245 | ty_app!(TypeCtor::Adt(Adt::Struct(struct1)), st1), | ||
246 | ty_app!(TypeCtor::Adt(Adt::Struct(struct2)), st2), | ||
247 | ) if struct1 == struct2 => { | ||
248 | let field_tys = self.db.field_types(struct1.id.into()); | ||
249 | let struct_data = self.db.struct_data(struct1.id.0); | ||
250 | |||
251 | let mut fields = struct_data.variant_data.fields().iter(); | ||
252 | let (last_field_id, _data) = fields.next_back()?; | ||
253 | |||
254 | // Get the generic parameter involved in the last field. | ||
255 | let unsize_generic_index = { | ||
256 | let mut index = None; | ||
257 | let mut multiple_param = false; | ||
258 | field_tys[last_field_id].walk(&mut |ty| match ty { | ||
259 | &Ty::Param { idx, .. } => { | ||
260 | if index.is_none() { | ||
261 | index = Some(idx); | ||
262 | } else if Some(idx) != index { | ||
263 | multiple_param = true; | ||
264 | } | ||
265 | } | ||
266 | _ => {} | ||
267 | }); | ||
268 | |||
269 | if multiple_param { | ||
270 | return None; | ||
271 | } | ||
272 | index? | ||
273 | }; | ||
274 | |||
275 | // Check other fields do not involve it. | ||
276 | let mut multiple_used = false; | ||
277 | fields.for_each(|(field_id, _data)| { | ||
278 | field_tys[field_id].walk(&mut |ty| match ty { | ||
279 | &Ty::Param { idx, .. } if idx == unsize_generic_index => { | ||
280 | multiple_used = true | ||
281 | } | ||
282 | _ => {} | ||
283 | }) | ||
284 | }); | ||
285 | if multiple_used { | ||
286 | return None; | ||
287 | } | ||
288 | |||
289 | let unsize_generic_index = unsize_generic_index as usize; | ||
290 | |||
291 | // Check `Unsize` first | ||
292 | match self.check_unsize_and_coerce( | ||
293 | st1.get(unsize_generic_index)?, | ||
294 | st2.get(unsize_generic_index)?, | ||
295 | depth + 1, | ||
296 | ) { | ||
297 | Some(true) => {} | ||
298 | ret => return ret, | ||
299 | } | ||
300 | |||
301 | // Then unify other parameters | ||
302 | let ret = st1 | ||
303 | .iter() | ||
304 | .zip(st2.iter()) | ||
305 | .enumerate() | ||
306 | .filter(|&(idx, _)| idx != unsize_generic_index) | ||
307 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
308 | |||
309 | Some(ret) | ||
310 | } | ||
311 | |||
312 | _ => None, | ||
313 | } | ||
314 | } | ||
315 | |||
316 | /// Unify `from_ty` to `to_ty` with optional auto Deref | ||
317 | /// | ||
318 | /// Note that the parameters are already stripped the outer reference. | ||
319 | fn unify_autoderef_behind_ref(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
320 | let canonicalized = self.canonicalizer().canonicalize_ty(from_ty.clone()); | ||
321 | let to_ty = self.resolve_ty_shallow(&to_ty); | ||
322 | // FIXME: Auto DerefMut | ||
323 | for derefed_ty in | ||
324 | autoderef::autoderef(self.db, &self.resolver.clone(), canonicalized.value.clone()) | ||
325 | { | ||
326 | let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value); | ||
327 | match (&*self.resolve_ty_shallow(&derefed_ty), &*to_ty) { | ||
328 | // Stop when constructor matches. | ||
329 | (ty_app!(from_ctor, st1), ty_app!(to_ctor, st2)) if from_ctor == to_ctor => { | ||
330 | // It will not recurse to `coerce`. | ||
331 | return self.unify_substs(st1, st2, 0); | ||
332 | } | ||
333 | _ => {} | ||
334 | } | ||
335 | } | ||
336 | |||
337 | false | ||
338 | } | ||
339 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/expr.rs b/crates/ra_hir/src/ty/infer/expr.rs deleted file mode 100644 index 663ff9435..000000000 --- a/crates/ra_hir/src/ty/infer/expr.rs +++ /dev/null | |||
@@ -1,667 +0,0 @@ | |||
1 | //! Type inference for expressions. | ||
2 | |||
3 | use std::iter::{repeat, repeat_with}; | ||
4 | use std::sync::Arc; | ||
5 | |||
6 | use hir_def::{ | ||
7 | builtin_type::Signedness, | ||
8 | generics::GenericParams, | ||
9 | path::{GenericArg, GenericArgs}, | ||
10 | resolver::resolver_for_expr, | ||
11 | }; | ||
12 | use hir_expand::name; | ||
13 | |||
14 | use crate::{ | ||
15 | db::HirDatabase, | ||
16 | expr::{Array, BinaryOp, Expr, ExprId, Literal, Statement, UnaryOp}, | ||
17 | ty::{ | ||
18 | autoderef, method_resolution, op, CallableDef, InferTy, IntTy, Mutability, Namespace, | ||
19 | Obligation, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk, | ||
20 | Uncertain, | ||
21 | }, | ||
22 | Adt, Name, | ||
23 | }; | ||
24 | |||
25 | use super::{BindingMode, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch}; | ||
26 | |||
27 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
28 | pub(super) fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
29 | let ty = self.infer_expr_inner(tgt_expr, expected); | ||
30 | let could_unify = self.unify(&ty, &expected.ty); | ||
31 | if !could_unify { | ||
32 | self.result.type_mismatches.insert( | ||
33 | tgt_expr, | ||
34 | TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }, | ||
35 | ); | ||
36 | } | ||
37 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
38 | ty | ||
39 | } | ||
40 | |||
41 | /// Infer type of expression with possibly implicit coerce to the expected type. | ||
42 | /// Return the type after possible coercion. | ||
43 | fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty { | ||
44 | let ty = self.infer_expr_inner(expr, &expected); | ||
45 | let ty = if !self.coerce(&ty, &expected.ty) { | ||
46 | self.result | ||
47 | .type_mismatches | ||
48 | .insert(expr, TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }); | ||
49 | // Return actual type when type mismatch. | ||
50 | // This is needed for diagnostic when return type mismatch. | ||
51 | ty | ||
52 | } else if expected.ty == Ty::Unknown { | ||
53 | ty | ||
54 | } else { | ||
55 | expected.ty.clone() | ||
56 | }; | ||
57 | |||
58 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
59 | } | ||
60 | |||
61 | fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
62 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
63 | let ty = match &body[tgt_expr] { | ||
64 | Expr::Missing => Ty::Unknown, | ||
65 | Expr::If { condition, then_branch, else_branch } => { | ||
66 | // if let is desugared to match, so this is always simple if | ||
67 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
68 | |||
69 | let then_ty = self.infer_expr_inner(*then_branch, &expected); | ||
70 | let else_ty = match else_branch { | ||
71 | Some(else_branch) => self.infer_expr_inner(*else_branch, &expected), | ||
72 | None => Ty::unit(), | ||
73 | }; | ||
74 | |||
75 | self.coerce_merge_branch(&then_ty, &else_ty) | ||
76 | } | ||
77 | Expr::Block { statements, tail } => self.infer_block(statements, *tail, expected), | ||
78 | Expr::TryBlock { body } => { | ||
79 | let _inner = self.infer_expr(*body, expected); | ||
80 | // FIXME should be std::result::Result<{inner}, _> | ||
81 | Ty::Unknown | ||
82 | } | ||
83 | Expr::Loop { body } => { | ||
84 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
85 | // FIXME handle break with value | ||
86 | Ty::simple(TypeCtor::Never) | ||
87 | } | ||
88 | Expr::While { condition, body } => { | ||
89 | // while let is desugared to a match loop, so this is always simple while | ||
90 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
91 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
92 | Ty::unit() | ||
93 | } | ||
94 | Expr::For { iterable, body, pat } => { | ||
95 | let iterable_ty = self.infer_expr(*iterable, &Expectation::none()); | ||
96 | |||
97 | let pat_ty = match self.resolve_into_iter_item() { | ||
98 | Some(into_iter_item_alias) => { | ||
99 | let pat_ty = self.new_type_var(); | ||
100 | let projection = ProjectionPredicate { | ||
101 | ty: pat_ty.clone(), | ||
102 | projection_ty: ProjectionTy { | ||
103 | associated_ty: into_iter_item_alias, | ||
104 | parameters: Substs::single(iterable_ty), | ||
105 | }, | ||
106 | }; | ||
107 | self.obligations.push(Obligation::Projection(projection)); | ||
108 | self.resolve_ty_as_possible(&mut vec![], pat_ty) | ||
109 | } | ||
110 | None => Ty::Unknown, | ||
111 | }; | ||
112 | |||
113 | self.infer_pat(*pat, &pat_ty, BindingMode::default()); | ||
114 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
115 | Ty::unit() | ||
116 | } | ||
117 | Expr::Lambda { body, args, arg_types } => { | ||
118 | assert_eq!(args.len(), arg_types.len()); | ||
119 | |||
120 | let mut sig_tys = Vec::new(); | ||
121 | |||
122 | for (arg_pat, arg_type) in args.iter().zip(arg_types.iter()) { | ||
123 | let expected = if let Some(type_ref) = arg_type { | ||
124 | self.make_ty(type_ref) | ||
125 | } else { | ||
126 | Ty::Unknown | ||
127 | }; | ||
128 | let arg_ty = self.infer_pat(*arg_pat, &expected, BindingMode::default()); | ||
129 | sig_tys.push(arg_ty); | ||
130 | } | ||
131 | |||
132 | // add return type | ||
133 | let ret_ty = self.new_type_var(); | ||
134 | sig_tys.push(ret_ty.clone()); | ||
135 | let sig_ty = Ty::apply( | ||
136 | TypeCtor::FnPtr { num_args: sig_tys.len() as u16 - 1 }, | ||
137 | Substs(sig_tys.into()), | ||
138 | ); | ||
139 | let closure_ty = | ||
140 | Ty::apply_one(TypeCtor::Closure { def: self.owner, expr: tgt_expr }, sig_ty); | ||
141 | |||
142 | // Eagerly try to relate the closure type with the expected | ||
143 | // type, otherwise we often won't have enough information to | ||
144 | // infer the body. | ||
145 | self.coerce(&closure_ty, &expected.ty); | ||
146 | |||
147 | self.infer_expr(*body, &Expectation::has_type(ret_ty)); | ||
148 | closure_ty | ||
149 | } | ||
150 | Expr::Call { callee, args } => { | ||
151 | let callee_ty = self.infer_expr(*callee, &Expectation::none()); | ||
152 | let (param_tys, ret_ty) = match callee_ty.callable_sig(self.db) { | ||
153 | Some(sig) => (sig.params().to_vec(), sig.ret().clone()), | ||
154 | None => { | ||
155 | // Not callable | ||
156 | // FIXME: report an error | ||
157 | (Vec::new(), Ty::Unknown) | ||
158 | } | ||
159 | }; | ||
160 | self.register_obligations_for_call(&callee_ty); | ||
161 | self.check_call_arguments(args, ¶m_tys); | ||
162 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
163 | ret_ty | ||
164 | } | ||
165 | Expr::MethodCall { receiver, args, method_name, generic_args } => self | ||
166 | .infer_method_call(tgt_expr, *receiver, &args, &method_name, generic_args.as_ref()), | ||
167 | Expr::Match { expr, arms } => { | ||
168 | let input_ty = self.infer_expr(*expr, &Expectation::none()); | ||
169 | |||
170 | let mut result_ty = self.new_maybe_never_type_var(); | ||
171 | |||
172 | for arm in arms { | ||
173 | for &pat in &arm.pats { | ||
174 | let _pat_ty = self.infer_pat(pat, &input_ty, BindingMode::default()); | ||
175 | } | ||
176 | if let Some(guard_expr) = arm.guard { | ||
177 | self.infer_expr( | ||
178 | guard_expr, | ||
179 | &Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
180 | ); | ||
181 | } | ||
182 | |||
183 | let arm_ty = self.infer_expr_inner(arm.expr, &expected); | ||
184 | result_ty = self.coerce_merge_branch(&result_ty, &arm_ty); | ||
185 | } | ||
186 | |||
187 | result_ty | ||
188 | } | ||
189 | Expr::Path(p) => { | ||
190 | // FIXME this could be more efficient... | ||
191 | let resolver = resolver_for_expr(self.db, self.owner.into(), tgt_expr); | ||
192 | self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown) | ||
193 | } | ||
194 | Expr::Continue => Ty::simple(TypeCtor::Never), | ||
195 | Expr::Break { expr } => { | ||
196 | if let Some(expr) = expr { | ||
197 | // FIXME handle break with value | ||
198 | self.infer_expr(*expr, &Expectation::none()); | ||
199 | } | ||
200 | Ty::simple(TypeCtor::Never) | ||
201 | } | ||
202 | Expr::Return { expr } => { | ||
203 | if let Some(expr) = expr { | ||
204 | self.infer_expr(*expr, &Expectation::has_type(self.return_ty.clone())); | ||
205 | } | ||
206 | Ty::simple(TypeCtor::Never) | ||
207 | } | ||
208 | Expr::RecordLit { path, fields, spread } => { | ||
209 | let (ty, def_id) = self.resolve_variant(path.as_ref()); | ||
210 | if let Some(variant) = def_id { | ||
211 | self.write_variant_resolution(tgt_expr.into(), variant); | ||
212 | } | ||
213 | |||
214 | self.unify(&ty, &expected.ty); | ||
215 | |||
216 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
217 | let field_types = | ||
218 | def_id.map(|it| self.db.field_types(it.into())).unwrap_or_default(); | ||
219 | for (field_idx, field) in fields.iter().enumerate() { | ||
220 | let field_def = def_id.and_then(|it| match it.field(self.db, &field.name) { | ||
221 | Some(field) => Some(field), | ||
222 | None => { | ||
223 | self.push_diagnostic(InferenceDiagnostic::NoSuchField { | ||
224 | expr: tgt_expr, | ||
225 | field: field_idx, | ||
226 | }); | ||
227 | None | ||
228 | } | ||
229 | }); | ||
230 | if let Some(field_def) = field_def { | ||
231 | self.result.record_field_resolutions.insert(field.expr, field_def); | ||
232 | } | ||
233 | let field_ty = field_def | ||
234 | .map_or(Ty::Unknown, |it| field_types[it.id].clone()) | ||
235 | .subst(&substs); | ||
236 | self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty)); | ||
237 | } | ||
238 | if let Some(expr) = spread { | ||
239 | self.infer_expr(*expr, &Expectation::has_type(ty.clone())); | ||
240 | } | ||
241 | ty | ||
242 | } | ||
243 | Expr::Field { expr, name } => { | ||
244 | let receiver_ty = self.infer_expr(*expr, &Expectation::none()); | ||
245 | let canonicalized = self.canonicalizer().canonicalize_ty(receiver_ty); | ||
246 | let ty = autoderef::autoderef( | ||
247 | self.db, | ||
248 | &self.resolver.clone(), | ||
249 | canonicalized.value.clone(), | ||
250 | ) | ||
251 | .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) { | ||
252 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
253 | TypeCtor::Tuple { .. } => name | ||
254 | .as_tuple_index() | ||
255 | .and_then(|idx| a_ty.parameters.0.get(idx).cloned()), | ||
256 | TypeCtor::Adt(Adt::Struct(s)) => s.field(self.db, name).map(|field| { | ||
257 | self.write_field_resolution(tgt_expr, field); | ||
258 | self.db.field_types(s.id.into())[field.id] | ||
259 | .clone() | ||
260 | .subst(&a_ty.parameters) | ||
261 | }), | ||
262 | _ => None, | ||
263 | }, | ||
264 | _ => None, | ||
265 | }) | ||
266 | .unwrap_or(Ty::Unknown); | ||
267 | let ty = self.insert_type_vars(ty); | ||
268 | self.normalize_associated_types_in(ty) | ||
269 | } | ||
270 | Expr::Await { expr } => { | ||
271 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
272 | let ty = match self.resolve_future_future_output() { | ||
273 | Some(future_future_output_alias) => { | ||
274 | let ty = self.new_type_var(); | ||
275 | let projection = ProjectionPredicate { | ||
276 | ty: ty.clone(), | ||
277 | projection_ty: ProjectionTy { | ||
278 | associated_ty: future_future_output_alias, | ||
279 | parameters: Substs::single(inner_ty), | ||
280 | }, | ||
281 | }; | ||
282 | self.obligations.push(Obligation::Projection(projection)); | ||
283 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
284 | } | ||
285 | None => Ty::Unknown, | ||
286 | }; | ||
287 | ty | ||
288 | } | ||
289 | Expr::Try { expr } => { | ||
290 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
291 | let ty = match self.resolve_ops_try_ok() { | ||
292 | Some(ops_try_ok_alias) => { | ||
293 | let ty = self.new_type_var(); | ||
294 | let projection = ProjectionPredicate { | ||
295 | ty: ty.clone(), | ||
296 | projection_ty: ProjectionTy { | ||
297 | associated_ty: ops_try_ok_alias, | ||
298 | parameters: Substs::single(inner_ty), | ||
299 | }, | ||
300 | }; | ||
301 | self.obligations.push(Obligation::Projection(projection)); | ||
302 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
303 | } | ||
304 | None => Ty::Unknown, | ||
305 | }; | ||
306 | ty | ||
307 | } | ||
308 | Expr::Cast { expr, type_ref } => { | ||
309 | let _inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
310 | let cast_ty = self.make_ty(type_ref); | ||
311 | // FIXME check the cast... | ||
312 | cast_ty | ||
313 | } | ||
314 | Expr::Ref { expr, mutability } => { | ||
315 | let expectation = | ||
316 | if let Some((exp_inner, exp_mutability)) = &expected.ty.as_reference() { | ||
317 | if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared { | ||
318 | // FIXME: throw type error - expected mut reference but found shared ref, | ||
319 | // which cannot be coerced | ||
320 | } | ||
321 | Expectation::has_type(Ty::clone(exp_inner)) | ||
322 | } else { | ||
323 | Expectation::none() | ||
324 | }; | ||
325 | // FIXME reference coercions etc. | ||
326 | let inner_ty = self.infer_expr(*expr, &expectation); | ||
327 | Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) | ||
328 | } | ||
329 | Expr::Box { expr } => { | ||
330 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
331 | if let Some(box_) = self.resolve_boxed_box() { | ||
332 | Ty::apply_one(TypeCtor::Adt(box_), inner_ty) | ||
333 | } else { | ||
334 | Ty::Unknown | ||
335 | } | ||
336 | } | ||
337 | Expr::UnaryOp { expr, op } => { | ||
338 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
339 | match op { | ||
340 | UnaryOp::Deref => { | ||
341 | let canonicalized = self.canonicalizer().canonicalize_ty(inner_ty); | ||
342 | if let Some(derefed_ty) = | ||
343 | autoderef::deref(self.db, &self.resolver, &canonicalized.value) | ||
344 | { | ||
345 | canonicalized.decanonicalize_ty(derefed_ty.value) | ||
346 | } else { | ||
347 | Ty::Unknown | ||
348 | } | ||
349 | } | ||
350 | UnaryOp::Neg => { | ||
351 | match &inner_ty { | ||
352 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
353 | TypeCtor::Int(Uncertain::Unknown) | ||
354 | | TypeCtor::Int(Uncertain::Known(IntTy { | ||
355 | signedness: Signedness::Signed, | ||
356 | .. | ||
357 | })) | ||
358 | | TypeCtor::Float(..) => inner_ty, | ||
359 | _ => Ty::Unknown, | ||
360 | }, | ||
361 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => { | ||
362 | inner_ty | ||
363 | } | ||
364 | // FIXME: resolve ops::Neg trait | ||
365 | _ => Ty::Unknown, | ||
366 | } | ||
367 | } | ||
368 | UnaryOp::Not => { | ||
369 | match &inner_ty { | ||
370 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
371 | TypeCtor::Bool | TypeCtor::Int(_) => inner_ty, | ||
372 | _ => Ty::Unknown, | ||
373 | }, | ||
374 | Ty::Infer(InferTy::IntVar(..)) => inner_ty, | ||
375 | // FIXME: resolve ops::Not trait for inner_ty | ||
376 | _ => Ty::Unknown, | ||
377 | } | ||
378 | } | ||
379 | } | ||
380 | } | ||
381 | Expr::BinaryOp { lhs, rhs, op } => match op { | ||
382 | Some(op) => { | ||
383 | let lhs_expectation = match op { | ||
384 | BinaryOp::LogicOp(..) => Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
385 | _ => Expectation::none(), | ||
386 | }; | ||
387 | let lhs_ty = self.infer_expr(*lhs, &lhs_expectation); | ||
388 | // FIXME: find implementation of trait corresponding to operation | ||
389 | // symbol and resolve associated `Output` type | ||
390 | let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty); | ||
391 | let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation)); | ||
392 | |||
393 | // FIXME: similar as above, return ty is often associated trait type | ||
394 | op::binary_op_return_ty(*op, rhs_ty) | ||
395 | } | ||
396 | _ => Ty::Unknown, | ||
397 | }, | ||
398 | Expr::Index { base, index } => { | ||
399 | let _base_ty = self.infer_expr(*base, &Expectation::none()); | ||
400 | let _index_ty = self.infer_expr(*index, &Expectation::none()); | ||
401 | // FIXME: use `std::ops::Index::Output` to figure out the real return type | ||
402 | Ty::Unknown | ||
403 | } | ||
404 | Expr::Tuple { exprs } => { | ||
405 | let mut tys = match &expected.ty { | ||
406 | ty_app!(TypeCtor::Tuple { .. }, st) => st | ||
407 | .iter() | ||
408 | .cloned() | ||
409 | .chain(repeat_with(|| self.new_type_var())) | ||
410 | .take(exprs.len()) | ||
411 | .collect::<Vec<_>>(), | ||
412 | _ => (0..exprs.len()).map(|_| self.new_type_var()).collect(), | ||
413 | }; | ||
414 | |||
415 | for (expr, ty) in exprs.iter().zip(tys.iter_mut()) { | ||
416 | self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone())); | ||
417 | } | ||
418 | |||
419 | Ty::apply(TypeCtor::Tuple { cardinality: tys.len() as u16 }, Substs(tys.into())) | ||
420 | } | ||
421 | Expr::Array(array) => { | ||
422 | let elem_ty = match &expected.ty { | ||
423 | ty_app!(TypeCtor::Array, st) | ty_app!(TypeCtor::Slice, st) => { | ||
424 | st.as_single().clone() | ||
425 | } | ||
426 | _ => self.new_type_var(), | ||
427 | }; | ||
428 | |||
429 | match array { | ||
430 | Array::ElementList(items) => { | ||
431 | for expr in items.iter() { | ||
432 | self.infer_expr_coerce(*expr, &Expectation::has_type(elem_ty.clone())); | ||
433 | } | ||
434 | } | ||
435 | Array::Repeat { initializer, repeat } => { | ||
436 | self.infer_expr_coerce( | ||
437 | *initializer, | ||
438 | &Expectation::has_type(elem_ty.clone()), | ||
439 | ); | ||
440 | self.infer_expr( | ||
441 | *repeat, | ||
442 | &Expectation::has_type(Ty::simple(TypeCtor::Int(Uncertain::Known( | ||
443 | IntTy::usize(), | ||
444 | )))), | ||
445 | ); | ||
446 | } | ||
447 | } | ||
448 | |||
449 | Ty::apply_one(TypeCtor::Array, elem_ty) | ||
450 | } | ||
451 | Expr::Literal(lit) => match lit { | ||
452 | Literal::Bool(..) => Ty::simple(TypeCtor::Bool), | ||
453 | Literal::String(..) => { | ||
454 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), Ty::simple(TypeCtor::Str)) | ||
455 | } | ||
456 | Literal::ByteString(..) => { | ||
457 | let byte_type = Ty::simple(TypeCtor::Int(Uncertain::Known(IntTy::u8()))); | ||
458 | let slice_type = Ty::apply_one(TypeCtor::Slice, byte_type); | ||
459 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), slice_type) | ||
460 | } | ||
461 | Literal::Char(..) => Ty::simple(TypeCtor::Char), | ||
462 | Literal::Int(_v, ty) => Ty::simple(TypeCtor::Int((*ty).into())), | ||
463 | Literal::Float(_v, ty) => Ty::simple(TypeCtor::Float((*ty).into())), | ||
464 | }, | ||
465 | }; | ||
466 | // use a new type variable if we got Ty::Unknown here | ||
467 | let ty = self.insert_type_vars_shallow(ty); | ||
468 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
469 | self.write_expr_ty(tgt_expr, ty.clone()); | ||
470 | ty | ||
471 | } | ||
472 | |||
473 | fn infer_block( | ||
474 | &mut self, | ||
475 | statements: &[Statement], | ||
476 | tail: Option<ExprId>, | ||
477 | expected: &Expectation, | ||
478 | ) -> Ty { | ||
479 | let mut diverges = false; | ||
480 | for stmt in statements { | ||
481 | match stmt { | ||
482 | Statement::Let { pat, type_ref, initializer } => { | ||
483 | let decl_ty = | ||
484 | type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(Ty::Unknown); | ||
485 | |||
486 | // Always use the declared type when specified | ||
487 | let mut ty = decl_ty.clone(); | ||
488 | |||
489 | if let Some(expr) = initializer { | ||
490 | let actual_ty = | ||
491 | self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone())); | ||
492 | if decl_ty == Ty::Unknown { | ||
493 | ty = actual_ty; | ||
494 | } | ||
495 | } | ||
496 | |||
497 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
498 | self.infer_pat(*pat, &ty, BindingMode::default()); | ||
499 | } | ||
500 | Statement::Expr(expr) => { | ||
501 | if let ty_app!(TypeCtor::Never) = self.infer_expr(*expr, &Expectation::none()) { | ||
502 | diverges = true; | ||
503 | } | ||
504 | } | ||
505 | } | ||
506 | } | ||
507 | |||
508 | let ty = if let Some(expr) = tail { | ||
509 | self.infer_expr_coerce(expr, expected) | ||
510 | } else { | ||
511 | self.coerce(&Ty::unit(), &expected.ty); | ||
512 | Ty::unit() | ||
513 | }; | ||
514 | if diverges { | ||
515 | Ty::simple(TypeCtor::Never) | ||
516 | } else { | ||
517 | ty | ||
518 | } | ||
519 | } | ||
520 | |||
521 | fn infer_method_call( | ||
522 | &mut self, | ||
523 | tgt_expr: ExprId, | ||
524 | receiver: ExprId, | ||
525 | args: &[ExprId], | ||
526 | method_name: &Name, | ||
527 | generic_args: Option<&GenericArgs>, | ||
528 | ) -> Ty { | ||
529 | let receiver_ty = self.infer_expr(receiver, &Expectation::none()); | ||
530 | let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone()); | ||
531 | let resolved = method_resolution::lookup_method( | ||
532 | &canonicalized_receiver.value, | ||
533 | self.db, | ||
534 | method_name, | ||
535 | &self.resolver, | ||
536 | ); | ||
537 | let (derefed_receiver_ty, method_ty, def_generics) = match resolved { | ||
538 | Some((ty, func)) => { | ||
539 | let ty = canonicalized_receiver.decanonicalize_ty(ty); | ||
540 | self.write_method_resolution(tgt_expr, func); | ||
541 | ( | ||
542 | ty, | ||
543 | self.db.type_for_def(func.into(), Namespace::Values), | ||
544 | Some(self.db.generic_params(func.id.into())), | ||
545 | ) | ||
546 | } | ||
547 | None => (receiver_ty, Ty::Unknown, None), | ||
548 | }; | ||
549 | let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty); | ||
550 | let method_ty = method_ty.apply_substs(substs); | ||
551 | let method_ty = self.insert_type_vars(method_ty); | ||
552 | self.register_obligations_for_call(&method_ty); | ||
553 | let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) { | ||
554 | Some(sig) => { | ||
555 | if !sig.params().is_empty() { | ||
556 | (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone()) | ||
557 | } else { | ||
558 | (Ty::Unknown, Vec::new(), sig.ret().clone()) | ||
559 | } | ||
560 | } | ||
561 | None => (Ty::Unknown, Vec::new(), Ty::Unknown), | ||
562 | }; | ||
563 | // Apply autoref so the below unification works correctly | ||
564 | // FIXME: return correct autorefs from lookup_method | ||
565 | let actual_receiver_ty = match expected_receiver_ty.as_reference() { | ||
566 | Some((_, mutability)) => Ty::apply_one(TypeCtor::Ref(mutability), derefed_receiver_ty), | ||
567 | _ => derefed_receiver_ty, | ||
568 | }; | ||
569 | self.unify(&expected_receiver_ty, &actual_receiver_ty); | ||
570 | |||
571 | self.check_call_arguments(args, ¶m_tys); | ||
572 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
573 | ret_ty | ||
574 | } | ||
575 | |||
576 | fn check_call_arguments(&mut self, args: &[ExprId], param_tys: &[Ty]) { | ||
577 | // Quoting https://github.com/rust-lang/rust/blob/6ef275e6c3cb1384ec78128eceeb4963ff788dca/src/librustc_typeck/check/mod.rs#L3325 -- | ||
578 | // We do this in a pretty awful way: first we type-check any arguments | ||
579 | // that are not closures, then we type-check the closures. This is so | ||
580 | // that we have more information about the types of arguments when we | ||
581 | // type-check the functions. This isn't really the right way to do this. | ||
582 | for &check_closures in &[false, true] { | ||
583 | let param_iter = param_tys.iter().cloned().chain(repeat(Ty::Unknown)); | ||
584 | for (&arg, param_ty) in args.iter().zip(param_iter) { | ||
585 | let is_closure = match &self.body[arg] { | ||
586 | Expr::Lambda { .. } => true, | ||
587 | _ => false, | ||
588 | }; | ||
589 | |||
590 | if is_closure != check_closures { | ||
591 | continue; | ||
592 | } | ||
593 | |||
594 | let param_ty = self.normalize_associated_types_in(param_ty); | ||
595 | self.infer_expr_coerce(arg, &Expectation::has_type(param_ty.clone())); | ||
596 | } | ||
597 | } | ||
598 | } | ||
599 | |||
600 | fn substs_for_method_call( | ||
601 | &mut self, | ||
602 | def_generics: Option<Arc<GenericParams>>, | ||
603 | generic_args: Option<&GenericArgs>, | ||
604 | receiver_ty: &Ty, | ||
605 | ) -> Substs { | ||
606 | let (parent_param_count, param_count) = | ||
607 | def_generics.as_ref().map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); | ||
608 | let mut substs = Vec::with_capacity(parent_param_count + param_count); | ||
609 | // Parent arguments are unknown, except for the receiver type | ||
610 | if let Some(parent_generics) = def_generics.and_then(|p| p.parent_params.clone()) { | ||
611 | for param in &parent_generics.params { | ||
612 | if param.name == name::SELF_TYPE { | ||
613 | substs.push(receiver_ty.clone()); | ||
614 | } else { | ||
615 | substs.push(Ty::Unknown); | ||
616 | } | ||
617 | } | ||
618 | } | ||
619 | // handle provided type arguments | ||
620 | if let Some(generic_args) = generic_args { | ||
621 | // if args are provided, it should be all of them, but we can't rely on that | ||
622 | for arg in generic_args.args.iter().take(param_count) { | ||
623 | match arg { | ||
624 | GenericArg::Type(type_ref) => { | ||
625 | let ty = self.make_ty(type_ref); | ||
626 | substs.push(ty); | ||
627 | } | ||
628 | } | ||
629 | } | ||
630 | }; | ||
631 | let supplied_params = substs.len(); | ||
632 | for _ in supplied_params..parent_param_count + param_count { | ||
633 | substs.push(Ty::Unknown); | ||
634 | } | ||
635 | assert_eq!(substs.len(), parent_param_count + param_count); | ||
636 | Substs(substs.into()) | ||
637 | } | ||
638 | |||
639 | fn register_obligations_for_call(&mut self, callable_ty: &Ty) { | ||
640 | if let Ty::Apply(a_ty) = callable_ty { | ||
641 | if let TypeCtor::FnDef(def) = a_ty.ctor { | ||
642 | let generic_predicates = self.db.generic_predicates(def.into()); | ||
643 | for predicate in generic_predicates.iter() { | ||
644 | let predicate = predicate.clone().subst(&a_ty.parameters); | ||
645 | if let Some(obligation) = Obligation::from_predicate(predicate) { | ||
646 | self.obligations.push(obligation); | ||
647 | } | ||
648 | } | ||
649 | // add obligation for trait implementation, if this is a trait method | ||
650 | match def { | ||
651 | CallableDef::Function(f) => { | ||
652 | if let Some(trait_) = f.parent_trait(self.db) { | ||
653 | // construct a TraitDef | ||
654 | let substs = a_ty.parameters.prefix( | ||
655 | self.db | ||
656 | .generic_params(trait_.id.into()) | ||
657 | .count_params_including_parent(), | ||
658 | ); | ||
659 | self.obligations.push(Obligation::Trait(TraitRef { trait_, substs })); | ||
660 | } | ||
661 | } | ||
662 | CallableDef::Struct(_) | CallableDef::EnumVariant(_) => {} | ||
663 | } | ||
664 | } | ||
665 | } | ||
666 | } | ||
667 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/pat.rs b/crates/ra_hir/src/ty/infer/pat.rs deleted file mode 100644 index 641d61e87..000000000 --- a/crates/ra_hir/src/ty/infer/pat.rs +++ /dev/null | |||
@@ -1,183 +0,0 @@ | |||
1 | //! Type inference for patterns. | ||
2 | |||
3 | use std::iter::repeat; | ||
4 | use std::sync::Arc; | ||
5 | |||
6 | use test_utils::tested_by; | ||
7 | |||
8 | use super::{BindingMode, InferenceContext}; | ||
9 | use crate::{ | ||
10 | db::HirDatabase, | ||
11 | expr::{BindingAnnotation, Pat, PatId, RecordFieldPat}, | ||
12 | ty::{Mutability, Substs, Ty, TypeCtor, TypeWalk}, | ||
13 | Name, Path, | ||
14 | }; | ||
15 | |||
16 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
17 | fn infer_tuple_struct_pat( | ||
18 | &mut self, | ||
19 | path: Option<&Path>, | ||
20 | subpats: &[PatId], | ||
21 | expected: &Ty, | ||
22 | default_bm: BindingMode, | ||
23 | ) -> Ty { | ||
24 | let (ty, def) = self.resolve_variant(path); | ||
25 | |||
26 | self.unify(&ty, expected); | ||
27 | |||
28 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
29 | |||
30 | let field_tys = def.map(|it| self.db.field_types(it.into())).unwrap_or_default(); | ||
31 | for (i, &subpat) in subpats.iter().enumerate() { | ||
32 | let expected_ty = def | ||
33 | .and_then(|d| d.field(self.db, &Name::new_tuple_field(i))) | ||
34 | .map_or(Ty::Unknown, |field| field_tys[field.id].clone()) | ||
35 | .subst(&substs); | ||
36 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
37 | self.infer_pat(subpat, &expected_ty, default_bm); | ||
38 | } | ||
39 | |||
40 | ty | ||
41 | } | ||
42 | |||
43 | fn infer_record_pat( | ||
44 | &mut self, | ||
45 | path: Option<&Path>, | ||
46 | subpats: &[RecordFieldPat], | ||
47 | expected: &Ty, | ||
48 | default_bm: BindingMode, | ||
49 | id: PatId, | ||
50 | ) -> Ty { | ||
51 | let (ty, def) = self.resolve_variant(path); | ||
52 | if let Some(variant) = def { | ||
53 | self.write_variant_resolution(id.into(), variant); | ||
54 | } | ||
55 | |||
56 | self.unify(&ty, expected); | ||
57 | |||
58 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
59 | |||
60 | let field_tys = def.map(|it| self.db.field_types(it.into())).unwrap_or_default(); | ||
61 | for subpat in subpats { | ||
62 | let matching_field = def.and_then(|it| it.field(self.db, &subpat.name)); | ||
63 | let expected_ty = matching_field | ||
64 | .map_or(Ty::Unknown, |field| field_tys[field.id].clone()) | ||
65 | .subst(&substs); | ||
66 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
67 | self.infer_pat(subpat.pat, &expected_ty, default_bm); | ||
68 | } | ||
69 | |||
70 | ty | ||
71 | } | ||
72 | |||
73 | pub(super) fn infer_pat( | ||
74 | &mut self, | ||
75 | pat: PatId, | ||
76 | mut expected: &Ty, | ||
77 | mut default_bm: BindingMode, | ||
78 | ) -> Ty { | ||
79 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
80 | |||
81 | let is_non_ref_pat = match &body[pat] { | ||
82 | Pat::Tuple(..) | ||
83 | | Pat::TupleStruct { .. } | ||
84 | | Pat::Record { .. } | ||
85 | | Pat::Range { .. } | ||
86 | | Pat::Slice { .. } => true, | ||
87 | // FIXME: Path/Lit might actually evaluate to ref, but inference is unimplemented. | ||
88 | Pat::Path(..) | Pat::Lit(..) => true, | ||
89 | Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Missing => false, | ||
90 | }; | ||
91 | if is_non_ref_pat { | ||
92 | while let Some((inner, mutability)) = expected.as_reference() { | ||
93 | expected = inner; | ||
94 | default_bm = match default_bm { | ||
95 | BindingMode::Move => BindingMode::Ref(mutability), | ||
96 | BindingMode::Ref(Mutability::Shared) => BindingMode::Ref(Mutability::Shared), | ||
97 | BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability), | ||
98 | } | ||
99 | } | ||
100 | } else if let Pat::Ref { .. } = &body[pat] { | ||
101 | tested_by!(match_ergonomics_ref); | ||
102 | // When you encounter a `&pat` pattern, reset to Move. | ||
103 | // This is so that `w` is by value: `let (_, &w) = &(1, &2);` | ||
104 | default_bm = BindingMode::Move; | ||
105 | } | ||
106 | |||
107 | // Lose mutability. | ||
108 | let default_bm = default_bm; | ||
109 | let expected = expected; | ||
110 | |||
111 | let ty = match &body[pat] { | ||
112 | Pat::Tuple(ref args) => { | ||
113 | let expectations = match expected.as_tuple() { | ||
114 | Some(parameters) => &*parameters.0, | ||
115 | _ => &[], | ||
116 | }; | ||
117 | let expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown)); | ||
118 | |||
119 | let inner_tys = args | ||
120 | .iter() | ||
121 | .zip(expectations_iter) | ||
122 | .map(|(&pat, ty)| self.infer_pat(pat, ty, default_bm)) | ||
123 | .collect(); | ||
124 | |||
125 | Ty::apply(TypeCtor::Tuple { cardinality: args.len() as u16 }, Substs(inner_tys)) | ||
126 | } | ||
127 | Pat::Ref { pat, mutability } => { | ||
128 | let expectation = match expected.as_reference() { | ||
129 | Some((inner_ty, exp_mut)) => { | ||
130 | if *mutability != exp_mut { | ||
131 | // FIXME: emit type error? | ||
132 | } | ||
133 | inner_ty | ||
134 | } | ||
135 | _ => &Ty::Unknown, | ||
136 | }; | ||
137 | let subty = self.infer_pat(*pat, expectation, default_bm); | ||
138 | Ty::apply_one(TypeCtor::Ref(*mutability), subty) | ||
139 | } | ||
140 | Pat::TupleStruct { path: p, args: subpats } => { | ||
141 | self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm) | ||
142 | } | ||
143 | Pat::Record { path: p, args: fields } => { | ||
144 | self.infer_record_pat(p.as_ref(), fields, expected, default_bm, pat) | ||
145 | } | ||
146 | Pat::Path(path) => { | ||
147 | // FIXME use correct resolver for the surrounding expression | ||
148 | let resolver = self.resolver.clone(); | ||
149 | self.infer_path(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown) | ||
150 | } | ||
151 | Pat::Bind { mode, name: _, subpat } => { | ||
152 | let mode = if mode == &BindingAnnotation::Unannotated { | ||
153 | default_bm | ||
154 | } else { | ||
155 | BindingMode::convert(*mode) | ||
156 | }; | ||
157 | let inner_ty = if let Some(subpat) = subpat { | ||
158 | self.infer_pat(*subpat, expected, default_bm) | ||
159 | } else { | ||
160 | expected.clone() | ||
161 | }; | ||
162 | let inner_ty = self.insert_type_vars_shallow(inner_ty); | ||
163 | |||
164 | let bound_ty = match mode { | ||
165 | BindingMode::Ref(mutability) => { | ||
166 | Ty::apply_one(TypeCtor::Ref(mutability), inner_ty.clone()) | ||
167 | } | ||
168 | BindingMode::Move => inner_ty.clone(), | ||
169 | }; | ||
170 | let bound_ty = self.resolve_ty_as_possible(&mut vec![], bound_ty); | ||
171 | self.write_pat_ty(pat, bound_ty); | ||
172 | return inner_ty; | ||
173 | } | ||
174 | _ => Ty::Unknown, | ||
175 | }; | ||
176 | // use a new type variable if we got Ty::Unknown here | ||
177 | let ty = self.insert_type_vars_shallow(ty); | ||
178 | self.unify(&ty, expected); | ||
179 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
180 | self.write_pat_ty(pat, ty.clone()); | ||
181 | ty | ||
182 | } | ||
183 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/path.rs b/crates/ra_hir/src/ty/infer/path.rs deleted file mode 100644 index ee54d8217..000000000 --- a/crates/ra_hir/src/ty/infer/path.rs +++ /dev/null | |||
@@ -1,258 +0,0 @@ | |||
1 | //! Path expression resolution. | ||
2 | |||
3 | use hir_def::{ | ||
4 | path::PathSegment, | ||
5 | resolver::{ResolveValueResult, Resolver, TypeNs, ValueNs}, | ||
6 | }; | ||
7 | |||
8 | use crate::{ | ||
9 | db::HirDatabase, | ||
10 | ty::{method_resolution, Namespace, Substs, Ty, TypableDef, TypeWalk}, | ||
11 | AssocItem, Container, Function, Name, Path, | ||
12 | }; | ||
13 | |||
14 | use super::{ExprOrPatId, InferenceContext, TraitRef}; | ||
15 | |||
16 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
17 | pub(super) fn infer_path( | ||
18 | &mut self, | ||
19 | resolver: &Resolver, | ||
20 | path: &Path, | ||
21 | id: ExprOrPatId, | ||
22 | ) -> Option<Ty> { | ||
23 | let ty = self.resolve_value_path(resolver, path, id)?; | ||
24 | let ty = self.insert_type_vars(ty); | ||
25 | let ty = self.normalize_associated_types_in(ty); | ||
26 | Some(ty) | ||
27 | } | ||
28 | |||
29 | fn resolve_value_path( | ||
30 | &mut self, | ||
31 | resolver: &Resolver, | ||
32 | path: &Path, | ||
33 | id: ExprOrPatId, | ||
34 | ) -> Option<Ty> { | ||
35 | let (value, self_subst) = if let crate::PathKind::Type(type_ref) = &path.kind { | ||
36 | if path.segments.is_empty() { | ||
37 | // This can't actually happen syntax-wise | ||
38 | return None; | ||
39 | } | ||
40 | let ty = self.make_ty(type_ref); | ||
41 | let remaining_segments_for_ty = &path.segments[..path.segments.len() - 1]; | ||
42 | let ty = Ty::from_type_relative_path(self.db, resolver, ty, remaining_segments_for_ty); | ||
43 | self.resolve_ty_assoc_item( | ||
44 | ty, | ||
45 | &path.segments.last().expect("path had at least one segment").name, | ||
46 | id, | ||
47 | )? | ||
48 | } else { | ||
49 | let value_or_partial = resolver.resolve_path_in_value_ns(self.db, &path)?; | ||
50 | |||
51 | match value_or_partial { | ||
52 | ResolveValueResult::ValueNs(it) => (it, None), | ||
53 | ResolveValueResult::Partial(def, remaining_index) => { | ||
54 | self.resolve_assoc_item(def, path, remaining_index, id)? | ||
55 | } | ||
56 | } | ||
57 | }; | ||
58 | |||
59 | let typable: TypableDef = match value { | ||
60 | ValueNs::LocalBinding(pat) => { | ||
61 | let ty = self.result.type_of_pat.get(pat)?.clone(); | ||
62 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
63 | return Some(ty); | ||
64 | } | ||
65 | ValueNs::FunctionId(it) => it.into(), | ||
66 | ValueNs::ConstId(it) => it.into(), | ||
67 | ValueNs::StaticId(it) => it.into(), | ||
68 | ValueNs::StructId(it) => it.into(), | ||
69 | ValueNs::EnumVariantId(it) => it.into(), | ||
70 | }; | ||
71 | |||
72 | let mut ty = self.db.type_for_def(typable, Namespace::Values); | ||
73 | if let Some(self_subst) = self_subst { | ||
74 | ty = ty.subst(&self_subst); | ||
75 | } | ||
76 | |||
77 | let substs = Ty::substs_from_path(self.db, &self.resolver, path, typable); | ||
78 | let ty = ty.subst(&substs); | ||
79 | Some(ty) | ||
80 | } | ||
81 | |||
82 | fn resolve_assoc_item( | ||
83 | &mut self, | ||
84 | def: TypeNs, | ||
85 | path: &Path, | ||
86 | remaining_index: usize, | ||
87 | id: ExprOrPatId, | ||
88 | ) -> Option<(ValueNs, Option<Substs>)> { | ||
89 | assert!(remaining_index < path.segments.len()); | ||
90 | // there may be more intermediate segments between the resolved one and | ||
91 | // the end. Only the last segment needs to be resolved to a value; from | ||
92 | // the segments before that, we need to get either a type or a trait ref. | ||
93 | |||
94 | let resolved_segment = &path.segments[remaining_index - 1]; | ||
95 | let remaining_segments = &path.segments[remaining_index..]; | ||
96 | let is_before_last = remaining_segments.len() == 1; | ||
97 | |||
98 | match (def, is_before_last) { | ||
99 | (TypeNs::TraitId(trait_), true) => { | ||
100 | let segment = | ||
101 | remaining_segments.last().expect("there should be at least one segment here"); | ||
102 | let trait_ref = TraitRef::from_resolved_path( | ||
103 | self.db, | ||
104 | &self.resolver, | ||
105 | trait_.into(), | ||
106 | resolved_segment, | ||
107 | None, | ||
108 | ); | ||
109 | self.resolve_trait_assoc_item(trait_ref, segment, id) | ||
110 | } | ||
111 | (def, _) => { | ||
112 | // Either we already have a type (e.g. `Vec::new`), or we have a | ||
113 | // trait but it's not the last segment, so the next segment | ||
114 | // should resolve to an associated type of that trait (e.g. `<T | ||
115 | // as Iterator>::Item::default`) | ||
116 | let remaining_segments_for_ty = &remaining_segments[..remaining_segments.len() - 1]; | ||
117 | let ty = Ty::from_partly_resolved_hir_path( | ||
118 | self.db, | ||
119 | &self.resolver, | ||
120 | def, | ||
121 | resolved_segment, | ||
122 | remaining_segments_for_ty, | ||
123 | ); | ||
124 | if let Ty::Unknown = ty { | ||
125 | return None; | ||
126 | } | ||
127 | |||
128 | let ty = self.insert_type_vars(ty); | ||
129 | let ty = self.normalize_associated_types_in(ty); | ||
130 | |||
131 | let segment = | ||
132 | remaining_segments.last().expect("there should be at least one segment here"); | ||
133 | |||
134 | self.resolve_ty_assoc_item(ty, &segment.name, id) | ||
135 | } | ||
136 | } | ||
137 | } | ||
138 | |||
139 | fn resolve_trait_assoc_item( | ||
140 | &mut self, | ||
141 | trait_ref: TraitRef, | ||
142 | segment: &PathSegment, | ||
143 | id: ExprOrPatId, | ||
144 | ) -> Option<(ValueNs, Option<Substs>)> { | ||
145 | let trait_ = trait_ref.trait_; | ||
146 | let item = trait_.items(self.db).iter().copied().find_map(|item| match item { | ||
147 | AssocItem::Function(func) => { | ||
148 | if segment.name == func.name(self.db) { | ||
149 | Some(AssocItem::Function(func)) | ||
150 | } else { | ||
151 | None | ||
152 | } | ||
153 | } | ||
154 | |||
155 | AssocItem::Const(konst) => { | ||
156 | if konst.name(self.db).map_or(false, |n| n == segment.name) { | ||
157 | Some(AssocItem::Const(konst)) | ||
158 | } else { | ||
159 | None | ||
160 | } | ||
161 | } | ||
162 | AssocItem::TypeAlias(_) => None, | ||
163 | })?; | ||
164 | let def = match item { | ||
165 | AssocItem::Function(f) => ValueNs::FunctionId(f.id), | ||
166 | AssocItem::Const(c) => ValueNs::ConstId(c.id), | ||
167 | AssocItem::TypeAlias(_) => unreachable!(), | ||
168 | }; | ||
169 | let substs = Substs::build_for_def(self.db, item) | ||
170 | .use_parent_substs(&trait_ref.substs) | ||
171 | .fill_with_params() | ||
172 | .build(); | ||
173 | |||
174 | self.write_assoc_resolution(id, item); | ||
175 | Some((def, Some(substs))) | ||
176 | } | ||
177 | |||
178 | fn resolve_ty_assoc_item( | ||
179 | &mut self, | ||
180 | ty: Ty, | ||
181 | name: &Name, | ||
182 | id: ExprOrPatId, | ||
183 | ) -> Option<(ValueNs, Option<Substs>)> { | ||
184 | if let Ty::Unknown = ty { | ||
185 | return None; | ||
186 | } | ||
187 | |||
188 | let canonical_ty = self.canonicalizer().canonicalize_ty(ty.clone()); | ||
189 | |||
190 | method_resolution::iterate_method_candidates( | ||
191 | &canonical_ty.value, | ||
192 | self.db, | ||
193 | &self.resolver.clone(), | ||
194 | Some(name), | ||
195 | method_resolution::LookupMode::Path, | ||
196 | move |_ty, item| { | ||
197 | let def = match item { | ||
198 | AssocItem::Function(f) => ValueNs::FunctionId(f.id), | ||
199 | AssocItem::Const(c) => ValueNs::ConstId(c.id), | ||
200 | AssocItem::TypeAlias(_) => unreachable!(), | ||
201 | }; | ||
202 | let substs = match item.container(self.db) { | ||
203 | Container::ImplBlock(_) => self.find_self_types(&def, ty.clone()), | ||
204 | Container::Trait(t) => { | ||
205 | // we're picking this method | ||
206 | let trait_substs = Substs::build_for_def(self.db, t) | ||
207 | .push(ty.clone()) | ||
208 | .fill(std::iter::repeat_with(|| self.new_type_var())) | ||
209 | .build(); | ||
210 | let substs = Substs::build_for_def(self.db, item) | ||
211 | .use_parent_substs(&trait_substs) | ||
212 | .fill_with_params() | ||
213 | .build(); | ||
214 | self.obligations.push(super::Obligation::Trait(TraitRef { | ||
215 | trait_: t, | ||
216 | substs: trait_substs, | ||
217 | })); | ||
218 | Some(substs) | ||
219 | } | ||
220 | }; | ||
221 | |||
222 | self.write_assoc_resolution(id, item); | ||
223 | Some((def, substs)) | ||
224 | }, | ||
225 | ) | ||
226 | } | ||
227 | |||
228 | fn find_self_types(&self, def: &ValueNs, actual_def_ty: Ty) -> Option<Substs> { | ||
229 | if let ValueNs::FunctionId(func) = def { | ||
230 | let func = Function::from(*func); | ||
231 | // We only do the infer if parent has generic params | ||
232 | let gen = self.db.generic_params(func.id.into()); | ||
233 | if gen.count_parent_params() == 0 { | ||
234 | return None; | ||
235 | } | ||
236 | |||
237 | let impl_block = func.impl_block(self.db)?.target_ty(self.db); | ||
238 | let impl_block_substs = impl_block.substs()?; | ||
239 | let actual_substs = actual_def_ty.substs()?; | ||
240 | |||
241 | let mut new_substs = vec![Ty::Unknown; gen.count_parent_params()]; | ||
242 | |||
243 | // The following code *link up* the function actual parma type | ||
244 | // and impl_block type param index | ||
245 | impl_block_substs.iter().zip(actual_substs.iter()).for_each(|(param, pty)| { | ||
246 | if let Ty::Param { idx, .. } = param { | ||
247 | if let Some(s) = new_substs.get_mut(*idx as usize) { | ||
248 | *s = pty.clone(); | ||
249 | } | ||
250 | } | ||
251 | }); | ||
252 | |||
253 | Some(Substs(new_substs.into())) | ||
254 | } else { | ||
255 | None | ||
256 | } | ||
257 | } | ||
258 | } | ||
diff --git a/crates/ra_hir/src/ty/infer/unify.rs b/crates/ra_hir/src/ty/infer/unify.rs deleted file mode 100644 index 64d9394cf..000000000 --- a/crates/ra_hir/src/ty/infer/unify.rs +++ /dev/null | |||
@@ -1,164 +0,0 @@ | |||
1 | //! Unification and canonicalization logic. | ||
2 | |||
3 | use super::{InferenceContext, Obligation}; | ||
4 | use crate::db::HirDatabase; | ||
5 | use crate::ty::{ | ||
6 | Canonical, InEnvironment, InferTy, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, | ||
7 | TypeWalk, | ||
8 | }; | ||
9 | use crate::util::make_mut_slice; | ||
10 | |||
11 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | ||
12 | pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b, D> | ||
13 | where | ||
14 | 'a: 'b, | ||
15 | { | ||
16 | Canonicalizer { ctx: self, free_vars: Vec::new(), var_stack: Vec::new() } | ||
17 | } | ||
18 | } | ||
19 | |||
20 | pub(super) struct Canonicalizer<'a, 'b, D: HirDatabase> | ||
21 | where | ||
22 | 'a: 'b, | ||
23 | { | ||
24 | ctx: &'b mut InferenceContext<'a, D>, | ||
25 | free_vars: Vec<InferTy>, | ||
26 | /// A stack of type variables that is used to detect recursive types (which | ||
27 | /// are an error, but we need to protect against them to avoid stack | ||
28 | /// overflows). | ||
29 | var_stack: Vec<super::TypeVarId>, | ||
30 | } | ||
31 | |||
32 | pub(super) struct Canonicalized<T> { | ||
33 | pub value: Canonical<T>, | ||
34 | free_vars: Vec<InferTy>, | ||
35 | } | ||
36 | |||
37 | impl<'a, 'b, D: HirDatabase> Canonicalizer<'a, 'b, D> | ||
38 | where | ||
39 | 'a: 'b, | ||
40 | { | ||
41 | fn add(&mut self, free_var: InferTy) -> usize { | ||
42 | self.free_vars.iter().position(|&v| v == free_var).unwrap_or_else(|| { | ||
43 | let next_index = self.free_vars.len(); | ||
44 | self.free_vars.push(free_var); | ||
45 | next_index | ||
46 | }) | ||
47 | } | ||
48 | |||
49 | fn do_canonicalize_ty(&mut self, ty: Ty) -> Ty { | ||
50 | ty.fold(&mut |ty| match ty { | ||
51 | Ty::Infer(tv) => { | ||
52 | let inner = tv.to_inner(); | ||
53 | if self.var_stack.contains(&inner) { | ||
54 | // recursive type | ||
55 | return tv.fallback_value(); | ||
56 | } | ||
57 | if let Some(known_ty) = | ||
58 | self.ctx.var_unification_table.inlined_probe_value(inner).known() | ||
59 | { | ||
60 | self.var_stack.push(inner); | ||
61 | let result = self.do_canonicalize_ty(known_ty.clone()); | ||
62 | self.var_stack.pop(); | ||
63 | result | ||
64 | } else { | ||
65 | let root = self.ctx.var_unification_table.find(inner); | ||
66 | let free_var = match tv { | ||
67 | InferTy::TypeVar(_) => InferTy::TypeVar(root), | ||
68 | InferTy::IntVar(_) => InferTy::IntVar(root), | ||
69 | InferTy::FloatVar(_) => InferTy::FloatVar(root), | ||
70 | InferTy::MaybeNeverTypeVar(_) => InferTy::MaybeNeverTypeVar(root), | ||
71 | }; | ||
72 | let position = self.add(free_var); | ||
73 | Ty::Bound(position as u32) | ||
74 | } | ||
75 | } | ||
76 | _ => ty, | ||
77 | }) | ||
78 | } | ||
79 | |||
80 | fn do_canonicalize_trait_ref(&mut self, mut trait_ref: TraitRef) -> TraitRef { | ||
81 | for ty in make_mut_slice(&mut trait_ref.substs.0) { | ||
82 | *ty = self.do_canonicalize_ty(ty.clone()); | ||
83 | } | ||
84 | trait_ref | ||
85 | } | ||
86 | |||
87 | fn into_canonicalized<T>(self, result: T) -> Canonicalized<T> { | ||
88 | Canonicalized { | ||
89 | value: Canonical { value: result, num_vars: self.free_vars.len() }, | ||
90 | free_vars: self.free_vars, | ||
91 | } | ||
92 | } | ||
93 | |||
94 | fn do_canonicalize_projection_ty(&mut self, mut projection_ty: ProjectionTy) -> ProjectionTy { | ||
95 | for ty in make_mut_slice(&mut projection_ty.parameters.0) { | ||
96 | *ty = self.do_canonicalize_ty(ty.clone()); | ||
97 | } | ||
98 | projection_ty | ||
99 | } | ||
100 | |||
101 | fn do_canonicalize_projection_predicate( | ||
102 | &mut self, | ||
103 | projection: ProjectionPredicate, | ||
104 | ) -> ProjectionPredicate { | ||
105 | let ty = self.do_canonicalize_ty(projection.ty); | ||
106 | let projection_ty = self.do_canonicalize_projection_ty(projection.projection_ty); | ||
107 | |||
108 | ProjectionPredicate { ty, projection_ty } | ||
109 | } | ||
110 | |||
111 | // FIXME: add some point, we need to introduce a `Fold` trait that abstracts | ||
112 | // over all the things that can be canonicalized (like Chalk and rustc have) | ||
113 | |||
114 | pub(crate) fn canonicalize_ty(mut self, ty: Ty) -> Canonicalized<Ty> { | ||
115 | let result = self.do_canonicalize_ty(ty); | ||
116 | self.into_canonicalized(result) | ||
117 | } | ||
118 | |||
119 | pub(crate) fn canonicalize_obligation( | ||
120 | mut self, | ||
121 | obligation: InEnvironment<Obligation>, | ||
122 | ) -> Canonicalized<InEnvironment<Obligation>> { | ||
123 | let result = match obligation.value { | ||
124 | Obligation::Trait(tr) => Obligation::Trait(self.do_canonicalize_trait_ref(tr)), | ||
125 | Obligation::Projection(pr) => { | ||
126 | Obligation::Projection(self.do_canonicalize_projection_predicate(pr)) | ||
127 | } | ||
128 | }; | ||
129 | self.into_canonicalized(InEnvironment { | ||
130 | value: result, | ||
131 | environment: obligation.environment, | ||
132 | }) | ||
133 | } | ||
134 | } | ||
135 | |||
136 | impl<T> Canonicalized<T> { | ||
137 | pub fn decanonicalize_ty(&self, mut ty: Ty) -> Ty { | ||
138 | ty.walk_mut_binders( | ||
139 | &mut |ty, binders| match ty { | ||
140 | &mut Ty::Bound(idx) => { | ||
141 | if idx as usize >= binders && (idx as usize - binders) < self.free_vars.len() { | ||
142 | *ty = Ty::Infer(self.free_vars[idx as usize - binders]); | ||
143 | } | ||
144 | } | ||
145 | _ => {} | ||
146 | }, | ||
147 | 0, | ||
148 | ); | ||
149 | ty | ||
150 | } | ||
151 | |||
152 | pub fn apply_solution( | ||
153 | &self, | ||
154 | ctx: &mut InferenceContext<'_, impl HirDatabase>, | ||
155 | solution: Canonical<Vec<Ty>>, | ||
156 | ) { | ||
157 | // the solution may contain new variables, which we need to convert to new inference vars | ||
158 | let new_vars = Substs((0..solution.num_vars).map(|_| ctx.new_type_var()).collect()); | ||
159 | for (i, ty) in solution.value.into_iter().enumerate() { | ||
160 | let var = self.free_vars[i]; | ||
161 | ctx.unify(&Ty::Infer(var), &ty.subst_bound_vars(&new_vars)); | ||
162 | } | ||
163 | } | ||
164 | } | ||
diff --git a/crates/ra_hir/src/ty/lower.rs b/crates/ra_hir/src/ty/lower.rs deleted file mode 100644 index a39beb2a0..000000000 --- a/crates/ra_hir/src/ty/lower.rs +++ /dev/null | |||
@@ -1,831 +0,0 @@ | |||
1 | //! Methods for lowering the HIR to types. There are two main cases here: | ||
2 | //! | ||
3 | //! - Lowering a type reference like `&usize` or `Option<foo::bar::Baz>` to a | ||
4 | //! type: The entry point for this is `Ty::from_hir`. | ||
5 | //! - Building the type for an item: This happens through the `type_for_def` query. | ||
6 | //! | ||
7 | //! This usually involves resolving names, collecting generic arguments etc. | ||
8 | use std::iter; | ||
9 | use std::sync::Arc; | ||
10 | |||
11 | use hir_def::{ | ||
12 | builtin_type::{BuiltinFloat, BuiltinInt, BuiltinType}, | ||
13 | generics::WherePredicate, | ||
14 | path::{GenericArg, PathSegment}, | ||
15 | resolver::{HasResolver, Resolver, TypeNs}, | ||
16 | type_ref::{TypeBound, TypeRef}, | ||
17 | AdtId, GenericDefId, LocalStructFieldId, VariantId, | ||
18 | }; | ||
19 | use ra_arena::map::ArenaMap; | ||
20 | |||
21 | use super::{ | ||
22 | FnSig, GenericPredicate, ProjectionPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, | ||
23 | TypeWalk, | ||
24 | }; | ||
25 | use crate::{ | ||
26 | db::HirDatabase, | ||
27 | ty::{ | ||
28 | primitive::{FloatTy, IntTy, Uncertain}, | ||
29 | Adt, | ||
30 | }, | ||
31 | util::make_mut_slice, | ||
32 | Const, Enum, EnumVariant, Function, GenericDef, ImplBlock, ModuleDef, Path, Static, Struct, | ||
33 | Trait, TypeAlias, Union, | ||
34 | }; | ||
35 | |||
36 | // FIXME: this is only really used in `type_for_def`, which contains a bunch of | ||
37 | // impossible cases. Perhaps we should recombine `TypeableDef` and `Namespace` | ||
38 | // into a `AsTypeDef`, `AsValueDef` enums? | ||
39 | #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] | ||
40 | pub enum Namespace { | ||
41 | Types, | ||
42 | Values, | ||
43 | // Note that only type inference uses this enum, and it doesn't care about macros. | ||
44 | // Macro, | ||
45 | } | ||
46 | |||
47 | impl Ty { | ||
48 | pub(crate) fn from_hir(db: &impl HirDatabase, resolver: &Resolver, type_ref: &TypeRef) -> Self { | ||
49 | match type_ref { | ||
50 | TypeRef::Never => Ty::simple(TypeCtor::Never), | ||
51 | TypeRef::Tuple(inner) => { | ||
52 | let inner_tys: Arc<[Ty]> = | ||
53 | inner.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect(); | ||
54 | Ty::apply( | ||
55 | TypeCtor::Tuple { cardinality: inner_tys.len() as u16 }, | ||
56 | Substs(inner_tys), | ||
57 | ) | ||
58 | } | ||
59 | TypeRef::Path(path) => Ty::from_hir_path(db, resolver, path), | ||
60 | TypeRef::RawPtr(inner, mutability) => { | ||
61 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
62 | Ty::apply_one(TypeCtor::RawPtr(*mutability), inner_ty) | ||
63 | } | ||
64 | TypeRef::Array(inner) => { | ||
65 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
66 | Ty::apply_one(TypeCtor::Array, inner_ty) | ||
67 | } | ||
68 | TypeRef::Slice(inner) => { | ||
69 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
70 | Ty::apply_one(TypeCtor::Slice, inner_ty) | ||
71 | } | ||
72 | TypeRef::Reference(inner, mutability) => { | ||
73 | let inner_ty = Ty::from_hir(db, resolver, inner); | ||
74 | Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) | ||
75 | } | ||
76 | TypeRef::Placeholder => Ty::Unknown, | ||
77 | TypeRef::Fn(params) => { | ||
78 | let sig = Substs(params.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect()); | ||
79 | Ty::apply(TypeCtor::FnPtr { num_args: sig.len() as u16 - 1 }, sig) | ||
80 | } | ||
81 | TypeRef::DynTrait(bounds) => { | ||
82 | let self_ty = Ty::Bound(0); | ||
83 | let predicates = bounds | ||
84 | .iter() | ||
85 | .flat_map(|b| { | ||
86 | GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) | ||
87 | }) | ||
88 | .collect(); | ||
89 | Ty::Dyn(predicates) | ||
90 | } | ||
91 | TypeRef::ImplTrait(bounds) => { | ||
92 | let self_ty = Ty::Bound(0); | ||
93 | let predicates = bounds | ||
94 | .iter() | ||
95 | .flat_map(|b| { | ||
96 | GenericPredicate::from_type_bound(db, resolver, b, self_ty.clone()) | ||
97 | }) | ||
98 | .collect(); | ||
99 | Ty::Opaque(predicates) | ||
100 | } | ||
101 | TypeRef::Error => Ty::Unknown, | ||
102 | } | ||
103 | } | ||
104 | |||
105 | /// This is only for `generic_predicates_for_param`, where we can't just | ||
106 | /// lower the self types of the predicates since that could lead to cycles. | ||
107 | /// So we just check here if the `type_ref` resolves to a generic param, and which. | ||
108 | fn from_hir_only_param( | ||
109 | db: &impl HirDatabase, | ||
110 | resolver: &Resolver, | ||
111 | type_ref: &TypeRef, | ||
112 | ) -> Option<u32> { | ||
113 | let path = match type_ref { | ||
114 | TypeRef::Path(path) => path, | ||
115 | _ => return None, | ||
116 | }; | ||
117 | if let crate::PathKind::Type(_) = &path.kind { | ||
118 | return None; | ||
119 | } | ||
120 | if path.segments.len() > 1 { | ||
121 | return None; | ||
122 | } | ||
123 | let resolution = match resolver.resolve_path_in_type_ns(db, path) { | ||
124 | Some((it, None)) => it, | ||
125 | _ => return None, | ||
126 | }; | ||
127 | if let TypeNs::GenericParam(idx) = resolution { | ||
128 | Some(idx) | ||
129 | } else { | ||
130 | None | ||
131 | } | ||
132 | } | ||
133 | |||
134 | pub(crate) fn from_type_relative_path( | ||
135 | db: &impl HirDatabase, | ||
136 | resolver: &Resolver, | ||
137 | ty: Ty, | ||
138 | remaining_segments: &[PathSegment], | ||
139 | ) -> Ty { | ||
140 | if remaining_segments.len() == 1 { | ||
141 | // resolve unselected assoc types | ||
142 | let segment = &remaining_segments[0]; | ||
143 | Ty::select_associated_type(db, resolver, ty, segment) | ||
144 | } else if remaining_segments.len() > 1 { | ||
145 | // FIXME report error (ambiguous associated type) | ||
146 | Ty::Unknown | ||
147 | } else { | ||
148 | ty | ||
149 | } | ||
150 | } | ||
151 | |||
152 | pub(crate) fn from_partly_resolved_hir_path( | ||
153 | db: &impl HirDatabase, | ||
154 | resolver: &Resolver, | ||
155 | resolution: TypeNs, | ||
156 | resolved_segment: &PathSegment, | ||
157 | remaining_segments: &[PathSegment], | ||
158 | ) -> Ty { | ||
159 | let ty = match resolution { | ||
160 | TypeNs::TraitId(trait_) => { | ||
161 | let trait_ref = TraitRef::from_resolved_path( | ||
162 | db, | ||
163 | resolver, | ||
164 | trait_.into(), | ||
165 | resolved_segment, | ||
166 | None, | ||
167 | ); | ||
168 | return if remaining_segments.len() == 1 { | ||
169 | let segment = &remaining_segments[0]; | ||
170 | match trait_ref | ||
171 | .trait_ | ||
172 | .associated_type_by_name_including_super_traits(db, &segment.name) | ||
173 | { | ||
174 | Some(associated_ty) => { | ||
175 | // FIXME handle type parameters on the segment | ||
176 | Ty::Projection(ProjectionTy { | ||
177 | associated_ty, | ||
178 | parameters: trait_ref.substs, | ||
179 | }) | ||
180 | } | ||
181 | None => { | ||
182 | // FIXME: report error (associated type not found) | ||
183 | Ty::Unknown | ||
184 | } | ||
185 | } | ||
186 | } else if remaining_segments.len() > 1 { | ||
187 | // FIXME report error (ambiguous associated type) | ||
188 | Ty::Unknown | ||
189 | } else { | ||
190 | Ty::Dyn(Arc::new([GenericPredicate::Implemented(trait_ref)])) | ||
191 | }; | ||
192 | } | ||
193 | TypeNs::GenericParam(idx) => { | ||
194 | // FIXME: maybe return name in resolution? | ||
195 | let name = resolved_segment.name.clone(); | ||
196 | Ty::Param { idx, name } | ||
197 | } | ||
198 | TypeNs::SelfType(impl_block) => ImplBlock::from(impl_block).target_ty(db), | ||
199 | TypeNs::AdtSelfType(adt) => Adt::from(adt).ty(db), | ||
200 | |||
201 | TypeNs::AdtId(it) => Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()), | ||
202 | TypeNs::BuiltinType(it) => { | ||
203 | Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()) | ||
204 | } | ||
205 | TypeNs::TypeAliasId(it) => { | ||
206 | Ty::from_hir_path_inner(db, resolver, resolved_segment, it.into()) | ||
207 | } | ||
208 | // FIXME: report error | ||
209 | TypeNs::EnumVariantId(_) => return Ty::Unknown, | ||
210 | }; | ||
211 | |||
212 | Ty::from_type_relative_path(db, resolver, ty, remaining_segments) | ||
213 | } | ||
214 | |||
215 | pub(crate) fn from_hir_path(db: &impl HirDatabase, resolver: &Resolver, path: &Path) -> Ty { | ||
216 | // Resolve the path (in type namespace) | ||
217 | if let crate::PathKind::Type(type_ref) = &path.kind { | ||
218 | let ty = Ty::from_hir(db, resolver, &type_ref); | ||
219 | let remaining_segments = &path.segments[..]; | ||
220 | return Ty::from_type_relative_path(db, resolver, ty, remaining_segments); | ||
221 | } | ||
222 | let (resolution, remaining_index) = match resolver.resolve_path_in_type_ns(db, path) { | ||
223 | Some(it) => it, | ||
224 | None => return Ty::Unknown, | ||
225 | }; | ||
226 | let (resolved_segment, remaining_segments) = match remaining_index { | ||
227 | None => ( | ||
228 | path.segments.last().expect("resolved path has at least one element"), | ||
229 | &[] as &[PathSegment], | ||
230 | ), | ||
231 | Some(i) => (&path.segments[i - 1], &path.segments[i..]), | ||
232 | }; | ||
233 | Ty::from_partly_resolved_hir_path( | ||
234 | db, | ||
235 | resolver, | ||
236 | resolution, | ||
237 | resolved_segment, | ||
238 | remaining_segments, | ||
239 | ) | ||
240 | } | ||
241 | |||
242 | fn select_associated_type( | ||
243 | db: &impl HirDatabase, | ||
244 | resolver: &Resolver, | ||
245 | self_ty: Ty, | ||
246 | segment: &PathSegment, | ||
247 | ) -> Ty { | ||
248 | let param_idx = match self_ty { | ||
249 | Ty::Param { idx, .. } => idx, | ||
250 | _ => return Ty::Unknown, // Error: Ambiguous associated type | ||
251 | }; | ||
252 | let def = match resolver.generic_def() { | ||
253 | Some(def) => def, | ||
254 | None => return Ty::Unknown, // this can't actually happen | ||
255 | }; | ||
256 | let predicates = db.generic_predicates_for_param(def.into(), param_idx); | ||
257 | let traits_from_env = predicates.iter().filter_map(|pred| match pred { | ||
258 | GenericPredicate::Implemented(tr) if tr.self_ty() == &self_ty => Some(tr.trait_), | ||
259 | _ => None, | ||
260 | }); | ||
261 | let traits = traits_from_env.flat_map(|t| t.all_super_traits(db)); | ||
262 | for t in traits { | ||
263 | if let Some(associated_ty) = t.associated_type_by_name(db, &segment.name) { | ||
264 | let substs = | ||
265 | Substs::build_for_def(db, t).push(self_ty.clone()).fill_with_unknown().build(); | ||
266 | // FIXME handle type parameters on the segment | ||
267 | return Ty::Projection(ProjectionTy { associated_ty, parameters: substs }); | ||
268 | } | ||
269 | } | ||
270 | Ty::Unknown | ||
271 | } | ||
272 | |||
273 | fn from_hir_path_inner( | ||
274 | db: &impl HirDatabase, | ||
275 | resolver: &Resolver, | ||
276 | segment: &PathSegment, | ||
277 | typable: TypableDef, | ||
278 | ) -> Ty { | ||
279 | let ty = db.type_for_def(typable, Namespace::Types); | ||
280 | let substs = Ty::substs_from_path_segment(db, resolver, segment, typable); | ||
281 | ty.subst(&substs) | ||
282 | } | ||
283 | |||
284 | pub(super) fn substs_from_path_segment( | ||
285 | db: &impl HirDatabase, | ||
286 | resolver: &Resolver, | ||
287 | segment: &PathSegment, | ||
288 | resolved: TypableDef, | ||
289 | ) -> Substs { | ||
290 | let def_generic: Option<GenericDef> = match resolved { | ||
291 | TypableDef::Function(func) => Some(func.into()), | ||
292 | TypableDef::Adt(adt) => Some(adt.into()), | ||
293 | TypableDef::EnumVariant(var) => Some(var.parent_enum(db).into()), | ||
294 | TypableDef::TypeAlias(t) => Some(t.into()), | ||
295 | TypableDef::Const(_) | TypableDef::Static(_) | TypableDef::BuiltinType(_) => None, | ||
296 | }; | ||
297 | substs_from_path_segment(db, resolver, segment, def_generic, false) | ||
298 | } | ||
299 | |||
300 | /// Collect generic arguments from a path into a `Substs`. See also | ||
301 | /// `create_substs_for_ast_path` and `def_to_ty` in rustc. | ||
302 | pub(super) fn substs_from_path( | ||
303 | db: &impl HirDatabase, | ||
304 | resolver: &Resolver, | ||
305 | path: &Path, | ||
306 | resolved: TypableDef, | ||
307 | ) -> Substs { | ||
308 | let last = path.segments.last().expect("path should have at least one segment"); | ||
309 | let segment = match resolved { | ||
310 | TypableDef::Function(_) | ||
311 | | TypableDef::Adt(_) | ||
312 | | TypableDef::Const(_) | ||
313 | | TypableDef::Static(_) | ||
314 | | TypableDef::TypeAlias(_) | ||
315 | | TypableDef::BuiltinType(_) => last, | ||
316 | TypableDef::EnumVariant(_) => { | ||
317 | // the generic args for an enum variant may be either specified | ||
318 | // on the segment referring to the enum, or on the segment | ||
319 | // referring to the variant. So `Option::<T>::None` and | ||
320 | // `Option::None::<T>` are both allowed (though the former is | ||
321 | // preferred). See also `def_ids_for_path_segments` in rustc. | ||
322 | let len = path.segments.len(); | ||
323 | let segment = if len >= 2 && path.segments[len - 2].args_and_bindings.is_some() { | ||
324 | // Option::<T>::None | ||
325 | &path.segments[len - 2] | ||
326 | } else { | ||
327 | // Option::None::<T> | ||
328 | last | ||
329 | }; | ||
330 | segment | ||
331 | } | ||
332 | }; | ||
333 | Ty::substs_from_path_segment(db, resolver, segment, resolved) | ||
334 | } | ||
335 | } | ||
336 | |||
337 | pub(super) fn substs_from_path_segment( | ||
338 | db: &impl HirDatabase, | ||
339 | resolver: &Resolver, | ||
340 | segment: &PathSegment, | ||
341 | def_generic: Option<GenericDef>, | ||
342 | add_self_param: bool, | ||
343 | ) -> Substs { | ||
344 | let mut substs = Vec::new(); | ||
345 | let def_generics = def_generic.map(|def| db.generic_params(def.into())); | ||
346 | |||
347 | let (parent_param_count, param_count) = | ||
348 | def_generics.map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); | ||
349 | substs.extend(iter::repeat(Ty::Unknown).take(parent_param_count)); | ||
350 | if add_self_param { | ||
351 | // FIXME this add_self_param argument is kind of a hack: Traits have the | ||
352 | // Self type as an implicit first type parameter, but it can't be | ||
353 | // actually provided in the type arguments | ||
354 | // (well, actually sometimes it can, in the form of type-relative paths: `<Foo as Default>::default()`) | ||
355 | substs.push(Ty::Unknown); | ||
356 | } | ||
357 | if let Some(generic_args) = &segment.args_and_bindings { | ||
358 | // if args are provided, it should be all of them, but we can't rely on that | ||
359 | let self_param_correction = if add_self_param { 1 } else { 0 }; | ||
360 | let param_count = param_count - self_param_correction; | ||
361 | for arg in generic_args.args.iter().take(param_count) { | ||
362 | match arg { | ||
363 | GenericArg::Type(type_ref) => { | ||
364 | let ty = Ty::from_hir(db, resolver, type_ref); | ||
365 | substs.push(ty); | ||
366 | } | ||
367 | } | ||
368 | } | ||
369 | } | ||
370 | // add placeholders for args that were not provided | ||
371 | let supplied_params = substs.len(); | ||
372 | for _ in supplied_params..parent_param_count + param_count { | ||
373 | substs.push(Ty::Unknown); | ||
374 | } | ||
375 | assert_eq!(substs.len(), parent_param_count + param_count); | ||
376 | |||
377 | // handle defaults | ||
378 | if let Some(def_generic) = def_generic { | ||
379 | let default_substs = db.generic_defaults(def_generic); | ||
380 | assert_eq!(substs.len(), default_substs.len()); | ||
381 | |||
382 | for (i, default_ty) in default_substs.iter().enumerate() { | ||
383 | if substs[i] == Ty::Unknown { | ||
384 | substs[i] = default_ty.clone(); | ||
385 | } | ||
386 | } | ||
387 | } | ||
388 | |||
389 | Substs(substs.into()) | ||
390 | } | ||
391 | |||
392 | impl TraitRef { | ||
393 | pub(crate) fn from_path( | ||
394 | db: &impl HirDatabase, | ||
395 | resolver: &Resolver, | ||
396 | path: &Path, | ||
397 | explicit_self_ty: Option<Ty>, | ||
398 | ) -> Option<Self> { | ||
399 | let resolved = match resolver.resolve_path_in_type_ns_fully(db, &path)? { | ||
400 | TypeNs::TraitId(tr) => tr, | ||
401 | _ => return None, | ||
402 | }; | ||
403 | let segment = path.segments.last().expect("path should have at least one segment"); | ||
404 | Some(TraitRef::from_resolved_path(db, resolver, resolved.into(), segment, explicit_self_ty)) | ||
405 | } | ||
406 | |||
407 | pub(super) fn from_resolved_path( | ||
408 | db: &impl HirDatabase, | ||
409 | resolver: &Resolver, | ||
410 | resolved: Trait, | ||
411 | segment: &PathSegment, | ||
412 | explicit_self_ty: Option<Ty>, | ||
413 | ) -> Self { | ||
414 | let mut substs = TraitRef::substs_from_path(db, resolver, segment, resolved); | ||
415 | if let Some(self_ty) = explicit_self_ty { | ||
416 | make_mut_slice(&mut substs.0)[0] = self_ty; | ||
417 | } | ||
418 | TraitRef { trait_: resolved, substs } | ||
419 | } | ||
420 | |||
421 | pub(crate) fn from_hir( | ||
422 | db: &impl HirDatabase, | ||
423 | resolver: &Resolver, | ||
424 | type_ref: &TypeRef, | ||
425 | explicit_self_ty: Option<Ty>, | ||
426 | ) -> Option<Self> { | ||
427 | let path = match type_ref { | ||
428 | TypeRef::Path(path) => path, | ||
429 | _ => return None, | ||
430 | }; | ||
431 | TraitRef::from_path(db, resolver, path, explicit_self_ty) | ||
432 | } | ||
433 | |||
434 | fn substs_from_path( | ||
435 | db: &impl HirDatabase, | ||
436 | resolver: &Resolver, | ||
437 | segment: &PathSegment, | ||
438 | resolved: Trait, | ||
439 | ) -> Substs { | ||
440 | let has_self_param = | ||
441 | segment.args_and_bindings.as_ref().map(|a| a.has_self_type).unwrap_or(false); | ||
442 | substs_from_path_segment(db, resolver, segment, Some(resolved.into()), !has_self_param) | ||
443 | } | ||
444 | |||
445 | pub(crate) fn for_trait(db: &impl HirDatabase, trait_: Trait) -> TraitRef { | ||
446 | let substs = Substs::identity(&db.generic_params(trait_.id.into())); | ||
447 | TraitRef { trait_, substs } | ||
448 | } | ||
449 | |||
450 | pub(crate) fn from_type_bound( | ||
451 | db: &impl HirDatabase, | ||
452 | resolver: &Resolver, | ||
453 | bound: &TypeBound, | ||
454 | self_ty: Ty, | ||
455 | ) -> Option<TraitRef> { | ||
456 | match bound { | ||
457 | TypeBound::Path(path) => TraitRef::from_path(db, resolver, path, Some(self_ty)), | ||
458 | TypeBound::Error => None, | ||
459 | } | ||
460 | } | ||
461 | } | ||
462 | |||
463 | impl GenericPredicate { | ||
464 | pub(crate) fn from_where_predicate<'a>( | ||
465 | db: &'a impl HirDatabase, | ||
466 | resolver: &'a Resolver, | ||
467 | where_predicate: &'a WherePredicate, | ||
468 | ) -> impl Iterator<Item = GenericPredicate> + 'a { | ||
469 | let self_ty = Ty::from_hir(db, resolver, &where_predicate.type_ref); | ||
470 | GenericPredicate::from_type_bound(db, resolver, &where_predicate.bound, self_ty) | ||
471 | } | ||
472 | |||
473 | pub(crate) fn from_type_bound<'a>( | ||
474 | db: &'a impl HirDatabase, | ||
475 | resolver: &'a Resolver, | ||
476 | bound: &'a TypeBound, | ||
477 | self_ty: Ty, | ||
478 | ) -> impl Iterator<Item = GenericPredicate> + 'a { | ||
479 | let trait_ref = TraitRef::from_type_bound(db, &resolver, bound, self_ty); | ||
480 | iter::once(trait_ref.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented)) | ||
481 | .chain( | ||
482 | trait_ref.into_iter().flat_map(move |tr| { | ||
483 | assoc_type_bindings_from_type_bound(db, resolver, bound, tr) | ||
484 | }), | ||
485 | ) | ||
486 | } | ||
487 | } | ||
488 | |||
489 | fn assoc_type_bindings_from_type_bound<'a>( | ||
490 | db: &'a impl HirDatabase, | ||
491 | resolver: &'a Resolver, | ||
492 | bound: &'a TypeBound, | ||
493 | trait_ref: TraitRef, | ||
494 | ) -> impl Iterator<Item = GenericPredicate> + 'a { | ||
495 | let last_segment = match bound { | ||
496 | TypeBound::Path(path) => path.segments.last(), | ||
497 | TypeBound::Error => None, | ||
498 | }; | ||
499 | last_segment | ||
500 | .into_iter() | ||
501 | .flat_map(|segment| segment.args_and_bindings.iter()) | ||
502 | .flat_map(|args_and_bindings| args_and_bindings.bindings.iter()) | ||
503 | .map(move |(name, type_ref)| { | ||
504 | let associated_ty = | ||
505 | match trait_ref.trait_.associated_type_by_name_including_super_traits(db, &name) { | ||
506 | None => return GenericPredicate::Error, | ||
507 | Some(t) => t, | ||
508 | }; | ||
509 | let projection_ty = | ||
510 | ProjectionTy { associated_ty, parameters: trait_ref.substs.clone() }; | ||
511 | let ty = Ty::from_hir(db, resolver, type_ref); | ||
512 | let projection_predicate = ProjectionPredicate { projection_ty, ty }; | ||
513 | GenericPredicate::Projection(projection_predicate) | ||
514 | }) | ||
515 | } | ||
516 | |||
517 | /// Build the declared type of an item. This depends on the namespace; e.g. for | ||
518 | /// `struct Foo(usize)`, we have two types: The type of the struct itself, and | ||
519 | /// the constructor function `(usize) -> Foo` which lives in the values | ||
520 | /// namespace. | ||
521 | pub(crate) fn type_for_def(db: &impl HirDatabase, def: TypableDef, ns: Namespace) -> Ty { | ||
522 | match (def, ns) { | ||
523 | (TypableDef::Function(f), Namespace::Values) => type_for_fn(db, f), | ||
524 | (TypableDef::Adt(Adt::Struct(s)), Namespace::Values) => type_for_struct_constructor(db, s), | ||
525 | (TypableDef::Adt(adt), Namespace::Types) => type_for_adt(db, adt), | ||
526 | (TypableDef::EnumVariant(v), Namespace::Values) => type_for_enum_variant_constructor(db, v), | ||
527 | (TypableDef::TypeAlias(t), Namespace::Types) => type_for_type_alias(db, t), | ||
528 | (TypableDef::Const(c), Namespace::Values) => type_for_const(db, c), | ||
529 | (TypableDef::Static(c), Namespace::Values) => type_for_static(db, c), | ||
530 | (TypableDef::BuiltinType(t), Namespace::Types) => type_for_builtin(t), | ||
531 | |||
532 | // 'error' cases: | ||
533 | (TypableDef::Function(_), Namespace::Types) => Ty::Unknown, | ||
534 | (TypableDef::Adt(Adt::Union(_)), Namespace::Values) => Ty::Unknown, | ||
535 | (TypableDef::Adt(Adt::Enum(_)), Namespace::Values) => Ty::Unknown, | ||
536 | (TypableDef::EnumVariant(_), Namespace::Types) => Ty::Unknown, | ||
537 | (TypableDef::TypeAlias(_), Namespace::Values) => Ty::Unknown, | ||
538 | (TypableDef::Const(_), Namespace::Types) => Ty::Unknown, | ||
539 | (TypableDef::Static(_), Namespace::Types) => Ty::Unknown, | ||
540 | (TypableDef::BuiltinType(_), Namespace::Values) => Ty::Unknown, | ||
541 | } | ||
542 | } | ||
543 | |||
544 | /// Build the signature of a callable item (function, struct or enum variant). | ||
545 | pub(crate) fn callable_item_sig(db: &impl HirDatabase, def: CallableDef) -> FnSig { | ||
546 | match def { | ||
547 | CallableDef::Function(f) => fn_sig_for_fn(db, f), | ||
548 | CallableDef::Struct(s) => fn_sig_for_struct_constructor(db, s), | ||
549 | CallableDef::EnumVariant(e) => fn_sig_for_enum_variant_constructor(db, e), | ||
550 | } | ||
551 | } | ||
552 | |||
553 | /// Build the type of all specific fields of a struct or enum variant. | ||
554 | pub(crate) fn field_types_query( | ||
555 | db: &impl HirDatabase, | ||
556 | variant_id: VariantId, | ||
557 | ) -> Arc<ArenaMap<LocalStructFieldId, Ty>> { | ||
558 | let (resolver, var_data) = match variant_id { | ||
559 | VariantId::StructId(it) => (it.resolver(db), db.struct_data(it.0).variant_data.clone()), | ||
560 | VariantId::EnumVariantId(it) => ( | ||
561 | it.parent.resolver(db), | ||
562 | db.enum_data(it.parent).variants[it.local_id].variant_data.clone(), | ||
563 | ), | ||
564 | }; | ||
565 | let mut res = ArenaMap::default(); | ||
566 | for (field_id, field_data) in var_data.fields().iter() { | ||
567 | res.insert(field_id, Ty::from_hir(db, &resolver, &field_data.type_ref)) | ||
568 | } | ||
569 | Arc::new(res) | ||
570 | } | ||
571 | |||
572 | /// This query exists only to be used when resolving short-hand associated types | ||
573 | /// like `T::Item`. | ||
574 | /// | ||
575 | /// See the analogous query in rustc and its comment: | ||
576 | /// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46 | ||
577 | /// This is a query mostly to handle cycles somewhat gracefully; e.g. the | ||
578 | /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but | ||
579 | /// these are fine: `T: Foo<U::Item>, U: Foo<()>`. | ||
580 | pub(crate) fn generic_predicates_for_param_query( | ||
581 | db: &impl HirDatabase, | ||
582 | def: GenericDef, | ||
583 | param_idx: u32, | ||
584 | ) -> Arc<[GenericPredicate]> { | ||
585 | let resolver = GenericDefId::from(def).resolver(db); | ||
586 | resolver | ||
587 | .where_predicates_in_scope() | ||
588 | // we have to filter out all other predicates *first*, before attempting to lower them | ||
589 | .filter(|pred| Ty::from_hir_only_param(db, &resolver, &pred.type_ref) == Some(param_idx)) | ||
590 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | ||
591 | .collect() | ||
592 | } | ||
593 | |||
594 | pub(crate) fn trait_env( | ||
595 | db: &impl HirDatabase, | ||
596 | resolver: &Resolver, | ||
597 | ) -> Arc<super::TraitEnvironment> { | ||
598 | let predicates = resolver | ||
599 | .where_predicates_in_scope() | ||
600 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | ||
601 | .collect::<Vec<_>>(); | ||
602 | |||
603 | Arc::new(super::TraitEnvironment { predicates }) | ||
604 | } | ||
605 | |||
606 | /// Resolve the where clause(s) of an item with generics. | ||
607 | pub(crate) fn generic_predicates_query( | ||
608 | db: &impl HirDatabase, | ||
609 | def: GenericDef, | ||
610 | ) -> Arc<[GenericPredicate]> { | ||
611 | let resolver = GenericDefId::from(def).resolver(db); | ||
612 | resolver | ||
613 | .where_predicates_in_scope() | ||
614 | .flat_map(|pred| GenericPredicate::from_where_predicate(db, &resolver, pred)) | ||
615 | .collect() | ||
616 | } | ||
617 | |||
618 | /// Resolve the default type params from generics | ||
619 | pub(crate) fn generic_defaults_query(db: &impl HirDatabase, def: GenericDef) -> Substs { | ||
620 | let resolver = GenericDefId::from(def).resolver(db); | ||
621 | let generic_params = db.generic_params(def.into()); | ||
622 | |||
623 | let defaults = generic_params | ||
624 | .params_including_parent() | ||
625 | .into_iter() | ||
626 | .map(|p| p.default.as_ref().map_or(Ty::Unknown, |t| Ty::from_hir(db, &resolver, t))) | ||
627 | .collect(); | ||
628 | |||
629 | Substs(defaults) | ||
630 | } | ||
631 | |||
632 | fn fn_sig_for_fn(db: &impl HirDatabase, def: Function) -> FnSig { | ||
633 | let data = db.function_data(def.id); | ||
634 | let resolver = def.id.resolver(db); | ||
635 | let params = data.params.iter().map(|tr| Ty::from_hir(db, &resolver, tr)).collect::<Vec<_>>(); | ||
636 | let ret = Ty::from_hir(db, &resolver, &data.ret_type); | ||
637 | FnSig::from_params_and_return(params, ret) | ||
638 | } | ||
639 | |||
640 | /// Build the declared type of a function. This should not need to look at the | ||
641 | /// function body. | ||
642 | fn type_for_fn(db: &impl HirDatabase, def: Function) -> Ty { | ||
643 | let generics = db.generic_params(def.id.into()); | ||
644 | let substs = Substs::identity(&generics); | ||
645 | Ty::apply(TypeCtor::FnDef(def.into()), substs) | ||
646 | } | ||
647 | |||
648 | /// Build the declared type of a const. | ||
649 | fn type_for_const(db: &impl HirDatabase, def: Const) -> Ty { | ||
650 | let data = db.const_data(def.id); | ||
651 | let resolver = def.id.resolver(db); | ||
652 | |||
653 | Ty::from_hir(db, &resolver, &data.type_ref) | ||
654 | } | ||
655 | |||
656 | /// Build the declared type of a static. | ||
657 | fn type_for_static(db: &impl HirDatabase, def: Static) -> Ty { | ||
658 | let data = db.static_data(def.id); | ||
659 | let resolver = def.id.resolver(db); | ||
660 | |||
661 | Ty::from_hir(db, &resolver, &data.type_ref) | ||
662 | } | ||
663 | |||
664 | /// Build the declared type of a static. | ||
665 | fn type_for_builtin(def: BuiltinType) -> Ty { | ||
666 | Ty::simple(match def { | ||
667 | BuiltinType::Char => TypeCtor::Char, | ||
668 | BuiltinType::Bool => TypeCtor::Bool, | ||
669 | BuiltinType::Str => TypeCtor::Str, | ||
670 | BuiltinType::Int(t) => TypeCtor::Int(IntTy::from(t).into()), | ||
671 | BuiltinType::Float(t) => TypeCtor::Float(FloatTy::from(t).into()), | ||
672 | }) | ||
673 | } | ||
674 | |||
675 | impl From<BuiltinInt> for IntTy { | ||
676 | fn from(t: BuiltinInt) -> Self { | ||
677 | IntTy { signedness: t.signedness, bitness: t.bitness } | ||
678 | } | ||
679 | } | ||
680 | |||
681 | impl From<BuiltinFloat> for FloatTy { | ||
682 | fn from(t: BuiltinFloat) -> Self { | ||
683 | FloatTy { bitness: t.bitness } | ||
684 | } | ||
685 | } | ||
686 | |||
687 | impl From<Option<BuiltinInt>> for Uncertain<IntTy> { | ||
688 | fn from(t: Option<BuiltinInt>) -> Self { | ||
689 | match t { | ||
690 | None => Uncertain::Unknown, | ||
691 | Some(t) => Uncertain::Known(t.into()), | ||
692 | } | ||
693 | } | ||
694 | } | ||
695 | |||
696 | impl From<Option<BuiltinFloat>> for Uncertain<FloatTy> { | ||
697 | fn from(t: Option<BuiltinFloat>) -> Self { | ||
698 | match t { | ||
699 | None => Uncertain::Unknown, | ||
700 | Some(t) => Uncertain::Known(t.into()), | ||
701 | } | ||
702 | } | ||
703 | } | ||
704 | |||
705 | fn fn_sig_for_struct_constructor(db: &impl HirDatabase, def: Struct) -> FnSig { | ||
706 | let struct_data = db.struct_data(def.id.into()); | ||
707 | let fields = struct_data.variant_data.fields(); | ||
708 | let resolver = def.id.resolver(db); | ||
709 | let params = fields | ||
710 | .iter() | ||
711 | .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) | ||
712 | .collect::<Vec<_>>(); | ||
713 | let ret = type_for_adt(db, def); | ||
714 | FnSig::from_params_and_return(params, ret) | ||
715 | } | ||
716 | |||
717 | /// Build the type of a tuple struct constructor. | ||
718 | fn type_for_struct_constructor(db: &impl HirDatabase, def: Struct) -> Ty { | ||
719 | let struct_data = db.struct_data(def.id.into()); | ||
720 | if struct_data.variant_data.is_unit() { | ||
721 | return type_for_adt(db, def); // Unit struct | ||
722 | } | ||
723 | let generics = db.generic_params(def.id.into()); | ||
724 | let substs = Substs::identity(&generics); | ||
725 | Ty::apply(TypeCtor::FnDef(def.into()), substs) | ||
726 | } | ||
727 | |||
728 | fn fn_sig_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariant) -> FnSig { | ||
729 | let var_data = def.variant_data(db); | ||
730 | let fields = var_data.fields(); | ||
731 | let resolver = def.parent.id.resolver(db); | ||
732 | let params = fields | ||
733 | .iter() | ||
734 | .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) | ||
735 | .collect::<Vec<_>>(); | ||
736 | let generics = db.generic_params(def.parent_enum(db).id.into()); | ||
737 | let substs = Substs::identity(&generics); | ||
738 | let ret = type_for_adt(db, def.parent_enum(db)).subst(&substs); | ||
739 | FnSig::from_params_and_return(params, ret) | ||
740 | } | ||
741 | |||
742 | /// Build the type of a tuple enum variant constructor. | ||
743 | fn type_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariant) -> Ty { | ||
744 | let var_data = def.variant_data(db); | ||
745 | if var_data.is_unit() { | ||
746 | return type_for_adt(db, def.parent_enum(db)); // Unit variant | ||
747 | } | ||
748 | let generics = db.generic_params(def.parent_enum(db).id.into()); | ||
749 | let substs = Substs::identity(&generics); | ||
750 | Ty::apply(TypeCtor::FnDef(def.into()), substs) | ||
751 | } | ||
752 | |||
753 | fn type_for_adt(db: &impl HirDatabase, adt: impl Into<Adt>) -> Ty { | ||
754 | let adt = adt.into(); | ||
755 | let adt_id: AdtId = adt.into(); | ||
756 | let generics = db.generic_params(adt_id.into()); | ||
757 | Ty::apply(TypeCtor::Adt(adt), Substs::identity(&generics)) | ||
758 | } | ||
759 | |||
760 | fn type_for_type_alias(db: &impl HirDatabase, t: TypeAlias) -> Ty { | ||
761 | let generics = db.generic_params(t.id.into()); | ||
762 | let resolver = t.id.resolver(db); | ||
763 | let type_ref = t.type_ref(db); | ||
764 | let substs = Substs::identity(&generics); | ||
765 | let inner = Ty::from_hir(db, &resolver, &type_ref.unwrap_or(TypeRef::Error)); | ||
766 | inner.subst(&substs) | ||
767 | } | ||
768 | |||
769 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
770 | pub enum TypableDef { | ||
771 | Function(Function), | ||
772 | Adt(Adt), | ||
773 | EnumVariant(EnumVariant), | ||
774 | TypeAlias(TypeAlias), | ||
775 | Const(Const), | ||
776 | Static(Static), | ||
777 | BuiltinType(BuiltinType), | ||
778 | } | ||
779 | impl_froms!( | ||
780 | TypableDef: Function, | ||
781 | Adt(Struct, Enum, Union), | ||
782 | EnumVariant, | ||
783 | TypeAlias, | ||
784 | Const, | ||
785 | Static, | ||
786 | BuiltinType | ||
787 | ); | ||
788 | |||
789 | impl From<ModuleDef> for Option<TypableDef> { | ||
790 | fn from(def: ModuleDef) -> Option<TypableDef> { | ||
791 | let res = match def { | ||
792 | ModuleDef::Function(f) => f.into(), | ||
793 | ModuleDef::Adt(adt) => adt.into(), | ||
794 | ModuleDef::EnumVariant(v) => v.into(), | ||
795 | ModuleDef::TypeAlias(t) => t.into(), | ||
796 | ModuleDef::Const(v) => v.into(), | ||
797 | ModuleDef::Static(v) => v.into(), | ||
798 | ModuleDef::BuiltinType(t) => t.into(), | ||
799 | ModuleDef::Module(_) | ModuleDef::Trait(_) => return None, | ||
800 | }; | ||
801 | Some(res) | ||
802 | } | ||
803 | } | ||
804 | |||
805 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | ||
806 | pub enum CallableDef { | ||
807 | Function(Function), | ||
808 | Struct(Struct), | ||
809 | EnumVariant(EnumVariant), | ||
810 | } | ||
811 | impl_froms!(CallableDef: Function, Struct, EnumVariant); | ||
812 | |||
813 | impl CallableDef { | ||
814 | pub fn krate(self, db: &impl HirDatabase) -> Option<crate::Crate> { | ||
815 | match self { | ||
816 | CallableDef::Function(f) => f.krate(db), | ||
817 | CallableDef::Struct(s) => s.krate(db), | ||
818 | CallableDef::EnumVariant(e) => e.parent_enum(db).krate(db), | ||
819 | } | ||
820 | } | ||
821 | } | ||
822 | |||
823 | impl From<CallableDef> for GenericDef { | ||
824 | fn from(def: CallableDef) -> GenericDef { | ||
825 | match def { | ||
826 | CallableDef::Function(f) => f.into(), | ||
827 | CallableDef::Struct(s) => s.into(), | ||
828 | CallableDef::EnumVariant(e) => e.into(), | ||
829 | } | ||
830 | } | ||
831 | } | ||
diff --git a/crates/ra_hir/src/ty/method_resolution.rs b/crates/ra_hir/src/ty/method_resolution.rs deleted file mode 100644 index caa5f5f74..000000000 --- a/crates/ra_hir/src/ty/method_resolution.rs +++ /dev/null | |||
@@ -1,375 +0,0 @@ | |||
1 | //! This module is concerned with finding methods that a given type provides. | ||
2 | //! For details about how this works in rustc, see the method lookup page in the | ||
3 | //! [rustc guide](https://rust-lang.github.io/rustc-guide/method-lookup.html) | ||
4 | //! and the corresponding code mostly in librustc_typeck/check/method/probe.rs. | ||
5 | use std::sync::Arc; | ||
6 | |||
7 | use arrayvec::ArrayVec; | ||
8 | use hir_def::{lang_item::LangItemTarget, resolver::Resolver, AstItemDef}; | ||
9 | use rustc_hash::FxHashMap; | ||
10 | |||
11 | use crate::{ | ||
12 | db::HirDatabase, | ||
13 | ty::primitive::{FloatBitness, Uncertain}, | ||
14 | ty::{Ty, TypeCtor}, | ||
15 | AssocItem, Crate, Function, ImplBlock, Module, Mutability, Name, Trait, | ||
16 | }; | ||
17 | |||
18 | use super::{autoderef, lower, Canonical, InEnvironment, TraitEnvironment, TraitRef}; | ||
19 | |||
20 | /// This is used as a key for indexing impls. | ||
21 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] | ||
22 | pub enum TyFingerprint { | ||
23 | Apply(TypeCtor), | ||
24 | } | ||
25 | |||
26 | impl TyFingerprint { | ||
27 | /// Creates a TyFingerprint for looking up an impl. Only certain types can | ||
28 | /// have impls: if we have some `struct S`, we can have an `impl S`, but not | ||
29 | /// `impl &S`. Hence, this will return `None` for reference types and such. | ||
30 | fn for_impl(ty: &Ty) -> Option<TyFingerprint> { | ||
31 | match ty { | ||
32 | Ty::Apply(a_ty) => Some(TyFingerprint::Apply(a_ty.ctor)), | ||
33 | _ => None, | ||
34 | } | ||
35 | } | ||
36 | } | ||
37 | |||
38 | #[derive(Debug, PartialEq, Eq)] | ||
39 | pub struct CrateImplBlocks { | ||
40 | impls: FxHashMap<TyFingerprint, Vec<ImplBlock>>, | ||
41 | impls_by_trait: FxHashMap<Trait, Vec<ImplBlock>>, | ||
42 | } | ||
43 | |||
44 | impl CrateImplBlocks { | ||
45 | pub(crate) fn impls_in_crate_query( | ||
46 | db: &impl HirDatabase, | ||
47 | krate: Crate, | ||
48 | ) -> Arc<CrateImplBlocks> { | ||
49 | let mut crate_impl_blocks = | ||
50 | CrateImplBlocks { impls: FxHashMap::default(), impls_by_trait: FxHashMap::default() }; | ||
51 | if let Some(module) = krate.root_module(db) { | ||
52 | crate_impl_blocks.collect_recursive(db, module); | ||
53 | } | ||
54 | Arc::new(crate_impl_blocks) | ||
55 | } | ||
56 | pub fn lookup_impl_blocks(&self, ty: &Ty) -> impl Iterator<Item = ImplBlock> + '_ { | ||
57 | let fingerprint = TyFingerprint::for_impl(ty); | ||
58 | fingerprint.and_then(|f| self.impls.get(&f)).into_iter().flatten().copied() | ||
59 | } | ||
60 | |||
61 | pub fn lookup_impl_blocks_for_trait(&self, tr: Trait) -> impl Iterator<Item = ImplBlock> + '_ { | ||
62 | self.impls_by_trait.get(&tr).into_iter().flatten().copied() | ||
63 | } | ||
64 | |||
65 | pub fn all_impls<'a>(&'a self) -> impl Iterator<Item = ImplBlock> + 'a { | ||
66 | self.impls.values().chain(self.impls_by_trait.values()).flatten().copied() | ||
67 | } | ||
68 | |||
69 | fn collect_recursive(&mut self, db: &impl HirDatabase, module: Module) { | ||
70 | for impl_block in module.impl_blocks(db) { | ||
71 | let target_ty = impl_block.target_ty(db); | ||
72 | |||
73 | if impl_block.target_trait(db).is_some() { | ||
74 | if let Some(tr) = impl_block.target_trait_ref(db) { | ||
75 | self.impls_by_trait.entry(tr.trait_).or_default().push(impl_block); | ||
76 | } | ||
77 | } else { | ||
78 | if let Some(target_ty_fp) = TyFingerprint::for_impl(&target_ty) { | ||
79 | self.impls.entry(target_ty_fp).or_default().push(impl_block); | ||
80 | } | ||
81 | } | ||
82 | } | ||
83 | |||
84 | for child in module.children(db) { | ||
85 | self.collect_recursive(db, child); | ||
86 | } | ||
87 | } | ||
88 | } | ||
89 | |||
90 | fn def_crates(db: &impl HirDatabase, cur_crate: Crate, ty: &Ty) -> Option<ArrayVec<[Crate; 2]>> { | ||
91 | // Types like slice can have inherent impls in several crates, (core and alloc). | ||
92 | // The corresponding impls are marked with lang items, so we can use them to find the required crates. | ||
93 | macro_rules! lang_item_crate { | ||
94 | ($($name:expr),+ $(,)?) => {{ | ||
95 | let mut v = ArrayVec::<[LangItemTarget; 2]>::new(); | ||
96 | $( | ||
97 | v.extend(db.lang_item(cur_crate.crate_id, $name.into())); | ||
98 | )+ | ||
99 | v | ||
100 | }}; | ||
101 | } | ||
102 | |||
103 | let lang_item_targets = match ty { | ||
104 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
105 | TypeCtor::Adt(def_id) => return Some(std::iter::once(def_id.krate(db)?).collect()), | ||
106 | TypeCtor::Bool => lang_item_crate!("bool"), | ||
107 | TypeCtor::Char => lang_item_crate!("char"), | ||
108 | TypeCtor::Float(Uncertain::Known(f)) => match f.bitness { | ||
109 | // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime) | ||
110 | FloatBitness::X32 => lang_item_crate!("f32", "f32_runtime"), | ||
111 | FloatBitness::X64 => lang_item_crate!("f64", "f64_runtime"), | ||
112 | }, | ||
113 | TypeCtor::Int(Uncertain::Known(i)) => lang_item_crate!(i.ty_to_string()), | ||
114 | TypeCtor::Str => lang_item_crate!("str_alloc", "str"), | ||
115 | TypeCtor::Slice => lang_item_crate!("slice_alloc", "slice"), | ||
116 | TypeCtor::RawPtr(Mutability::Shared) => lang_item_crate!("const_ptr"), | ||
117 | TypeCtor::RawPtr(Mutability::Mut) => lang_item_crate!("mut_ptr"), | ||
118 | _ => return None, | ||
119 | }, | ||
120 | _ => return None, | ||
121 | }; | ||
122 | let res = lang_item_targets | ||
123 | .into_iter() | ||
124 | .filter_map(|it| match it { | ||
125 | LangItemTarget::ImplBlockId(it) => Some(it), | ||
126 | _ => None, | ||
127 | }) | ||
128 | .map(|it| it.module(db).krate.into()) | ||
129 | .collect(); | ||
130 | Some(res) | ||
131 | } | ||
132 | |||
133 | /// Look up the method with the given name, returning the actual autoderefed | ||
134 | /// receiver type (but without autoref applied yet). | ||
135 | pub(crate) fn lookup_method( | ||
136 | ty: &Canonical<Ty>, | ||
137 | db: &impl HirDatabase, | ||
138 | name: &Name, | ||
139 | resolver: &Resolver, | ||
140 | ) -> Option<(Ty, Function)> { | ||
141 | iterate_method_candidates(ty, db, resolver, Some(name), LookupMode::MethodCall, |ty, f| match f | ||
142 | { | ||
143 | AssocItem::Function(f) => Some((ty.clone(), f)), | ||
144 | _ => None, | ||
145 | }) | ||
146 | } | ||
147 | |||
148 | /// Whether we're looking up a dotted method call (like `v.len()`) or a path | ||
149 | /// (like `Vec::new`). | ||
150 | #[derive(Copy, Clone, Debug, PartialEq, Eq)] | ||
151 | pub enum LookupMode { | ||
152 | /// Looking up a method call like `v.len()`: We only consider candidates | ||
153 | /// that have a `self` parameter, and do autoderef. | ||
154 | MethodCall, | ||
155 | /// Looking up a path like `Vec::new` or `Vec::default`: We consider all | ||
156 | /// candidates including associated constants, but don't do autoderef. | ||
157 | Path, | ||
158 | } | ||
159 | |||
160 | // This would be nicer if it just returned an iterator, but that runs into | ||
161 | // lifetime problems, because we need to borrow temp `CrateImplBlocks`. | ||
162 | // FIXME add a context type here? | ||
163 | pub(crate) fn iterate_method_candidates<T>( | ||
164 | ty: &Canonical<Ty>, | ||
165 | db: &impl HirDatabase, | ||
166 | resolver: &Resolver, | ||
167 | name: Option<&Name>, | ||
168 | mode: LookupMode, | ||
169 | mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>, | ||
170 | ) -> Option<T> { | ||
171 | let krate = resolver.krate()?; | ||
172 | match mode { | ||
173 | LookupMode::MethodCall => { | ||
174 | // For method calls, rust first does any number of autoderef, and then one | ||
175 | // autoref (i.e. when the method takes &self or &mut self). We just ignore | ||
176 | // the autoref currently -- when we find a method matching the given name, | ||
177 | // we assume it fits. | ||
178 | |||
179 | // Also note that when we've got a receiver like &S, even if the method we | ||
180 | // find in the end takes &self, we still do the autoderef step (just as | ||
181 | // rustc does an autoderef and then autoref again). | ||
182 | |||
183 | for derefed_ty in autoderef::autoderef(db, resolver, ty.clone()) { | ||
184 | if let Some(result) = iterate_inherent_methods( | ||
185 | &derefed_ty, | ||
186 | db, | ||
187 | name, | ||
188 | mode, | ||
189 | krate.into(), | ||
190 | &mut callback, | ||
191 | ) { | ||
192 | return Some(result); | ||
193 | } | ||
194 | if let Some(result) = iterate_trait_method_candidates( | ||
195 | &derefed_ty, | ||
196 | db, | ||
197 | resolver, | ||
198 | name, | ||
199 | mode, | ||
200 | &mut callback, | ||
201 | ) { | ||
202 | return Some(result); | ||
203 | } | ||
204 | } | ||
205 | } | ||
206 | LookupMode::Path => { | ||
207 | // No autoderef for path lookups | ||
208 | if let Some(result) = | ||
209 | iterate_inherent_methods(&ty, db, name, mode, krate.into(), &mut callback) | ||
210 | { | ||
211 | return Some(result); | ||
212 | } | ||
213 | if let Some(result) = | ||
214 | iterate_trait_method_candidates(&ty, db, resolver, name, mode, &mut callback) | ||
215 | { | ||
216 | return Some(result); | ||
217 | } | ||
218 | } | ||
219 | } | ||
220 | None | ||
221 | } | ||
222 | |||
223 | fn iterate_trait_method_candidates<T>( | ||
224 | ty: &Canonical<Ty>, | ||
225 | db: &impl HirDatabase, | ||
226 | resolver: &Resolver, | ||
227 | name: Option<&Name>, | ||
228 | mode: LookupMode, | ||
229 | mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>, | ||
230 | ) -> Option<T> { | ||
231 | let krate = resolver.krate()?; | ||
232 | // FIXME: maybe put the trait_env behind a query (need to figure out good input parameters for that) | ||
233 | let env = lower::trait_env(db, resolver); | ||
234 | // if ty is `impl Trait` or `dyn Trait`, the trait doesn't need to be in scope | ||
235 | let inherent_trait = ty.value.inherent_trait().into_iter(); | ||
236 | // if we have `T: Trait` in the param env, the trait doesn't need to be in scope | ||
237 | let traits_from_env = env | ||
238 | .trait_predicates_for_self_ty(&ty.value) | ||
239 | .map(|tr| tr.trait_) | ||
240 | .flat_map(|t| t.all_super_traits(db)); | ||
241 | let traits = inherent_trait | ||
242 | .chain(traits_from_env) | ||
243 | .chain(resolver.traits_in_scope(db).into_iter().map(Trait::from)); | ||
244 | 'traits: for t in traits { | ||
245 | let data = db.trait_data(t.id); | ||
246 | |||
247 | // we'll be lazy about checking whether the type implements the | ||
248 | // trait, but if we find out it doesn't, we'll skip the rest of the | ||
249 | // iteration | ||
250 | let mut known_implemented = false; | ||
251 | for &item in data.items.iter() { | ||
252 | if !is_valid_candidate(db, name, mode, item.into()) { | ||
253 | continue; | ||
254 | } | ||
255 | if !known_implemented { | ||
256 | let goal = generic_implements_goal(db, env.clone(), t, ty.clone()); | ||
257 | if db.trait_solve(krate.into(), goal).is_none() { | ||
258 | continue 'traits; | ||
259 | } | ||
260 | } | ||
261 | known_implemented = true; | ||
262 | if let Some(result) = callback(&ty.value, item.into()) { | ||
263 | return Some(result); | ||
264 | } | ||
265 | } | ||
266 | } | ||
267 | None | ||
268 | } | ||
269 | |||
270 | fn iterate_inherent_methods<T>( | ||
271 | ty: &Canonical<Ty>, | ||
272 | db: &impl HirDatabase, | ||
273 | name: Option<&Name>, | ||
274 | mode: LookupMode, | ||
275 | krate: Crate, | ||
276 | mut callback: impl FnMut(&Ty, AssocItem) -> Option<T>, | ||
277 | ) -> Option<T> { | ||
278 | for krate in def_crates(db, krate, &ty.value)? { | ||
279 | let impls = db.impls_in_crate(krate); | ||
280 | |||
281 | for impl_block in impls.lookup_impl_blocks(&ty.value) { | ||
282 | for item in impl_block.items(db) { | ||
283 | if !is_valid_candidate(db, name, mode, item) { | ||
284 | continue; | ||
285 | } | ||
286 | if let Some(result) = callback(&ty.value, item) { | ||
287 | return Some(result); | ||
288 | } | ||
289 | } | ||
290 | } | ||
291 | } | ||
292 | None | ||
293 | } | ||
294 | |||
295 | fn is_valid_candidate( | ||
296 | db: &impl HirDatabase, | ||
297 | name: Option<&Name>, | ||
298 | mode: LookupMode, | ||
299 | item: AssocItem, | ||
300 | ) -> bool { | ||
301 | match item { | ||
302 | AssocItem::Function(m) => { | ||
303 | let data = db.function_data(m.id); | ||
304 | name.map_or(true, |name| data.name == *name) | ||
305 | && (data.has_self_param || mode == LookupMode::Path) | ||
306 | } | ||
307 | AssocItem::Const(c) => { | ||
308 | name.map_or(true, |name| Some(name) == c.name(db).as_ref()) | ||
309 | && (mode == LookupMode::Path) | ||
310 | } | ||
311 | _ => false, | ||
312 | } | ||
313 | } | ||
314 | |||
315 | pub(crate) fn implements_trait( | ||
316 | ty: &Canonical<Ty>, | ||
317 | db: &impl HirDatabase, | ||
318 | resolver: &Resolver, | ||
319 | krate: Crate, | ||
320 | trait_: Trait, | ||
321 | ) -> bool { | ||
322 | if ty.value.inherent_trait() == Some(trait_) { | ||
323 | // FIXME this is a bit of a hack, since Chalk should say the same thing | ||
324 | // anyway, but currently Chalk doesn't implement `dyn/impl Trait` yet | ||
325 | return true; | ||
326 | } | ||
327 | let env = lower::trait_env(db, resolver); | ||
328 | let goal = generic_implements_goal(db, env, trait_, ty.clone()); | ||
329 | let solution = db.trait_solve(krate, goal); | ||
330 | |||
331 | solution.is_some() | ||
332 | } | ||
333 | |||
334 | impl Ty { | ||
335 | // This would be nicer if it just returned an iterator, but that runs into | ||
336 | // lifetime problems, because we need to borrow temp `CrateImplBlocks`. | ||
337 | pub fn iterate_impl_items<T>( | ||
338 | self, | ||
339 | db: &impl HirDatabase, | ||
340 | krate: Crate, | ||
341 | mut callback: impl FnMut(AssocItem) -> Option<T>, | ||
342 | ) -> Option<T> { | ||
343 | for krate in def_crates(db, krate, &self)? { | ||
344 | let impls = db.impls_in_crate(krate); | ||
345 | |||
346 | for impl_block in impls.lookup_impl_blocks(&self) { | ||
347 | for item in impl_block.items(db) { | ||
348 | if let Some(result) = callback(item) { | ||
349 | return Some(result); | ||
350 | } | ||
351 | } | ||
352 | } | ||
353 | } | ||
354 | None | ||
355 | } | ||
356 | } | ||
357 | |||
358 | /// This creates Substs for a trait with the given Self type and type variables | ||
359 | /// for all other parameters, to query Chalk with it. | ||
360 | fn generic_implements_goal( | ||
361 | db: &impl HirDatabase, | ||
362 | env: Arc<TraitEnvironment>, | ||
363 | trait_: Trait, | ||
364 | self_ty: Canonical<Ty>, | ||
365 | ) -> Canonical<InEnvironment<super::Obligation>> { | ||
366 | let num_vars = self_ty.num_vars; | ||
367 | let substs = super::Substs::build_for_def(db, trait_) | ||
368 | .push(self_ty.value) | ||
369 | .fill_with_bound_vars(num_vars as u32) | ||
370 | .build(); | ||
371 | let num_vars = substs.len() - 1 + self_ty.num_vars; | ||
372 | let trait_ref = TraitRef { trait_, substs }; | ||
373 | let obligation = super::Obligation::Trait(trait_ref); | ||
374 | Canonical { num_vars, value: InEnvironment::new(env, obligation) } | ||
375 | } | ||
diff --git a/crates/ra_hir/src/ty/op.rs b/crates/ra_hir/src/ty/op.rs deleted file mode 100644 index bcfa3a6a2..000000000 --- a/crates/ra_hir/src/ty/op.rs +++ /dev/null | |||
@@ -1,52 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use super::{InferTy, Ty, TypeCtor}; | ||
4 | use crate::{ | ||
5 | expr::{BinaryOp, CmpOp}, | ||
6 | ty::ApplicationTy, | ||
7 | }; | ||
8 | |||
9 | pub(super) fn binary_op_return_ty(op: BinaryOp, rhs_ty: Ty) -> Ty { | ||
10 | match op { | ||
11 | BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => Ty::simple(TypeCtor::Bool), | ||
12 | BinaryOp::Assignment { .. } => Ty::unit(), | ||
13 | BinaryOp::ArithOp(_) => match rhs_ty { | ||
14 | Ty::Apply(ApplicationTy { ctor, .. }) => match ctor { | ||
15 | TypeCtor::Int(..) | TypeCtor::Float(..) => rhs_ty, | ||
16 | _ => Ty::Unknown, | ||
17 | }, | ||
18 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => rhs_ty, | ||
19 | _ => Ty::Unknown, | ||
20 | }, | ||
21 | } | ||
22 | } | ||
23 | |||
24 | pub(super) fn binary_op_rhs_expectation(op: BinaryOp, lhs_ty: Ty) -> Ty { | ||
25 | match op { | ||
26 | BinaryOp::LogicOp(..) => Ty::simple(TypeCtor::Bool), | ||
27 | BinaryOp::Assignment { op: None } | BinaryOp::CmpOp(CmpOp::Eq { negated: _ }) => { | ||
28 | match lhs_ty { | ||
29 | Ty::Apply(ApplicationTy { ctor, .. }) => match ctor { | ||
30 | TypeCtor::Int(..) | ||
31 | | TypeCtor::Float(..) | ||
32 | | TypeCtor::Str | ||
33 | | TypeCtor::Char | ||
34 | | TypeCtor::Bool => lhs_ty, | ||
35 | _ => Ty::Unknown, | ||
36 | }, | ||
37 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => lhs_ty, | ||
38 | _ => Ty::Unknown, | ||
39 | } | ||
40 | } | ||
41 | BinaryOp::CmpOp(CmpOp::Ord { .. }) | ||
42 | | BinaryOp::Assignment { op: Some(_) } | ||
43 | | BinaryOp::ArithOp(_) => match lhs_ty { | ||
44 | Ty::Apply(ApplicationTy { ctor, .. }) => match ctor { | ||
45 | TypeCtor::Int(..) | TypeCtor::Float(..) => lhs_ty, | ||
46 | _ => Ty::Unknown, | ||
47 | }, | ||
48 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => lhs_ty, | ||
49 | _ => Ty::Unknown, | ||
50 | }, | ||
51 | } | ||
52 | } | ||
diff --git a/crates/ra_hir/src/ty/primitive.rs b/crates/ra_hir/src/ty/primitive.rs deleted file mode 100644 index 47789db87..000000000 --- a/crates/ra_hir/src/ty/primitive.rs +++ /dev/null | |||
@@ -1,160 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use std::fmt; | ||
4 | |||
5 | pub use hir_def::builtin_type::{FloatBitness, IntBitness, Signedness}; | ||
6 | |||
7 | #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] | ||
8 | pub enum Uncertain<T> { | ||
9 | Unknown, | ||
10 | Known(T), | ||
11 | } | ||
12 | |||
13 | impl From<IntTy> for Uncertain<IntTy> { | ||
14 | fn from(ty: IntTy) -> Self { | ||
15 | Uncertain::Known(ty) | ||
16 | } | ||
17 | } | ||
18 | |||
19 | impl fmt::Display for Uncertain<IntTy> { | ||
20 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
21 | match *self { | ||
22 | Uncertain::Unknown => write!(f, "{{integer}}"), | ||
23 | Uncertain::Known(ty) => write!(f, "{}", ty), | ||
24 | } | ||
25 | } | ||
26 | } | ||
27 | |||
28 | impl From<FloatTy> for Uncertain<FloatTy> { | ||
29 | fn from(ty: FloatTy) -> Self { | ||
30 | Uncertain::Known(ty) | ||
31 | } | ||
32 | } | ||
33 | |||
34 | impl fmt::Display for Uncertain<FloatTy> { | ||
35 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
36 | match *self { | ||
37 | Uncertain::Unknown => write!(f, "{{float}}"), | ||
38 | Uncertain::Known(ty) => write!(f, "{}", ty), | ||
39 | } | ||
40 | } | ||
41 | } | ||
42 | |||
43 | #[derive(Copy, Clone, Eq, PartialEq, Hash)] | ||
44 | pub struct IntTy { | ||
45 | pub signedness: Signedness, | ||
46 | pub bitness: IntBitness, | ||
47 | } | ||
48 | |||
49 | impl fmt::Debug for IntTy { | ||
50 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
51 | fmt::Display::fmt(self, f) | ||
52 | } | ||
53 | } | ||
54 | |||
55 | impl fmt::Display for IntTy { | ||
56 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
57 | write!(f, "{}", self.ty_to_string()) | ||
58 | } | ||
59 | } | ||
60 | |||
61 | impl IntTy { | ||
62 | pub fn isize() -> IntTy { | ||
63 | IntTy { signedness: Signedness::Signed, bitness: IntBitness::Xsize } | ||
64 | } | ||
65 | |||
66 | pub fn i8() -> IntTy { | ||
67 | IntTy { signedness: Signedness::Signed, bitness: IntBitness::X8 } | ||
68 | } | ||
69 | |||
70 | pub fn i16() -> IntTy { | ||
71 | IntTy { signedness: Signedness::Signed, bitness: IntBitness::X16 } | ||
72 | } | ||
73 | |||
74 | pub fn i32() -> IntTy { | ||
75 | IntTy { signedness: Signedness::Signed, bitness: IntBitness::X32 } | ||
76 | } | ||
77 | |||
78 | pub fn i64() -> IntTy { | ||
79 | IntTy { signedness: Signedness::Signed, bitness: IntBitness::X64 } | ||
80 | } | ||
81 | |||
82 | pub fn i128() -> IntTy { | ||
83 | IntTy { signedness: Signedness::Signed, bitness: IntBitness::X128 } | ||
84 | } | ||
85 | |||
86 | pub fn usize() -> IntTy { | ||
87 | IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::Xsize } | ||
88 | } | ||
89 | |||
90 | pub fn u8() -> IntTy { | ||
91 | IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X8 } | ||
92 | } | ||
93 | |||
94 | pub fn u16() -> IntTy { | ||
95 | IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X16 } | ||
96 | } | ||
97 | |||
98 | pub fn u32() -> IntTy { | ||
99 | IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X32 } | ||
100 | } | ||
101 | |||
102 | pub fn u64() -> IntTy { | ||
103 | IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X64 } | ||
104 | } | ||
105 | |||
106 | pub fn u128() -> IntTy { | ||
107 | IntTy { signedness: Signedness::Unsigned, bitness: IntBitness::X128 } | ||
108 | } | ||
109 | |||
110 | pub(crate) fn ty_to_string(self) -> &'static str { | ||
111 | match (self.signedness, self.bitness) { | ||
112 | (Signedness::Signed, IntBitness::Xsize) => "isize", | ||
113 | (Signedness::Signed, IntBitness::X8) => "i8", | ||
114 | (Signedness::Signed, IntBitness::X16) => "i16", | ||
115 | (Signedness::Signed, IntBitness::X32) => "i32", | ||
116 | (Signedness::Signed, IntBitness::X64) => "i64", | ||
117 | (Signedness::Signed, IntBitness::X128) => "i128", | ||
118 | (Signedness::Unsigned, IntBitness::Xsize) => "usize", | ||
119 | (Signedness::Unsigned, IntBitness::X8) => "u8", | ||
120 | (Signedness::Unsigned, IntBitness::X16) => "u16", | ||
121 | (Signedness::Unsigned, IntBitness::X32) => "u32", | ||
122 | (Signedness::Unsigned, IntBitness::X64) => "u64", | ||
123 | (Signedness::Unsigned, IntBitness::X128) => "u128", | ||
124 | } | ||
125 | } | ||
126 | } | ||
127 | |||
128 | #[derive(Copy, Clone, PartialEq, Eq, Hash)] | ||
129 | pub struct FloatTy { | ||
130 | pub bitness: FloatBitness, | ||
131 | } | ||
132 | |||
133 | impl fmt::Debug for FloatTy { | ||
134 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
135 | fmt::Display::fmt(self, f) | ||
136 | } | ||
137 | } | ||
138 | |||
139 | impl fmt::Display for FloatTy { | ||
140 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
141 | write!(f, "{}", self.ty_to_string()) | ||
142 | } | ||
143 | } | ||
144 | |||
145 | impl FloatTy { | ||
146 | pub fn f32() -> FloatTy { | ||
147 | FloatTy { bitness: FloatBitness::X32 } | ||
148 | } | ||
149 | |||
150 | pub fn f64() -> FloatTy { | ||
151 | FloatTy { bitness: FloatBitness::X64 } | ||
152 | } | ||
153 | |||
154 | pub(crate) fn ty_to_string(self) -> &'static str { | ||
155 | match self.bitness { | ||
156 | FloatBitness::X32 => "f32", | ||
157 | FloatBitness::X64 => "f64", | ||
158 | } | ||
159 | } | ||
160 | } | ||
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs deleted file mode 100644 index 3209c66bd..000000000 --- a/crates/ra_hir/src/ty/tests.rs +++ /dev/null | |||
@@ -1,4895 +0,0 @@ | |||
1 | mod never_type; | ||
2 | mod coercion; | ||
3 | |||
4 | use std::fmt::Write; | ||
5 | use std::sync::Arc; | ||
6 | |||
7 | use insta::assert_snapshot; | ||
8 | use ra_db::{fixture::WithFixture, salsa::Database, FilePosition, SourceDatabase}; | ||
9 | use ra_syntax::{ | ||
10 | algo, | ||
11 | ast::{self, AstNode}, | ||
12 | SyntaxKind::*, | ||
13 | }; | ||
14 | use rustc_hash::FxHashSet; | ||
15 | use test_utils::covers; | ||
16 | |||
17 | use crate::{ | ||
18 | expr::BodySourceMap, test_db::TestDB, ty::display::HirDisplay, ty::InferenceResult, Source, | ||
19 | SourceAnalyzer, | ||
20 | }; | ||
21 | |||
22 | // These tests compare the inference results for all expressions in a file | ||
23 | // against snapshots of the expected results using insta. Use cargo-insta to | ||
24 | // update the snapshots. | ||
25 | |||
26 | #[test] | ||
27 | fn cfg_impl_block() { | ||
28 | let (db, pos) = TestDB::with_position( | ||
29 | r#" | ||
30 | //- /main.rs crate:main deps:foo cfg:test | ||
31 | use foo::S as T; | ||
32 | struct S; | ||
33 | |||
34 | #[cfg(test)] | ||
35 | impl S { | ||
36 | fn foo1(&self) -> i32 { 0 } | ||
37 | } | ||
38 | |||
39 | #[cfg(not(test))] | ||
40 | impl S { | ||
41 | fn foo2(&self) -> i32 { 0 } | ||
42 | } | ||
43 | |||
44 | fn test() { | ||
45 | let t = (S.foo1(), S.foo2(), T.foo3(), T.foo4()); | ||
46 | t<|>; | ||
47 | } | ||
48 | |||
49 | //- /foo.rs crate:foo | ||
50 | struct S; | ||
51 | |||
52 | #[cfg(not(test))] | ||
53 | impl S { | ||
54 | fn foo3(&self) -> i32 { 0 } | ||
55 | } | ||
56 | |||
57 | #[cfg(test)] | ||
58 | impl S { | ||
59 | fn foo4(&self) -> i32 { 0 } | ||
60 | } | ||
61 | "#, | ||
62 | ); | ||
63 | assert_eq!("(i32, {unknown}, i32, {unknown})", type_at_pos(&db, pos)); | ||
64 | } | ||
65 | |||
66 | #[test] | ||
67 | fn infer_await() { | ||
68 | let (db, pos) = TestDB::with_position( | ||
69 | r#" | ||
70 | //- /main.rs crate:main deps:std | ||
71 | |||
72 | struct IntFuture; | ||
73 | |||
74 | impl Future for IntFuture { | ||
75 | type Output = u64; | ||
76 | } | ||
77 | |||
78 | fn test() { | ||
79 | let r = IntFuture; | ||
80 | let v = r.await; | ||
81 | v<|>; | ||
82 | } | ||
83 | |||
84 | //- /std.rs crate:std | ||
85 | #[prelude_import] use future::*; | ||
86 | mod future { | ||
87 | trait Future { | ||
88 | type Output; | ||
89 | } | ||
90 | } | ||
91 | |||
92 | "#, | ||
93 | ); | ||
94 | assert_eq!("u64", type_at_pos(&db, pos)); | ||
95 | } | ||
96 | |||
97 | #[test] | ||
98 | fn infer_box() { | ||
99 | let (db, pos) = TestDB::with_position( | ||
100 | r#" | ||
101 | //- /main.rs crate:main deps:std | ||
102 | |||
103 | fn test() { | ||
104 | let x = box 1; | ||
105 | let t = (x, box x, box &1, box [1]); | ||
106 | t<|>; | ||
107 | } | ||
108 | |||
109 | //- /std.rs crate:std | ||
110 | #[prelude_import] use prelude::*; | ||
111 | mod prelude {} | ||
112 | |||
113 | mod boxed { | ||
114 | pub struct Box<T: ?Sized> { | ||
115 | inner: *mut T, | ||
116 | } | ||
117 | } | ||
118 | |||
119 | "#, | ||
120 | ); | ||
121 | assert_eq!("(Box<i32>, Box<Box<i32>>, Box<&i32>, Box<[i32;_]>)", type_at_pos(&db, pos)); | ||
122 | } | ||
123 | |||
124 | #[test] | ||
125 | fn infer_adt_self() { | ||
126 | let (db, pos) = TestDB::with_position( | ||
127 | r#" | ||
128 | //- /main.rs | ||
129 | enum Nat { Succ(Self), Demo(Nat), Zero } | ||
130 | |||
131 | fn test() { | ||
132 | let foo: Nat = Nat::Zero; | ||
133 | if let Nat::Succ(x) = foo { | ||
134 | x<|> | ||
135 | } | ||
136 | } | ||
137 | |||
138 | "#, | ||
139 | ); | ||
140 | assert_eq!("Nat", type_at_pos(&db, pos)); | ||
141 | } | ||
142 | |||
143 | #[test] | ||
144 | fn infer_try() { | ||
145 | let (db, pos) = TestDB::with_position( | ||
146 | r#" | ||
147 | //- /main.rs crate:main deps:std | ||
148 | |||
149 | fn test() { | ||
150 | let r: Result<i32, u64> = Result::Ok(1); | ||
151 | let v = r?; | ||
152 | v<|>; | ||
153 | } | ||
154 | |||
155 | //- /std.rs crate:std | ||
156 | |||
157 | #[prelude_import] use ops::*; | ||
158 | mod ops { | ||
159 | trait Try { | ||
160 | type Ok; | ||
161 | type Error; | ||
162 | } | ||
163 | } | ||
164 | |||
165 | #[prelude_import] use result::*; | ||
166 | mod result { | ||
167 | enum Result<O, E> { | ||
168 | Ok(O), | ||
169 | Err(E) | ||
170 | } | ||
171 | |||
172 | impl<O, E> crate::ops::Try for Result<O, E> { | ||
173 | type Ok = O; | ||
174 | type Error = E; | ||
175 | } | ||
176 | } | ||
177 | |||
178 | "#, | ||
179 | ); | ||
180 | assert_eq!("i32", type_at_pos(&db, pos)); | ||
181 | } | ||
182 | |||
183 | #[test] | ||
184 | fn infer_for_loop() { | ||
185 | let (db, pos) = TestDB::with_position( | ||
186 | r#" | ||
187 | //- /main.rs crate:main deps:std | ||
188 | |||
189 | use std::collections::Vec; | ||
190 | |||
191 | fn test() { | ||
192 | let v = Vec::new(); | ||
193 | v.push("foo"); | ||
194 | for x in v { | ||
195 | x<|>; | ||
196 | } | ||
197 | } | ||
198 | |||
199 | //- /std.rs crate:std | ||
200 | |||
201 | #[prelude_import] use iter::*; | ||
202 | mod iter { | ||
203 | trait IntoIterator { | ||
204 | type Item; | ||
205 | } | ||
206 | } | ||
207 | |||
208 | mod collections { | ||
209 | struct Vec<T> {} | ||
210 | impl<T> Vec<T> { | ||
211 | fn new() -> Self { Vec {} } | ||
212 | fn push(&mut self, t: T) { } | ||
213 | } | ||
214 | |||
215 | impl<T> crate::iter::IntoIterator for Vec<T> { | ||
216 | type Item=T; | ||
217 | } | ||
218 | } | ||
219 | "#, | ||
220 | ); | ||
221 | assert_eq!("&str", type_at_pos(&db, pos)); | ||
222 | } | ||
223 | |||
224 | #[test] | ||
225 | fn infer_while_let() { | ||
226 | let (db, pos) = TestDB::with_position( | ||
227 | r#" | ||
228 | //- /main.rs | ||
229 | enum Option<T> { Some(T), None } | ||
230 | |||
231 | fn test() { | ||
232 | let foo: Option<f32> = None; | ||
233 | while let Option::Some(x) = foo { | ||
234 | <|>x | ||
235 | } | ||
236 | } | ||
237 | |||
238 | "#, | ||
239 | ); | ||
240 | assert_eq!("f32", type_at_pos(&db, pos)); | ||
241 | } | ||
242 | |||
243 | #[test] | ||
244 | fn infer_basics() { | ||
245 | assert_snapshot!( | ||
246 | infer(r#" | ||
247 | fn test(a: u32, b: isize, c: !, d: &str) { | ||
248 | a; | ||
249 | b; | ||
250 | c; | ||
251 | d; | ||
252 | 1usize; | ||
253 | 1isize; | ||
254 | "test"; | ||
255 | 1.0f32; | ||
256 | }"#), | ||
257 | @r###" | ||
258 | [9; 10) 'a': u32 | ||
259 | [17; 18) 'b': isize | ||
260 | [27; 28) 'c': ! | ||
261 | [33; 34) 'd': &str | ||
262 | [42; 121) '{ ...f32; }': ! | ||
263 | [48; 49) 'a': u32 | ||
264 | [55; 56) 'b': isize | ||
265 | [62; 63) 'c': ! | ||
266 | [69; 70) 'd': &str | ||
267 | [76; 82) '1usize': usize | ||
268 | [88; 94) '1isize': isize | ||
269 | [100; 106) '"test"': &str | ||
270 | [112; 118) '1.0f32': f32 | ||
271 | "### | ||
272 | ); | ||
273 | } | ||
274 | |||
275 | #[test] | ||
276 | fn infer_let() { | ||
277 | assert_snapshot!( | ||
278 | infer(r#" | ||
279 | fn test() { | ||
280 | let a = 1isize; | ||
281 | let b: usize = 1; | ||
282 | let c = b; | ||
283 | let d: u32; | ||
284 | let e; | ||
285 | let f: i32 = e; | ||
286 | } | ||
287 | "#), | ||
288 | @r###" | ||
289 | [11; 118) '{ ...= e; }': () | ||
290 | [21; 22) 'a': isize | ||
291 | [25; 31) '1isize': isize | ||
292 | [41; 42) 'b': usize | ||
293 | [52; 53) '1': usize | ||
294 | [63; 64) 'c': usize | ||
295 | [67; 68) 'b': usize | ||
296 | [78; 79) 'd': u32 | ||
297 | [94; 95) 'e': i32 | ||
298 | [105; 106) 'f': i32 | ||
299 | [114; 115) 'e': i32 | ||
300 | "### | ||
301 | ); | ||
302 | } | ||
303 | |||
304 | #[test] | ||
305 | fn infer_paths() { | ||
306 | assert_snapshot!( | ||
307 | infer(r#" | ||
308 | fn a() -> u32 { 1 } | ||
309 | |||
310 | mod b { | ||
311 | fn c() -> u32 { 1 } | ||
312 | } | ||
313 | |||
314 | fn test() { | ||
315 | a(); | ||
316 | b::c(); | ||
317 | } | ||
318 | "#), | ||
319 | @r###" | ||
320 | [15; 20) '{ 1 }': u32 | ||
321 | [17; 18) '1': u32 | ||
322 | [48; 53) '{ 1 }': u32 | ||
323 | [50; 51) '1': u32 | ||
324 | [67; 91) '{ ...c(); }': () | ||
325 | [73; 74) 'a': fn a() -> u32 | ||
326 | [73; 76) 'a()': u32 | ||
327 | [82; 86) 'b::c': fn c() -> u32 | ||
328 | [82; 88) 'b::c()': u32 | ||
329 | "### | ||
330 | ); | ||
331 | } | ||
332 | |||
333 | #[test] | ||
334 | fn infer_path_type() { | ||
335 | assert_snapshot!( | ||
336 | infer(r#" | ||
337 | struct S; | ||
338 | |||
339 | impl S { | ||
340 | fn foo() -> i32 { 1 } | ||
341 | } | ||
342 | |||
343 | fn test() { | ||
344 | S::foo(); | ||
345 | <S>::foo(); | ||
346 | } | ||
347 | "#), | ||
348 | @r###" | ||
349 | [41; 46) '{ 1 }': i32 | ||
350 | [43; 44) '1': i32 | ||
351 | [60; 93) '{ ...o(); }': () | ||
352 | [66; 72) 'S::foo': fn foo() -> i32 | ||
353 | [66; 74) 'S::foo()': i32 | ||
354 | [80; 88) '<S>::foo': fn foo() -> i32 | ||
355 | [80; 90) '<S>::foo()': i32 | ||
356 | "### | ||
357 | ); | ||
358 | } | ||
359 | |||
360 | #[test] | ||
361 | fn infer_slice_method() { | ||
362 | assert_snapshot!( | ||
363 | infer(r#" | ||
364 | #[lang = "slice"] | ||
365 | impl<T> [T] { | ||
366 | fn foo(&self) -> T { | ||
367 | loop {} | ||
368 | } | ||
369 | } | ||
370 | |||
371 | #[lang = "slice_alloc"] | ||
372 | impl<T> [T] {} | ||
373 | |||
374 | fn test() { | ||
375 | <[_]>::foo(b"foo"); | ||
376 | } | ||
377 | "#), | ||
378 | @r###" | ||
379 | [45; 49) 'self': &[T] | ||
380 | [56; 79) '{ ... }': T | ||
381 | [66; 73) 'loop {}': ! | ||
382 | [71; 73) '{}': () | ||
383 | [133; 160) '{ ...o"); }': () | ||
384 | [139; 149) '<[_]>::foo': fn foo<u8>(&[T]) -> T | ||
385 | [139; 157) '<[_]>:..."foo")': u8 | ||
386 | [150; 156) 'b"foo"': &[u8] | ||
387 | "### | ||
388 | ); | ||
389 | } | ||
390 | |||
391 | #[test] | ||
392 | fn infer_struct() { | ||
393 | assert_snapshot!( | ||
394 | infer(r#" | ||
395 | struct A { | ||
396 | b: B, | ||
397 | c: C, | ||
398 | } | ||
399 | struct B; | ||
400 | struct C(usize); | ||
401 | |||
402 | fn test() { | ||
403 | let c = C(1); | ||
404 | B; | ||
405 | let a: A = A { b: B, c: C(1) }; | ||
406 | a.b; | ||
407 | a.c; | ||
408 | } | ||
409 | "#), | ||
410 | @r###" | ||
411 | [72; 154) '{ ...a.c; }': () | ||
412 | [82; 83) 'c': C | ||
413 | [86; 87) 'C': C(usize) -> C | ||
414 | [86; 90) 'C(1)': C | ||
415 | [88; 89) '1': usize | ||
416 | [96; 97) 'B': B | ||
417 | [107; 108) 'a': A | ||
418 | [114; 133) 'A { b:...C(1) }': A | ||
419 | [121; 122) 'B': B | ||
420 | [127; 128) 'C': C(usize) -> C | ||
421 | [127; 131) 'C(1)': C | ||
422 | [129; 130) '1': usize | ||
423 | [139; 140) 'a': A | ||
424 | [139; 142) 'a.b': B | ||
425 | [148; 149) 'a': A | ||
426 | [148; 151) 'a.c': C | ||
427 | "### | ||
428 | ); | ||
429 | } | ||
430 | |||
431 | #[test] | ||
432 | fn infer_enum() { | ||
433 | assert_snapshot!( | ||
434 | infer(r#" | ||
435 | enum E { | ||
436 | V1 { field: u32 }, | ||
437 | V2 | ||
438 | } | ||
439 | fn test() { | ||
440 | E::V1 { field: 1 }; | ||
441 | E::V2; | ||
442 | }"#), | ||
443 | @r###" | ||
444 | [48; 82) '{ E:...:V2; }': () | ||
445 | [52; 70) 'E::V1 ...d: 1 }': E | ||
446 | [67; 68) '1': u32 | ||
447 | [74; 79) 'E::V2': E | ||
448 | "### | ||
449 | ); | ||
450 | } | ||
451 | |||
452 | #[test] | ||
453 | fn infer_refs() { | ||
454 | assert_snapshot!( | ||
455 | infer(r#" | ||
456 | fn test(a: &u32, b: &mut u32, c: *const u32, d: *mut u32) { | ||
457 | a; | ||
458 | *a; | ||
459 | &a; | ||
460 | &mut a; | ||
461 | b; | ||
462 | *b; | ||
463 | &b; | ||
464 | c; | ||
465 | *c; | ||
466 | d; | ||
467 | *d; | ||
468 | } | ||
469 | "#), | ||
470 | @r###" | ||
471 | [9; 10) 'a': &u32 | ||
472 | [18; 19) 'b': &mut u32 | ||
473 | [31; 32) 'c': *const u32 | ||
474 | [46; 47) 'd': *mut u32 | ||
475 | [59; 150) '{ ... *d; }': () | ||
476 | [65; 66) 'a': &u32 | ||
477 | [72; 74) '*a': u32 | ||
478 | [73; 74) 'a': &u32 | ||
479 | [80; 82) '&a': &&u32 | ||
480 | [81; 82) 'a': &u32 | ||
481 | [88; 94) '&mut a': &mut &u32 | ||
482 | [93; 94) 'a': &u32 | ||
483 | [100; 101) 'b': &mut u32 | ||
484 | [107; 109) '*b': u32 | ||
485 | [108; 109) 'b': &mut u32 | ||
486 | [115; 117) '&b': &&mut u32 | ||
487 | [116; 117) 'b': &mut u32 | ||
488 | [123; 124) 'c': *const u32 | ||
489 | [130; 132) '*c': u32 | ||
490 | [131; 132) 'c': *const u32 | ||
491 | [138; 139) 'd': *mut u32 | ||
492 | [145; 147) '*d': u32 | ||
493 | [146; 147) 'd': *mut u32 | ||
494 | "### | ||
495 | ); | ||
496 | } | ||
497 | |||
498 | #[test] | ||
499 | fn infer_literals() { | ||
500 | assert_snapshot!( | ||
501 | infer(r##" | ||
502 | fn test() { | ||
503 | 5i32; | ||
504 | 5f32; | ||
505 | 5f64; | ||
506 | "hello"; | ||
507 | b"bytes"; | ||
508 | 'c'; | ||
509 | b'b'; | ||
510 | 3.14; | ||
511 | 5000; | ||
512 | false; | ||
513 | true; | ||
514 | r#" | ||
515 | //! doc | ||
516 | // non-doc | ||
517 | mod foo {} | ||
518 | "#; | ||
519 | br#"yolo"#; | ||
520 | } | ||
521 | "##), | ||
522 | @r###" | ||
523 | [11; 221) '{ ...o"#; }': () | ||
524 | [17; 21) '5i32': i32 | ||
525 | [27; 31) '5f32': f32 | ||
526 | [37; 41) '5f64': f64 | ||
527 | [47; 54) '"hello"': &str | ||
528 | [60; 68) 'b"bytes"': &[u8] | ||
529 | [74; 77) ''c'': char | ||
530 | [83; 87) 'b'b'': u8 | ||
531 | [93; 97) '3.14': f64 | ||
532 | [103; 107) '5000': i32 | ||
533 | [113; 118) 'false': bool | ||
534 | [124; 128) 'true': bool | ||
535 | [134; 202) 'r#" ... "#': &str | ||
536 | [208; 218) 'br#"yolo"#': &[u8] | ||
537 | "### | ||
538 | ); | ||
539 | } | ||
540 | |||
541 | #[test] | ||
542 | fn infer_unary_op() { | ||
543 | assert_snapshot!( | ||
544 | infer(r#" | ||
545 | enum SomeType {} | ||
546 | |||
547 | fn test(x: SomeType) { | ||
548 | let b = false; | ||
549 | let c = !b; | ||
550 | let a = 100; | ||
551 | let d: i128 = -a; | ||
552 | let e = -100; | ||
553 | let f = !!!true; | ||
554 | let g = !42; | ||
555 | let h = !10u32; | ||
556 | let j = !a; | ||
557 | -3.14; | ||
558 | !3; | ||
559 | -x; | ||
560 | !x; | ||
561 | -"hello"; | ||
562 | !"hello"; | ||
563 | } | ||
564 | "#), | ||
565 | @r###" | ||
566 | [27; 28) 'x': SomeType | ||
567 | [40; 272) '{ ...lo"; }': () | ||
568 | [50; 51) 'b': bool | ||
569 | [54; 59) 'false': bool | ||
570 | [69; 70) 'c': bool | ||
571 | [73; 75) '!b': bool | ||
572 | [74; 75) 'b': bool | ||
573 | [85; 86) 'a': i128 | ||
574 | [89; 92) '100': i128 | ||
575 | [102; 103) 'd': i128 | ||
576 | [112; 114) '-a': i128 | ||
577 | [113; 114) 'a': i128 | ||
578 | [124; 125) 'e': i32 | ||
579 | [128; 132) '-100': i32 | ||
580 | [129; 132) '100': i32 | ||
581 | [142; 143) 'f': bool | ||
582 | [146; 153) '!!!true': bool | ||
583 | [147; 153) '!!true': bool | ||
584 | [148; 153) '!true': bool | ||
585 | [149; 153) 'true': bool | ||
586 | [163; 164) 'g': i32 | ||
587 | [167; 170) '!42': i32 | ||
588 | [168; 170) '42': i32 | ||
589 | [180; 181) 'h': u32 | ||
590 | [184; 190) '!10u32': u32 | ||
591 | [185; 190) '10u32': u32 | ||
592 | [200; 201) 'j': i128 | ||
593 | [204; 206) '!a': i128 | ||
594 | [205; 206) 'a': i128 | ||
595 | [212; 217) '-3.14': f64 | ||
596 | [213; 217) '3.14': f64 | ||
597 | [223; 225) '!3': i32 | ||
598 | [224; 225) '3': i32 | ||
599 | [231; 233) '-x': {unknown} | ||
600 | [232; 233) 'x': SomeType | ||
601 | [239; 241) '!x': {unknown} | ||
602 | [240; 241) 'x': SomeType | ||
603 | [247; 255) '-"hello"': {unknown} | ||
604 | [248; 255) '"hello"': &str | ||
605 | [261; 269) '!"hello"': {unknown} | ||
606 | [262; 269) '"hello"': &str | ||
607 | "### | ||
608 | ); | ||
609 | } | ||
610 | |||
611 | #[test] | ||
612 | fn infer_backwards() { | ||
613 | assert_snapshot!( | ||
614 | infer(r#" | ||
615 | fn takes_u32(x: u32) {} | ||
616 | |||
617 | struct S { i32_field: i32 } | ||
618 | |||
619 | fn test() -> &mut &f64 { | ||
620 | let a = unknown_function(); | ||
621 | takes_u32(a); | ||
622 | let b = unknown_function(); | ||
623 | S { i32_field: b }; | ||
624 | let c = unknown_function(); | ||
625 | &mut &c | ||
626 | } | ||
627 | "#), | ||
628 | @r###" | ||
629 | [14; 15) 'x': u32 | ||
630 | [22; 24) '{}': () | ||
631 | [78; 231) '{ ...t &c }': &mut &f64 | ||
632 | [88; 89) 'a': u32 | ||
633 | [92; 108) 'unknow...nction': {unknown} | ||
634 | [92; 110) 'unknow...tion()': u32 | ||
635 | [116; 125) 'takes_u32': fn takes_u32(u32) -> () | ||
636 | [116; 128) 'takes_u32(a)': () | ||
637 | [126; 127) 'a': u32 | ||
638 | [138; 139) 'b': i32 | ||
639 | [142; 158) 'unknow...nction': {unknown} | ||
640 | [142; 160) 'unknow...tion()': i32 | ||
641 | [166; 184) 'S { i3...d: b }': S | ||
642 | [181; 182) 'b': i32 | ||
643 | [194; 195) 'c': f64 | ||
644 | [198; 214) 'unknow...nction': {unknown} | ||
645 | [198; 216) 'unknow...tion()': f64 | ||
646 | [222; 229) '&mut &c': &mut &f64 | ||
647 | [227; 229) '&c': &f64 | ||
648 | [228; 229) 'c': f64 | ||
649 | "### | ||
650 | ); | ||
651 | } | ||
652 | |||
653 | #[test] | ||
654 | fn infer_self() { | ||
655 | assert_snapshot!( | ||
656 | infer(r#" | ||
657 | struct S; | ||
658 | |||
659 | impl S { | ||
660 | fn test(&self) { | ||
661 | self; | ||
662 | } | ||
663 | fn test2(self: &Self) { | ||
664 | self; | ||
665 | } | ||
666 | fn test3() -> Self { | ||
667 | S {} | ||
668 | } | ||
669 | fn test4() -> Self { | ||
670 | Self {} | ||
671 | } | ||
672 | } | ||
673 | "#), | ||
674 | @r###" | ||
675 | [34; 38) 'self': &S | ||
676 | [40; 61) '{ ... }': () | ||
677 | [50; 54) 'self': &S | ||
678 | [75; 79) 'self': &S | ||
679 | [88; 109) '{ ... }': () | ||
680 | [98; 102) 'self': &S | ||
681 | [133; 153) '{ ... }': S | ||
682 | [143; 147) 'S {}': S | ||
683 | [177; 200) '{ ... }': S | ||
684 | [187; 194) 'Self {}': S | ||
685 | "### | ||
686 | ); | ||
687 | } | ||
688 | |||
689 | #[test] | ||
690 | fn infer_binary_op() { | ||
691 | assert_snapshot!( | ||
692 | infer(r#" | ||
693 | fn f(x: bool) -> i32 { | ||
694 | 0i32 | ||
695 | } | ||
696 | |||
697 | fn test() -> bool { | ||
698 | let x = a && b; | ||
699 | let y = true || false; | ||
700 | let z = x == y; | ||
701 | let t = x != y; | ||
702 | let minus_forty: isize = -40isize; | ||
703 | let h = minus_forty <= CONST_2; | ||
704 | let c = f(z || y) + 5; | ||
705 | let d = b; | ||
706 | let g = minus_forty ^= i; | ||
707 | let ten: usize = 10; | ||
708 | let ten_is_eleven = ten == some_num; | ||
709 | |||
710 | ten < 3 | ||
711 | } | ||
712 | "#), | ||
713 | @r###" | ||
714 | [6; 7) 'x': bool | ||
715 | [22; 34) '{ 0i32 }': i32 | ||
716 | [28; 32) '0i32': i32 | ||
717 | [54; 370) '{ ... < 3 }': bool | ||
718 | [64; 65) 'x': bool | ||
719 | [68; 69) 'a': bool | ||
720 | [68; 74) 'a && b': bool | ||
721 | [73; 74) 'b': bool | ||
722 | [84; 85) 'y': bool | ||
723 | [88; 92) 'true': bool | ||
724 | [88; 101) 'true || false': bool | ||
725 | [96; 101) 'false': bool | ||
726 | [111; 112) 'z': bool | ||
727 | [115; 116) 'x': bool | ||
728 | [115; 121) 'x == y': bool | ||
729 | [120; 121) 'y': bool | ||
730 | [131; 132) 't': bool | ||
731 | [135; 136) 'x': bool | ||
732 | [135; 141) 'x != y': bool | ||
733 | [140; 141) 'y': bool | ||
734 | [151; 162) 'minus_forty': isize | ||
735 | [172; 180) '-40isize': isize | ||
736 | [173; 180) '40isize': isize | ||
737 | [190; 191) 'h': bool | ||
738 | [194; 205) 'minus_forty': isize | ||
739 | [194; 216) 'minus_...ONST_2': bool | ||
740 | [209; 216) 'CONST_2': isize | ||
741 | [226; 227) 'c': i32 | ||
742 | [230; 231) 'f': fn f(bool) -> i32 | ||
743 | [230; 239) 'f(z || y)': i32 | ||
744 | [230; 243) 'f(z || y) + 5': i32 | ||
745 | [232; 233) 'z': bool | ||
746 | [232; 238) 'z || y': bool | ||
747 | [237; 238) 'y': bool | ||
748 | [242; 243) '5': i32 | ||
749 | [253; 254) 'd': {unknown} | ||
750 | [257; 258) 'b': {unknown} | ||
751 | [268; 269) 'g': () | ||
752 | [272; 283) 'minus_forty': isize | ||
753 | [272; 288) 'minus_...y ^= i': () | ||
754 | [287; 288) 'i': isize | ||
755 | [298; 301) 'ten': usize | ||
756 | [311; 313) '10': usize | ||
757 | [323; 336) 'ten_is_eleven': bool | ||
758 | [339; 342) 'ten': usize | ||
759 | [339; 354) 'ten == some_num': bool | ||
760 | [346; 354) 'some_num': usize | ||
761 | [361; 364) 'ten': usize | ||
762 | [361; 368) 'ten < 3': bool | ||
763 | [367; 368) '3': usize | ||
764 | "### | ||
765 | ); | ||
766 | } | ||
767 | |||
768 | #[test] | ||
769 | fn infer_field_autoderef() { | ||
770 | assert_snapshot!( | ||
771 | infer(r#" | ||
772 | struct A { | ||
773 | b: B, | ||
774 | } | ||
775 | struct B; | ||
776 | |||
777 | fn test1(a: A) { | ||
778 | let a1 = a; | ||
779 | a1.b; | ||
780 | let a2 = &a; | ||
781 | a2.b; | ||
782 | let a3 = &mut a; | ||
783 | a3.b; | ||
784 | let a4 = &&&&&&&a; | ||
785 | a4.b; | ||
786 | let a5 = &mut &&mut &&mut a; | ||
787 | a5.b; | ||
788 | } | ||
789 | |||
790 | fn test2(a1: *const A, a2: *mut A) { | ||
791 | a1.b; | ||
792 | a2.b; | ||
793 | } | ||
794 | "#), | ||
795 | @r###" | ||
796 | [44; 45) 'a': A | ||
797 | [50; 213) '{ ...5.b; }': () | ||
798 | [60; 62) 'a1': A | ||
799 | [65; 66) 'a': A | ||
800 | [72; 74) 'a1': A | ||
801 | [72; 76) 'a1.b': B | ||
802 | [86; 88) 'a2': &A | ||
803 | [91; 93) '&a': &A | ||
804 | [92; 93) 'a': A | ||
805 | [99; 101) 'a2': &A | ||
806 | [99; 103) 'a2.b': B | ||
807 | [113; 115) 'a3': &mut A | ||
808 | [118; 124) '&mut a': &mut A | ||
809 | [123; 124) 'a': A | ||
810 | [130; 132) 'a3': &mut A | ||
811 | [130; 134) 'a3.b': B | ||
812 | [144; 146) 'a4': &&&&&&&A | ||
813 | [149; 157) '&&&&&&&a': &&&&&&&A | ||
814 | [150; 157) '&&&&&&a': &&&&&&A | ||
815 | [151; 157) '&&&&&a': &&&&&A | ||
816 | [152; 157) '&&&&a': &&&&A | ||
817 | [153; 157) '&&&a': &&&A | ||
818 | [154; 157) '&&a': &&A | ||
819 | [155; 157) '&a': &A | ||
820 | [156; 157) 'a': A | ||
821 | [163; 165) 'a4': &&&&&&&A | ||
822 | [163; 167) 'a4.b': B | ||
823 | [177; 179) 'a5': &mut &&mut &&mut A | ||
824 | [182; 200) '&mut &...&mut a': &mut &&mut &&mut A | ||
825 | [187; 200) '&&mut &&mut a': &&mut &&mut A | ||
826 | [188; 200) '&mut &&mut a': &mut &&mut A | ||
827 | [193; 200) '&&mut a': &&mut A | ||
828 | [194; 200) '&mut a': &mut A | ||
829 | [199; 200) 'a': A | ||
830 | [206; 208) 'a5': &mut &&mut &&mut A | ||
831 | [206; 210) 'a5.b': B | ||
832 | [224; 226) 'a1': *const A | ||
833 | [238; 240) 'a2': *mut A | ||
834 | [250; 273) '{ ...2.b; }': () | ||
835 | [256; 258) 'a1': *const A | ||
836 | [256; 260) 'a1.b': B | ||
837 | [266; 268) 'a2': *mut A | ||
838 | [266; 270) 'a2.b': B | ||
839 | "### | ||
840 | ); | ||
841 | } | ||
842 | |||
843 | #[test] | ||
844 | fn infer_argument_autoderef() { | ||
845 | assert_snapshot!( | ||
846 | infer(r#" | ||
847 | #[lang = "deref"] | ||
848 | pub trait Deref { | ||
849 | type Target; | ||
850 | fn deref(&self) -> &Self::Target; | ||
851 | } | ||
852 | |||
853 | struct A<T>(T); | ||
854 | |||
855 | impl<T> A<T> { | ||
856 | fn foo(&self) -> &T { | ||
857 | &self.0 | ||
858 | } | ||
859 | } | ||
860 | |||
861 | struct B<T>(T); | ||
862 | |||
863 | impl<T> Deref for B<T> { | ||
864 | type Target = T; | ||
865 | fn deref(&self) -> &Self::Target { | ||
866 | &self.0 | ||
867 | } | ||
868 | } | ||
869 | |||
870 | fn test() { | ||
871 | let t = A::foo(&&B(B(A(42)))); | ||
872 | } | ||
873 | "#), | ||
874 | @r###" | ||
875 | [68; 72) 'self': &Self | ||
876 | [139; 143) 'self': &A<T> | ||
877 | [151; 174) '{ ... }': &T | ||
878 | [161; 168) '&self.0': &T | ||
879 | [162; 166) 'self': &A<T> | ||
880 | [162; 168) 'self.0': T | ||
881 | [255; 259) 'self': &B<T> | ||
882 | [278; 301) '{ ... }': &T | ||
883 | [288; 295) '&self.0': &T | ||
884 | [289; 293) 'self': &B<T> | ||
885 | [289; 295) 'self.0': T | ||
886 | [315; 353) '{ ...))); }': () | ||
887 | [325; 326) 't': &i32 | ||
888 | [329; 335) 'A::foo': fn foo<i32>(&A<T>) -> &T | ||
889 | [329; 350) 'A::foo...42))))': &i32 | ||
890 | [336; 349) '&&B(B(A(42)))': &&B<B<A<i32>>> | ||
891 | [337; 349) '&B(B(A(42)))': &B<B<A<i32>>> | ||
892 | [338; 339) 'B': B<B<A<i32>>>(T) -> B<T> | ||
893 | [338; 349) 'B(B(A(42)))': B<B<A<i32>>> | ||
894 | [340; 341) 'B': B<A<i32>>(T) -> B<T> | ||
895 | [340; 348) 'B(A(42))': B<A<i32>> | ||
896 | [342; 343) 'A': A<i32>(T) -> A<T> | ||
897 | [342; 347) 'A(42)': A<i32> | ||
898 | [344; 346) '42': i32 | ||
899 | "### | ||
900 | ); | ||
901 | } | ||
902 | |||
903 | #[test] | ||
904 | fn infer_method_argument_autoderef() { | ||
905 | assert_snapshot!( | ||
906 | infer(r#" | ||
907 | #[lang = "deref"] | ||
908 | pub trait Deref { | ||
909 | type Target; | ||
910 | fn deref(&self) -> &Self::Target; | ||
911 | } | ||
912 | |||
913 | struct A<T>(*mut T); | ||
914 | |||
915 | impl<T> A<T> { | ||
916 | fn foo(&self, x: &A<T>) -> &T { | ||
917 | &*x.0 | ||
918 | } | ||
919 | } | ||
920 | |||
921 | struct B<T>(T); | ||
922 | |||
923 | impl<T> Deref for B<T> { | ||
924 | type Target = T; | ||
925 | fn deref(&self) -> &Self::Target { | ||
926 | &self.0 | ||
927 | } | ||
928 | } | ||
929 | |||
930 | fn test(a: A<i32>) { | ||
931 | let t = A(0 as *mut _).foo(&&B(B(a))); | ||
932 | } | ||
933 | "#), | ||
934 | @r###" | ||
935 | [68; 72) 'self': &Self | ||
936 | [144; 148) 'self': &A<T> | ||
937 | [150; 151) 'x': &A<T> | ||
938 | [166; 187) '{ ... }': &T | ||
939 | [176; 181) '&*x.0': &T | ||
940 | [177; 181) '*x.0': T | ||
941 | [178; 179) 'x': &A<T> | ||
942 | [178; 181) 'x.0': *mut T | ||
943 | [268; 272) 'self': &B<T> | ||
944 | [291; 314) '{ ... }': &T | ||
945 | [301; 308) '&self.0': &T | ||
946 | [302; 306) 'self': &B<T> | ||
947 | [302; 308) 'self.0': T | ||
948 | [326; 327) 'a': A<i32> | ||
949 | [337; 383) '{ ...))); }': () | ||
950 | [347; 348) 't': &i32 | ||
951 | [351; 352) 'A': A<i32>(*mut T) -> A<T> | ||
952 | [351; 365) 'A(0 as *mut _)': A<i32> | ||
953 | [351; 380) 'A(0 as...B(a)))': &i32 | ||
954 | [353; 354) '0': i32 | ||
955 | [353; 364) '0 as *mut _': *mut i32 | ||
956 | [370; 379) '&&B(B(a))': &&B<B<A<i32>>> | ||
957 | [371; 379) '&B(B(a))': &B<B<A<i32>>> | ||
958 | [372; 373) 'B': B<B<A<i32>>>(T) -> B<T> | ||
959 | [372; 379) 'B(B(a))': B<B<A<i32>>> | ||
960 | [374; 375) 'B': B<A<i32>>(T) -> B<T> | ||
961 | [374; 378) 'B(a)': B<A<i32>> | ||
962 | [376; 377) 'a': A<i32> | ||
963 | "### | ||
964 | ); | ||
965 | } | ||
966 | |||
967 | #[test] | ||
968 | fn bug_484() { | ||
969 | assert_snapshot!( | ||
970 | infer(r#" | ||
971 | fn test() { | ||
972 | let x = if true {}; | ||
973 | } | ||
974 | "#), | ||
975 | @r###" | ||
976 | [11; 37) '{ l... {}; }': () | ||
977 | [20; 21) 'x': () | ||
978 | [24; 34) 'if true {}': () | ||
979 | [27; 31) 'true': bool | ||
980 | [32; 34) '{}': () | ||
981 | "### | ||
982 | ); | ||
983 | } | ||
984 | |||
985 | #[test] | ||
986 | fn infer_in_elseif() { | ||
987 | assert_snapshot!( | ||
988 | infer(r#" | ||
989 | struct Foo { field: i32 } | ||
990 | fn main(foo: Foo) { | ||
991 | if true { | ||
992 | |||
993 | } else if false { | ||
994 | foo.field | ||
995 | } | ||
996 | } | ||
997 | "#), | ||
998 | @r###" | ||
999 | [35; 38) 'foo': Foo | ||
1000 | [45; 109) '{ ... } }': () | ||
1001 | [51; 107) 'if tru... }': () | ||
1002 | [54; 58) 'true': bool | ||
1003 | [59; 67) '{ }': () | ||
1004 | [73; 107) 'if fal... }': () | ||
1005 | [76; 81) 'false': bool | ||
1006 | [82; 107) '{ ... }': i32 | ||
1007 | [92; 95) 'foo': Foo | ||
1008 | [92; 101) 'foo.field': i32 | ||
1009 | "### | ||
1010 | ) | ||
1011 | } | ||
1012 | |||
1013 | #[test] | ||
1014 | fn infer_if_match_with_return() { | ||
1015 | assert_snapshot!( | ||
1016 | infer(r#" | ||
1017 | fn foo() { | ||
1018 | let _x1 = if true { | ||
1019 | 1 | ||
1020 | } else { | ||
1021 | return; | ||
1022 | }; | ||
1023 | let _x2 = if true { | ||
1024 | 2 | ||
1025 | } else { | ||
1026 | return | ||
1027 | }; | ||
1028 | let _x3 = match true { | ||
1029 | true => 3, | ||
1030 | _ => { | ||
1031 | return; | ||
1032 | } | ||
1033 | }; | ||
1034 | let _x4 = match true { | ||
1035 | true => 4, | ||
1036 | _ => return | ||
1037 | }; | ||
1038 | }"#), | ||
1039 | @r###" | ||
1040 | [10; 323) '{ ... }; }': () | ||
1041 | [20; 23) '_x1': i32 | ||
1042 | [26; 80) 'if tru... }': i32 | ||
1043 | [29; 33) 'true': bool | ||
1044 | [34; 51) '{ ... }': i32 | ||
1045 | [44; 45) '1': i32 | ||
1046 | [57; 80) '{ ... }': ! | ||
1047 | [67; 73) 'return': ! | ||
1048 | [90; 93) '_x2': i32 | ||
1049 | [96; 149) 'if tru... }': i32 | ||
1050 | [99; 103) 'true': bool | ||
1051 | [104; 121) '{ ... }': i32 | ||
1052 | [114; 115) '2': i32 | ||
1053 | [127; 149) '{ ... }': ! | ||
1054 | [137; 143) 'return': ! | ||
1055 | [159; 162) '_x3': i32 | ||
1056 | [165; 247) 'match ... }': i32 | ||
1057 | [171; 175) 'true': bool | ||
1058 | [186; 190) 'true': bool | ||
1059 | [194; 195) '3': i32 | ||
1060 | [205; 206) '_': bool | ||
1061 | [210; 241) '{ ... }': ! | ||
1062 | [224; 230) 'return': ! | ||
1063 | [257; 260) '_x4': i32 | ||
1064 | [263; 320) 'match ... }': i32 | ||
1065 | [269; 273) 'true': bool | ||
1066 | [284; 288) 'true': bool | ||
1067 | [292; 293) '4': i32 | ||
1068 | [303; 304) '_': bool | ||
1069 | [308; 314) 'return': ! | ||
1070 | "### | ||
1071 | ) | ||
1072 | } | ||
1073 | |||
1074 | #[test] | ||
1075 | fn infer_inherent_method() { | ||
1076 | assert_snapshot!( | ||
1077 | infer(r#" | ||
1078 | struct A; | ||
1079 | |||
1080 | impl A { | ||
1081 | fn foo(self, x: u32) -> i32 {} | ||
1082 | } | ||
1083 | |||
1084 | mod b { | ||
1085 | impl super::A { | ||
1086 | fn bar(&self, x: u64) -> i64 {} | ||
1087 | } | ||
1088 | } | ||
1089 | |||
1090 | fn test(a: A) { | ||
1091 | a.foo(1); | ||
1092 | (&a).bar(1); | ||
1093 | a.bar(1); | ||
1094 | } | ||
1095 | "#), | ||
1096 | @r###" | ||
1097 | [32; 36) 'self': A | ||
1098 | [38; 39) 'x': u32 | ||
1099 | [53; 55) '{}': () | ||
1100 | [103; 107) 'self': &A | ||
1101 | [109; 110) 'x': u64 | ||
1102 | [124; 126) '{}': () | ||
1103 | [144; 145) 'a': A | ||
1104 | [150; 198) '{ ...(1); }': () | ||
1105 | [156; 157) 'a': A | ||
1106 | [156; 164) 'a.foo(1)': i32 | ||
1107 | [162; 163) '1': u32 | ||
1108 | [170; 181) '(&a).bar(1)': i64 | ||
1109 | [171; 173) '&a': &A | ||
1110 | [172; 173) 'a': A | ||
1111 | [179; 180) '1': u64 | ||
1112 | [187; 188) 'a': A | ||
1113 | [187; 195) 'a.bar(1)': i64 | ||
1114 | [193; 194) '1': u64 | ||
1115 | "### | ||
1116 | ); | ||
1117 | } | ||
1118 | |||
1119 | #[test] | ||
1120 | fn infer_inherent_method_str() { | ||
1121 | assert_snapshot!( | ||
1122 | infer(r#" | ||
1123 | #[lang = "str"] | ||
1124 | impl str { | ||
1125 | fn foo(&self) -> i32 {} | ||
1126 | } | ||
1127 | |||
1128 | fn test() { | ||
1129 | "foo".foo(); | ||
1130 | } | ||
1131 | "#), | ||
1132 | @r###" | ||
1133 | [40; 44) 'self': &str | ||
1134 | [53; 55) '{}': () | ||
1135 | [69; 89) '{ ...o(); }': () | ||
1136 | [75; 80) '"foo"': &str | ||
1137 | [75; 86) '"foo".foo()': i32 | ||
1138 | "### | ||
1139 | ); | ||
1140 | } | ||
1141 | |||
1142 | #[test] | ||
1143 | fn infer_tuple() { | ||
1144 | assert_snapshot!( | ||
1145 | infer(r#" | ||
1146 | fn test(x: &str, y: isize) { | ||
1147 | let a: (u32, &str) = (1, "a"); | ||
1148 | let b = (a, x); | ||
1149 | let c = (y, x); | ||
1150 | let d = (c, x); | ||
1151 | let e = (1, "e"); | ||
1152 | let f = (e, "d"); | ||
1153 | } | ||
1154 | "#), | ||
1155 | @r###" | ||
1156 | [9; 10) 'x': &str | ||
1157 | [18; 19) 'y': isize | ||
1158 | [28; 170) '{ ...d"); }': () | ||
1159 | [38; 39) 'a': (u32, &str) | ||
1160 | [55; 63) '(1, "a")': (u32, &str) | ||
1161 | [56; 57) '1': u32 | ||
1162 | [59; 62) '"a"': &str | ||
1163 | [73; 74) 'b': ((u32, &str), &str) | ||
1164 | [77; 83) '(a, x)': ((u32, &str), &str) | ||
1165 | [78; 79) 'a': (u32, &str) | ||
1166 | [81; 82) 'x': &str | ||
1167 | [93; 94) 'c': (isize, &str) | ||
1168 | [97; 103) '(y, x)': (isize, &str) | ||
1169 | [98; 99) 'y': isize | ||
1170 | [101; 102) 'x': &str | ||
1171 | [113; 114) 'd': ((isize, &str), &str) | ||
1172 | [117; 123) '(c, x)': ((isize, &str), &str) | ||
1173 | [118; 119) 'c': (isize, &str) | ||
1174 | [121; 122) 'x': &str | ||
1175 | [133; 134) 'e': (i32, &str) | ||
1176 | [137; 145) '(1, "e")': (i32, &str) | ||
1177 | [138; 139) '1': i32 | ||
1178 | [141; 144) '"e"': &str | ||
1179 | [155; 156) 'f': ((i32, &str), &str) | ||
1180 | [159; 167) '(e, "d")': ((i32, &str), &str) | ||
1181 | [160; 161) 'e': (i32, &str) | ||
1182 | [163; 166) '"d"': &str | ||
1183 | "### | ||
1184 | ); | ||
1185 | } | ||
1186 | |||
1187 | #[test] | ||
1188 | fn infer_array() { | ||
1189 | assert_snapshot!( | ||
1190 | infer(r#" | ||
1191 | fn test(x: &str, y: isize) { | ||
1192 | let a = [x]; | ||
1193 | let b = [a, a]; | ||
1194 | let c = [b, b]; | ||
1195 | |||
1196 | let d = [y, 1, 2, 3]; | ||
1197 | let d = [1, y, 2, 3]; | ||
1198 | let e = [y]; | ||
1199 | let f = [d, d]; | ||
1200 | let g = [e, e]; | ||
1201 | |||
1202 | let h = [1, 2]; | ||
1203 | let i = ["a", "b"]; | ||
1204 | |||
1205 | let b = [a, ["b"]]; | ||
1206 | let x: [u8; 0] = []; | ||
1207 | } | ||
1208 | "#), | ||
1209 | @r###" | ||
1210 | [9; 10) 'x': &str | ||
1211 | [18; 19) 'y': isize | ||
1212 | [28; 293) '{ ... []; }': () | ||
1213 | [38; 39) 'a': [&str;_] | ||
1214 | [42; 45) '[x]': [&str;_] | ||
1215 | [43; 44) 'x': &str | ||
1216 | [55; 56) 'b': [[&str;_];_] | ||
1217 | [59; 65) '[a, a]': [[&str;_];_] | ||
1218 | [60; 61) 'a': [&str;_] | ||
1219 | [63; 64) 'a': [&str;_] | ||
1220 | [75; 76) 'c': [[[&str;_];_];_] | ||
1221 | [79; 85) '[b, b]': [[[&str;_];_];_] | ||
1222 | [80; 81) 'b': [[&str;_];_] | ||
1223 | [83; 84) 'b': [[&str;_];_] | ||
1224 | [96; 97) 'd': [isize;_] | ||
1225 | [100; 112) '[y, 1, 2, 3]': [isize;_] | ||
1226 | [101; 102) 'y': isize | ||
1227 | [104; 105) '1': isize | ||
1228 | [107; 108) '2': isize | ||
1229 | [110; 111) '3': isize | ||
1230 | [122; 123) 'd': [isize;_] | ||
1231 | [126; 138) '[1, y, 2, 3]': [isize;_] | ||
1232 | [127; 128) '1': isize | ||
1233 | [130; 131) 'y': isize | ||
1234 | [133; 134) '2': isize | ||
1235 | [136; 137) '3': isize | ||
1236 | [148; 149) 'e': [isize;_] | ||
1237 | [152; 155) '[y]': [isize;_] | ||
1238 | [153; 154) 'y': isize | ||
1239 | [165; 166) 'f': [[isize;_];_] | ||
1240 | [169; 175) '[d, d]': [[isize;_];_] | ||
1241 | [170; 171) 'd': [isize;_] | ||
1242 | [173; 174) 'd': [isize;_] | ||
1243 | [185; 186) 'g': [[isize;_];_] | ||
1244 | [189; 195) '[e, e]': [[isize;_];_] | ||
1245 | [190; 191) 'e': [isize;_] | ||
1246 | [193; 194) 'e': [isize;_] | ||
1247 | [206; 207) 'h': [i32;_] | ||
1248 | [210; 216) '[1, 2]': [i32;_] | ||
1249 | [211; 212) '1': i32 | ||
1250 | [214; 215) '2': i32 | ||
1251 | [226; 227) 'i': [&str;_] | ||
1252 | [230; 240) '["a", "b"]': [&str;_] | ||
1253 | [231; 234) '"a"': &str | ||
1254 | [236; 239) '"b"': &str | ||
1255 | [251; 252) 'b': [[&str;_];_] | ||
1256 | [255; 265) '[a, ["b"]]': [[&str;_];_] | ||
1257 | [256; 257) 'a': [&str;_] | ||
1258 | [259; 264) '["b"]': [&str;_] | ||
1259 | [260; 263) '"b"': &str | ||
1260 | [275; 276) 'x': [u8;_] | ||
1261 | [288; 290) '[]': [u8;_] | ||
1262 | "### | ||
1263 | ); | ||
1264 | } | ||
1265 | |||
1266 | #[test] | ||
1267 | fn infer_pattern() { | ||
1268 | assert_snapshot!( | ||
1269 | infer(r#" | ||
1270 | fn test(x: &i32) { | ||
1271 | let y = x; | ||
1272 | let &z = x; | ||
1273 | let a = z; | ||
1274 | let (c, d) = (1, "hello"); | ||
1275 | |||
1276 | for (e, f) in some_iter { | ||
1277 | let g = e; | ||
1278 | } | ||
1279 | |||
1280 | if let [val] = opt { | ||
1281 | let h = val; | ||
1282 | } | ||
1283 | |||
1284 | let lambda = |a: u64, b, c: i32| { a + b; c }; | ||
1285 | |||
1286 | let ref ref_to_x = x; | ||
1287 | let mut mut_x = x; | ||
1288 | let ref mut mut_ref_to_x = x; | ||
1289 | let k = mut_ref_to_x; | ||
1290 | } | ||
1291 | "#), | ||
1292 | @r###" | ||
1293 | [9; 10) 'x': &i32 | ||
1294 | [18; 369) '{ ...o_x; }': () | ||
1295 | [28; 29) 'y': &i32 | ||
1296 | [32; 33) 'x': &i32 | ||
1297 | [43; 45) '&z': &i32 | ||
1298 | [44; 45) 'z': i32 | ||
1299 | [48; 49) 'x': &i32 | ||
1300 | [59; 60) 'a': i32 | ||
1301 | [63; 64) 'z': i32 | ||
1302 | [74; 80) '(c, d)': (i32, &str) | ||
1303 | [75; 76) 'c': i32 | ||
1304 | [78; 79) 'd': &str | ||
1305 | [83; 95) '(1, "hello")': (i32, &str) | ||
1306 | [84; 85) '1': i32 | ||
1307 | [87; 94) '"hello"': &str | ||
1308 | [102; 152) 'for (e... }': () | ||
1309 | [106; 112) '(e, f)': ({unknown}, {unknown}) | ||
1310 | [107; 108) 'e': {unknown} | ||
1311 | [110; 111) 'f': {unknown} | ||
1312 | [116; 125) 'some_iter': {unknown} | ||
1313 | [126; 152) '{ ... }': () | ||
1314 | [140; 141) 'g': {unknown} | ||
1315 | [144; 145) 'e': {unknown} | ||
1316 | [158; 205) 'if let... }': () | ||
1317 | [165; 170) '[val]': {unknown} | ||
1318 | [173; 176) 'opt': {unknown} | ||
1319 | [177; 205) '{ ... }': () | ||
1320 | [191; 192) 'h': {unknown} | ||
1321 | [195; 198) 'val': {unknown} | ||
1322 | [215; 221) 'lambda': |u64, u64, i32| -> i32 | ||
1323 | [224; 256) '|a: u6...b; c }': |u64, u64, i32| -> i32 | ||
1324 | [225; 226) 'a': u64 | ||
1325 | [233; 234) 'b': u64 | ||
1326 | [236; 237) 'c': i32 | ||
1327 | [244; 256) '{ a + b; c }': i32 | ||
1328 | [246; 247) 'a': u64 | ||
1329 | [246; 251) 'a + b': u64 | ||
1330 | [250; 251) 'b': u64 | ||
1331 | [253; 254) 'c': i32 | ||
1332 | [267; 279) 'ref ref_to_x': &&i32 | ||
1333 | [282; 283) 'x': &i32 | ||
1334 | [293; 302) 'mut mut_x': &i32 | ||
1335 | [305; 306) 'x': &i32 | ||
1336 | [316; 336) 'ref mu...f_to_x': &mut &i32 | ||
1337 | [339; 340) 'x': &i32 | ||
1338 | [350; 351) 'k': &mut &i32 | ||
1339 | [354; 366) 'mut_ref_to_x': &mut &i32 | ||
1340 | "### | ||
1341 | ); | ||
1342 | } | ||
1343 | |||
1344 | #[test] | ||
1345 | fn infer_pattern_match_ergonomics() { | ||
1346 | assert_snapshot!( | ||
1347 | infer(r#" | ||
1348 | struct A<T>(T); | ||
1349 | |||
1350 | fn test() { | ||
1351 | let A(n) = &A(1); | ||
1352 | let A(n) = &mut A(1); | ||
1353 | } | ||
1354 | "#), | ||
1355 | @r###" | ||
1356 | [28; 79) '{ ...(1); }': () | ||
1357 | [38; 42) 'A(n)': A<i32> | ||
1358 | [40; 41) 'n': &i32 | ||
1359 | [45; 50) '&A(1)': &A<i32> | ||
1360 | [46; 47) 'A': A<i32>(T) -> A<T> | ||
1361 | [46; 50) 'A(1)': A<i32> | ||
1362 | [48; 49) '1': i32 | ||
1363 | [60; 64) 'A(n)': A<i32> | ||
1364 | [62; 63) 'n': &mut i32 | ||
1365 | [67; 76) '&mut A(1)': &mut A<i32> | ||
1366 | [72; 73) 'A': A<i32>(T) -> A<T> | ||
1367 | [72; 76) 'A(1)': A<i32> | ||
1368 | [74; 75) '1': i32 | ||
1369 | "### | ||
1370 | ); | ||
1371 | } | ||
1372 | |||
1373 | #[test] | ||
1374 | fn infer_pattern_match_ergonomics_ref() { | ||
1375 | covers!(match_ergonomics_ref); | ||
1376 | assert_snapshot!( | ||
1377 | infer(r#" | ||
1378 | fn test() { | ||
1379 | let v = &(1, &2); | ||
1380 | let (_, &w) = v; | ||
1381 | } | ||
1382 | "#), | ||
1383 | @r###" | ||
1384 | [11; 57) '{ ...= v; }': () | ||
1385 | [21; 22) 'v': &(i32, &i32) | ||
1386 | [25; 33) '&(1, &2)': &(i32, &i32) | ||
1387 | [26; 33) '(1, &2)': (i32, &i32) | ||
1388 | [27; 28) '1': i32 | ||
1389 | [30; 32) '&2': &i32 | ||
1390 | [31; 32) '2': i32 | ||
1391 | [43; 50) '(_, &w)': (i32, &i32) | ||
1392 | [44; 45) '_': i32 | ||
1393 | [47; 49) '&w': &i32 | ||
1394 | [48; 49) 'w': i32 | ||
1395 | [53; 54) 'v': &(i32, &i32) | ||
1396 | "### | ||
1397 | ); | ||
1398 | } | ||
1399 | |||
1400 | #[test] | ||
1401 | fn infer_adt_pattern() { | ||
1402 | assert_snapshot!( | ||
1403 | infer(r#" | ||
1404 | enum E { | ||
1405 | A { x: usize }, | ||
1406 | B | ||
1407 | } | ||
1408 | |||
1409 | struct S(u32, E); | ||
1410 | |||
1411 | fn test() { | ||
1412 | let e = E::A { x: 3 }; | ||
1413 | |||
1414 | let S(y, z) = foo; | ||
1415 | let E::A { x: new_var } = e; | ||
1416 | |||
1417 | match e { | ||
1418 | E::A { x } => x, | ||
1419 | E::B if foo => 1, | ||
1420 | E::B => 10, | ||
1421 | }; | ||
1422 | |||
1423 | let ref d @ E::A { .. } = e; | ||
1424 | d; | ||
1425 | } | ||
1426 | "#), | ||
1427 | @r###" | ||
1428 | [68; 289) '{ ... d; }': () | ||
1429 | [78; 79) 'e': E | ||
1430 | [82; 95) 'E::A { x: 3 }': E | ||
1431 | [92; 93) '3': usize | ||
1432 | [106; 113) 'S(y, z)': S | ||
1433 | [108; 109) 'y': u32 | ||
1434 | [111; 112) 'z': E | ||
1435 | [116; 119) 'foo': S | ||
1436 | [129; 148) 'E::A {..._var }': E | ||
1437 | [139; 146) 'new_var': usize | ||
1438 | [151; 152) 'e': E | ||
1439 | [159; 245) 'match ... }': usize | ||
1440 | [165; 166) 'e': E | ||
1441 | [177; 187) 'E::A { x }': E | ||
1442 | [184; 185) 'x': usize | ||
1443 | [191; 192) 'x': usize | ||
1444 | [202; 206) 'E::B': E | ||
1445 | [210; 213) 'foo': bool | ||
1446 | [217; 218) '1': usize | ||
1447 | [228; 232) 'E::B': E | ||
1448 | [236; 238) '10': usize | ||
1449 | [256; 275) 'ref d ...{ .. }': &E | ||
1450 | [264; 275) 'E::A { .. }': E | ||
1451 | [278; 279) 'e': E | ||
1452 | [285; 286) 'd': &E | ||
1453 | "### | ||
1454 | ); | ||
1455 | } | ||
1456 | |||
1457 | #[test] | ||
1458 | fn infer_struct_generics() { | ||
1459 | assert_snapshot!( | ||
1460 | infer(r#" | ||
1461 | struct A<T> { | ||
1462 | x: T, | ||
1463 | } | ||
1464 | |||
1465 | fn test(a1: A<u32>, i: i32) { | ||
1466 | a1.x; | ||
1467 | let a2 = A { x: i }; | ||
1468 | a2.x; | ||
1469 | let a3 = A::<i128> { x: 1 }; | ||
1470 | a3.x; | ||
1471 | } | ||
1472 | "#), | ||
1473 | @r###" | ||
1474 | [36; 38) 'a1': A<u32> | ||
1475 | [48; 49) 'i': i32 | ||
1476 | [56; 147) '{ ...3.x; }': () | ||
1477 | [62; 64) 'a1': A<u32> | ||
1478 | [62; 66) 'a1.x': u32 | ||
1479 | [76; 78) 'a2': A<i32> | ||
1480 | [81; 91) 'A { x: i }': A<i32> | ||
1481 | [88; 89) 'i': i32 | ||
1482 | [97; 99) 'a2': A<i32> | ||
1483 | [97; 101) 'a2.x': i32 | ||
1484 | [111; 113) 'a3': A<i128> | ||
1485 | [116; 134) 'A::<i1...x: 1 }': A<i128> | ||
1486 | [131; 132) '1': i128 | ||
1487 | [140; 142) 'a3': A<i128> | ||
1488 | [140; 144) 'a3.x': i128 | ||
1489 | "### | ||
1490 | ); | ||
1491 | } | ||
1492 | |||
1493 | #[test] | ||
1494 | fn infer_tuple_struct_generics() { | ||
1495 | assert_snapshot!( | ||
1496 | infer(r#" | ||
1497 | struct A<T>(T); | ||
1498 | enum Option<T> { Some(T), None } | ||
1499 | use Option::*; | ||
1500 | |||
1501 | fn test() { | ||
1502 | A(42); | ||
1503 | A(42u128); | ||
1504 | Some("x"); | ||
1505 | Option::Some("x"); | ||
1506 | None; | ||
1507 | let x: Option<i64> = None; | ||
1508 | } | ||
1509 | "#), | ||
1510 | @r###" | ||
1511 | [76; 184) '{ ...one; }': () | ||
1512 | [82; 83) 'A': A<i32>(T) -> A<T> | ||
1513 | [82; 87) 'A(42)': A<i32> | ||
1514 | [84; 86) '42': i32 | ||
1515 | [93; 94) 'A': A<u128>(T) -> A<T> | ||
1516 | [93; 102) 'A(42u128)': A<u128> | ||
1517 | [95; 101) '42u128': u128 | ||
1518 | [108; 112) 'Some': Some<&str>(T) -> Option<T> | ||
1519 | [108; 117) 'Some("x")': Option<&str> | ||
1520 | [113; 116) '"x"': &str | ||
1521 | [123; 135) 'Option::Some': Some<&str>(T) -> Option<T> | ||
1522 | [123; 140) 'Option...e("x")': Option<&str> | ||
1523 | [136; 139) '"x"': &str | ||
1524 | [146; 150) 'None': Option<{unknown}> | ||
1525 | [160; 161) 'x': Option<i64> | ||
1526 | [177; 181) 'None': Option<i64> | ||
1527 | "### | ||
1528 | ); | ||
1529 | } | ||
1530 | |||
1531 | #[test] | ||
1532 | fn infer_generics_in_patterns() { | ||
1533 | assert_snapshot!( | ||
1534 | infer(r#" | ||
1535 | struct A<T> { | ||
1536 | x: T, | ||
1537 | } | ||
1538 | |||
1539 | enum Option<T> { | ||
1540 | Some(T), | ||
1541 | None, | ||
1542 | } | ||
1543 | |||
1544 | fn test(a1: A<u32>, o: Option<u64>) { | ||
1545 | let A { x: x2 } = a1; | ||
1546 | let A::<i64> { x: x3 } = A { x: 1 }; | ||
1547 | match o { | ||
1548 | Option::Some(t) => t, | ||
1549 | _ => 1, | ||
1550 | }; | ||
1551 | } | ||
1552 | "#), | ||
1553 | @r###" | ||
1554 | [79; 81) 'a1': A<u32> | ||
1555 | [91; 92) 'o': Option<u64> | ||
1556 | [107; 244) '{ ... }; }': () | ||
1557 | [117; 128) 'A { x: x2 }': A<u32> | ||
1558 | [124; 126) 'x2': u32 | ||
1559 | [131; 133) 'a1': A<u32> | ||
1560 | [143; 161) 'A::<i6...: x3 }': A<i64> | ||
1561 | [157; 159) 'x3': i64 | ||
1562 | [164; 174) 'A { x: 1 }': A<i64> | ||
1563 | [171; 172) '1': i64 | ||
1564 | [180; 241) 'match ... }': u64 | ||
1565 | [186; 187) 'o': Option<u64> | ||
1566 | [198; 213) 'Option::Some(t)': Option<u64> | ||
1567 | [211; 212) 't': u64 | ||
1568 | [217; 218) 't': u64 | ||
1569 | [228; 229) '_': Option<u64> | ||
1570 | [233; 234) '1': u64 | ||
1571 | "### | ||
1572 | ); | ||
1573 | } | ||
1574 | |||
1575 | #[test] | ||
1576 | fn infer_function_generics() { | ||
1577 | assert_snapshot!( | ||
1578 | infer(r#" | ||
1579 | fn id<T>(t: T) -> T { t } | ||
1580 | |||
1581 | fn test() { | ||
1582 | id(1u32); | ||
1583 | id::<i128>(1); | ||
1584 | let x: u64 = id(1); | ||
1585 | } | ||
1586 | "#), | ||
1587 | @r###" | ||
1588 | [10; 11) 't': T | ||
1589 | [21; 26) '{ t }': T | ||
1590 | [23; 24) 't': T | ||
1591 | [38; 98) '{ ...(1); }': () | ||
1592 | [44; 46) 'id': fn id<u32>(T) -> T | ||
1593 | [44; 52) 'id(1u32)': u32 | ||
1594 | [47; 51) '1u32': u32 | ||
1595 | [58; 68) 'id::<i128>': fn id<i128>(T) -> T | ||
1596 | [58; 71) 'id::<i128>(1)': i128 | ||
1597 | [69; 70) '1': i128 | ||
1598 | [81; 82) 'x': u64 | ||
1599 | [90; 92) 'id': fn id<u64>(T) -> T | ||
1600 | [90; 95) 'id(1)': u64 | ||
1601 | [93; 94) '1': u64 | ||
1602 | "### | ||
1603 | ); | ||
1604 | } | ||
1605 | |||
1606 | #[test] | ||
1607 | fn infer_impl_generics() { | ||
1608 | assert_snapshot!( | ||
1609 | infer(r#" | ||
1610 | struct A<T1, T2> { | ||
1611 | x: T1, | ||
1612 | y: T2, | ||
1613 | } | ||
1614 | impl<Y, X> A<X, Y> { | ||
1615 | fn x(self) -> X { | ||
1616 | self.x | ||
1617 | } | ||
1618 | fn y(self) -> Y { | ||
1619 | self.y | ||
1620 | } | ||
1621 | fn z<T>(self, t: T) -> (X, Y, T) { | ||
1622 | (self.x, self.y, t) | ||
1623 | } | ||
1624 | } | ||
1625 | |||
1626 | fn test() -> i128 { | ||
1627 | let a = A { x: 1u64, y: 1i64 }; | ||
1628 | a.x(); | ||
1629 | a.y(); | ||
1630 | a.z(1i128); | ||
1631 | a.z::<u128>(1); | ||
1632 | } | ||
1633 | "#), | ||
1634 | @r###" | ||
1635 | [74; 78) 'self': A<X, Y> | ||
1636 | [85; 107) '{ ... }': X | ||
1637 | [95; 99) 'self': A<X, Y> | ||
1638 | [95; 101) 'self.x': X | ||
1639 | [117; 121) 'self': A<X, Y> | ||
1640 | [128; 150) '{ ... }': Y | ||
1641 | [138; 142) 'self': A<X, Y> | ||
1642 | [138; 144) 'self.y': Y | ||
1643 | [163; 167) 'self': A<X, Y> | ||
1644 | [169; 170) 't': T | ||
1645 | [188; 223) '{ ... }': (X, Y, T) | ||
1646 | [198; 217) '(self.....y, t)': (X, Y, T) | ||
1647 | [199; 203) 'self': A<X, Y> | ||
1648 | [199; 205) 'self.x': X | ||
1649 | [207; 211) 'self': A<X, Y> | ||
1650 | [207; 213) 'self.y': Y | ||
1651 | [215; 216) 't': T | ||
1652 | [245; 342) '{ ...(1); }': () | ||
1653 | [255; 256) 'a': A<u64, i64> | ||
1654 | [259; 281) 'A { x:...1i64 }': A<u64, i64> | ||
1655 | [266; 270) '1u64': u64 | ||
1656 | [275; 279) '1i64': i64 | ||
1657 | [287; 288) 'a': A<u64, i64> | ||
1658 | [287; 292) 'a.x()': u64 | ||
1659 | [298; 299) 'a': A<u64, i64> | ||
1660 | [298; 303) 'a.y()': i64 | ||
1661 | [309; 310) 'a': A<u64, i64> | ||
1662 | [309; 319) 'a.z(1i128)': (u64, i64, i128) | ||
1663 | [313; 318) '1i128': i128 | ||
1664 | [325; 326) 'a': A<u64, i64> | ||
1665 | [325; 339) 'a.z::<u128>(1)': (u64, i64, u128) | ||
1666 | [337; 338) '1': u128 | ||
1667 | "### | ||
1668 | ); | ||
1669 | } | ||
1670 | |||
1671 | #[test] | ||
1672 | fn infer_impl_generics_with_autoderef() { | ||
1673 | assert_snapshot!( | ||
1674 | infer(r#" | ||
1675 | enum Option<T> { | ||
1676 | Some(T), | ||
1677 | None, | ||
1678 | } | ||
1679 | impl<T> Option<T> { | ||
1680 | fn as_ref(&self) -> Option<&T> {} | ||
1681 | } | ||
1682 | fn test(o: Option<u32>) { | ||
1683 | (&o).as_ref(); | ||
1684 | o.as_ref(); | ||
1685 | } | ||
1686 | "#), | ||
1687 | @r###" | ||
1688 | [78; 82) 'self': &Option<T> | ||
1689 | [98; 100) '{}': () | ||
1690 | [111; 112) 'o': Option<u32> | ||
1691 | [127; 165) '{ ...f(); }': () | ||
1692 | [133; 146) '(&o).as_ref()': Option<&u32> | ||
1693 | [134; 136) '&o': &Option<u32> | ||
1694 | [135; 136) 'o': Option<u32> | ||
1695 | [152; 153) 'o': Option<u32> | ||
1696 | [152; 162) 'o.as_ref()': Option<&u32> | ||
1697 | "### | ||
1698 | ); | ||
1699 | } | ||
1700 | |||
1701 | #[test] | ||
1702 | fn infer_generic_chain() { | ||
1703 | assert_snapshot!( | ||
1704 | infer(r#" | ||
1705 | struct A<T> { | ||
1706 | x: T, | ||
1707 | } | ||
1708 | impl<T2> A<T2> { | ||
1709 | fn x(self) -> T2 { | ||
1710 | self.x | ||
1711 | } | ||
1712 | } | ||
1713 | fn id<T>(t: T) -> T { t } | ||
1714 | |||
1715 | fn test() -> i128 { | ||
1716 | let x = 1; | ||
1717 | let y = id(x); | ||
1718 | let a = A { x: id(y) }; | ||
1719 | let z = id(a.x); | ||
1720 | let b = A { x: z }; | ||
1721 | b.x() | ||
1722 | } | ||
1723 | "#), | ||
1724 | @r###" | ||
1725 | [53; 57) 'self': A<T2> | ||
1726 | [65; 87) '{ ... }': T2 | ||
1727 | [75; 79) 'self': A<T2> | ||
1728 | [75; 81) 'self.x': T2 | ||
1729 | [99; 100) 't': T | ||
1730 | [110; 115) '{ t }': T | ||
1731 | [112; 113) 't': T | ||
1732 | [135; 261) '{ ....x() }': i128 | ||
1733 | [146; 147) 'x': i128 | ||
1734 | [150; 151) '1': i128 | ||
1735 | [162; 163) 'y': i128 | ||
1736 | [166; 168) 'id': fn id<i128>(T) -> T | ||
1737 | [166; 171) 'id(x)': i128 | ||
1738 | [169; 170) 'x': i128 | ||
1739 | [182; 183) 'a': A<i128> | ||
1740 | [186; 200) 'A { x: id(y) }': A<i128> | ||
1741 | [193; 195) 'id': fn id<i128>(T) -> T | ||
1742 | [193; 198) 'id(y)': i128 | ||
1743 | [196; 197) 'y': i128 | ||
1744 | [211; 212) 'z': i128 | ||
1745 | [215; 217) 'id': fn id<i128>(T) -> T | ||
1746 | [215; 222) 'id(a.x)': i128 | ||
1747 | [218; 219) 'a': A<i128> | ||
1748 | [218; 221) 'a.x': i128 | ||
1749 | [233; 234) 'b': A<i128> | ||
1750 | [237; 247) 'A { x: z }': A<i128> | ||
1751 | [244; 245) 'z': i128 | ||
1752 | [254; 255) 'b': A<i128> | ||
1753 | [254; 259) 'b.x()': i128 | ||
1754 | "### | ||
1755 | ); | ||
1756 | } | ||
1757 | |||
1758 | #[test] | ||
1759 | fn infer_associated_const() { | ||
1760 | assert_snapshot!( | ||
1761 | infer(r#" | ||
1762 | struct Struct; | ||
1763 | |||
1764 | impl Struct { | ||
1765 | const FOO: u32 = 1; | ||
1766 | } | ||
1767 | |||
1768 | enum Enum {} | ||
1769 | |||
1770 | impl Enum { | ||
1771 | const BAR: u32 = 2; | ||
1772 | } | ||
1773 | |||
1774 | trait Trait { | ||
1775 | const ID: u32; | ||
1776 | } | ||
1777 | |||
1778 | struct TraitTest; | ||
1779 | |||
1780 | impl Trait for TraitTest { | ||
1781 | const ID: u32 = 5; | ||
1782 | } | ||
1783 | |||
1784 | fn test() { | ||
1785 | let x = Struct::FOO; | ||
1786 | let y = Enum::BAR; | ||
1787 | let z = TraitTest::ID; | ||
1788 | } | ||
1789 | "#), | ||
1790 | @r###" | ||
1791 | [52; 53) '1': u32 | ||
1792 | [105; 106) '2': u32 | ||
1793 | [213; 214) '5': u32 | ||
1794 | [229; 307) '{ ...:ID; }': () | ||
1795 | [239; 240) 'x': u32 | ||
1796 | [243; 254) 'Struct::FOO': u32 | ||
1797 | [264; 265) 'y': u32 | ||
1798 | [268; 277) 'Enum::BAR': u32 | ||
1799 | [287; 288) 'z': u32 | ||
1800 | [291; 304) 'TraitTest::ID': u32 | ||
1801 | "### | ||
1802 | ); | ||
1803 | } | ||
1804 | |||
1805 | #[test] | ||
1806 | fn infer_associated_method_struct() { | ||
1807 | assert_snapshot!( | ||
1808 | infer(r#" | ||
1809 | struct A { x: u32 } | ||
1810 | |||
1811 | impl A { | ||
1812 | fn new() -> A { | ||
1813 | A { x: 0 } | ||
1814 | } | ||
1815 | } | ||
1816 | fn test() { | ||
1817 | let a = A::new(); | ||
1818 | a.x; | ||
1819 | } | ||
1820 | "#), | ||
1821 | @r###" | ||
1822 | [49; 75) '{ ... }': A | ||
1823 | [59; 69) 'A { x: 0 }': A | ||
1824 | [66; 67) '0': u32 | ||
1825 | [88; 122) '{ ...a.x; }': () | ||
1826 | [98; 99) 'a': A | ||
1827 | [102; 108) 'A::new': fn new() -> A | ||
1828 | [102; 110) 'A::new()': A | ||
1829 | [116; 117) 'a': A | ||
1830 | [116; 119) 'a.x': u32 | ||
1831 | "### | ||
1832 | ); | ||
1833 | } | ||
1834 | |||
1835 | #[test] | ||
1836 | fn infer_associated_method_enum() { | ||
1837 | assert_snapshot!( | ||
1838 | infer(r#" | ||
1839 | enum A { B, C } | ||
1840 | |||
1841 | impl A { | ||
1842 | pub fn b() -> A { | ||
1843 | A::B | ||
1844 | } | ||
1845 | pub fn c() -> A { | ||
1846 | A::C | ||
1847 | } | ||
1848 | } | ||
1849 | fn test() { | ||
1850 | let a = A::b(); | ||
1851 | a; | ||
1852 | let c = A::c(); | ||
1853 | c; | ||
1854 | } | ||
1855 | "#), | ||
1856 | @r###" | ||
1857 | [47; 67) '{ ... }': A | ||
1858 | [57; 61) 'A::B': A | ||
1859 | [88; 108) '{ ... }': A | ||
1860 | [98; 102) 'A::C': A | ||
1861 | [121; 178) '{ ... c; }': () | ||
1862 | [131; 132) 'a': A | ||
1863 | [135; 139) 'A::b': fn b() -> A | ||
1864 | [135; 141) 'A::b()': A | ||
1865 | [147; 148) 'a': A | ||
1866 | [158; 159) 'c': A | ||
1867 | [162; 166) 'A::c': fn c() -> A | ||
1868 | [162; 168) 'A::c()': A | ||
1869 | [174; 175) 'c': A | ||
1870 | "### | ||
1871 | ); | ||
1872 | } | ||
1873 | |||
1874 | #[test] | ||
1875 | fn infer_associated_method_with_modules() { | ||
1876 | assert_snapshot!( | ||
1877 | infer(r#" | ||
1878 | mod a { | ||
1879 | struct A; | ||
1880 | impl A { pub fn thing() -> A { A {} }} | ||
1881 | } | ||
1882 | |||
1883 | mod b { | ||
1884 | struct B; | ||
1885 | impl B { pub fn thing() -> u32 { 99 }} | ||
1886 | |||
1887 | mod c { | ||
1888 | struct C; | ||
1889 | impl C { pub fn thing() -> C { C {} }} | ||
1890 | } | ||
1891 | } | ||
1892 | use b::c; | ||
1893 | |||
1894 | fn test() { | ||
1895 | let x = a::A::thing(); | ||
1896 | let y = b::B::thing(); | ||
1897 | let z = c::C::thing(); | ||
1898 | } | ||
1899 | "#), | ||
1900 | @r###" | ||
1901 | [56; 64) '{ A {} }': A | ||
1902 | [58; 62) 'A {}': A | ||
1903 | [126; 132) '{ 99 }': u32 | ||
1904 | [128; 130) '99': u32 | ||
1905 | [202; 210) '{ C {} }': C | ||
1906 | [204; 208) 'C {}': C | ||
1907 | [241; 325) '{ ...g(); }': () | ||
1908 | [251; 252) 'x': A | ||
1909 | [255; 266) 'a::A::thing': fn thing() -> A | ||
1910 | [255; 268) 'a::A::thing()': A | ||
1911 | [278; 279) 'y': u32 | ||
1912 | [282; 293) 'b::B::thing': fn thing() -> u32 | ||
1913 | [282; 295) 'b::B::thing()': u32 | ||
1914 | [305; 306) 'z': C | ||
1915 | [309; 320) 'c::C::thing': fn thing() -> C | ||
1916 | [309; 322) 'c::C::thing()': C | ||
1917 | "### | ||
1918 | ); | ||
1919 | } | ||
1920 | |||
1921 | #[test] | ||
1922 | fn infer_associated_method_generics() { | ||
1923 | assert_snapshot!( | ||
1924 | infer(r#" | ||
1925 | struct Gen<T> { | ||
1926 | val: T | ||
1927 | } | ||
1928 | |||
1929 | impl<T> Gen<T> { | ||
1930 | pub fn make(val: T) -> Gen<T> { | ||
1931 | Gen { val } | ||
1932 | } | ||
1933 | } | ||
1934 | |||
1935 | fn test() { | ||
1936 | let a = Gen::make(0u32); | ||
1937 | } | ||
1938 | "#), | ||
1939 | @r###" | ||
1940 | [64; 67) 'val': T | ||
1941 | [82; 109) '{ ... }': Gen<T> | ||
1942 | [92; 103) 'Gen { val }': Gen<T> | ||
1943 | [98; 101) 'val': T | ||
1944 | [123; 155) '{ ...32); }': () | ||
1945 | [133; 134) 'a': Gen<u32> | ||
1946 | [137; 146) 'Gen::make': fn make<u32>(T) -> Gen<T> | ||
1947 | [137; 152) 'Gen::make(0u32)': Gen<u32> | ||
1948 | [147; 151) '0u32': u32 | ||
1949 | "### | ||
1950 | ); | ||
1951 | } | ||
1952 | |||
1953 | #[test] | ||
1954 | fn infer_associated_method_generics_with_default_param() { | ||
1955 | assert_snapshot!( | ||
1956 | infer(r#" | ||
1957 | struct Gen<T=u32> { | ||
1958 | val: T | ||
1959 | } | ||
1960 | |||
1961 | impl<T> Gen<T> { | ||
1962 | pub fn make() -> Gen<T> { | ||
1963 | loop { } | ||
1964 | } | ||
1965 | } | ||
1966 | |||
1967 | fn test() { | ||
1968 | let a = Gen::make(); | ||
1969 | } | ||
1970 | "#), | ||
1971 | @r###" | ||
1972 | [80; 104) '{ ... }': Gen<T> | ||
1973 | [90; 98) 'loop { }': ! | ||
1974 | [95; 98) '{ }': () | ||
1975 | [118; 146) '{ ...e(); }': () | ||
1976 | [128; 129) 'a': Gen<u32> | ||
1977 | [132; 141) 'Gen::make': fn make<u32>() -> Gen<T> | ||
1978 | [132; 143) 'Gen::make()': Gen<u32> | ||
1979 | "### | ||
1980 | ); | ||
1981 | } | ||
1982 | |||
1983 | #[test] | ||
1984 | fn infer_associated_method_generics_with_default_tuple_param() { | ||
1985 | let t = type_at( | ||
1986 | r#" | ||
1987 | //- /main.rs | ||
1988 | struct Gen<T=()> { | ||
1989 | val: T | ||
1990 | } | ||
1991 | |||
1992 | impl<T> Gen<T> { | ||
1993 | pub fn make() -> Gen<T> { | ||
1994 | loop { } | ||
1995 | } | ||
1996 | } | ||
1997 | |||
1998 | fn test() { | ||
1999 | let a = Gen::make(); | ||
2000 | a.val<|>; | ||
2001 | } | ||
2002 | "#, | ||
2003 | ); | ||
2004 | assert_eq!(t, "()"); | ||
2005 | } | ||
2006 | |||
2007 | #[test] | ||
2008 | fn infer_associated_method_generics_without_args() { | ||
2009 | assert_snapshot!( | ||
2010 | infer(r#" | ||
2011 | struct Gen<T> { | ||
2012 | val: T | ||
2013 | } | ||
2014 | |||
2015 | impl<T> Gen<T> { | ||
2016 | pub fn make() -> Gen<T> { | ||
2017 | loop { } | ||
2018 | } | ||
2019 | } | ||
2020 | |||
2021 | fn test() { | ||
2022 | let a = Gen::<u32>::make(); | ||
2023 | } | ||
2024 | "#), | ||
2025 | @r###" | ||
2026 | [76; 100) '{ ... }': Gen<T> | ||
2027 | [86; 94) 'loop { }': ! | ||
2028 | [91; 94) '{ }': () | ||
2029 | [114; 149) '{ ...e(); }': () | ||
2030 | [124; 125) 'a': Gen<u32> | ||
2031 | [128; 144) 'Gen::<...::make': fn make<u32>() -> Gen<T> | ||
2032 | [128; 146) 'Gen::<...make()': Gen<u32> | ||
2033 | "### | ||
2034 | ); | ||
2035 | } | ||
2036 | |||
2037 | #[test] | ||
2038 | fn infer_associated_method_generics_2_type_params_without_args() { | ||
2039 | assert_snapshot!( | ||
2040 | infer(r#" | ||
2041 | struct Gen<T, U> { | ||
2042 | val: T, | ||
2043 | val2: U, | ||
2044 | } | ||
2045 | |||
2046 | impl<T> Gen<u32, T> { | ||
2047 | pub fn make() -> Gen<u32,T> { | ||
2048 | loop { } | ||
2049 | } | ||
2050 | } | ||
2051 | |||
2052 | fn test() { | ||
2053 | let a = Gen::<u32, u64>::make(); | ||
2054 | } | ||
2055 | "#), | ||
2056 | @r###" | ||
2057 | [102; 126) '{ ... }': Gen<u32, T> | ||
2058 | [112; 120) 'loop { }': ! | ||
2059 | [117; 120) '{ }': () | ||
2060 | [140; 180) '{ ...e(); }': () | ||
2061 | [150; 151) 'a': Gen<u32, u64> | ||
2062 | [154; 175) 'Gen::<...::make': fn make<u64>() -> Gen<u32, T> | ||
2063 | [154; 177) 'Gen::<...make()': Gen<u32, u64> | ||
2064 | "### | ||
2065 | ); | ||
2066 | } | ||
2067 | |||
2068 | #[test] | ||
2069 | fn infer_type_alias() { | ||
2070 | assert_snapshot!( | ||
2071 | infer(r#" | ||
2072 | struct A<X, Y> { x: X, y: Y } | ||
2073 | type Foo = A<u32, i128>; | ||
2074 | type Bar<T> = A<T, u128>; | ||
2075 | type Baz<U, V> = A<V, U>; | ||
2076 | fn test(x: Foo, y: Bar<&str>, z: Baz<i8, u8>) { | ||
2077 | x.x; | ||
2078 | x.y; | ||
2079 | y.x; | ||
2080 | y.y; | ||
2081 | z.x; | ||
2082 | z.y; | ||
2083 | } | ||
2084 | "#), | ||
2085 | @r###" | ||
2086 | [116; 117) 'x': A<u32, i128> | ||
2087 | [124; 125) 'y': A<&str, u128> | ||
2088 | [138; 139) 'z': A<u8, i8> | ||
2089 | [154; 211) '{ ...z.y; }': () | ||
2090 | [160; 161) 'x': A<u32, i128> | ||
2091 | [160; 163) 'x.x': u32 | ||
2092 | [169; 170) 'x': A<u32, i128> | ||
2093 | [169; 172) 'x.y': i128 | ||
2094 | [178; 179) 'y': A<&str, u128> | ||
2095 | [178; 181) 'y.x': &str | ||
2096 | [187; 188) 'y': A<&str, u128> | ||
2097 | [187; 190) 'y.y': u128 | ||
2098 | [196; 197) 'z': A<u8, i8> | ||
2099 | [196; 199) 'z.x': u8 | ||
2100 | [205; 206) 'z': A<u8, i8> | ||
2101 | [205; 208) 'z.y': i8 | ||
2102 | "### | ||
2103 | ) | ||
2104 | } | ||
2105 | |||
2106 | #[test] | ||
2107 | #[should_panic] // we currently can't handle this | ||
2108 | fn recursive_type_alias() { | ||
2109 | assert_snapshot!( | ||
2110 | infer(r#" | ||
2111 | struct A<X> {} | ||
2112 | type Foo = Foo; | ||
2113 | type Bar = A<Bar>; | ||
2114 | fn test(x: Foo) {} | ||
2115 | "#), | ||
2116 | @"" | ||
2117 | ) | ||
2118 | } | ||
2119 | |||
2120 | #[test] | ||
2121 | fn no_panic_on_field_of_enum() { | ||
2122 | assert_snapshot!( | ||
2123 | infer(r#" | ||
2124 | enum X {} | ||
2125 | |||
2126 | fn test(x: X) { | ||
2127 | x.some_field; | ||
2128 | } | ||
2129 | "#), | ||
2130 | @r###" | ||
2131 | [20; 21) 'x': X | ||
2132 | [26; 47) '{ ...eld; }': () | ||
2133 | [32; 33) 'x': X | ||
2134 | [32; 44) 'x.some_field': {unknown} | ||
2135 | "### | ||
2136 | ); | ||
2137 | } | ||
2138 | |||
2139 | #[test] | ||
2140 | fn bug_585() { | ||
2141 | assert_snapshot!( | ||
2142 | infer(r#" | ||
2143 | fn test() { | ||
2144 | X {}; | ||
2145 | match x { | ||
2146 | A::B {} => (), | ||
2147 | A::Y() => (), | ||
2148 | } | ||
2149 | } | ||
2150 | "#), | ||
2151 | @r###" | ||
2152 | [11; 89) '{ ... } }': () | ||
2153 | [17; 21) 'X {}': {unknown} | ||
2154 | [27; 87) 'match ... }': () | ||
2155 | [33; 34) 'x': {unknown} | ||
2156 | [45; 52) 'A::B {}': {unknown} | ||
2157 | [56; 58) '()': () | ||
2158 | [68; 74) 'A::Y()': {unknown} | ||
2159 | [78; 80) '()': () | ||
2160 | "### | ||
2161 | ); | ||
2162 | } | ||
2163 | |||
2164 | #[test] | ||
2165 | fn bug_651() { | ||
2166 | assert_snapshot!( | ||
2167 | infer(r#" | ||
2168 | fn quux() { | ||
2169 | let y = 92; | ||
2170 | 1 + y; | ||
2171 | } | ||
2172 | "#), | ||
2173 | @r###" | ||
2174 | [11; 41) '{ ...+ y; }': () | ||
2175 | [21; 22) 'y': i32 | ||
2176 | [25; 27) '92': i32 | ||
2177 | [33; 34) '1': i32 | ||
2178 | [33; 38) '1 + y': i32 | ||
2179 | [37; 38) 'y': i32 | ||
2180 | "### | ||
2181 | ); | ||
2182 | } | ||
2183 | |||
2184 | #[test] | ||
2185 | fn recursive_vars() { | ||
2186 | covers!(type_var_cycles_resolve_completely); | ||
2187 | covers!(type_var_cycles_resolve_as_possible); | ||
2188 | assert_snapshot!( | ||
2189 | infer(r#" | ||
2190 | fn test() { | ||
2191 | let y = unknown; | ||
2192 | [y, &y]; | ||
2193 | } | ||
2194 | "#), | ||
2195 | @r###" | ||
2196 | [11; 48) '{ ...&y]; }': () | ||
2197 | [21; 22) 'y': &{unknown} | ||
2198 | [25; 32) 'unknown': &{unknown} | ||
2199 | [38; 45) '[y, &y]': [&&{unknown};_] | ||
2200 | [39; 40) 'y': &{unknown} | ||
2201 | [42; 44) '&y': &&{unknown} | ||
2202 | [43; 44) 'y': &{unknown} | ||
2203 | "### | ||
2204 | ); | ||
2205 | } | ||
2206 | |||
2207 | #[test] | ||
2208 | fn recursive_vars_2() { | ||
2209 | covers!(type_var_cycles_resolve_completely); | ||
2210 | covers!(type_var_cycles_resolve_as_possible); | ||
2211 | assert_snapshot!( | ||
2212 | infer(r#" | ||
2213 | fn test() { | ||
2214 | let x = unknown; | ||
2215 | let y = unknown; | ||
2216 | [(x, y), (&y, &x)]; | ||
2217 | } | ||
2218 | "#), | ||
2219 | @r###" | ||
2220 | [11; 80) '{ ...x)]; }': () | ||
2221 | [21; 22) 'x': &&{unknown} | ||
2222 | [25; 32) 'unknown': &&{unknown} | ||
2223 | [42; 43) 'y': &&{unknown} | ||
2224 | [46; 53) 'unknown': &&{unknown} | ||
2225 | [59; 77) '[(x, y..., &x)]': [(&&&{unknown}, &&&{unknown});_] | ||
2226 | [60; 66) '(x, y)': (&&&{unknown}, &&&{unknown}) | ||
2227 | [61; 62) 'x': &&{unknown} | ||
2228 | [64; 65) 'y': &&{unknown} | ||
2229 | [68; 76) '(&y, &x)': (&&&{unknown}, &&&{unknown}) | ||
2230 | [69; 71) '&y': &&&{unknown} | ||
2231 | [70; 71) 'y': &&{unknown} | ||
2232 | [73; 75) '&x': &&&{unknown} | ||
2233 | [74; 75) 'x': &&{unknown} | ||
2234 | "### | ||
2235 | ); | ||
2236 | } | ||
2237 | |||
2238 | #[test] | ||
2239 | fn infer_type_param() { | ||
2240 | assert_snapshot!( | ||
2241 | infer(r#" | ||
2242 | fn id<T>(x: T) -> T { | ||
2243 | x | ||
2244 | } | ||
2245 | |||
2246 | fn clone<T>(x: &T) -> T { | ||
2247 | *x | ||
2248 | } | ||
2249 | |||
2250 | fn test() { | ||
2251 | let y = 10u32; | ||
2252 | id(y); | ||
2253 | let x: bool = clone(z); | ||
2254 | id::<i128>(1); | ||
2255 | } | ||
2256 | "#), | ||
2257 | @r###" | ||
2258 | [10; 11) 'x': T | ||
2259 | [21; 30) '{ x }': T | ||
2260 | [27; 28) 'x': T | ||
2261 | [44; 45) 'x': &T | ||
2262 | [56; 66) '{ *x }': T | ||
2263 | [62; 64) '*x': T | ||
2264 | [63; 64) 'x': &T | ||
2265 | [78; 158) '{ ...(1); }': () | ||
2266 | [88; 89) 'y': u32 | ||
2267 | [92; 97) '10u32': u32 | ||
2268 | [103; 105) 'id': fn id<u32>(T) -> T | ||
2269 | [103; 108) 'id(y)': u32 | ||
2270 | [106; 107) 'y': u32 | ||
2271 | [118; 119) 'x': bool | ||
2272 | [128; 133) 'clone': fn clone<bool>(&T) -> T | ||
2273 | [128; 136) 'clone(z)': bool | ||
2274 | [134; 135) 'z': &bool | ||
2275 | [142; 152) 'id::<i128>': fn id<i128>(T) -> T | ||
2276 | [142; 155) 'id::<i128>(1)': i128 | ||
2277 | [153; 154) '1': i128 | ||
2278 | "### | ||
2279 | ); | ||
2280 | } | ||
2281 | |||
2282 | #[test] | ||
2283 | fn infer_std_crash_1() { | ||
2284 | // caused stack overflow, taken from std | ||
2285 | assert_snapshot!( | ||
2286 | infer(r#" | ||
2287 | enum Maybe<T> { | ||
2288 | Real(T), | ||
2289 | Fake, | ||
2290 | } | ||
2291 | |||
2292 | fn write() { | ||
2293 | match something_unknown { | ||
2294 | Maybe::Real(ref mut something) => (), | ||
2295 | } | ||
2296 | } | ||
2297 | "#), | ||
2298 | @r###" | ||
2299 | [54; 139) '{ ... } }': () | ||
2300 | [60; 137) 'match ... }': () | ||
2301 | [66; 83) 'someth...nknown': Maybe<{unknown}> | ||
2302 | [94; 124) 'Maybe:...thing)': Maybe<{unknown}> | ||
2303 | [106; 123) 'ref mu...ething': &mut {unknown} | ||
2304 | [128; 130) '()': () | ||
2305 | "### | ||
2306 | ); | ||
2307 | } | ||
2308 | |||
2309 | #[test] | ||
2310 | fn infer_std_crash_2() { | ||
2311 | covers!(type_var_resolves_to_int_var); | ||
2312 | // caused "equating two type variables, ...", taken from std | ||
2313 | assert_snapshot!( | ||
2314 | infer(r#" | ||
2315 | fn test_line_buffer() { | ||
2316 | &[0, b'\n', 1, b'\n']; | ||
2317 | } | ||
2318 | "#), | ||
2319 | @r###" | ||
2320 | [23; 53) '{ ...n']; }': () | ||
2321 | [29; 50) '&[0, b...b'\n']': &[u8;_] | ||
2322 | [30; 50) '[0, b'...b'\n']': [u8;_] | ||
2323 | [31; 32) '0': u8 | ||
2324 | [34; 39) 'b'\n'': u8 | ||
2325 | [41; 42) '1': u8 | ||
2326 | [44; 49) 'b'\n'': u8 | ||
2327 | "### | ||
2328 | ); | ||
2329 | } | ||
2330 | |||
2331 | #[test] | ||
2332 | fn infer_std_crash_3() { | ||
2333 | // taken from rustc | ||
2334 | assert_snapshot!( | ||
2335 | infer(r#" | ||
2336 | pub fn compute() { | ||
2337 | match nope!() { | ||
2338 | SizeSkeleton::Pointer { non_zero: true, tail } => {} | ||
2339 | } | ||
2340 | } | ||
2341 | "#), | ||
2342 | @r###" | ||
2343 | [18; 108) '{ ... } }': () | ||
2344 | [24; 106) 'match ... }': () | ||
2345 | [30; 37) 'nope!()': {unknown} | ||
2346 | [48; 94) 'SizeSk...tail }': {unknown} | ||
2347 | [82; 86) 'true': {unknown} | ||
2348 | [88; 92) 'tail': {unknown} | ||
2349 | [98; 100) '{}': () | ||
2350 | "### | ||
2351 | ); | ||
2352 | } | ||
2353 | |||
2354 | #[test] | ||
2355 | fn infer_std_crash_4() { | ||
2356 | // taken from rustc | ||
2357 | assert_snapshot!( | ||
2358 | infer(r#" | ||
2359 | pub fn primitive_type() { | ||
2360 | match *self { | ||
2361 | BorrowedRef { type_: Primitive(p), ..} => {}, | ||
2362 | } | ||
2363 | } | ||
2364 | "#), | ||
2365 | @r###" | ||
2366 | [25; 106) '{ ... } }': () | ||
2367 | [31; 104) 'match ... }': () | ||
2368 | [37; 42) '*self': {unknown} | ||
2369 | [38; 42) 'self': {unknown} | ||
2370 | [53; 91) 'Borrow...), ..}': {unknown} | ||
2371 | [74; 86) 'Primitive(p)': {unknown} | ||
2372 | [84; 85) 'p': {unknown} | ||
2373 | [95; 97) '{}': () | ||
2374 | "### | ||
2375 | ); | ||
2376 | } | ||
2377 | |||
2378 | #[test] | ||
2379 | fn infer_std_crash_5() { | ||
2380 | // taken from rustc | ||
2381 | assert_snapshot!( | ||
2382 | infer(r#" | ||
2383 | fn extra_compiler_flags() { | ||
2384 | for content in doesnt_matter { | ||
2385 | let name = if doesnt_matter { | ||
2386 | first | ||
2387 | } else { | ||
2388 | &content | ||
2389 | }; | ||
2390 | |||
2391 | let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) { | ||
2392 | name | ||
2393 | } else { | ||
2394 | content | ||
2395 | }; | ||
2396 | } | ||
2397 | } | ||
2398 | "#), | ||
2399 | @r###" | ||
2400 | [27; 323) '{ ... } }': () | ||
2401 | [33; 321) 'for co... }': () | ||
2402 | [37; 44) 'content': &{unknown} | ||
2403 | [48; 61) 'doesnt_matter': {unknown} | ||
2404 | [62; 321) '{ ... }': () | ||
2405 | [76; 80) 'name': &&{unknown} | ||
2406 | [83; 167) 'if doe... }': &&{unknown} | ||
2407 | [86; 99) 'doesnt_matter': bool | ||
2408 | [100; 129) '{ ... }': &&{unknown} | ||
2409 | [114; 119) 'first': &&{unknown} | ||
2410 | [135; 167) '{ ... }': &&{unknown} | ||
2411 | [149; 157) '&content': &&{unknown} | ||
2412 | [150; 157) 'content': &{unknown} | ||
2413 | [182; 189) 'content': &{unknown} | ||
2414 | [192; 314) 'if ICE... }': &{unknown} | ||
2415 | [195; 232) 'ICE_RE..._VALUE': {unknown} | ||
2416 | [195; 248) 'ICE_RE...&name)': bool | ||
2417 | [242; 247) '&name': &&&{unknown} | ||
2418 | [243; 247) 'name': &&{unknown} | ||
2419 | [249; 277) '{ ... }': &&{unknown} | ||
2420 | [263; 267) 'name': &&{unknown} | ||
2421 | [283; 314) '{ ... }': &{unknown} | ||
2422 | [297; 304) 'content': &{unknown} | ||
2423 | "### | ||
2424 | ); | ||
2425 | } | ||
2426 | |||
2427 | #[test] | ||
2428 | fn infer_nested_generics_crash() { | ||
2429 | // another crash found typechecking rustc | ||
2430 | assert_snapshot!( | ||
2431 | infer(r#" | ||
2432 | struct Canonical<V> { | ||
2433 | value: V, | ||
2434 | } | ||
2435 | struct QueryResponse<V> { | ||
2436 | value: V, | ||
2437 | } | ||
2438 | fn test<R>(query_response: Canonical<QueryResponse<R>>) { | ||
2439 | &query_response.value; | ||
2440 | } | ||
2441 | "#), | ||
2442 | @r###" | ||
2443 | [92; 106) 'query_response': Canonical<QueryResponse<R>> | ||
2444 | [137; 167) '{ ...lue; }': () | ||
2445 | [143; 164) '&query....value': &QueryResponse<R> | ||
2446 | [144; 158) 'query_response': Canonical<QueryResponse<R>> | ||
2447 | [144; 164) 'query_....value': QueryResponse<R> | ||
2448 | "### | ||
2449 | ); | ||
2450 | } | ||
2451 | |||
2452 | #[test] | ||
2453 | fn bug_1030() { | ||
2454 | assert_snapshot!(infer(r#" | ||
2455 | struct HashSet<T, H>; | ||
2456 | struct FxHasher; | ||
2457 | type FxHashSet<T> = HashSet<T, FxHasher>; | ||
2458 | |||
2459 | impl<T, H> HashSet<T, H> { | ||
2460 | fn default() -> HashSet<T, H> {} | ||
2461 | } | ||
2462 | |||
2463 | pub fn main_loop() { | ||
2464 | FxHashSet::default(); | ||
2465 | } | ||
2466 | "#), | ||
2467 | @r###" | ||
2468 | [144; 146) '{}': () | ||
2469 | [169; 198) '{ ...t(); }': () | ||
2470 | [175; 193) 'FxHash...efault': fn default<{unknown}, FxHasher>() -> HashSet<T, H> | ||
2471 | [175; 195) 'FxHash...ault()': HashSet<{unknown}, FxHasher> | ||
2472 | "### | ||
2473 | ); | ||
2474 | } | ||
2475 | |||
2476 | #[test] | ||
2477 | fn cross_crate_associated_method_call() { | ||
2478 | let (db, pos) = TestDB::with_position( | ||
2479 | r#" | ||
2480 | //- /main.rs crate:main deps:other_crate | ||
2481 | fn test() { | ||
2482 | let x = other_crate::foo::S::thing(); | ||
2483 | x<|>; | ||
2484 | } | ||
2485 | |||
2486 | //- /lib.rs crate:other_crate | ||
2487 | mod foo { | ||
2488 | struct S; | ||
2489 | impl S { | ||
2490 | fn thing() -> i128 {} | ||
2491 | } | ||
2492 | } | ||
2493 | "#, | ||
2494 | ); | ||
2495 | assert_eq!("i128", type_at_pos(&db, pos)); | ||
2496 | } | ||
2497 | |||
2498 | #[test] | ||
2499 | fn infer_const() { | ||
2500 | assert_snapshot!( | ||
2501 | infer(r#" | ||
2502 | struct Foo; | ||
2503 | impl Foo { const ASSOC_CONST: u32 = 0; } | ||
2504 | const GLOBAL_CONST: u32 = 101; | ||
2505 | fn test() { | ||
2506 | const LOCAL_CONST: u32 = 99; | ||
2507 | let x = LOCAL_CONST; | ||
2508 | let z = GLOBAL_CONST; | ||
2509 | let id = Foo::ASSOC_CONST; | ||
2510 | } | ||
2511 | "#), | ||
2512 | @r###" | ||
2513 | [49; 50) '0': u32 | ||
2514 | [80; 83) '101': u32 | ||
2515 | [95; 213) '{ ...NST; }': () | ||
2516 | [138; 139) 'x': {unknown} | ||
2517 | [142; 153) 'LOCAL_CONST': {unknown} | ||
2518 | [163; 164) 'z': u32 | ||
2519 | [167; 179) 'GLOBAL_CONST': u32 | ||
2520 | [189; 191) 'id': u32 | ||
2521 | [194; 210) 'Foo::A..._CONST': u32 | ||
2522 | "### | ||
2523 | ); | ||
2524 | } | ||
2525 | |||
2526 | #[test] | ||
2527 | fn infer_static() { | ||
2528 | assert_snapshot!( | ||
2529 | infer(r#" | ||
2530 | static GLOBAL_STATIC: u32 = 101; | ||
2531 | static mut GLOBAL_STATIC_MUT: u32 = 101; | ||
2532 | fn test() { | ||
2533 | static LOCAL_STATIC: u32 = 99; | ||
2534 | static mut LOCAL_STATIC_MUT: u32 = 99; | ||
2535 | let x = LOCAL_STATIC; | ||
2536 | let y = LOCAL_STATIC_MUT; | ||
2537 | let z = GLOBAL_STATIC; | ||
2538 | let w = GLOBAL_STATIC_MUT; | ||
2539 | } | ||
2540 | "#), | ||
2541 | @r###" | ||
2542 | [29; 32) '101': u32 | ||
2543 | [70; 73) '101': u32 | ||
2544 | [85; 280) '{ ...MUT; }': () | ||
2545 | [173; 174) 'x': {unknown} | ||
2546 | [177; 189) 'LOCAL_STATIC': {unknown} | ||
2547 | [199; 200) 'y': {unknown} | ||
2548 | [203; 219) 'LOCAL_...IC_MUT': {unknown} | ||
2549 | [229; 230) 'z': u32 | ||
2550 | [233; 246) 'GLOBAL_STATIC': u32 | ||
2551 | [256; 257) 'w': u32 | ||
2552 | [260; 277) 'GLOBAL...IC_MUT': u32 | ||
2553 | "### | ||
2554 | ); | ||
2555 | } | ||
2556 | |||
2557 | #[test] | ||
2558 | fn infer_trait_method_simple() { | ||
2559 | // the trait implementation is intentionally incomplete -- it shouldn't matter | ||
2560 | assert_snapshot!( | ||
2561 | infer(r#" | ||
2562 | trait Trait1 { | ||
2563 | fn method(&self) -> u32; | ||
2564 | } | ||
2565 | struct S1; | ||
2566 | impl Trait1 for S1 {} | ||
2567 | trait Trait2 { | ||
2568 | fn method(&self) -> i128; | ||
2569 | } | ||
2570 | struct S2; | ||
2571 | impl Trait2 for S2 {} | ||
2572 | fn test() { | ||
2573 | S1.method(); // -> u32 | ||
2574 | S2.method(); // -> i128 | ||
2575 | } | ||
2576 | "#), | ||
2577 | @r###" | ||
2578 | [31; 35) 'self': &Self | ||
2579 | [110; 114) 'self': &Self | ||
2580 | [170; 228) '{ ...i128 }': () | ||
2581 | [176; 178) 'S1': S1 | ||
2582 | [176; 187) 'S1.method()': u32 | ||
2583 | [203; 205) 'S2': S2 | ||
2584 | [203; 214) 'S2.method()': i128 | ||
2585 | "### | ||
2586 | ); | ||
2587 | } | ||
2588 | |||
2589 | #[test] | ||
2590 | fn infer_trait_method_scoped() { | ||
2591 | // the trait implementation is intentionally incomplete -- it shouldn't matter | ||
2592 | assert_snapshot!( | ||
2593 | infer(r#" | ||
2594 | struct S; | ||
2595 | mod foo { | ||
2596 | pub trait Trait1 { | ||
2597 | fn method(&self) -> u32; | ||
2598 | } | ||
2599 | impl Trait1 for super::S {} | ||
2600 | } | ||
2601 | mod bar { | ||
2602 | pub trait Trait2 { | ||
2603 | fn method(&self) -> i128; | ||
2604 | } | ||
2605 | impl Trait2 for super::S {} | ||
2606 | } | ||
2607 | |||
2608 | mod foo_test { | ||
2609 | use super::S; | ||
2610 | use super::foo::Trait1; | ||
2611 | fn test() { | ||
2612 | S.method(); // -> u32 | ||
2613 | } | ||
2614 | } | ||
2615 | |||
2616 | mod bar_test { | ||
2617 | use super::S; | ||
2618 | use super::bar::Trait2; | ||
2619 | fn test() { | ||
2620 | S.method(); // -> i128 | ||
2621 | } | ||
2622 | } | ||
2623 | "#), | ||
2624 | @r###" | ||
2625 | [63; 67) 'self': &Self | ||
2626 | [169; 173) 'self': &Self | ||
2627 | [300; 337) '{ ... }': () | ||
2628 | [310; 311) 'S': S | ||
2629 | [310; 320) 'S.method()': u32 | ||
2630 | [416; 454) '{ ... }': () | ||
2631 | [426; 427) 'S': S | ||
2632 | [426; 436) 'S.method()': i128 | ||
2633 | "### | ||
2634 | ); | ||
2635 | } | ||
2636 | |||
2637 | #[test] | ||
2638 | fn infer_trait_method_generic_1() { | ||
2639 | // the trait implementation is intentionally incomplete -- it shouldn't matter | ||
2640 | assert_snapshot!( | ||
2641 | infer(r#" | ||
2642 | trait Trait<T> { | ||
2643 | fn method(&self) -> T; | ||
2644 | } | ||
2645 | struct S; | ||
2646 | impl Trait<u32> for S {} | ||
2647 | fn test() { | ||
2648 | S.method(); | ||
2649 | } | ||
2650 | "#), | ||
2651 | @r###" | ||
2652 | [33; 37) 'self': &Self | ||
2653 | [92; 111) '{ ...d(); }': () | ||
2654 | [98; 99) 'S': S | ||
2655 | [98; 108) 'S.method()': u32 | ||
2656 | "### | ||
2657 | ); | ||
2658 | } | ||
2659 | |||
2660 | #[test] | ||
2661 | fn infer_trait_method_generic_more_params() { | ||
2662 | // the trait implementation is intentionally incomplete -- it shouldn't matter | ||
2663 | assert_snapshot!( | ||
2664 | infer(r#" | ||
2665 | trait Trait<T1, T2, T3> { | ||
2666 | fn method1(&self) -> (T1, T2, T3); | ||
2667 | fn method2(&self) -> (T3, T2, T1); | ||
2668 | } | ||
2669 | struct S1; | ||
2670 | impl Trait<u8, u16, u32> for S1 {} | ||
2671 | struct S2; | ||
2672 | impl<T> Trait<i8, i16, T> for S2 {} | ||
2673 | fn test() { | ||
2674 | S1.method1(); // u8, u16, u32 | ||
2675 | S1.method2(); // u32, u16, u8 | ||
2676 | S2.method1(); // i8, i16, {unknown} | ||
2677 | S2.method2(); // {unknown}, i16, i8 | ||
2678 | } | ||
2679 | "#), | ||
2680 | @r###" | ||
2681 | [43; 47) 'self': &Self | ||
2682 | [82; 86) 'self': &Self | ||
2683 | [210; 361) '{ ..., i8 }': () | ||
2684 | [216; 218) 'S1': S1 | ||
2685 | [216; 228) 'S1.method1()': (u8, u16, u32) | ||
2686 | [250; 252) 'S1': S1 | ||
2687 | [250; 262) 'S1.method2()': (u32, u16, u8) | ||
2688 | [284; 286) 'S2': S2 | ||
2689 | [284; 296) 'S2.method1()': (i8, i16, {unknown}) | ||
2690 | [324; 326) 'S2': S2 | ||
2691 | [324; 336) 'S2.method2()': ({unknown}, i16, i8) | ||
2692 | "### | ||
2693 | ); | ||
2694 | } | ||
2695 | |||
2696 | #[test] | ||
2697 | fn infer_trait_method_generic_2() { | ||
2698 | // the trait implementation is intentionally incomplete -- it shouldn't matter | ||
2699 | assert_snapshot!( | ||
2700 | infer(r#" | ||
2701 | trait Trait<T> { | ||
2702 | fn method(&self) -> T; | ||
2703 | } | ||
2704 | struct S<T>(T); | ||
2705 | impl<U> Trait<U> for S<U> {} | ||
2706 | fn test() { | ||
2707 | S(1u32).method(); | ||
2708 | } | ||
2709 | "#), | ||
2710 | @r###" | ||
2711 | [33; 37) 'self': &Self | ||
2712 | [102; 127) '{ ...d(); }': () | ||
2713 | [108; 109) 'S': S<u32>(T) -> S<T> | ||
2714 | [108; 115) 'S(1u32)': S<u32> | ||
2715 | [108; 124) 'S(1u32...thod()': u32 | ||
2716 | [110; 114) '1u32': u32 | ||
2717 | "### | ||
2718 | ); | ||
2719 | } | ||
2720 | |||
2721 | #[test] | ||
2722 | fn infer_trait_assoc_method() { | ||
2723 | assert_snapshot!( | ||
2724 | infer(r#" | ||
2725 | trait Default { | ||
2726 | fn default() -> Self; | ||
2727 | } | ||
2728 | struct S; | ||
2729 | impl Default for S {} | ||
2730 | fn test() { | ||
2731 | let s1: S = Default::default(); | ||
2732 | let s2 = S::default(); | ||
2733 | let s3 = <S as Default>::default(); | ||
2734 | } | ||
2735 | "#), | ||
2736 | @r###" | ||
2737 | [87; 193) '{ ...t(); }': () | ||
2738 | [97; 99) 's1': S | ||
2739 | [105; 121) 'Defaul...efault': fn default<S>() -> Self | ||
2740 | [105; 123) 'Defaul...ault()': S | ||
2741 | [133; 135) 's2': S | ||
2742 | [138; 148) 'S::default': fn default<S>() -> Self | ||
2743 | [138; 150) 'S::default()': S | ||
2744 | [160; 162) 's3': S | ||
2745 | [165; 188) '<S as ...efault': fn default<S>() -> Self | ||
2746 | [165; 190) '<S as ...ault()': S | ||
2747 | "### | ||
2748 | ); | ||
2749 | } | ||
2750 | |||
2751 | #[test] | ||
2752 | fn infer_trait_assoc_method_generics_1() { | ||
2753 | assert_snapshot!( | ||
2754 | infer(r#" | ||
2755 | trait Trait<T> { | ||
2756 | fn make() -> T; | ||
2757 | } | ||
2758 | struct S; | ||
2759 | impl Trait<u32> for S {} | ||
2760 | struct G<T>; | ||
2761 | impl<T> Trait<T> for G<T> {} | ||
2762 | fn test() { | ||
2763 | let a = S::make(); | ||
2764 | let b = G::<u64>::make(); | ||
2765 | let c: f64 = G::make(); | ||
2766 | } | ||
2767 | "#), | ||
2768 | @r###" | ||
2769 | [127; 211) '{ ...e(); }': () | ||
2770 | [137; 138) 'a': u32 | ||
2771 | [141; 148) 'S::make': fn make<S, u32>() -> T | ||
2772 | [141; 150) 'S::make()': u32 | ||
2773 | [160; 161) 'b': u64 | ||
2774 | [164; 178) 'G::<u64>::make': fn make<G<u64>, u64>() -> T | ||
2775 | [164; 180) 'G::<u6...make()': u64 | ||
2776 | [190; 191) 'c': f64 | ||
2777 | [199; 206) 'G::make': fn make<G<f64>, f64>() -> T | ||
2778 | [199; 208) 'G::make()': f64 | ||
2779 | "### | ||
2780 | ); | ||
2781 | } | ||
2782 | |||
2783 | #[test] | ||
2784 | fn infer_trait_assoc_method_generics_2() { | ||
2785 | assert_snapshot!( | ||
2786 | infer(r#" | ||
2787 | trait Trait<T> { | ||
2788 | fn make<U>() -> (T, U); | ||
2789 | } | ||
2790 | struct S; | ||
2791 | impl Trait<u32> for S {} | ||
2792 | struct G<T>; | ||
2793 | impl<T> Trait<T> for G<T> {} | ||
2794 | fn test() { | ||
2795 | let a = S::make::<i64>(); | ||
2796 | let b: (_, i64) = S::make(); | ||
2797 | let c = G::<u32>::make::<i64>(); | ||
2798 | let d: (u32, _) = G::make::<i64>(); | ||
2799 | let e: (u32, i64) = G::make(); | ||
2800 | } | ||
2801 | "#), | ||
2802 | @r###" | ||
2803 | [135; 313) '{ ...e(); }': () | ||
2804 | [145; 146) 'a': (u32, i64) | ||
2805 | [149; 163) 'S::make::<i64>': fn make<S, u32, i64>() -> (T, U) | ||
2806 | [149; 165) 'S::mak...i64>()': (u32, i64) | ||
2807 | [175; 176) 'b': (u32, i64) | ||
2808 | [189; 196) 'S::make': fn make<S, u32, i64>() -> (T, U) | ||
2809 | [189; 198) 'S::make()': (u32, i64) | ||
2810 | [208; 209) 'c': (u32, i64) | ||
2811 | [212; 233) 'G::<u3...:<i64>': fn make<G<u32>, u32, i64>() -> (T, U) | ||
2812 | [212; 235) 'G::<u3...i64>()': (u32, i64) | ||
2813 | [245; 246) 'd': (u32, i64) | ||
2814 | [259; 273) 'G::make::<i64>': fn make<G<u32>, u32, i64>() -> (T, U) | ||
2815 | [259; 275) 'G::mak...i64>()': (u32, i64) | ||
2816 | [285; 286) 'e': (u32, i64) | ||
2817 | [301; 308) 'G::make': fn make<G<u32>, u32, i64>() -> (T, U) | ||
2818 | [301; 310) 'G::make()': (u32, i64) | ||
2819 | "### | ||
2820 | ); | ||
2821 | } | ||
2822 | |||
2823 | #[test] | ||
2824 | fn infer_trait_assoc_method_generics_3() { | ||
2825 | assert_snapshot!( | ||
2826 | infer(r#" | ||
2827 | trait Trait<T> { | ||
2828 | fn make() -> (Self, T); | ||
2829 | } | ||
2830 | struct S<T>; | ||
2831 | impl Trait<i64> for S<i32> {} | ||
2832 | fn test() { | ||
2833 | let a = S::make(); | ||
2834 | } | ||
2835 | "#), | ||
2836 | @r###" | ||
2837 | [101; 127) '{ ...e(); }': () | ||
2838 | [111; 112) 'a': (S<i32>, i64) | ||
2839 | [115; 122) 'S::make': fn make<S<i32>, i64>() -> (Self, T) | ||
2840 | [115; 124) 'S::make()': (S<i32>, i64) | ||
2841 | "### | ||
2842 | ); | ||
2843 | } | ||
2844 | |||
2845 | #[test] | ||
2846 | fn infer_trait_assoc_method_generics_4() { | ||
2847 | assert_snapshot!( | ||
2848 | infer(r#" | ||
2849 | trait Trait<T> { | ||
2850 | fn make() -> (Self, T); | ||
2851 | } | ||
2852 | struct S<T>; | ||
2853 | impl Trait<i64> for S<u64> {} | ||
2854 | impl Trait<i32> for S<u32> {} | ||
2855 | fn test() { | ||
2856 | let a: (S<u64>, _) = S::make(); | ||
2857 | let b: (_, i32) = S::make(); | ||
2858 | } | ||
2859 | "#), | ||
2860 | @r###" | ||
2861 | [131; 203) '{ ...e(); }': () | ||
2862 | [141; 142) 'a': (S<u64>, i64) | ||
2863 | [158; 165) 'S::make': fn make<S<u64>, i64>() -> (Self, T) | ||
2864 | [158; 167) 'S::make()': (S<u64>, i64) | ||
2865 | [177; 178) 'b': (S<u32>, i32) | ||
2866 | [191; 198) 'S::make': fn make<S<u32>, i32>() -> (Self, T) | ||
2867 | [191; 200) 'S::make()': (S<u32>, i32) | ||
2868 | "### | ||
2869 | ); | ||
2870 | } | ||
2871 | |||
2872 | #[test] | ||
2873 | fn infer_trait_assoc_method_generics_5() { | ||
2874 | assert_snapshot!( | ||
2875 | infer(r#" | ||
2876 | trait Trait<T> { | ||
2877 | fn make<U>() -> (Self, T, U); | ||
2878 | } | ||
2879 | struct S<T>; | ||
2880 | impl Trait<i64> for S<u64> {} | ||
2881 | fn test() { | ||
2882 | let a = <S as Trait<i64>>::make::<u8>(); | ||
2883 | let b: (S<u64>, _, _) = Trait::<i64>::make::<u8>(); | ||
2884 | } | ||
2885 | "#), | ||
2886 | @r###" | ||
2887 | [107; 211) '{ ...>(); }': () | ||
2888 | [117; 118) 'a': (S<u64>, i64, u8) | ||
2889 | [121; 150) '<S as ...::<u8>': fn make<S<u64>, i64, u8>() -> (Self, T, U) | ||
2890 | [121; 152) '<S as ...<u8>()': (S<u64>, i64, u8) | ||
2891 | [162; 163) 'b': (S<u64>, i64, u8) | ||
2892 | [182; 206) 'Trait:...::<u8>': fn make<S<u64>, i64, u8>() -> (Self, T, U) | ||
2893 | [182; 208) 'Trait:...<u8>()': (S<u64>, i64, u8) | ||
2894 | "### | ||
2895 | ); | ||
2896 | } | ||
2897 | |||
2898 | #[test] | ||
2899 | fn infer_from_bound_1() { | ||
2900 | assert_snapshot!( | ||
2901 | infer(r#" | ||
2902 | trait Trait<T> {} | ||
2903 | struct S<T>(T); | ||
2904 | impl<U> Trait<U> for S<U> {} | ||
2905 | fn foo<T: Trait<u32>>(t: T) {} | ||
2906 | fn test() { | ||
2907 | let s = S(unknown); | ||
2908 | foo(s); | ||
2909 | } | ||
2910 | "#), | ||
2911 | @r###" | ||
2912 | [86; 87) 't': T | ||
2913 | [92; 94) '{}': () | ||
2914 | [105; 144) '{ ...(s); }': () | ||
2915 | [115; 116) 's': S<u32> | ||
2916 | [119; 120) 'S': S<u32>(T) -> S<T> | ||
2917 | [119; 129) 'S(unknown)': S<u32> | ||
2918 | [121; 128) 'unknown': u32 | ||
2919 | [135; 138) 'foo': fn foo<S<u32>>(T) -> () | ||
2920 | [135; 141) 'foo(s)': () | ||
2921 | [139; 140) 's': S<u32> | ||
2922 | "### | ||
2923 | ); | ||
2924 | } | ||
2925 | |||
2926 | #[test] | ||
2927 | fn infer_from_bound_2() { | ||
2928 | assert_snapshot!( | ||
2929 | infer(r#" | ||
2930 | trait Trait<T> {} | ||
2931 | struct S<T>(T); | ||
2932 | impl<U> Trait<U> for S<U> {} | ||
2933 | fn foo<U, T: Trait<U>>(t: T) -> U {} | ||
2934 | fn test() { | ||
2935 | let s = S(unknown); | ||
2936 | let x: u32 = foo(s); | ||
2937 | } | ||
2938 | "#), | ||
2939 | @r###" | ||
2940 | [87; 88) 't': T | ||
2941 | [98; 100) '{}': () | ||
2942 | [111; 163) '{ ...(s); }': () | ||
2943 | [121; 122) 's': S<u32> | ||
2944 | [125; 126) 'S': S<u32>(T) -> S<T> | ||
2945 | [125; 135) 'S(unknown)': S<u32> | ||
2946 | [127; 134) 'unknown': u32 | ||
2947 | [145; 146) 'x': u32 | ||
2948 | [154; 157) 'foo': fn foo<u32, S<u32>>(T) -> U | ||
2949 | [154; 160) 'foo(s)': u32 | ||
2950 | [158; 159) 's': S<u32> | ||
2951 | "### | ||
2952 | ); | ||
2953 | } | ||
2954 | |||
2955 | #[test] | ||
2956 | fn infer_call_trait_method_on_generic_param_1() { | ||
2957 | assert_snapshot!( | ||
2958 | infer(r#" | ||
2959 | trait Trait { | ||
2960 | fn method(&self) -> u32; | ||
2961 | } | ||
2962 | fn test<T: Trait>(t: T) { | ||
2963 | t.method(); | ||
2964 | } | ||
2965 | "#), | ||
2966 | @r###" | ||
2967 | [30; 34) 'self': &Self | ||
2968 | [64; 65) 't': T | ||
2969 | [70; 89) '{ ...d(); }': () | ||
2970 | [76; 77) 't': T | ||
2971 | [76; 86) 't.method()': u32 | ||
2972 | "### | ||
2973 | ); | ||
2974 | } | ||
2975 | |||
2976 | #[test] | ||
2977 | fn infer_call_trait_method_on_generic_param_2() { | ||
2978 | assert_snapshot!( | ||
2979 | infer(r#" | ||
2980 | trait Trait<T> { | ||
2981 | fn method(&self) -> T; | ||
2982 | } | ||
2983 | fn test<U, T: Trait<U>>(t: T) { | ||
2984 | t.method(); | ||
2985 | } | ||
2986 | "#), | ||
2987 | @r###" | ||
2988 | [33; 37) 'self': &Self | ||
2989 | [71; 72) 't': T | ||
2990 | [77; 96) '{ ...d(); }': () | ||
2991 | [83; 84) 't': T | ||
2992 | [83; 93) 't.method()': [missing name] | ||
2993 | "### | ||
2994 | ); | ||
2995 | } | ||
2996 | |||
2997 | #[test] | ||
2998 | fn infer_with_multiple_trait_impls() { | ||
2999 | assert_snapshot!( | ||
3000 | infer(r#" | ||
3001 | trait Into<T> { | ||
3002 | fn into(self) -> T; | ||
3003 | } | ||
3004 | struct S; | ||
3005 | impl Into<u32> for S {} | ||
3006 | impl Into<u64> for S {} | ||
3007 | fn test() { | ||
3008 | let x: u32 = S.into(); | ||
3009 | let y: u64 = S.into(); | ||
3010 | let z = Into::<u64>::into(S); | ||
3011 | } | ||
3012 | "#), | ||
3013 | @r###" | ||
3014 | [29; 33) 'self': Self | ||
3015 | [111; 202) '{ ...(S); }': () | ||
3016 | [121; 122) 'x': u32 | ||
3017 | [130; 131) 'S': S | ||
3018 | [130; 138) 'S.into()': u32 | ||
3019 | [148; 149) 'y': u64 | ||
3020 | [157; 158) 'S': S | ||
3021 | [157; 165) 'S.into()': u64 | ||
3022 | [175; 176) 'z': u64 | ||
3023 | [179; 196) 'Into::...::into': fn into<S, u64>(Self) -> T | ||
3024 | [179; 199) 'Into::...nto(S)': u64 | ||
3025 | [197; 198) 'S': S | ||
3026 | "### | ||
3027 | ); | ||
3028 | } | ||
3029 | |||
3030 | #[test] | ||
3031 | fn infer_project_associated_type() { | ||
3032 | // y, z, a don't yet work because of https://github.com/rust-lang/chalk/issues/234 | ||
3033 | assert_snapshot!( | ||
3034 | infer(r#" | ||
3035 | trait Iterable { | ||
3036 | type Item; | ||
3037 | } | ||
3038 | struct S; | ||
3039 | impl Iterable for S { type Item = u32; } | ||
3040 | fn test<T: Iterable>() { | ||
3041 | let x: <S as Iterable>::Item = 1; | ||
3042 | let y: <T as Iterable>::Item = no_matter; | ||
3043 | let z: T::Item = no_matter; | ||
3044 | let a: <T>::Item = no_matter; | ||
3045 | } | ||
3046 | "#), | ||
3047 | @r###" | ||
3048 | [108; 261) '{ ...ter; }': () | ||
3049 | [118; 119) 'x': u32 | ||
3050 | [145; 146) '1': u32 | ||
3051 | [156; 157) 'y': {unknown} | ||
3052 | [183; 192) 'no_matter': {unknown} | ||
3053 | [202; 203) 'z': {unknown} | ||
3054 | [215; 224) 'no_matter': {unknown} | ||
3055 | [234; 235) 'a': {unknown} | ||
3056 | [249; 258) 'no_matter': {unknown} | ||
3057 | "### | ||
3058 | ); | ||
3059 | } | ||
3060 | |||
3061 | #[test] | ||
3062 | fn infer_return_associated_type() { | ||
3063 | assert_snapshot!( | ||
3064 | infer(r#" | ||
3065 | trait Iterable { | ||
3066 | type Item; | ||
3067 | } | ||
3068 | struct S; | ||
3069 | impl Iterable for S { type Item = u32; } | ||
3070 | fn foo1<T: Iterable>(t: T) -> T::Item {} | ||
3071 | fn foo2<T: Iterable>(t: T) -> <T as Iterable>::Item {} | ||
3072 | fn foo3<T: Iterable>(t: T) -> <T>::Item {} | ||
3073 | fn test() { | ||
3074 | let x = foo1(S); | ||
3075 | let y = foo2(S); | ||
3076 | let z = foo3(S); | ||
3077 | } | ||
3078 | "#), | ||
3079 | @r###" | ||
3080 | [106; 107) 't': T | ||
3081 | [123; 125) '{}': () | ||
3082 | [147; 148) 't': T | ||
3083 | [178; 180) '{}': () | ||
3084 | [202; 203) 't': T | ||
3085 | [221; 223) '{}': () | ||
3086 | [234; 300) '{ ...(S); }': () | ||
3087 | [244; 245) 'x': u32 | ||
3088 | [248; 252) 'foo1': fn foo1<S>(T) -> <T as Iterable>::Item | ||
3089 | [248; 255) 'foo1(S)': u32 | ||
3090 | [253; 254) 'S': S | ||
3091 | [265; 266) 'y': u32 | ||
3092 | [269; 273) 'foo2': fn foo2<S>(T) -> <T as Iterable>::Item | ||
3093 | [269; 276) 'foo2(S)': u32 | ||
3094 | [274; 275) 'S': S | ||
3095 | [286; 287) 'z': u32 | ||
3096 | [290; 294) 'foo3': fn foo3<S>(T) -> <T as Iterable>::Item | ||
3097 | [290; 297) 'foo3(S)': u32 | ||
3098 | [295; 296) 'S': S | ||
3099 | "### | ||
3100 | ); | ||
3101 | } | ||
3102 | |||
3103 | #[test] | ||
3104 | fn infer_associated_type_bound() { | ||
3105 | assert_snapshot!( | ||
3106 | infer(r#" | ||
3107 | trait Iterable { | ||
3108 | type Item; | ||
3109 | } | ||
3110 | fn test<T: Iterable<Item=u32>>() { | ||
3111 | let y: T::Item = unknown; | ||
3112 | } | ||
3113 | "#), | ||
3114 | @r###" | ||
3115 | [67; 100) '{ ...own; }': () | ||
3116 | [77; 78) 'y': {unknown} | ||
3117 | [90; 97) 'unknown': {unknown} | ||
3118 | "### | ||
3119 | ); | ||
3120 | } | ||
3121 | |||
3122 | #[test] | ||
3123 | fn infer_const_body() { | ||
3124 | assert_snapshot!( | ||
3125 | infer(r#" | ||
3126 | const A: u32 = 1 + 1; | ||
3127 | static B: u64 = { let x = 1; x }; | ||
3128 | "#), | ||
3129 | @r###" | ||
3130 | [16; 17) '1': u32 | ||
3131 | [16; 21) '1 + 1': u32 | ||
3132 | [20; 21) '1': u32 | ||
3133 | [39; 55) '{ let ...1; x }': u64 | ||
3134 | [45; 46) 'x': u64 | ||
3135 | [49; 50) '1': u64 | ||
3136 | [52; 53) 'x': u64 | ||
3137 | "### | ||
3138 | ); | ||
3139 | } | ||
3140 | |||
3141 | #[test] | ||
3142 | fn tuple_struct_fields() { | ||
3143 | assert_snapshot!( | ||
3144 | infer(r#" | ||
3145 | struct S(i32, u64); | ||
3146 | fn test() -> u64 { | ||
3147 | let a = S(4, 6); | ||
3148 | let b = a.0; | ||
3149 | a.1 | ||
3150 | } | ||
3151 | "#), | ||
3152 | @r###" | ||
3153 | [38; 87) '{ ... a.1 }': u64 | ||
3154 | [48; 49) 'a': S | ||
3155 | [52; 53) 'S': S(i32, u64) -> S | ||
3156 | [52; 59) 'S(4, 6)': S | ||
3157 | [54; 55) '4': i32 | ||
3158 | [57; 58) '6': u64 | ||
3159 | [69; 70) 'b': i32 | ||
3160 | [73; 74) 'a': S | ||
3161 | [73; 76) 'a.0': i32 | ||
3162 | [82; 83) 'a': S | ||
3163 | [82; 85) 'a.1': u64 | ||
3164 | "### | ||
3165 | ); | ||
3166 | } | ||
3167 | |||
3168 | #[test] | ||
3169 | fn tuple_struct_with_fn() { | ||
3170 | assert_snapshot!( | ||
3171 | infer(r#" | ||
3172 | struct S(fn(u32) -> u64); | ||
3173 | fn test() -> u64 { | ||
3174 | let a = S(|i| 2*i); | ||
3175 | let b = a.0(4); | ||
3176 | a.0(2) | ||
3177 | } | ||
3178 | "#), | ||
3179 | @r###" | ||
3180 | [44; 102) '{ ...0(2) }': u64 | ||
3181 | [54; 55) 'a': S | ||
3182 | [58; 59) 'S': S(fn(u32) -> u64) -> S | ||
3183 | [58; 68) 'S(|i| 2*i)': S | ||
3184 | [60; 67) '|i| 2*i': |i32| -> i32 | ||
3185 | [61; 62) 'i': i32 | ||
3186 | [64; 65) '2': i32 | ||
3187 | [64; 67) '2*i': i32 | ||
3188 | [66; 67) 'i': i32 | ||
3189 | [78; 79) 'b': u64 | ||
3190 | [82; 83) 'a': S | ||
3191 | [82; 85) 'a.0': fn(u32) -> u64 | ||
3192 | [82; 88) 'a.0(4)': u64 | ||
3193 | [86; 87) '4': u32 | ||
3194 | [94; 95) 'a': S | ||
3195 | [94; 97) 'a.0': fn(u32) -> u64 | ||
3196 | [94; 100) 'a.0(2)': u64 | ||
3197 | [98; 99) '2': u32 | ||
3198 | "### | ||
3199 | ); | ||
3200 | } | ||
3201 | |||
3202 | #[test] | ||
3203 | fn indexing_arrays() { | ||
3204 | assert_snapshot!( | ||
3205 | infer("fn main() { &mut [9][2]; }"), | ||
3206 | @r###" | ||
3207 | [10; 26) '{ &mut...[2]; }': () | ||
3208 | [12; 23) '&mut [9][2]': &mut {unknown} | ||
3209 | [17; 20) '[9]': [i32;_] | ||
3210 | [17; 23) '[9][2]': {unknown} | ||
3211 | [18; 19) '9': i32 | ||
3212 | [21; 22) '2': i32 | ||
3213 | "### | ||
3214 | ) | ||
3215 | } | ||
3216 | |||
3217 | #[test] | ||
3218 | fn infer_macros_expanded() { | ||
3219 | assert_snapshot!( | ||
3220 | infer(r#" | ||
3221 | struct Foo(Vec<i32>); | ||
3222 | |||
3223 | macro_rules! foo { | ||
3224 | ($($item:expr),*) => { | ||
3225 | { | ||
3226 | Foo(vec![$($item,)*]) | ||
3227 | } | ||
3228 | }; | ||
3229 | } | ||
3230 | |||
3231 | fn main() { | ||
3232 | let x = foo!(1,2); | ||
3233 | } | ||
3234 | "#), | ||
3235 | @r###" | ||
3236 | ![0; 17) '{Foo(v...,2,])}': Foo | ||
3237 | ![1; 4) 'Foo': Foo({unknown}) -> Foo | ||
3238 | ![1; 16) 'Foo(vec![1,2,])': Foo | ||
3239 | ![5; 15) 'vec![1,2,]': {unknown} | ||
3240 | [156; 182) '{ ...,2); }': () | ||
3241 | [166; 167) 'x': Foo | ||
3242 | "### | ||
3243 | ); | ||
3244 | } | ||
3245 | |||
3246 | #[test] | ||
3247 | fn infer_legacy_textual_scoped_macros_expanded() { | ||
3248 | assert_snapshot!( | ||
3249 | infer(r#" | ||
3250 | struct Foo(Vec<i32>); | ||
3251 | |||
3252 | #[macro_use] | ||
3253 | mod m { | ||
3254 | macro_rules! foo { | ||
3255 | ($($item:expr),*) => { | ||
3256 | { | ||
3257 | Foo(vec![$($item,)*]) | ||
3258 | } | ||
3259 | }; | ||
3260 | } | ||
3261 | } | ||
3262 | |||
3263 | fn main() { | ||
3264 | let x = foo!(1,2); | ||
3265 | let y = crate::foo!(1,2); | ||
3266 | } | ||
3267 | "#), | ||
3268 | @r###" | ||
3269 | ![0; 17) '{Foo(v...,2,])}': Foo | ||
3270 | ![1; 4) 'Foo': Foo({unknown}) -> Foo | ||
3271 | ![1; 16) 'Foo(vec![1,2,])': Foo | ||
3272 | ![5; 15) 'vec![1,2,]': {unknown} | ||
3273 | [195; 251) '{ ...,2); }': () | ||
3274 | [205; 206) 'x': Foo | ||
3275 | [228; 229) 'y': {unknown} | ||
3276 | [232; 248) 'crate:...!(1,2)': {unknown} | ||
3277 | "### | ||
3278 | ); | ||
3279 | } | ||
3280 | |||
3281 | #[test] | ||
3282 | fn infer_path_qualified_macros_expanded() { | ||
3283 | assert_snapshot!( | ||
3284 | infer(r#" | ||
3285 | #[macro_export] | ||
3286 | macro_rules! foo { | ||
3287 | () => { 42i32 } | ||
3288 | } | ||
3289 | |||
3290 | mod m { | ||
3291 | pub use super::foo as bar; | ||
3292 | } | ||
3293 | |||
3294 | fn main() { | ||
3295 | let x = crate::foo!(); | ||
3296 | let y = m::bar!(); | ||
3297 | } | ||
3298 | "#), | ||
3299 | @r###" | ||
3300 | ![0; 5) '42i32': i32 | ||
3301 | ![0; 5) '42i32': i32 | ||
3302 | [111; 164) '{ ...!(); }': () | ||
3303 | [121; 122) 'x': i32 | ||
3304 | [148; 149) 'y': i32 | ||
3305 | "### | ||
3306 | ); | ||
3307 | } | ||
3308 | |||
3309 | #[test] | ||
3310 | fn infer_type_value_macro_having_same_name() { | ||
3311 | assert_snapshot!( | ||
3312 | infer(r#" | ||
3313 | #[macro_export] | ||
3314 | macro_rules! foo { | ||
3315 | () => { | ||
3316 | mod foo { | ||
3317 | pub use super::foo; | ||
3318 | } | ||
3319 | }; | ||
3320 | ($x:tt) => { | ||
3321 | $x | ||
3322 | }; | ||
3323 | } | ||
3324 | |||
3325 | foo!(); | ||
3326 | |||
3327 | fn foo() { | ||
3328 | let foo = foo::foo!(42i32); | ||
3329 | } | ||
3330 | "#), | ||
3331 | @r###" | ||
3332 | ![0; 5) '42i32': i32 | ||
3333 | [171; 206) '{ ...32); }': () | ||
3334 | [181; 184) 'foo': i32 | ||
3335 | "### | ||
3336 | ); | ||
3337 | } | ||
3338 | |||
3339 | #[test] | ||
3340 | fn processes_impls_generated_by_macros() { | ||
3341 | let t = type_at( | ||
3342 | r#" | ||
3343 | //- /main.rs | ||
3344 | macro_rules! m { | ||
3345 | ($ident:ident) => (impl Trait for $ident {}) | ||
3346 | } | ||
3347 | trait Trait { fn foo(self) -> u128 {} } | ||
3348 | struct S; | ||
3349 | m!(S); | ||
3350 | fn test() { S.foo()<|>; } | ||
3351 | "#, | ||
3352 | ); | ||
3353 | assert_eq!(t, "u128"); | ||
3354 | } | ||
3355 | |||
3356 | #[test] | ||
3357 | fn infer_macro_with_dollar_crate_is_correct_in_expr() { | ||
3358 | let (db, pos) = TestDB::with_position( | ||
3359 | r#" | ||
3360 | //- /main.rs crate:main deps:foo | ||
3361 | fn test() { | ||
3362 | let x = (foo::foo!(1), foo::foo!(2)); | ||
3363 | x<|>; | ||
3364 | } | ||
3365 | |||
3366 | //- /lib.rs crate:foo | ||
3367 | #[macro_export] | ||
3368 | macro_rules! foo { | ||
3369 | (1) => { $crate::bar!() }; | ||
3370 | (2) => { 1 + $crate::baz() }; | ||
3371 | } | ||
3372 | |||
3373 | #[macro_export] | ||
3374 | macro_rules! bar { | ||
3375 | () => { 42 } | ||
3376 | } | ||
3377 | |||
3378 | pub fn baz() -> usize { 31usize } | ||
3379 | "#, | ||
3380 | ); | ||
3381 | assert_eq!("(i32, usize)", type_at_pos(&db, pos)); | ||
3382 | } | ||
3383 | |||
3384 | #[ignore] | ||
3385 | #[test] | ||
3386 | fn method_resolution_trait_before_autoref() { | ||
3387 | let t = type_at( | ||
3388 | r#" | ||
3389 | //- /main.rs | ||
3390 | trait Trait { fn foo(self) -> u128; } | ||
3391 | struct S; | ||
3392 | impl S { fn foo(&self) -> i8 { 0 } } | ||
3393 | impl Trait for S { fn foo(self) -> u128 { 0 } } | ||
3394 | fn test() { S.foo()<|>; } | ||
3395 | "#, | ||
3396 | ); | ||
3397 | assert_eq!(t, "u128"); | ||
3398 | } | ||
3399 | |||
3400 | #[ignore] | ||
3401 | #[test] | ||
3402 | fn method_resolution_by_value_before_autoref() { | ||
3403 | let t = type_at( | ||
3404 | r#" | ||
3405 | //- /main.rs | ||
3406 | trait Clone { fn clone(&self) -> Self; } | ||
3407 | struct S; | ||
3408 | impl Clone for S {} | ||
3409 | impl Clone for &S {} | ||
3410 | fn test() { (S.clone(), (&S).clone(), (&&S).clone())<|>; } | ||
3411 | "#, | ||
3412 | ); | ||
3413 | assert_eq!(t, "(S, S, &S)"); | ||
3414 | } | ||
3415 | |||
3416 | #[test] | ||
3417 | fn method_resolution_trait_before_autoderef() { | ||
3418 | let t = type_at( | ||
3419 | r#" | ||
3420 | //- /main.rs | ||
3421 | trait Trait { fn foo(self) -> u128; } | ||
3422 | struct S; | ||
3423 | impl S { fn foo(self) -> i8 { 0 } } | ||
3424 | impl Trait for &S { fn foo(self) -> u128 { 0 } } | ||
3425 | fn test() { (&S).foo()<|>; } | ||
3426 | "#, | ||
3427 | ); | ||
3428 | assert_eq!(t, "u128"); | ||
3429 | } | ||
3430 | |||
3431 | #[test] | ||
3432 | fn method_resolution_impl_before_trait() { | ||
3433 | let t = type_at( | ||
3434 | r#" | ||
3435 | //- /main.rs | ||
3436 | trait Trait { fn foo(self) -> u128; } | ||
3437 | struct S; | ||
3438 | impl S { fn foo(self) -> i8 { 0 } } | ||
3439 | impl Trait for S { fn foo(self) -> u128 { 0 } } | ||
3440 | fn test() { S.foo()<|>; } | ||
3441 | "#, | ||
3442 | ); | ||
3443 | assert_eq!(t, "i8"); | ||
3444 | } | ||
3445 | |||
3446 | #[test] | ||
3447 | fn method_resolution_trait_autoderef() { | ||
3448 | let t = type_at( | ||
3449 | r#" | ||
3450 | //- /main.rs | ||
3451 | trait Trait { fn foo(self) -> u128; } | ||
3452 | struct S; | ||
3453 | impl Trait for S { fn foo(self) -> u128 { 0 } } | ||
3454 | fn test() { (&S).foo()<|>; } | ||
3455 | "#, | ||
3456 | ); | ||
3457 | assert_eq!(t, "u128"); | ||
3458 | } | ||
3459 | |||
3460 | #[test] | ||
3461 | fn method_resolution_trait_from_prelude() { | ||
3462 | let (db, pos) = TestDB::with_position( | ||
3463 | r#" | ||
3464 | //- /main.rs crate:main deps:other_crate | ||
3465 | struct S; | ||
3466 | impl Clone for S {} | ||
3467 | |||
3468 | fn test() { | ||
3469 | S.clone()<|>; | ||
3470 | } | ||
3471 | |||
3472 | //- /lib.rs crate:other_crate | ||
3473 | #[prelude_import] use foo::*; | ||
3474 | |||
3475 | mod foo { | ||
3476 | trait Clone { | ||
3477 | fn clone(&self) -> Self; | ||
3478 | } | ||
3479 | } | ||
3480 | "#, | ||
3481 | ); | ||
3482 | assert_eq!("S", type_at_pos(&db, pos)); | ||
3483 | } | ||
3484 | |||
3485 | #[test] | ||
3486 | fn method_resolution_where_clause_for_unknown_trait() { | ||
3487 | // The blanket impl shouldn't apply because we can't even resolve UnknownTrait | ||
3488 | let t = type_at( | ||
3489 | r#" | ||
3490 | //- /main.rs | ||
3491 | trait Trait { fn foo(self) -> u128; } | ||
3492 | struct S; | ||
3493 | impl<T> Trait for T where T: UnknownTrait {} | ||
3494 | fn test() { (&S).foo()<|>; } | ||
3495 | "#, | ||
3496 | ); | ||
3497 | assert_eq!(t, "{unknown}"); | ||
3498 | } | ||
3499 | |||
3500 | #[test] | ||
3501 | fn method_resolution_where_clause_not_met() { | ||
3502 | // The blanket impl shouldn't apply because we can't prove S: Clone | ||
3503 | let t = type_at( | ||
3504 | r#" | ||
3505 | //- /main.rs | ||
3506 | trait Clone {} | ||
3507 | trait Trait { fn foo(self) -> u128; } | ||
3508 | struct S; | ||
3509 | impl<T> Trait for T where T: Clone {} | ||
3510 | fn test() { (&S).foo()<|>; } | ||
3511 | "#, | ||
3512 | ); | ||
3513 | // This is also to make sure that we don't resolve to the foo method just | ||
3514 | // because that's the only method named foo we can find, which would make | ||
3515 | // the below tests not work | ||
3516 | assert_eq!(t, "{unknown}"); | ||
3517 | } | ||
3518 | |||
3519 | #[test] | ||
3520 | fn method_resolution_where_clause_inline_not_met() { | ||
3521 | // The blanket impl shouldn't apply because we can't prove S: Clone | ||
3522 | let t = type_at( | ||
3523 | r#" | ||
3524 | //- /main.rs | ||
3525 | trait Clone {} | ||
3526 | trait Trait { fn foo(self) -> u128; } | ||
3527 | struct S; | ||
3528 | impl<T: Clone> Trait for T {} | ||
3529 | fn test() { (&S).foo()<|>; } | ||
3530 | "#, | ||
3531 | ); | ||
3532 | assert_eq!(t, "{unknown}"); | ||
3533 | } | ||
3534 | |||
3535 | #[test] | ||
3536 | fn method_resolution_where_clause_1() { | ||
3537 | let t = type_at( | ||
3538 | r#" | ||
3539 | //- /main.rs | ||
3540 | trait Clone {} | ||
3541 | trait Trait { fn foo(self) -> u128; } | ||
3542 | struct S; | ||
3543 | impl Clone for S {} | ||
3544 | impl<T> Trait for T where T: Clone {} | ||
3545 | fn test() { S.foo()<|>; } | ||
3546 | "#, | ||
3547 | ); | ||
3548 | assert_eq!(t, "u128"); | ||
3549 | } | ||
3550 | |||
3551 | #[test] | ||
3552 | fn method_resolution_where_clause_2() { | ||
3553 | let t = type_at( | ||
3554 | r#" | ||
3555 | //- /main.rs | ||
3556 | trait Into<T> { fn into(self) -> T; } | ||
3557 | trait From<T> { fn from(other: T) -> Self; } | ||
3558 | struct S1; | ||
3559 | struct S2; | ||
3560 | impl From<S2> for S1 {} | ||
3561 | impl<T, U> Into<U> for T where U: From<T> {} | ||
3562 | fn test() { S2.into()<|>; } | ||
3563 | "#, | ||
3564 | ); | ||
3565 | assert_eq!(t, "{unknown}"); | ||
3566 | } | ||
3567 | |||
3568 | #[test] | ||
3569 | fn method_resolution_where_clause_inline() { | ||
3570 | let t = type_at( | ||
3571 | r#" | ||
3572 | //- /main.rs | ||
3573 | trait Into<T> { fn into(self) -> T; } | ||
3574 | trait From<T> { fn from(other: T) -> Self; } | ||
3575 | struct S1; | ||
3576 | struct S2; | ||
3577 | impl From<S2> for S1 {} | ||
3578 | impl<T, U: From<T>> Into<U> for T {} | ||
3579 | fn test() { S2.into()<|>; } | ||
3580 | "#, | ||
3581 | ); | ||
3582 | assert_eq!(t, "{unknown}"); | ||
3583 | } | ||
3584 | |||
3585 | #[test] | ||
3586 | fn method_resolution_encountering_fn_type() { | ||
3587 | type_at( | ||
3588 | r#" | ||
3589 | //- /main.rs | ||
3590 | fn foo() {} | ||
3591 | trait FnOnce { fn call(self); } | ||
3592 | fn test() { foo.call()<|>; } | ||
3593 | "#, | ||
3594 | ); | ||
3595 | } | ||
3596 | |||
3597 | #[test] | ||
3598 | fn method_resolution_slow() { | ||
3599 | // this can get quite slow if we set the solver size limit too high | ||
3600 | let t = type_at( | ||
3601 | r#" | ||
3602 | //- /main.rs | ||
3603 | trait SendX {} | ||
3604 | |||
3605 | struct S1; impl SendX for S1 {} | ||
3606 | struct S2; impl SendX for S2 {} | ||
3607 | struct U1; | ||
3608 | |||
3609 | trait Trait { fn method(self); } | ||
3610 | |||
3611 | struct X1<A, B> {} | ||
3612 | impl<A, B> SendX for X1<A, B> where A: SendX, B: SendX {} | ||
3613 | |||
3614 | struct S<B, C> {} | ||
3615 | |||
3616 | trait FnX {} | ||
3617 | |||
3618 | impl<B, C> Trait for S<B, C> where C: FnX, B: SendX {} | ||
3619 | |||
3620 | fn test() { (S {}).method()<|>; } | ||
3621 | "#, | ||
3622 | ); | ||
3623 | assert_eq!(t, "()"); | ||
3624 | } | ||
3625 | |||
3626 | #[test] | ||
3627 | fn shadowing_primitive() { | ||
3628 | let t = type_at( | ||
3629 | r#" | ||
3630 | //- /main.rs | ||
3631 | struct i32; | ||
3632 | struct Foo; | ||
3633 | |||
3634 | impl i32 { fn foo(&self) -> Foo { Foo } } | ||
3635 | |||
3636 | fn main() { | ||
3637 | let x: i32 = i32; | ||
3638 | x.foo()<|>; | ||
3639 | }"#, | ||
3640 | ); | ||
3641 | assert_eq!(t, "Foo"); | ||
3642 | } | ||
3643 | |||
3644 | #[test] | ||
3645 | fn deref_trait() { | ||
3646 | let t = type_at( | ||
3647 | r#" | ||
3648 | //- /main.rs | ||
3649 | #[lang = "deref"] | ||
3650 | trait Deref { | ||
3651 | type Target; | ||
3652 | fn deref(&self) -> &Self::Target; | ||
3653 | } | ||
3654 | |||
3655 | struct Arc<T>; | ||
3656 | impl<T> Deref for Arc<T> { | ||
3657 | type Target = T; | ||
3658 | } | ||
3659 | |||
3660 | struct S; | ||
3661 | impl S { | ||
3662 | fn foo(&self) -> u128 {} | ||
3663 | } | ||
3664 | |||
3665 | fn test(s: Arc<S>) { | ||
3666 | (*s, s.foo())<|>; | ||
3667 | } | ||
3668 | "#, | ||
3669 | ); | ||
3670 | assert_eq!(t, "(S, u128)"); | ||
3671 | } | ||
3672 | |||
3673 | #[test] | ||
3674 | fn deref_trait_with_inference_var() { | ||
3675 | let t = type_at( | ||
3676 | r#" | ||
3677 | //- /main.rs | ||
3678 | #[lang = "deref"] | ||
3679 | trait Deref { | ||
3680 | type Target; | ||
3681 | fn deref(&self) -> &Self::Target; | ||
3682 | } | ||
3683 | |||
3684 | struct Arc<T>; | ||
3685 | fn new_arc<T>() -> Arc<T> {} | ||
3686 | impl<T> Deref for Arc<T> { | ||
3687 | type Target = T; | ||
3688 | } | ||
3689 | |||
3690 | struct S; | ||
3691 | fn foo(a: Arc<S>) {} | ||
3692 | |||
3693 | fn test() { | ||
3694 | let a = new_arc(); | ||
3695 | let b = (*a)<|>; | ||
3696 | foo(a); | ||
3697 | } | ||
3698 | "#, | ||
3699 | ); | ||
3700 | assert_eq!(t, "S"); | ||
3701 | } | ||
3702 | |||
3703 | #[test] | ||
3704 | fn deref_trait_infinite_recursion() { | ||
3705 | let t = type_at( | ||
3706 | r#" | ||
3707 | //- /main.rs | ||
3708 | #[lang = "deref"] | ||
3709 | trait Deref { | ||
3710 | type Target; | ||
3711 | fn deref(&self) -> &Self::Target; | ||
3712 | } | ||
3713 | |||
3714 | struct S; | ||
3715 | |||
3716 | impl Deref for S { | ||
3717 | type Target = S; | ||
3718 | } | ||
3719 | |||
3720 | fn test(s: S) { | ||
3721 | s.foo()<|>; | ||
3722 | } | ||
3723 | "#, | ||
3724 | ); | ||
3725 | assert_eq!(t, "{unknown}"); | ||
3726 | } | ||
3727 | |||
3728 | #[test] | ||
3729 | fn deref_trait_with_question_mark_size() { | ||
3730 | let t = type_at( | ||
3731 | r#" | ||
3732 | //- /main.rs | ||
3733 | #[lang = "deref"] | ||
3734 | trait Deref { | ||
3735 | type Target; | ||
3736 | fn deref(&self) -> &Self::Target; | ||
3737 | } | ||
3738 | |||
3739 | struct Arc<T>; | ||
3740 | impl<T> Deref for Arc<T> { | ||
3741 | type Target = T; | ||
3742 | } | ||
3743 | |||
3744 | struct S; | ||
3745 | impl S { | ||
3746 | fn foo(&self) -> u128 {} | ||
3747 | } | ||
3748 | |||
3749 | fn test(s: Arc<S>) { | ||
3750 | (*s, s.foo())<|>; | ||
3751 | } | ||
3752 | "#, | ||
3753 | ); | ||
3754 | assert_eq!(t, "(S, u128)"); | ||
3755 | } | ||
3756 | |||
3757 | #[test] | ||
3758 | fn obligation_from_function_clause() { | ||
3759 | let t = type_at( | ||
3760 | r#" | ||
3761 | //- /main.rs | ||
3762 | struct S; | ||
3763 | |||
3764 | trait Trait<T> {} | ||
3765 | impl Trait<u32> for S {} | ||
3766 | |||
3767 | fn foo<T: Trait<U>, U>(t: T) -> U {} | ||
3768 | |||
3769 | fn test(s: S) { | ||
3770 | foo(s)<|>; | ||
3771 | } | ||
3772 | "#, | ||
3773 | ); | ||
3774 | assert_eq!(t, "u32"); | ||
3775 | } | ||
3776 | |||
3777 | #[test] | ||
3778 | fn obligation_from_method_clause() { | ||
3779 | let t = type_at( | ||
3780 | r#" | ||
3781 | //- /main.rs | ||
3782 | struct S; | ||
3783 | |||
3784 | trait Trait<T> {} | ||
3785 | impl Trait<isize> for S {} | ||
3786 | |||
3787 | struct O; | ||
3788 | impl O { | ||
3789 | fn foo<T: Trait<U>, U>(&self, t: T) -> U {} | ||
3790 | } | ||
3791 | |||
3792 | fn test() { | ||
3793 | O.foo(S)<|>; | ||
3794 | } | ||
3795 | "#, | ||
3796 | ); | ||
3797 | assert_eq!(t, "isize"); | ||
3798 | } | ||
3799 | |||
3800 | #[test] | ||
3801 | fn obligation_from_self_method_clause() { | ||
3802 | let t = type_at( | ||
3803 | r#" | ||
3804 | //- /main.rs | ||
3805 | struct S; | ||
3806 | |||
3807 | trait Trait<T> {} | ||
3808 | impl Trait<i64> for S {} | ||
3809 | |||
3810 | impl S { | ||
3811 | fn foo<U>(&self) -> U where Self: Trait<U> {} | ||
3812 | } | ||
3813 | |||
3814 | fn test() { | ||
3815 | S.foo()<|>; | ||
3816 | } | ||
3817 | "#, | ||
3818 | ); | ||
3819 | assert_eq!(t, "i64"); | ||
3820 | } | ||
3821 | |||
3822 | #[test] | ||
3823 | fn obligation_from_impl_clause() { | ||
3824 | let t = type_at( | ||
3825 | r#" | ||
3826 | //- /main.rs | ||
3827 | struct S; | ||
3828 | |||
3829 | trait Trait<T> {} | ||
3830 | impl Trait<&str> for S {} | ||
3831 | |||
3832 | struct O<T>; | ||
3833 | impl<U, T: Trait<U>> O<T> { | ||
3834 | fn foo(&self) -> U {} | ||
3835 | } | ||
3836 | |||
3837 | fn test(o: O<S>) { | ||
3838 | o.foo()<|>; | ||
3839 | } | ||
3840 | "#, | ||
3841 | ); | ||
3842 | assert_eq!(t, "&str"); | ||
3843 | } | ||
3844 | |||
3845 | #[test] | ||
3846 | fn generic_param_env_1() { | ||
3847 | let t = type_at( | ||
3848 | r#" | ||
3849 | //- /main.rs | ||
3850 | trait Clone {} | ||
3851 | trait Trait { fn foo(self) -> u128; } | ||
3852 | struct S; | ||
3853 | impl Clone for S {} | ||
3854 | impl<T> Trait for T where T: Clone {} | ||
3855 | fn test<T: Clone>(t: T) { t.foo()<|>; } | ||
3856 | "#, | ||
3857 | ); | ||
3858 | assert_eq!(t, "u128"); | ||
3859 | } | ||
3860 | |||
3861 | #[test] | ||
3862 | fn generic_param_env_1_not_met() { | ||
3863 | let t = type_at( | ||
3864 | r#" | ||
3865 | //- /main.rs | ||
3866 | trait Clone {} | ||
3867 | trait Trait { fn foo(self) -> u128; } | ||
3868 | struct S; | ||
3869 | impl Clone for S {} | ||
3870 | impl<T> Trait for T where T: Clone {} | ||
3871 | fn test<T>(t: T) { t.foo()<|>; } | ||
3872 | "#, | ||
3873 | ); | ||
3874 | assert_eq!(t, "{unknown}"); | ||
3875 | } | ||
3876 | |||
3877 | #[test] | ||
3878 | fn generic_param_env_2() { | ||
3879 | let t = type_at( | ||
3880 | r#" | ||
3881 | //- /main.rs | ||
3882 | trait Trait { fn foo(self) -> u128; } | ||
3883 | struct S; | ||
3884 | impl Trait for S {} | ||
3885 | fn test<T: Trait>(t: T) { t.foo()<|>; } | ||
3886 | "#, | ||
3887 | ); | ||
3888 | assert_eq!(t, "u128"); | ||
3889 | } | ||
3890 | |||
3891 | #[test] | ||
3892 | fn generic_param_env_2_not_met() { | ||
3893 | let t = type_at( | ||
3894 | r#" | ||
3895 | //- /main.rs | ||
3896 | trait Trait { fn foo(self) -> u128; } | ||
3897 | struct S; | ||
3898 | impl Trait for S {} | ||
3899 | fn test<T>(t: T) { t.foo()<|>; } | ||
3900 | "#, | ||
3901 | ); | ||
3902 | assert_eq!(t, "{unknown}"); | ||
3903 | } | ||
3904 | |||
3905 | #[test] | ||
3906 | fn generic_param_env_deref() { | ||
3907 | let t = type_at( | ||
3908 | r#" | ||
3909 | //- /main.rs | ||
3910 | #[lang = "deref"] | ||
3911 | trait Deref { | ||
3912 | type Target; | ||
3913 | } | ||
3914 | trait Trait {} | ||
3915 | impl<T> Deref for T where T: Trait { | ||
3916 | type Target = i128; | ||
3917 | } | ||
3918 | fn test<T: Trait>(t: T) { (*t)<|>; } | ||
3919 | "#, | ||
3920 | ); | ||
3921 | assert_eq!(t, "i128"); | ||
3922 | } | ||
3923 | |||
3924 | #[test] | ||
3925 | fn associated_type_placeholder() { | ||
3926 | let t = type_at( | ||
3927 | r#" | ||
3928 | //- /main.rs | ||
3929 | pub trait ApplyL { | ||
3930 | type Out; | ||
3931 | } | ||
3932 | |||
3933 | pub struct RefMutL<T>; | ||
3934 | |||
3935 | impl<T> ApplyL for RefMutL<T> { | ||
3936 | type Out = <T as ApplyL>::Out; | ||
3937 | } | ||
3938 | |||
3939 | fn test<T: ApplyL>() { | ||
3940 | let y: <RefMutL<T> as ApplyL>::Out = no_matter; | ||
3941 | y<|>; | ||
3942 | } | ||
3943 | "#, | ||
3944 | ); | ||
3945 | // inside the generic function, the associated type gets normalized to a placeholder `ApplL::Out<T>` [https://rust-lang.github.io/rustc-guide/traits/associated-types.html#placeholder-associated-types]. | ||
3946 | // FIXME: fix type parameter names going missing when going through Chalk | ||
3947 | assert_eq!(t, "ApplyL::Out<[missing name]>"); | ||
3948 | } | ||
3949 | |||
3950 | #[test] | ||
3951 | fn associated_type_placeholder_2() { | ||
3952 | let t = type_at( | ||
3953 | r#" | ||
3954 | //- /main.rs | ||
3955 | pub trait ApplyL { | ||
3956 | type Out; | ||
3957 | } | ||
3958 | fn foo<T: ApplyL>(t: T) -> <T as ApplyL>::Out; | ||
3959 | |||
3960 | fn test<T: ApplyL>(t: T) { | ||
3961 | let y = foo(t); | ||
3962 | y<|>; | ||
3963 | } | ||
3964 | "#, | ||
3965 | ); | ||
3966 | // FIXME here Chalk doesn't normalize the type to a placeholder. I think we | ||
3967 | // need to add a rule like Normalize(<T as ApplyL>::Out -> ApplyL::Out<T>) | ||
3968 | // to the trait env ourselves here; probably Chalk can't do this by itself. | ||
3969 | // assert_eq!(t, "ApplyL::Out<[missing name]>"); | ||
3970 | assert_eq!(t, "{unknown}"); | ||
3971 | } | ||
3972 | |||
3973 | #[test] | ||
3974 | fn impl_trait() { | ||
3975 | assert_snapshot!( | ||
3976 | infer(r#" | ||
3977 | trait Trait<T> { | ||
3978 | fn foo(&self) -> T; | ||
3979 | fn foo2(&self) -> i64; | ||
3980 | } | ||
3981 | fn bar() -> impl Trait<u64> {} | ||
3982 | |||
3983 | fn test(x: impl Trait<u64>, y: &impl Trait<u64>) { | ||
3984 | x; | ||
3985 | y; | ||
3986 | let z = bar(); | ||
3987 | x.foo(); | ||
3988 | y.foo(); | ||
3989 | z.foo(); | ||
3990 | x.foo2(); | ||
3991 | y.foo2(); | ||
3992 | z.foo2(); | ||
3993 | } | ||
3994 | "#), | ||
3995 | @r###" | ||
3996 | [30; 34) 'self': &Self | ||
3997 | [55; 59) 'self': &Self | ||
3998 | [99; 101) '{}': () | ||
3999 | [111; 112) 'x': impl Trait<u64> | ||
4000 | [131; 132) 'y': &impl Trait<u64> | ||
4001 | [152; 269) '{ ...2(); }': () | ||
4002 | [158; 159) 'x': impl Trait<u64> | ||
4003 | [165; 166) 'y': &impl Trait<u64> | ||
4004 | [176; 177) 'z': impl Trait<u64> | ||
4005 | [180; 183) 'bar': fn bar() -> impl Trait<u64> | ||
4006 | [180; 185) 'bar()': impl Trait<u64> | ||
4007 | [191; 192) 'x': impl Trait<u64> | ||
4008 | [191; 198) 'x.foo()': u64 | ||
4009 | [204; 205) 'y': &impl Trait<u64> | ||
4010 | [204; 211) 'y.foo()': u64 | ||
4011 | [217; 218) 'z': impl Trait<u64> | ||
4012 | [217; 224) 'z.foo()': u64 | ||
4013 | [230; 231) 'x': impl Trait<u64> | ||
4014 | [230; 238) 'x.foo2()': i64 | ||
4015 | [244; 245) 'y': &impl Trait<u64> | ||
4016 | [244; 252) 'y.foo2()': i64 | ||
4017 | [258; 259) 'z': impl Trait<u64> | ||
4018 | [258; 266) 'z.foo2()': i64 | ||
4019 | "### | ||
4020 | ); | ||
4021 | } | ||
4022 | |||
4023 | #[test] | ||
4024 | fn dyn_trait() { | ||
4025 | assert_snapshot!( | ||
4026 | infer(r#" | ||
4027 | trait Trait<T> { | ||
4028 | fn foo(&self) -> T; | ||
4029 | fn foo2(&self) -> i64; | ||
4030 | } | ||
4031 | fn bar() -> dyn Trait<u64> {} | ||
4032 | |||
4033 | fn test(x: dyn Trait<u64>, y: &dyn Trait<u64>) { | ||
4034 | x; | ||
4035 | y; | ||
4036 | let z = bar(); | ||
4037 | x.foo(); | ||
4038 | y.foo(); | ||
4039 | z.foo(); | ||
4040 | x.foo2(); | ||
4041 | y.foo2(); | ||
4042 | z.foo2(); | ||
4043 | } | ||
4044 | "#), | ||
4045 | @r###" | ||
4046 | [30; 34) 'self': &Self | ||
4047 | [55; 59) 'self': &Self | ||
4048 | [98; 100) '{}': () | ||
4049 | [110; 111) 'x': dyn Trait<u64> | ||
4050 | [129; 130) 'y': &dyn Trait<u64> | ||
4051 | [149; 266) '{ ...2(); }': () | ||
4052 | [155; 156) 'x': dyn Trait<u64> | ||
4053 | [162; 163) 'y': &dyn Trait<u64> | ||
4054 | [173; 174) 'z': dyn Trait<u64> | ||
4055 | [177; 180) 'bar': fn bar() -> dyn Trait<u64> | ||
4056 | [177; 182) 'bar()': dyn Trait<u64> | ||
4057 | [188; 189) 'x': dyn Trait<u64> | ||
4058 | [188; 195) 'x.foo()': u64 | ||
4059 | [201; 202) 'y': &dyn Trait<u64> | ||
4060 | [201; 208) 'y.foo()': u64 | ||
4061 | [214; 215) 'z': dyn Trait<u64> | ||
4062 | [214; 221) 'z.foo()': u64 | ||
4063 | [227; 228) 'x': dyn Trait<u64> | ||
4064 | [227; 235) 'x.foo2()': i64 | ||
4065 | [241; 242) 'y': &dyn Trait<u64> | ||
4066 | [241; 249) 'y.foo2()': i64 | ||
4067 | [255; 256) 'z': dyn Trait<u64> | ||
4068 | [255; 263) 'z.foo2()': i64 | ||
4069 | "### | ||
4070 | ); | ||
4071 | } | ||
4072 | |||
4073 | #[test] | ||
4074 | fn dyn_trait_bare() { | ||
4075 | assert_snapshot!( | ||
4076 | infer(r#" | ||
4077 | trait Trait { | ||
4078 | fn foo(&self) -> u64; | ||
4079 | } | ||
4080 | fn bar() -> Trait {} | ||
4081 | |||
4082 | fn test(x: Trait, y: &Trait) -> u64 { | ||
4083 | x; | ||
4084 | y; | ||
4085 | let z = bar(); | ||
4086 | x.foo(); | ||
4087 | y.foo(); | ||
4088 | z.foo(); | ||
4089 | } | ||
4090 | "#), | ||
4091 | @r###" | ||
4092 | [27; 31) 'self': &Self | ||
4093 | [61; 63) '{}': () | ||
4094 | [73; 74) 'x': dyn Trait | ||
4095 | [83; 84) 'y': &dyn Trait | ||
4096 | [101; 176) '{ ...o(); }': () | ||
4097 | [107; 108) 'x': dyn Trait | ||
4098 | [114; 115) 'y': &dyn Trait | ||
4099 | [125; 126) 'z': dyn Trait | ||
4100 | [129; 132) 'bar': fn bar() -> dyn Trait | ||
4101 | [129; 134) 'bar()': dyn Trait | ||
4102 | [140; 141) 'x': dyn Trait | ||
4103 | [140; 147) 'x.foo()': u64 | ||
4104 | [153; 154) 'y': &dyn Trait | ||
4105 | [153; 160) 'y.foo()': u64 | ||
4106 | [166; 167) 'z': dyn Trait | ||
4107 | [166; 173) 'z.foo()': u64 | ||
4108 | "### | ||
4109 | ); | ||
4110 | } | ||
4111 | |||
4112 | #[test] | ||
4113 | fn weird_bounds() { | ||
4114 | assert_snapshot!( | ||
4115 | infer(r#" | ||
4116 | trait Trait {} | ||
4117 | fn test() { | ||
4118 | let a: impl Trait + 'lifetime = foo; | ||
4119 | let b: impl 'lifetime = foo; | ||
4120 | let b: impl (Trait) = foo; | ||
4121 | let b: impl ('lifetime) = foo; | ||
4122 | let d: impl ?Sized = foo; | ||
4123 | let e: impl Trait + ?Sized = foo; | ||
4124 | } | ||
4125 | "#), | ||
4126 | @r###" | ||
4127 | [26; 237) '{ ...foo; }': () | ||
4128 | [36; 37) 'a': impl Trait + {error} | ||
4129 | [64; 67) 'foo': impl Trait + {error} | ||
4130 | [77; 78) 'b': impl {error} | ||
4131 | [97; 100) 'foo': impl {error} | ||
4132 | [110; 111) 'b': impl Trait | ||
4133 | [128; 131) 'foo': impl Trait | ||
4134 | [141; 142) 'b': impl {error} | ||
4135 | [163; 166) 'foo': impl {error} | ||
4136 | [176; 177) 'd': impl {error} | ||
4137 | [193; 196) 'foo': impl {error} | ||
4138 | [206; 207) 'e': impl Trait + {error} | ||
4139 | [231; 234) 'foo': impl Trait + {error} | ||
4140 | "### | ||
4141 | ); | ||
4142 | } | ||
4143 | |||
4144 | #[test] | ||
4145 | fn assoc_type_bindings() { | ||
4146 | assert_snapshot!( | ||
4147 | infer(r#" | ||
4148 | trait Trait { | ||
4149 | type Type; | ||
4150 | } | ||
4151 | |||
4152 | fn get<T: Trait>(t: T) -> <T as Trait>::Type {} | ||
4153 | fn get2<U, T: Trait<Type = U>>(t: T) -> U {} | ||
4154 | fn set<T: Trait<Type = u64>>(t: T) -> T {t} | ||
4155 | |||
4156 | struct S<T>; | ||
4157 | impl<T> Trait for S<T> { type Type = T; } | ||
4158 | |||
4159 | fn test<T: Trait<Type = u32>>(x: T, y: impl Trait<Type = i64>) { | ||
4160 | get(x); | ||
4161 | get2(x); | ||
4162 | get(y); | ||
4163 | get2(y); | ||
4164 | get(set(S)); | ||
4165 | get2(set(S)); | ||
4166 | get2(S::<str>); | ||
4167 | } | ||
4168 | "#), | ||
4169 | @r###" | ||
4170 | [50; 51) 't': T | ||
4171 | [78; 80) '{}': () | ||
4172 | [112; 113) 't': T | ||
4173 | [123; 125) '{}': () | ||
4174 | [155; 156) 't': T | ||
4175 | [166; 169) '{t}': T | ||
4176 | [167; 168) 't': T | ||
4177 | [257; 258) 'x': T | ||
4178 | [263; 264) 'y': impl Trait<Type = i64> | ||
4179 | [290; 398) '{ ...r>); }': () | ||
4180 | [296; 299) 'get': fn get<T>(T) -> <T as Trait>::Type | ||
4181 | [296; 302) 'get(x)': {unknown} | ||
4182 | [300; 301) 'x': T | ||
4183 | [308; 312) 'get2': fn get2<{unknown}, T>(T) -> U | ||
4184 | [308; 315) 'get2(x)': {unknown} | ||
4185 | [313; 314) 'x': T | ||
4186 | [321; 324) 'get': fn get<impl Trait<Type = i64>>(T) -> <T as Trait>::Type | ||
4187 | [321; 327) 'get(y)': {unknown} | ||
4188 | [325; 326) 'y': impl Trait<Type = i64> | ||
4189 | [333; 337) 'get2': fn get2<{unknown}, impl Trait<Type = i64>>(T) -> U | ||
4190 | [333; 340) 'get2(y)': {unknown} | ||
4191 | [338; 339) 'y': impl Trait<Type = i64> | ||
4192 | [346; 349) 'get': fn get<S<u64>>(T) -> <T as Trait>::Type | ||
4193 | [346; 357) 'get(set(S))': u64 | ||
4194 | [350; 353) 'set': fn set<S<u64>>(T) -> T | ||
4195 | [350; 356) 'set(S)': S<u64> | ||
4196 | [354; 355) 'S': S<u64> | ||
4197 | [363; 367) 'get2': fn get2<u64, S<u64>>(T) -> U | ||
4198 | [363; 375) 'get2(set(S))': u64 | ||
4199 | [368; 371) 'set': fn set<S<u64>>(T) -> T | ||
4200 | [368; 374) 'set(S)': S<u64> | ||
4201 | [372; 373) 'S': S<u64> | ||
4202 | [381; 385) 'get2': fn get2<str, S<str>>(T) -> U | ||
4203 | [381; 395) 'get2(S::<str>)': str | ||
4204 | [386; 394) 'S::<str>': S<str> | ||
4205 | "### | ||
4206 | ); | ||
4207 | } | ||
4208 | |||
4209 | #[test] | ||
4210 | fn impl_trait_assoc_binding_projection_bug() { | ||
4211 | let (db, pos) = TestDB::with_position( | ||
4212 | r#" | ||
4213 | //- /main.rs crate:main deps:std | ||
4214 | pub trait Language { | ||
4215 | type Kind; | ||
4216 | } | ||
4217 | pub enum RustLanguage {} | ||
4218 | impl Language for RustLanguage { | ||
4219 | type Kind = SyntaxKind; | ||
4220 | } | ||
4221 | struct SyntaxNode<L> {} | ||
4222 | fn foo() -> impl Iterator<Item = SyntaxNode<RustLanguage>> {} | ||
4223 | |||
4224 | trait Clone { | ||
4225 | fn clone(&self) -> Self; | ||
4226 | } | ||
4227 | |||
4228 | fn api_walkthrough() { | ||
4229 | for node in foo() { | ||
4230 | node.clone()<|>; | ||
4231 | } | ||
4232 | } | ||
4233 | |||
4234 | //- /std.rs crate:std | ||
4235 | #[prelude_import] use iter::*; | ||
4236 | mod iter { | ||
4237 | trait IntoIterator { | ||
4238 | type Item; | ||
4239 | } | ||
4240 | trait Iterator { | ||
4241 | type Item; | ||
4242 | } | ||
4243 | impl<T: Iterator> IntoIterator for T { | ||
4244 | type Item = <T as Iterator>::Item; | ||
4245 | } | ||
4246 | } | ||
4247 | "#, | ||
4248 | ); | ||
4249 | assert_eq!("{unknown}", type_at_pos(&db, pos)); | ||
4250 | } | ||
4251 | |||
4252 | #[test] | ||
4253 | fn projection_eq_within_chalk() { | ||
4254 | // std::env::set_var("CHALK_DEBUG", "1"); | ||
4255 | assert_snapshot!( | ||
4256 | infer(r#" | ||
4257 | trait Trait1 { | ||
4258 | type Type; | ||
4259 | } | ||
4260 | trait Trait2<T> { | ||
4261 | fn foo(self) -> T; | ||
4262 | } | ||
4263 | impl<T, U> Trait2<T> for U where U: Trait1<Type = T> {} | ||
4264 | |||
4265 | fn test<T: Trait1<Type = u32>>(x: T) { | ||
4266 | x.foo(); | ||
4267 | } | ||
4268 | "#), | ||
4269 | @r###" | ||
4270 | [62; 66) 'self': Self | ||
4271 | [164; 165) 'x': T | ||
4272 | [170; 186) '{ ...o(); }': () | ||
4273 | [176; 177) 'x': T | ||
4274 | [176; 183) 'x.foo()': {unknown} | ||
4275 | "### | ||
4276 | ); | ||
4277 | } | ||
4278 | |||
4279 | #[test] | ||
4280 | fn where_clause_trait_in_scope_for_method_resolution() { | ||
4281 | let t = type_at( | ||
4282 | r#" | ||
4283 | //- /main.rs | ||
4284 | mod foo { | ||
4285 | trait Trait { | ||
4286 | fn foo(&self) -> u32 {} | ||
4287 | } | ||
4288 | } | ||
4289 | |||
4290 | fn test<T: foo::Trait>(x: T) { | ||
4291 | x.foo()<|>; | ||
4292 | } | ||
4293 | "#, | ||
4294 | ); | ||
4295 | assert_eq!(t, "u32"); | ||
4296 | } | ||
4297 | |||
4298 | #[test] | ||
4299 | fn super_trait_method_resolution() { | ||
4300 | assert_snapshot!( | ||
4301 | infer(r#" | ||
4302 | mod foo { | ||
4303 | trait SuperTrait { | ||
4304 | fn foo(&self) -> u32 {} | ||
4305 | } | ||
4306 | } | ||
4307 | trait Trait1: foo::SuperTrait {} | ||
4308 | trait Trait2 where Self: foo::SuperTrait {} | ||
4309 | |||
4310 | fn test<T: Trait1, U: Trait2>(x: T, y: U) { | ||
4311 | x.foo(); | ||
4312 | y.foo(); | ||
4313 | } | ||
4314 | "#), | ||
4315 | @r###" | ||
4316 | [50; 54) 'self': &Self | ||
4317 | [63; 65) '{}': () | ||
4318 | [182; 183) 'x': T | ||
4319 | [188; 189) 'y': U | ||
4320 | [194; 223) '{ ...o(); }': () | ||
4321 | [200; 201) 'x': T | ||
4322 | [200; 207) 'x.foo()': u32 | ||
4323 | [213; 214) 'y': U | ||
4324 | [213; 220) 'y.foo()': u32 | ||
4325 | "### | ||
4326 | ); | ||
4327 | } | ||
4328 | |||
4329 | #[test] | ||
4330 | fn super_trait_cycle() { | ||
4331 | // This just needs to not crash | ||
4332 | assert_snapshot!( | ||
4333 | infer(r#" | ||
4334 | trait A: B {} | ||
4335 | trait B: A {} | ||
4336 | |||
4337 | fn test<T: A>(x: T) { | ||
4338 | x.foo(); | ||
4339 | } | ||
4340 | "#), | ||
4341 | @r###" | ||
4342 | [44; 45) 'x': T | ||
4343 | [50; 66) '{ ...o(); }': () | ||
4344 | [56; 57) 'x': T | ||
4345 | [56; 63) 'x.foo()': {unknown} | ||
4346 | "### | ||
4347 | ); | ||
4348 | } | ||
4349 | |||
4350 | #[test] | ||
4351 | fn super_trait_assoc_type_bounds() { | ||
4352 | assert_snapshot!( | ||
4353 | infer(r#" | ||
4354 | trait SuperTrait { type Type; } | ||
4355 | trait Trait where Self: SuperTrait {} | ||
4356 | |||
4357 | fn get2<U, T: Trait<Type = U>>(t: T) -> U {} | ||
4358 | fn set<T: Trait<Type = u64>>(t: T) -> T {t} | ||
4359 | |||
4360 | struct S<T>; | ||
4361 | impl<T> SuperTrait for S<T> { type Type = T; } | ||
4362 | impl<T> Trait for S<T> {} | ||
4363 | |||
4364 | fn test() { | ||
4365 | get2(set(S)); | ||
4366 | } | ||
4367 | "#), | ||
4368 | @r###" | ||
4369 | [103; 104) 't': T | ||
4370 | [114; 116) '{}': () | ||
4371 | [146; 147) 't': T | ||
4372 | [157; 160) '{t}': T | ||
4373 | [158; 159) 't': T | ||
4374 | [259; 280) '{ ...S)); }': () | ||
4375 | [265; 269) 'get2': fn get2<u64, S<u64>>(T) -> U | ||
4376 | [265; 277) 'get2(set(S))': u64 | ||
4377 | [270; 273) 'set': fn set<S<u64>>(T) -> T | ||
4378 | [270; 276) 'set(S)': S<u64> | ||
4379 | [274; 275) 'S': S<u64> | ||
4380 | "### | ||
4381 | ); | ||
4382 | } | ||
4383 | |||
4384 | #[test] | ||
4385 | fn fn_trait() { | ||
4386 | assert_snapshot!( | ||
4387 | infer(r#" | ||
4388 | trait FnOnce<Args> { | ||
4389 | type Output; | ||
4390 | |||
4391 | fn call_once(self, args: Args) -> <Self as FnOnce<Args>>::Output; | ||
4392 | } | ||
4393 | |||
4394 | fn test<F: FnOnce(u32, u64) -> u128>(f: F) { | ||
4395 | f.call_once((1, 2)); | ||
4396 | } | ||
4397 | "#), | ||
4398 | @r###" | ||
4399 | [57; 61) 'self': Self | ||
4400 | [63; 67) 'args': Args | ||
4401 | [150; 151) 'f': F | ||
4402 | [156; 184) '{ ...2)); }': () | ||
4403 | [162; 163) 'f': F | ||
4404 | [162; 181) 'f.call...1, 2))': {unknown} | ||
4405 | [174; 180) '(1, 2)': (u32, u64) | ||
4406 | [175; 176) '1': u32 | ||
4407 | [178; 179) '2': u64 | ||
4408 | "### | ||
4409 | ); | ||
4410 | } | ||
4411 | |||
4412 | #[test] | ||
4413 | fn closure_1() { | ||
4414 | assert_snapshot!( | ||
4415 | infer(r#" | ||
4416 | #[lang = "fn_once"] | ||
4417 | trait FnOnce<Args> { | ||
4418 | type Output; | ||
4419 | } | ||
4420 | |||
4421 | enum Option<T> { Some(T), None } | ||
4422 | impl<T> Option<T> { | ||
4423 | fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {} | ||
4424 | } | ||
4425 | |||
4426 | fn test() { | ||
4427 | let x = Option::Some(1u32); | ||
4428 | x.map(|v| v + 1); | ||
4429 | x.map(|_v| 1u64); | ||
4430 | let y: Option<i64> = x.map(|_v| 1); | ||
4431 | } | ||
4432 | "#), | ||
4433 | @r###" | ||
4434 | [148; 152) 'self': Option<T> | ||
4435 | [154; 155) 'f': F | ||
4436 | [173; 175) '{}': () | ||
4437 | [189; 308) '{ ... 1); }': () | ||
4438 | [199; 200) 'x': Option<u32> | ||
4439 | [203; 215) 'Option::Some': Some<u32>(T) -> Option<T> | ||
4440 | [203; 221) 'Option...(1u32)': Option<u32> | ||
4441 | [216; 220) '1u32': u32 | ||
4442 | [227; 228) 'x': Option<u32> | ||
4443 | [227; 243) 'x.map(...v + 1)': Option<u32> | ||
4444 | [233; 242) '|v| v + 1': |u32| -> u32 | ||
4445 | [234; 235) 'v': u32 | ||
4446 | [237; 238) 'v': u32 | ||
4447 | [237; 242) 'v + 1': u32 | ||
4448 | [241; 242) '1': u32 | ||
4449 | [249; 250) 'x': Option<u32> | ||
4450 | [249; 265) 'x.map(... 1u64)': Option<u64> | ||
4451 | [255; 264) '|_v| 1u64': |u32| -> u64 | ||
4452 | [256; 258) '_v': u32 | ||
4453 | [260; 264) '1u64': u64 | ||
4454 | [275; 276) 'y': Option<i64> | ||
4455 | [292; 293) 'x': Option<u32> | ||
4456 | [292; 305) 'x.map(|_v| 1)': Option<i64> | ||
4457 | [298; 304) '|_v| 1': |u32| -> i64 | ||
4458 | [299; 301) '_v': u32 | ||
4459 | [303; 304) '1': i64 | ||
4460 | "### | ||
4461 | ); | ||
4462 | } | ||
4463 | |||
4464 | #[test] | ||
4465 | fn closure_2() { | ||
4466 | assert_snapshot!( | ||
4467 | infer(r#" | ||
4468 | trait FnOnce<Args> { | ||
4469 | type Output; | ||
4470 | } | ||
4471 | |||
4472 | fn test<F: FnOnce(u32) -> u64>(f: F) { | ||
4473 | f(1); | ||
4474 | let g = |v| v + 1; | ||
4475 | g(1u64); | ||
4476 | let h = |v| 1u128 + v; | ||
4477 | } | ||
4478 | "#), | ||
4479 | @r###" | ||
4480 | [73; 74) 'f': F | ||
4481 | [79; 155) '{ ...+ v; }': () | ||
4482 | [85; 86) 'f': F | ||
4483 | [85; 89) 'f(1)': {unknown} | ||
4484 | [87; 88) '1': i32 | ||
4485 | [99; 100) 'g': |u64| -> i32 | ||
4486 | [103; 112) '|v| v + 1': |u64| -> i32 | ||
4487 | [104; 105) 'v': u64 | ||
4488 | [107; 108) 'v': u64 | ||
4489 | [107; 112) 'v + 1': i32 | ||
4490 | [111; 112) '1': i32 | ||
4491 | [118; 119) 'g': |u64| -> i32 | ||
4492 | [118; 125) 'g(1u64)': i32 | ||
4493 | [120; 124) '1u64': u64 | ||
4494 | [135; 136) 'h': |u128| -> u128 | ||
4495 | [139; 152) '|v| 1u128 + v': |u128| -> u128 | ||
4496 | [140; 141) 'v': u128 | ||
4497 | [143; 148) '1u128': u128 | ||
4498 | [143; 152) '1u128 + v': u128 | ||
4499 | [151; 152) 'v': u128 | ||
4500 | "### | ||
4501 | ); | ||
4502 | } | ||
4503 | |||
4504 | #[test] | ||
4505 | fn closure_as_argument_inference_order() { | ||
4506 | assert_snapshot!( | ||
4507 | infer(r#" | ||
4508 | #[lang = "fn_once"] | ||
4509 | trait FnOnce<Args> { | ||
4510 | type Output; | ||
4511 | } | ||
4512 | |||
4513 | fn foo1<T, U, F: FnOnce(T) -> U>(x: T, f: F) -> U {} | ||
4514 | fn foo2<T, U, F: FnOnce(T) -> U>(f: F, x: T) -> U {} | ||
4515 | |||
4516 | struct S; | ||
4517 | impl S { | ||
4518 | fn method(self) -> u64; | ||
4519 | |||
4520 | fn foo1<T, U, F: FnOnce(T) -> U>(self, x: T, f: F) -> U {} | ||
4521 | fn foo2<T, U, F: FnOnce(T) -> U>(self, f: F, x: T) -> U {} | ||
4522 | } | ||
4523 | |||
4524 | fn test() { | ||
4525 | let x1 = foo1(S, |s| s.method()); | ||
4526 | let x2 = foo2(|s| s.method(), S); | ||
4527 | let x3 = S.foo1(S, |s| s.method()); | ||
4528 | let x4 = S.foo2(|s| s.method(), S); | ||
4529 | } | ||
4530 | "#), | ||
4531 | @r###" | ||
4532 | [95; 96) 'x': T | ||
4533 | [101; 102) 'f': F | ||
4534 | [112; 114) '{}': () | ||
4535 | [148; 149) 'f': F | ||
4536 | [154; 155) 'x': T | ||
4537 | [165; 167) '{}': () | ||
4538 | [202; 206) 'self': S | ||
4539 | [254; 258) 'self': S | ||
4540 | [260; 261) 'x': T | ||
4541 | [266; 267) 'f': F | ||
4542 | [277; 279) '{}': () | ||
4543 | [317; 321) 'self': S | ||
4544 | [323; 324) 'f': F | ||
4545 | [329; 330) 'x': T | ||
4546 | [340; 342) '{}': () | ||
4547 | [356; 515) '{ ... S); }': () | ||
4548 | [366; 368) 'x1': u64 | ||
4549 | [371; 375) 'foo1': fn foo1<S, u64, |S| -> u64>(T, F) -> U | ||
4550 | [371; 394) 'foo1(S...hod())': u64 | ||
4551 | [376; 377) 'S': S | ||
4552 | [379; 393) '|s| s.method()': |S| -> u64 | ||
4553 | [380; 381) 's': S | ||
4554 | [383; 384) 's': S | ||
4555 | [383; 393) 's.method()': u64 | ||
4556 | [404; 406) 'x2': u64 | ||
4557 | [409; 413) 'foo2': fn foo2<S, u64, |S| -> u64>(F, T) -> U | ||
4558 | [409; 432) 'foo2(|...(), S)': u64 | ||
4559 | [414; 428) '|s| s.method()': |S| -> u64 | ||
4560 | [415; 416) 's': S | ||
4561 | [418; 419) 's': S | ||
4562 | [418; 428) 's.method()': u64 | ||
4563 | [430; 431) 'S': S | ||
4564 | [442; 444) 'x3': u64 | ||
4565 | [447; 448) 'S': S | ||
4566 | [447; 472) 'S.foo1...hod())': u64 | ||
4567 | [454; 455) 'S': S | ||
4568 | [457; 471) '|s| s.method()': |S| -> u64 | ||
4569 | [458; 459) 's': S | ||
4570 | [461; 462) 's': S | ||
4571 | [461; 471) 's.method()': u64 | ||
4572 | [482; 484) 'x4': u64 | ||
4573 | [487; 488) 'S': S | ||
4574 | [487; 512) 'S.foo2...(), S)': u64 | ||
4575 | [494; 508) '|s| s.method()': |S| -> u64 | ||
4576 | [495; 496) 's': S | ||
4577 | [498; 499) 's': S | ||
4578 | [498; 508) 's.method()': u64 | ||
4579 | [510; 511) 'S': S | ||
4580 | "### | ||
4581 | ); | ||
4582 | } | ||
4583 | |||
4584 | #[test] | ||
4585 | fn unselected_projection_in_trait_env_1() { | ||
4586 | let t = type_at( | ||
4587 | r#" | ||
4588 | //- /main.rs | ||
4589 | trait Trait { | ||
4590 | type Item; | ||
4591 | } | ||
4592 | |||
4593 | trait Trait2 { | ||
4594 | fn foo(&self) -> u32; | ||
4595 | } | ||
4596 | |||
4597 | fn test<T: Trait>() where T::Item: Trait2 { | ||
4598 | let x: T::Item = no_matter; | ||
4599 | x.foo()<|>; | ||
4600 | } | ||
4601 | "#, | ||
4602 | ); | ||
4603 | assert_eq!(t, "u32"); | ||
4604 | } | ||
4605 | |||
4606 | #[test] | ||
4607 | fn unselected_projection_in_trait_env_2() { | ||
4608 | let t = type_at( | ||
4609 | r#" | ||
4610 | //- /main.rs | ||
4611 | trait Trait<T> { | ||
4612 | type Item; | ||
4613 | } | ||
4614 | |||
4615 | trait Trait2 { | ||
4616 | fn foo(&self) -> u32; | ||
4617 | } | ||
4618 | |||
4619 | fn test<T, U>() where T::Item: Trait2, T: Trait<U::Item>, U: Trait<()> { | ||
4620 | let x: T::Item = no_matter; | ||
4621 | x.foo()<|>; | ||
4622 | } | ||
4623 | "#, | ||
4624 | ); | ||
4625 | assert_eq!(t, "u32"); | ||
4626 | } | ||
4627 | |||
4628 | #[test] | ||
4629 | // FIXME this is currently a Salsa panic; it would be nicer if it just returned | ||
4630 | // in Unknown, and we should be able to do that once Salsa allows us to handle | ||
4631 | // the cycle. But at least it doesn't overflow for now. | ||
4632 | #[should_panic] | ||
4633 | fn unselected_projection_in_trait_env_cycle_1() { | ||
4634 | let t = type_at( | ||
4635 | r#" | ||
4636 | //- /main.rs | ||
4637 | trait Trait { | ||
4638 | type Item; | ||
4639 | } | ||
4640 | |||
4641 | trait Trait2<T> {} | ||
4642 | |||
4643 | fn test<T: Trait>() where T: Trait2<T::Item> { | ||
4644 | let x: T::Item = no_matter<|>; | ||
4645 | } | ||
4646 | "#, | ||
4647 | ); | ||
4648 | // this is a legitimate cycle | ||
4649 | assert_eq!(t, "{unknown}"); | ||
4650 | } | ||
4651 | |||
4652 | #[test] | ||
4653 | // FIXME this is currently a Salsa panic; it would be nicer if it just returned | ||
4654 | // in Unknown, and we should be able to do that once Salsa allows us to handle | ||
4655 | // the cycle. But at least it doesn't overflow for now. | ||
4656 | #[should_panic] | ||
4657 | fn unselected_projection_in_trait_env_cycle_2() { | ||
4658 | let t = type_at( | ||
4659 | r#" | ||
4660 | //- /main.rs | ||
4661 | trait Trait<T> { | ||
4662 | type Item; | ||
4663 | } | ||
4664 | |||
4665 | fn test<T, U>() where T: Trait<U::Item>, U: Trait<T::Item> { | ||
4666 | let x: T::Item = no_matter<|>; | ||
4667 | } | ||
4668 | "#, | ||
4669 | ); | ||
4670 | // this is a legitimate cycle | ||
4671 | assert_eq!(t, "{unknown}"); | ||
4672 | } | ||
4673 | |||
4674 | fn type_at_pos(db: &TestDB, pos: FilePosition) -> String { | ||
4675 | let file = db.parse(pos.file_id).ok().unwrap(); | ||
4676 | let expr = algo::find_node_at_offset::<ast::Expr>(file.syntax(), pos.offset).unwrap(); | ||
4677 | let analyzer = | ||
4678 | SourceAnalyzer::new(db, Source::new(pos.file_id.into(), expr.syntax()), Some(pos.offset)); | ||
4679 | let ty = analyzer.type_of(db, &expr).unwrap(); | ||
4680 | ty.display(db).to_string() | ||
4681 | } | ||
4682 | |||
4683 | fn type_at(content: &str) -> String { | ||
4684 | let (db, file_pos) = TestDB::with_position(content); | ||
4685 | type_at_pos(&db, file_pos) | ||
4686 | } | ||
4687 | |||
4688 | fn infer(content: &str) -> String { | ||
4689 | let (db, file_id) = TestDB::with_single_file(content); | ||
4690 | let source_file = db.parse(file_id).ok().unwrap(); | ||
4691 | |||
4692 | let mut acc = String::new(); | ||
4693 | |||
4694 | let mut infer_def = |inference_result: Arc<InferenceResult>, | ||
4695 | body_source_map: Arc<BodySourceMap>| { | ||
4696 | let mut types = Vec::new(); | ||
4697 | |||
4698 | for (pat, ty) in inference_result.type_of_pat.iter() { | ||
4699 | let syntax_ptr = match body_source_map.pat_syntax(pat) { | ||
4700 | Some(sp) => { | ||
4701 | sp.map(|ast| ast.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr())) | ||
4702 | } | ||
4703 | None => continue, | ||
4704 | }; | ||
4705 | types.push((syntax_ptr, ty)); | ||
4706 | } | ||
4707 | |||
4708 | for (expr, ty) in inference_result.type_of_expr.iter() { | ||
4709 | let syntax_ptr = match body_source_map.expr_syntax(expr) { | ||
4710 | Some(sp) => { | ||
4711 | sp.map(|ast| ast.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr())) | ||
4712 | } | ||
4713 | None => continue, | ||
4714 | }; | ||
4715 | types.push((syntax_ptr, ty)); | ||
4716 | } | ||
4717 | |||
4718 | // sort ranges for consistency | ||
4719 | types.sort_by_key(|(src_ptr, _)| { | ||
4720 | (src_ptr.value.range().start(), src_ptr.value.range().end()) | ||
4721 | }); | ||
4722 | for (src_ptr, ty) in &types { | ||
4723 | let node = src_ptr.value.to_node(&src_ptr.file_syntax(&db)); | ||
4724 | |||
4725 | let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.clone()) { | ||
4726 | (self_param.self_kw_token().text_range(), "self".to_string()) | ||
4727 | } else { | ||
4728 | (src_ptr.value.range(), node.text().to_string().replace("\n", " ")) | ||
4729 | }; | ||
4730 | let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" }; | ||
4731 | write!( | ||
4732 | acc, | ||
4733 | "{}{} '{}': {}\n", | ||
4734 | macro_prefix, | ||
4735 | range, | ||
4736 | ellipsize(text, 15), | ||
4737 | ty.display(&db) | ||
4738 | ) | ||
4739 | .unwrap(); | ||
4740 | } | ||
4741 | }; | ||
4742 | |||
4743 | let mut analyzed = FxHashSet::default(); | ||
4744 | for node in source_file.syntax().descendants() { | ||
4745 | if node.kind() == FN_DEF || node.kind() == CONST_DEF || node.kind() == STATIC_DEF { | ||
4746 | let analyzer = SourceAnalyzer::new(&db, Source::new(file_id.into(), &node), None); | ||
4747 | if analyzed.insert(analyzer.analyzed_declaration()) { | ||
4748 | infer_def(analyzer.inference_result(), analyzer.body_source_map()); | ||
4749 | } | ||
4750 | } | ||
4751 | } | ||
4752 | |||
4753 | acc.truncate(acc.trim_end().len()); | ||
4754 | acc | ||
4755 | } | ||
4756 | |||
4757 | fn ellipsize(mut text: String, max_len: usize) -> String { | ||
4758 | if text.len() <= max_len { | ||
4759 | return text; | ||
4760 | } | ||
4761 | let ellipsis = "..."; | ||
4762 | let e_len = ellipsis.len(); | ||
4763 | let mut prefix_len = (max_len - e_len) / 2; | ||
4764 | while !text.is_char_boundary(prefix_len) { | ||
4765 | prefix_len += 1; | ||
4766 | } | ||
4767 | let mut suffix_len = max_len - e_len - prefix_len; | ||
4768 | while !text.is_char_boundary(text.len() - suffix_len) { | ||
4769 | suffix_len += 1; | ||
4770 | } | ||
4771 | text.replace_range(prefix_len..text.len() - suffix_len, ellipsis); | ||
4772 | text | ||
4773 | } | ||
4774 | |||
4775 | #[test] | ||
4776 | fn typing_whitespace_inside_a_function_should_not_invalidate_types() { | ||
4777 | let (mut db, pos) = TestDB::with_position( | ||
4778 | " | ||
4779 | //- /lib.rs | ||
4780 | fn foo() -> i32 { | ||
4781 | <|>1 + 1 | ||
4782 | } | ||
4783 | ", | ||
4784 | ); | ||
4785 | { | ||
4786 | let file = db.parse(pos.file_id).ok().unwrap(); | ||
4787 | let node = file.syntax().token_at_offset(pos.offset).right_biased().unwrap().parent(); | ||
4788 | let events = db.log_executed(|| { | ||
4789 | SourceAnalyzer::new(&db, Source::new(pos.file_id.into(), &node), None); | ||
4790 | }); | ||
4791 | assert!(format!("{:?}", events).contains("infer")) | ||
4792 | } | ||
4793 | |||
4794 | let new_text = " | ||
4795 | fn foo() -> i32 { | ||
4796 | 1 | ||
4797 | + | ||
4798 | 1 | ||
4799 | } | ||
4800 | " | ||
4801 | .to_string(); | ||
4802 | |||
4803 | db.query_mut(ra_db::FileTextQuery).set(pos.file_id, Arc::new(new_text)); | ||
4804 | |||
4805 | { | ||
4806 | let file = db.parse(pos.file_id).ok().unwrap(); | ||
4807 | let node = file.syntax().token_at_offset(pos.offset).right_biased().unwrap().parent(); | ||
4808 | let events = db.log_executed(|| { | ||
4809 | SourceAnalyzer::new(&db, Source::new(pos.file_id.into(), &node), None); | ||
4810 | }); | ||
4811 | assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events) | ||
4812 | } | ||
4813 | } | ||
4814 | |||
4815 | #[test] | ||
4816 | fn no_such_field_diagnostics() { | ||
4817 | let diagnostics = TestDB::with_files( | ||
4818 | r" | ||
4819 | //- /lib.rs | ||
4820 | struct S { foo: i32, bar: () } | ||
4821 | impl S { | ||
4822 | fn new() -> S { | ||
4823 | S { | ||
4824 | foo: 92, | ||
4825 | baz: 62, | ||
4826 | } | ||
4827 | } | ||
4828 | } | ||
4829 | ", | ||
4830 | ) | ||
4831 | .diagnostics(); | ||
4832 | |||
4833 | assert_snapshot!(diagnostics, @r###" | ||
4834 | "baz: 62": no such field | ||
4835 | "{\n foo: 92,\n baz: 62,\n }": fill structure fields | ||
4836 | "### | ||
4837 | ); | ||
4838 | } | ||
4839 | |||
4840 | #[test] | ||
4841 | fn infer_builtin_macros_line() { | ||
4842 | assert_snapshot!( | ||
4843 | infer(r#" | ||
4844 | #[rustc_builtin_macro] | ||
4845 | macro_rules! line {() => {}} | ||
4846 | |||
4847 | fn main() { | ||
4848 | let x = line!(); | ||
4849 | } | ||
4850 | "#), | ||
4851 | @r###" | ||
4852 | ![0; 1) '6': i32 | ||
4853 | [64; 88) '{ ...!(); }': () | ||
4854 | [74; 75) 'x': i32 | ||
4855 | "### | ||
4856 | ); | ||
4857 | } | ||
4858 | |||
4859 | #[test] | ||
4860 | fn infer_builtin_macros_file() { | ||
4861 | assert_snapshot!( | ||
4862 | infer(r#" | ||
4863 | #[rustc_builtin_macro] | ||
4864 | macro_rules! file {() => {}} | ||
4865 | |||
4866 | fn main() { | ||
4867 | let x = file!(); | ||
4868 | } | ||
4869 | "#), | ||
4870 | @r###" | ||
4871 | ![0; 2) '""': &str | ||
4872 | [64; 88) '{ ...!(); }': () | ||
4873 | [74; 75) 'x': &str | ||
4874 | "### | ||
4875 | ); | ||
4876 | } | ||
4877 | |||
4878 | #[test] | ||
4879 | fn infer_builtin_macros_column() { | ||
4880 | assert_snapshot!( | ||
4881 | infer(r#" | ||
4882 | #[rustc_builtin_macro] | ||
4883 | macro_rules! column {() => {}} | ||
4884 | |||
4885 | fn main() { | ||
4886 | let x = column!(); | ||
4887 | } | ||
4888 | "#), | ||
4889 | @r###" | ||
4890 | ![0; 2) '13': i32 | ||
4891 | [66; 92) '{ ...!(); }': () | ||
4892 | [76; 77) 'x': i32 | ||
4893 | "### | ||
4894 | ); | ||
4895 | } | ||
diff --git a/crates/ra_hir/src/ty/tests/coercion.rs b/crates/ra_hir/src/ty/tests/coercion.rs deleted file mode 100644 index 1530fcc63..000000000 --- a/crates/ra_hir/src/ty/tests/coercion.rs +++ /dev/null | |||
@@ -1,369 +0,0 @@ | |||
1 | use insta::assert_snapshot; | ||
2 | use test_utils::covers; | ||
3 | |||
4 | // Infer with some common definitions and impls. | ||
5 | fn infer(source: &str) -> String { | ||
6 | let defs = r#" | ||
7 | #[lang = "sized"] | ||
8 | pub trait Sized {} | ||
9 | #[lang = "unsize"] | ||
10 | pub trait Unsize<T: ?Sized> {} | ||
11 | #[lang = "coerce_unsized"] | ||
12 | pub trait CoerceUnsized<T> {} | ||
13 | |||
14 | impl<'a, 'b: 'a, T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<&'a U> for &'b T {} | ||
15 | impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<*mut U> for *mut T {} | ||
16 | "#; | ||
17 | |||
18 | // Append to the end to keep positions unchanged. | ||
19 | super::infer(&format!("{}{}", source, defs)) | ||
20 | } | ||
21 | |||
22 | #[test] | ||
23 | fn infer_block_expr_type_mismatch() { | ||
24 | assert_snapshot!( | ||
25 | infer(r#" | ||
26 | fn test() { | ||
27 | let a: i32 = { 1i64 }; | ||
28 | } | ||
29 | "#), | ||
30 | @r###" | ||
31 | [11; 41) '{ ...4 }; }': () | ||
32 | [21; 22) 'a': i32 | ||
33 | [30; 38) '{ 1i64 }': i64 | ||
34 | [32; 36) '1i64': i64 | ||
35 | "###); | ||
36 | } | ||
37 | |||
38 | #[test] | ||
39 | fn coerce_places() { | ||
40 | assert_snapshot!( | ||
41 | infer(r#" | ||
42 | struct S<T> { a: T } | ||
43 | |||
44 | fn f<T>(_: &[T]) -> T { loop {} } | ||
45 | fn g<T>(_: S<&[T]>) -> T { loop {} } | ||
46 | |||
47 | fn gen<T>() -> *mut [T; 2] { loop {} } | ||
48 | fn test1<U>() -> *mut [U] { | ||
49 | gen() | ||
50 | } | ||
51 | |||
52 | fn test2() { | ||
53 | let arr: &[u8; 1] = &[1]; | ||
54 | |||
55 | let a: &[_] = arr; | ||
56 | let b = f(arr); | ||
57 | let c: &[_] = { arr }; | ||
58 | let d = g(S { a: arr }); | ||
59 | let e: [&[_]; 1] = [arr]; | ||
60 | let f: [&[_]; 2] = [arr; 2]; | ||
61 | let g: (&[_], &[_]) = (arr, arr); | ||
62 | } | ||
63 | "#), | ||
64 | @r###" | ||
65 | [31; 32) '_': &[T] | ||
66 | [45; 56) '{ loop {} }': T | ||
67 | [47; 54) 'loop {}': ! | ||
68 | [52; 54) '{}': () | ||
69 | [65; 66) '_': S<&[T]> | ||
70 | [82; 93) '{ loop {} }': T | ||
71 | [84; 91) 'loop {}': ! | ||
72 | [89; 91) '{}': () | ||
73 | [122; 133) '{ loop {} }': *mut [T;_] | ||
74 | [124; 131) 'loop {}': ! | ||
75 | [129; 131) '{}': () | ||
76 | [160; 173) '{ gen() }': *mut [U] | ||
77 | [166; 169) 'gen': fn gen<U>() -> *mut [T;_] | ||
78 | [166; 171) 'gen()': *mut [U;_] | ||
79 | [186; 420) '{ ...rr); }': () | ||
80 | [196; 199) 'arr': &[u8;_] | ||
81 | [212; 216) '&[1]': &[u8;_] | ||
82 | [213; 216) '[1]': [u8;_] | ||
83 | [214; 215) '1': u8 | ||
84 | [227; 228) 'a': &[u8] | ||
85 | [237; 240) 'arr': &[u8;_] | ||
86 | [250; 251) 'b': u8 | ||
87 | [254; 255) 'f': fn f<u8>(&[T]) -> T | ||
88 | [254; 260) 'f(arr)': u8 | ||
89 | [256; 259) 'arr': &[u8;_] | ||
90 | [270; 271) 'c': &[u8] | ||
91 | [280; 287) '{ arr }': &[u8] | ||
92 | [282; 285) 'arr': &[u8;_] | ||
93 | [297; 298) 'd': u8 | ||
94 | [301; 302) 'g': fn g<u8>(S<&[T]>) -> T | ||
95 | [301; 316) 'g(S { a: arr })': u8 | ||
96 | [303; 315) 'S { a: arr }': S<&[u8]> | ||
97 | [310; 313) 'arr': &[u8;_] | ||
98 | [326; 327) 'e': [&[u8];_] | ||
99 | [341; 346) '[arr]': [&[u8];_] | ||
100 | [342; 345) 'arr': &[u8;_] | ||
101 | [356; 357) 'f': [&[u8];_] | ||
102 | [371; 379) '[arr; 2]': [&[u8];_] | ||
103 | [372; 375) 'arr': &[u8;_] | ||
104 | [377; 378) '2': usize | ||
105 | [389; 390) 'g': (&[u8], &[u8]) | ||
106 | [407; 417) '(arr, arr)': (&[u8], &[u8]) | ||
107 | [408; 411) 'arr': &[u8;_] | ||
108 | [413; 416) 'arr': &[u8;_] | ||
109 | "### | ||
110 | ); | ||
111 | } | ||
112 | |||
113 | #[test] | ||
114 | fn infer_let_stmt_coerce() { | ||
115 | assert_snapshot!( | ||
116 | infer(r#" | ||
117 | fn test() { | ||
118 | let x: &[i32] = &[1]; | ||
119 | } | ||
120 | "#), | ||
121 | @r###" | ||
122 | [11; 40) '{ ...[1]; }': () | ||
123 | [21; 22) 'x': &[i32] | ||
124 | [33; 37) '&[1]': &[i32;_] | ||
125 | [34; 37) '[1]': [i32;_] | ||
126 | [35; 36) '1': i32 | ||
127 | "###); | ||
128 | } | ||
129 | |||
130 | #[test] | ||
131 | fn infer_custom_coerce_unsized() { | ||
132 | assert_snapshot!( | ||
133 | infer(r#" | ||
134 | struct A<T: ?Sized>(*const T); | ||
135 | struct B<T: ?Sized>(*const T); | ||
136 | struct C<T: ?Sized> { inner: *const T } | ||
137 | |||
138 | impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<B<U>> for B<T> {} | ||
139 | impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<C<U>> for C<T> {} | ||
140 | |||
141 | fn foo1<T>(x: A<[T]>) -> A<[T]> { x } | ||
142 | fn foo2<T>(x: B<[T]>) -> B<[T]> { x } | ||
143 | fn foo3<T>(x: C<[T]>) -> C<[T]> { x } | ||
144 | |||
145 | fn test(a: A<[u8; 2]>, b: B<[u8; 2]>, c: C<[u8; 2]>) { | ||
146 | let d = foo1(a); | ||
147 | let e = foo2(b); | ||
148 | let f = foo3(c); | ||
149 | } | ||
150 | "#), | ||
151 | @r###" | ||
152 | [258; 259) 'x': A<[T]> | ||
153 | [279; 284) '{ x }': A<[T]> | ||
154 | [281; 282) 'x': A<[T]> | ||
155 | [296; 297) 'x': B<[T]> | ||
156 | [317; 322) '{ x }': B<[T]> | ||
157 | [319; 320) 'x': B<[T]> | ||
158 | [334; 335) 'x': C<[T]> | ||
159 | [355; 360) '{ x }': C<[T]> | ||
160 | [357; 358) 'x': C<[T]> | ||
161 | [370; 371) 'a': A<[u8;_]> | ||
162 | [385; 386) 'b': B<[u8;_]> | ||
163 | [400; 401) 'c': C<[u8;_]> | ||
164 | [415; 481) '{ ...(c); }': () | ||
165 | [425; 426) 'd': A<[{unknown}]> | ||
166 | [429; 433) 'foo1': fn foo1<{unknown}>(A<[T]>) -> A<[T]> | ||
167 | [429; 436) 'foo1(a)': A<[{unknown}]> | ||
168 | [434; 435) 'a': A<[u8;_]> | ||
169 | [446; 447) 'e': B<[u8]> | ||
170 | [450; 454) 'foo2': fn foo2<u8>(B<[T]>) -> B<[T]> | ||
171 | [450; 457) 'foo2(b)': B<[u8]> | ||
172 | [455; 456) 'b': B<[u8;_]> | ||
173 | [467; 468) 'f': C<[u8]> | ||
174 | [471; 475) 'foo3': fn foo3<u8>(C<[T]>) -> C<[T]> | ||
175 | [471; 478) 'foo3(c)': C<[u8]> | ||
176 | [476; 477) 'c': C<[u8;_]> | ||
177 | "### | ||
178 | ); | ||
179 | } | ||
180 | |||
181 | #[test] | ||
182 | fn infer_if_coerce() { | ||
183 | assert_snapshot!( | ||
184 | infer(r#" | ||
185 | fn foo<T>(x: &[T]) -> &[T] { loop {} } | ||
186 | fn test() { | ||
187 | let x = if true { | ||
188 | foo(&[1]) | ||
189 | } else { | ||
190 | &[1] | ||
191 | }; | ||
192 | } | ||
193 | "#), | ||
194 | @r###" | ||
195 | [11; 12) 'x': &[T] | ||
196 | [28; 39) '{ loop {} }': &[T] | ||
197 | [30; 37) 'loop {}': ! | ||
198 | [35; 37) '{}': () | ||
199 | [50; 126) '{ ... }; }': () | ||
200 | [60; 61) 'x': &[i32] | ||
201 | [64; 123) 'if tru... }': &[i32] | ||
202 | [67; 71) 'true': bool | ||
203 | [72; 97) '{ ... }': &[i32] | ||
204 | [82; 85) 'foo': fn foo<i32>(&[T]) -> &[T] | ||
205 | [82; 91) 'foo(&[1])': &[i32] | ||
206 | [86; 90) '&[1]': &[i32;_] | ||
207 | [87; 90) '[1]': [i32;_] | ||
208 | [88; 89) '1': i32 | ||
209 | [103; 123) '{ ... }': &[i32;_] | ||
210 | [113; 117) '&[1]': &[i32;_] | ||
211 | [114; 117) '[1]': [i32;_] | ||
212 | [115; 116) '1': i32 | ||
213 | "### | ||
214 | ); | ||
215 | } | ||
216 | |||
217 | #[test] | ||
218 | fn infer_if_else_coerce() { | ||
219 | assert_snapshot!( | ||
220 | infer(r#" | ||
221 | fn foo<T>(x: &[T]) -> &[T] { loop {} } | ||
222 | fn test() { | ||
223 | let x = if true { | ||
224 | &[1] | ||
225 | } else { | ||
226 | foo(&[1]) | ||
227 | }; | ||
228 | } | ||
229 | "#), | ||
230 | @r###" | ||
231 | [11; 12) 'x': &[T] | ||
232 | [28; 39) '{ loop {} }': &[T] | ||
233 | [30; 37) 'loop {}': ! | ||
234 | [35; 37) '{}': () | ||
235 | [50; 126) '{ ... }; }': () | ||
236 | [60; 61) 'x': &[i32] | ||
237 | [64; 123) 'if tru... }': &[i32] | ||
238 | [67; 71) 'true': bool | ||
239 | [72; 92) '{ ... }': &[i32;_] | ||
240 | [82; 86) '&[1]': &[i32;_] | ||
241 | [83; 86) '[1]': [i32;_] | ||
242 | [84; 85) '1': i32 | ||
243 | [98; 123) '{ ... }': &[i32] | ||
244 | [108; 111) 'foo': fn foo<i32>(&[T]) -> &[T] | ||
245 | [108; 117) 'foo(&[1])': &[i32] | ||
246 | [112; 116) '&[1]': &[i32;_] | ||
247 | [113; 116) '[1]': [i32;_] | ||
248 | [114; 115) '1': i32 | ||
249 | "### | ||
250 | ); | ||
251 | } | ||
252 | |||
253 | #[test] | ||
254 | fn infer_match_first_coerce() { | ||
255 | assert_snapshot!( | ||
256 | infer(r#" | ||
257 | fn foo<T>(x: &[T]) -> &[T] { loop {} } | ||
258 | fn test(i: i32) { | ||
259 | let x = match i { | ||
260 | 2 => foo(&[2]), | ||
261 | 1 => &[1], | ||
262 | _ => &[3], | ||
263 | }; | ||
264 | } | ||
265 | "#), | ||
266 | @r###" | ||
267 | [11; 12) 'x': &[T] | ||
268 | [28; 39) '{ loop {} }': &[T] | ||
269 | [30; 37) 'loop {}': ! | ||
270 | [35; 37) '{}': () | ||
271 | [48; 49) 'i': i32 | ||
272 | [56; 150) '{ ... }; }': () | ||
273 | [66; 67) 'x': &[i32] | ||
274 | [70; 147) 'match ... }': &[i32] | ||
275 | [76; 77) 'i': i32 | ||
276 | [88; 89) '2': i32 | ||
277 | [93; 96) 'foo': fn foo<i32>(&[T]) -> &[T] | ||
278 | [93; 102) 'foo(&[2])': &[i32] | ||
279 | [97; 101) '&[2]': &[i32;_] | ||
280 | [98; 101) '[2]': [i32;_] | ||
281 | [99; 100) '2': i32 | ||
282 | [112; 113) '1': i32 | ||
283 | [117; 121) '&[1]': &[i32;_] | ||
284 | [118; 121) '[1]': [i32;_] | ||
285 | [119; 120) '1': i32 | ||
286 | [131; 132) '_': i32 | ||
287 | [136; 140) '&[3]': &[i32;_] | ||
288 | [137; 140) '[3]': [i32;_] | ||
289 | [138; 139) '3': i32 | ||
290 | "### | ||
291 | ); | ||
292 | } | ||
293 | |||
294 | #[test] | ||
295 | fn infer_match_second_coerce() { | ||
296 | assert_snapshot!( | ||
297 | infer(r#" | ||
298 | fn foo<T>(x: &[T]) -> &[T] { loop {} } | ||
299 | fn test(i: i32) { | ||
300 | let x = match i { | ||
301 | 1 => &[1], | ||
302 | 2 => foo(&[2]), | ||
303 | _ => &[3], | ||
304 | }; | ||
305 | } | ||
306 | "#), | ||
307 | @r###" | ||
308 | [11; 12) 'x': &[T] | ||
309 | [28; 39) '{ loop {} }': &[T] | ||
310 | [30; 37) 'loop {}': ! | ||
311 | [35; 37) '{}': () | ||
312 | [48; 49) 'i': i32 | ||
313 | [56; 150) '{ ... }; }': () | ||
314 | [66; 67) 'x': &[i32] | ||
315 | [70; 147) 'match ... }': &[i32] | ||
316 | [76; 77) 'i': i32 | ||
317 | [88; 89) '1': i32 | ||
318 | [93; 97) '&[1]': &[i32;_] | ||
319 | [94; 97) '[1]': [i32;_] | ||
320 | [95; 96) '1': i32 | ||
321 | [107; 108) '2': i32 | ||
322 | [112; 115) 'foo': fn foo<i32>(&[T]) -> &[T] | ||
323 | [112; 121) 'foo(&[2])': &[i32] | ||
324 | [116; 120) '&[2]': &[i32;_] | ||
325 | [117; 120) '[2]': [i32;_] | ||
326 | [118; 119) '2': i32 | ||
327 | [131; 132) '_': i32 | ||
328 | [136; 140) '&[3]': &[i32;_] | ||
329 | [137; 140) '[3]': [i32;_] | ||
330 | [138; 139) '3': i32 | ||
331 | "### | ||
332 | ); | ||
333 | } | ||
334 | |||
335 | #[test] | ||
336 | fn coerce_merge_one_by_one1() { | ||
337 | covers!(coerce_merge_fail_fallback); | ||
338 | |||
339 | assert_snapshot!( | ||
340 | infer(r#" | ||
341 | fn test() { | ||
342 | let t = &mut 1; | ||
343 | let x = match 1 { | ||
344 | 1 => t as *mut i32, | ||
345 | 2 => t as &i32, | ||
346 | _ => t as *const i32, | ||
347 | }; | ||
348 | } | ||
349 | "#), | ||
350 | @r###" | ||
351 | [11; 145) '{ ... }; }': () | ||
352 | [21; 22) 't': &mut i32 | ||
353 | [25; 31) '&mut 1': &mut i32 | ||
354 | [30; 31) '1': i32 | ||
355 | [41; 42) 'x': *const i32 | ||
356 | [45; 142) 'match ... }': *const i32 | ||
357 | [51; 52) '1': i32 | ||
358 | [63; 64) '1': i32 | ||
359 | [68; 69) 't': &mut i32 | ||
360 | [68; 81) 't as *mut i32': *mut i32 | ||
361 | [91; 92) '2': i32 | ||
362 | [96; 97) 't': &mut i32 | ||
363 | [96; 105) 't as &i32': &i32 | ||
364 | [115; 116) '_': i32 | ||
365 | [120; 121) 't': &mut i32 | ||
366 | [120; 135) 't as *const i32': *const i32 | ||
367 | "### | ||
368 | ); | ||
369 | } | ||
diff --git a/crates/ra_hir/src/ty/tests/never_type.rs b/crates/ra_hir/src/ty/tests/never_type.rs deleted file mode 100644 index c202f545a..000000000 --- a/crates/ra_hir/src/ty/tests/never_type.rs +++ /dev/null | |||
@@ -1,246 +0,0 @@ | |||
1 | use super::type_at; | ||
2 | |||
3 | #[test] | ||
4 | fn infer_never1() { | ||
5 | let t = type_at( | ||
6 | r#" | ||
7 | //- /main.rs | ||
8 | fn test() { | ||
9 | let t = return; | ||
10 | t<|>; | ||
11 | } | ||
12 | "#, | ||
13 | ); | ||
14 | assert_eq!(t, "!"); | ||
15 | } | ||
16 | |||
17 | #[test] | ||
18 | fn infer_never2() { | ||
19 | let t = type_at( | ||
20 | r#" | ||
21 | //- /main.rs | ||
22 | fn gen<T>() -> T { loop {} } | ||
23 | |||
24 | fn test() { | ||
25 | let a = gen(); | ||
26 | if false { a } else { loop {} }; | ||
27 | a<|>; | ||
28 | } | ||
29 | "#, | ||
30 | ); | ||
31 | assert_eq!(t, "!"); | ||
32 | } | ||
33 | |||
34 | #[test] | ||
35 | fn infer_never3() { | ||
36 | let t = type_at( | ||
37 | r#" | ||
38 | //- /main.rs | ||
39 | fn gen<T>() -> T { loop {} } | ||
40 | |||
41 | fn test() { | ||
42 | let a = gen(); | ||
43 | if false { loop {} } else { a }; | ||
44 | a<|>; | ||
45 | } | ||
46 | "#, | ||
47 | ); | ||
48 | assert_eq!(t, "!"); | ||
49 | } | ||
50 | |||
51 | #[test] | ||
52 | fn never_type_in_generic_args() { | ||
53 | let t = type_at( | ||
54 | r#" | ||
55 | //- /main.rs | ||
56 | enum Option<T> { None, Some(T) } | ||
57 | |||
58 | fn test() { | ||
59 | let a = if true { Option::None } else { Option::Some(return) }; | ||
60 | a<|>; | ||
61 | } | ||
62 | "#, | ||
63 | ); | ||
64 | assert_eq!(t, "Option<!>"); | ||
65 | } | ||
66 | |||
67 | #[test] | ||
68 | fn never_type_can_be_reinferred1() { | ||
69 | let t = type_at( | ||
70 | r#" | ||
71 | //- /main.rs | ||
72 | fn gen<T>() -> T { loop {} } | ||
73 | |||
74 | fn test() { | ||
75 | let a = gen(); | ||
76 | if false { loop {} } else { a }; | ||
77 | a<|>; | ||
78 | if false { a }; | ||
79 | } | ||
80 | "#, | ||
81 | ); | ||
82 | assert_eq!(t, "()"); | ||
83 | } | ||
84 | |||
85 | #[test] | ||
86 | fn never_type_can_be_reinferred2() { | ||
87 | let t = type_at( | ||
88 | r#" | ||
89 | //- /main.rs | ||
90 | enum Option<T> { None, Some(T) } | ||
91 | |||
92 | fn test() { | ||
93 | let a = if true { Option::None } else { Option::Some(return) }; | ||
94 | a<|>; | ||
95 | match 42 { | ||
96 | 42 => a, | ||
97 | _ => Option::Some(42), | ||
98 | }; | ||
99 | } | ||
100 | "#, | ||
101 | ); | ||
102 | assert_eq!(t, "Option<i32>"); | ||
103 | } | ||
104 | #[test] | ||
105 | fn never_type_can_be_reinferred3() { | ||
106 | let t = type_at( | ||
107 | r#" | ||
108 | //- /main.rs | ||
109 | enum Option<T> { None, Some(T) } | ||
110 | |||
111 | fn test() { | ||
112 | let a = if true { Option::None } else { Option::Some(return) }; | ||
113 | a<|>; | ||
114 | match 42 { | ||
115 | 42 => a, | ||
116 | _ => Option::Some("str"), | ||
117 | }; | ||
118 | } | ||
119 | "#, | ||
120 | ); | ||
121 | assert_eq!(t, "Option<&str>"); | ||
122 | } | ||
123 | |||
124 | #[test] | ||
125 | fn match_no_arm() { | ||
126 | let t = type_at( | ||
127 | r#" | ||
128 | //- /main.rs | ||
129 | enum Void {} | ||
130 | |||
131 | fn test(a: Void) { | ||
132 | let t = match a {}; | ||
133 | t<|>; | ||
134 | } | ||
135 | "#, | ||
136 | ); | ||
137 | assert_eq!(t, "!"); | ||
138 | } | ||
139 | |||
140 | #[test] | ||
141 | fn if_never() { | ||
142 | let t = type_at( | ||
143 | r#" | ||
144 | //- /main.rs | ||
145 | fn test() { | ||
146 | let i = if true { | ||
147 | loop {} | ||
148 | } else { | ||
149 | 3.0 | ||
150 | }; | ||
151 | i<|>; | ||
152 | } | ||
153 | "#, | ||
154 | ); | ||
155 | assert_eq!(t, "f64"); | ||
156 | } | ||
157 | |||
158 | #[test] | ||
159 | fn if_else_never() { | ||
160 | let t = type_at( | ||
161 | r#" | ||
162 | //- /main.rs | ||
163 | fn test(input: bool) { | ||
164 | let i = if input { | ||
165 | 2.0 | ||
166 | } else { | ||
167 | return | ||
168 | }; | ||
169 | i<|>; | ||
170 | } | ||
171 | "#, | ||
172 | ); | ||
173 | assert_eq!(t, "f64"); | ||
174 | } | ||
175 | |||
176 | #[test] | ||
177 | fn match_first_arm_never() { | ||
178 | let t = type_at( | ||
179 | r#" | ||
180 | //- /main.rs | ||
181 | fn test(a: i32) { | ||
182 | let i = match a { | ||
183 | 1 => return, | ||
184 | 2 => 2.0, | ||
185 | 3 => loop {}, | ||
186 | _ => 3.0, | ||
187 | }; | ||
188 | i<|>; | ||
189 | } | ||
190 | "#, | ||
191 | ); | ||
192 | assert_eq!(t, "f64"); | ||
193 | } | ||
194 | |||
195 | #[test] | ||
196 | fn match_second_arm_never() { | ||
197 | let t = type_at( | ||
198 | r#" | ||
199 | //- /main.rs | ||
200 | fn test(a: i32) { | ||
201 | let i = match a { | ||
202 | 1 => 3.0, | ||
203 | 2 => loop {}, | ||
204 | 3 => 3.0, | ||
205 | _ => return, | ||
206 | }; | ||
207 | i<|>; | ||
208 | } | ||
209 | "#, | ||
210 | ); | ||
211 | assert_eq!(t, "f64"); | ||
212 | } | ||
213 | |||
214 | #[test] | ||
215 | fn match_all_arms_never() { | ||
216 | let t = type_at( | ||
217 | r#" | ||
218 | //- /main.rs | ||
219 | fn test(a: i32) { | ||
220 | let i = match a { | ||
221 | 2 => return, | ||
222 | _ => loop {}, | ||
223 | }; | ||
224 | i<|>; | ||
225 | } | ||
226 | "#, | ||
227 | ); | ||
228 | assert_eq!(t, "!"); | ||
229 | } | ||
230 | |||
231 | #[test] | ||
232 | fn match_no_never_arms() { | ||
233 | let t = type_at( | ||
234 | r#" | ||
235 | //- /main.rs | ||
236 | fn test(a: i32) { | ||
237 | let i = match a { | ||
238 | 2 => 2.0, | ||
239 | _ => 3.0, | ||
240 | }; | ||
241 | i<|>; | ||
242 | } | ||
243 | "#, | ||
244 | ); | ||
245 | assert_eq!(t, "f64"); | ||
246 | } | ||
diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs deleted file mode 100644 index 268fa09e4..000000000 --- a/crates/ra_hir/src/ty/traits.rs +++ /dev/null | |||
@@ -1,326 +0,0 @@ | |||
1 | //! Trait solving using Chalk. | ||
2 | use std::sync::{Arc, Mutex}; | ||
3 | |||
4 | use chalk_ir::{cast::Cast, family::ChalkIr}; | ||
5 | use log::debug; | ||
6 | use ra_db::{impl_intern_key, salsa}; | ||
7 | use ra_prof::profile; | ||
8 | use rustc_hash::FxHashSet; | ||
9 | |||
10 | use super::{Canonical, GenericPredicate, HirDisplay, ProjectionTy, TraitRef, Ty, TypeWalk}; | ||
11 | use crate::{db::HirDatabase, expr::ExprId, Crate, DefWithBody, ImplBlock, Trait, TypeAlias}; | ||
12 | |||
13 | use self::chalk::{from_chalk, ToChalk}; | ||
14 | |||
15 | pub(crate) mod chalk; | ||
16 | |||
17 | #[derive(Debug, Clone)] | ||
18 | pub struct TraitSolver { | ||
19 | krate: Crate, | ||
20 | inner: Arc<Mutex<chalk_solve::Solver<ChalkIr>>>, | ||
21 | } | ||
22 | |||
23 | /// We need eq for salsa | ||
24 | impl PartialEq for TraitSolver { | ||
25 | fn eq(&self, other: &TraitSolver) -> bool { | ||
26 | Arc::ptr_eq(&self.inner, &other.inner) | ||
27 | } | ||
28 | } | ||
29 | |||
30 | impl Eq for TraitSolver {} | ||
31 | |||
32 | impl TraitSolver { | ||
33 | fn solve( | ||
34 | &self, | ||
35 | db: &impl HirDatabase, | ||
36 | goal: &chalk_ir::UCanonical<chalk_ir::InEnvironment<chalk_ir::Goal<ChalkIr>>>, | ||
37 | ) -> Option<chalk_solve::Solution<ChalkIr>> { | ||
38 | let context = ChalkContext { db, krate: self.krate }; | ||
39 | debug!("solve goal: {:?}", goal); | ||
40 | let mut solver = match self.inner.lock() { | ||
41 | Ok(it) => it, | ||
42 | // Our cancellation works via unwinding, but, as chalk is not | ||
43 | // panic-safe, we need to make sure to propagate the cancellation. | ||
44 | // Ideally, we should also make chalk panic-safe. | ||
45 | Err(_) => ra_db::Canceled::throw(), | ||
46 | }; | ||
47 | let solution = solver.solve(&context, goal); | ||
48 | debug!("solve({:?}) => {:?}", goal, solution); | ||
49 | solution | ||
50 | } | ||
51 | } | ||
52 | |||
53 | /// This controls the maximum size of types Chalk considers. If we set this too | ||
54 | /// high, we can run into slow edge cases; if we set it too low, Chalk won't | ||
55 | /// find some solutions. | ||
56 | const CHALK_SOLVER_MAX_SIZE: usize = 4; | ||
57 | |||
58 | #[derive(Debug, Copy, Clone)] | ||
59 | struct ChalkContext<'a, DB> { | ||
60 | db: &'a DB, | ||
61 | krate: Crate, | ||
62 | } | ||
63 | |||
64 | pub(crate) fn trait_solver_query( | ||
65 | db: &(impl HirDatabase + salsa::Database), | ||
66 | krate: Crate, | ||
67 | ) -> TraitSolver { | ||
68 | db.salsa_runtime().report_untracked_read(); | ||
69 | // krate parameter is just so we cache a unique solver per crate | ||
70 | let solver_choice = chalk_solve::SolverChoice::SLG { max_size: CHALK_SOLVER_MAX_SIZE }; | ||
71 | debug!("Creating new solver for crate {:?}", krate); | ||
72 | TraitSolver { krate, inner: Arc::new(Mutex::new(solver_choice.into_solver())) } | ||
73 | } | ||
74 | |||
75 | /// Collects impls for the given trait in the whole dependency tree of `krate`. | ||
76 | pub(crate) fn impls_for_trait_query( | ||
77 | db: &impl HirDatabase, | ||
78 | krate: Crate, | ||
79 | trait_: Trait, | ||
80 | ) -> Arc<[ImplBlock]> { | ||
81 | let mut impls = FxHashSet::default(); | ||
82 | // We call the query recursively here. On the one hand, this means we can | ||
83 | // reuse results from queries for different crates; on the other hand, this | ||
84 | // will only ever get called for a few crates near the root of the tree (the | ||
85 | // ones the user is editing), so this may actually be a waste of memory. I'm | ||
86 | // doing it like this mainly for simplicity for now. | ||
87 | for dep in krate.dependencies(db) { | ||
88 | impls.extend(db.impls_for_trait(dep.krate, trait_).iter()); | ||
89 | } | ||
90 | let crate_impl_blocks = db.impls_in_crate(krate); | ||
91 | impls.extend(crate_impl_blocks.lookup_impl_blocks_for_trait(trait_)); | ||
92 | impls.into_iter().collect() | ||
93 | } | ||
94 | |||
95 | /// A set of clauses that we assume to be true. E.g. if we are inside this function: | ||
96 | /// ```rust | ||
97 | /// fn foo<T: Default>(t: T) {} | ||
98 | /// ``` | ||
99 | /// we assume that `T: Default`. | ||
100 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] | ||
101 | pub struct TraitEnvironment { | ||
102 | pub predicates: Vec<GenericPredicate>, | ||
103 | } | ||
104 | |||
105 | impl TraitEnvironment { | ||
106 | /// Returns trait refs with the given self type which are supposed to hold | ||
107 | /// in this trait env. E.g. if we are in `foo<T: SomeTrait>()`, this will | ||
108 | /// find that `T: SomeTrait` if we call it for `T`. | ||
109 | pub(crate) fn trait_predicates_for_self_ty<'a>( | ||
110 | &'a self, | ||
111 | ty: &'a Ty, | ||
112 | ) -> impl Iterator<Item = &'a TraitRef> + 'a { | ||
113 | self.predicates.iter().filter_map(move |pred| match pred { | ||
114 | GenericPredicate::Implemented(tr) if tr.self_ty() == ty => Some(tr), | ||
115 | _ => None, | ||
116 | }) | ||
117 | } | ||
118 | } | ||
119 | |||
120 | /// Something (usually a goal), along with an environment. | ||
121 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] | ||
122 | pub struct InEnvironment<T> { | ||
123 | pub environment: Arc<TraitEnvironment>, | ||
124 | pub value: T, | ||
125 | } | ||
126 | |||
127 | impl<T> InEnvironment<T> { | ||
128 | pub fn new(environment: Arc<TraitEnvironment>, value: T) -> InEnvironment<T> { | ||
129 | InEnvironment { environment, value } | ||
130 | } | ||
131 | } | ||
132 | |||
133 | /// Something that needs to be proven (by Chalk) during type checking, e.g. that | ||
134 | /// a certain type implements a certain trait. Proving the Obligation might | ||
135 | /// result in additional information about inference variables. | ||
136 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] | ||
137 | pub enum Obligation { | ||
138 | /// Prove that a certain type implements a trait (the type is the `Self` type | ||
139 | /// parameter to the `TraitRef`). | ||
140 | Trait(TraitRef), | ||
141 | Projection(ProjectionPredicate), | ||
142 | } | ||
143 | |||
144 | impl Obligation { | ||
145 | pub fn from_predicate(predicate: GenericPredicate) -> Option<Obligation> { | ||
146 | match predicate { | ||
147 | GenericPredicate::Implemented(trait_ref) => Some(Obligation::Trait(trait_ref)), | ||
148 | GenericPredicate::Projection(projection_pred) => { | ||
149 | Some(Obligation::Projection(projection_pred)) | ||
150 | } | ||
151 | GenericPredicate::Error => None, | ||
152 | } | ||
153 | } | ||
154 | } | ||
155 | |||
156 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] | ||
157 | pub struct ProjectionPredicate { | ||
158 | pub projection_ty: ProjectionTy, | ||
159 | pub ty: Ty, | ||
160 | } | ||
161 | |||
162 | impl TypeWalk for ProjectionPredicate { | ||
163 | fn walk(&self, f: &mut impl FnMut(&Ty)) { | ||
164 | self.projection_ty.walk(f); | ||
165 | self.ty.walk(f); | ||
166 | } | ||
167 | |||
168 | fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { | ||
169 | self.projection_ty.walk_mut_binders(f, binders); | ||
170 | self.ty.walk_mut_binders(f, binders); | ||
171 | } | ||
172 | } | ||
173 | |||
174 | /// Solve a trait goal using Chalk. | ||
175 | pub(crate) fn trait_solve_query( | ||
176 | db: &impl HirDatabase, | ||
177 | krate: Crate, | ||
178 | goal: Canonical<InEnvironment<Obligation>>, | ||
179 | ) -> Option<Solution> { | ||
180 | let _p = profile("trait_solve_query"); | ||
181 | debug!("trait_solve_query({})", goal.value.value.display(db)); | ||
182 | |||
183 | if let Obligation::Projection(pred) = &goal.value.value { | ||
184 | if let Ty::Bound(_) = &pred.projection_ty.parameters[0] { | ||
185 | // Hack: don't ask Chalk to normalize with an unknown self type, it'll say that's impossible | ||
186 | return Some(Solution::Ambig(Guidance::Unknown)); | ||
187 | } | ||
188 | } | ||
189 | |||
190 | let canonical = goal.to_chalk(db).cast(); | ||
191 | |||
192 | // We currently don't deal with universes (I think / hope they're not yet | ||
193 | // relevant for our use cases?) | ||
194 | let u_canonical = chalk_ir::UCanonical { canonical, universes: 1 }; | ||
195 | let solution = db.trait_solver(krate).solve(db, &u_canonical); | ||
196 | solution.map(|solution| solution_from_chalk(db, solution)) | ||
197 | } | ||
198 | |||
199 | fn solution_from_chalk( | ||
200 | db: &impl HirDatabase, | ||
201 | solution: chalk_solve::Solution<ChalkIr>, | ||
202 | ) -> Solution { | ||
203 | let convert_subst = |subst: chalk_ir::Canonical<chalk_ir::Substitution<ChalkIr>>| { | ||
204 | let value = subst | ||
205 | .value | ||
206 | .parameters | ||
207 | .into_iter() | ||
208 | .map(|p| { | ||
209 | let ty = match p { | ||
210 | chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty), | ||
211 | chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(), | ||
212 | }; | ||
213 | ty | ||
214 | }) | ||
215 | .collect(); | ||
216 | let result = Canonical { value, num_vars: subst.binders.len() }; | ||
217 | SolutionVariables(result) | ||
218 | }; | ||
219 | match solution { | ||
220 | chalk_solve::Solution::Unique(constr_subst) => { | ||
221 | let subst = chalk_ir::Canonical { | ||
222 | value: constr_subst.value.subst, | ||
223 | binders: constr_subst.binders, | ||
224 | }; | ||
225 | Solution::Unique(convert_subst(subst)) | ||
226 | } | ||
227 | chalk_solve::Solution::Ambig(chalk_solve::Guidance::Definite(subst)) => { | ||
228 | Solution::Ambig(Guidance::Definite(convert_subst(subst))) | ||
229 | } | ||
230 | chalk_solve::Solution::Ambig(chalk_solve::Guidance::Suggested(subst)) => { | ||
231 | Solution::Ambig(Guidance::Suggested(convert_subst(subst))) | ||
232 | } | ||
233 | chalk_solve::Solution::Ambig(chalk_solve::Guidance::Unknown) => { | ||
234 | Solution::Ambig(Guidance::Unknown) | ||
235 | } | ||
236 | } | ||
237 | } | ||
238 | |||
239 | #[derive(Clone, Debug, PartialEq, Eq)] | ||
240 | pub struct SolutionVariables(pub Canonical<Vec<Ty>>); | ||
241 | |||
242 | #[derive(Clone, Debug, PartialEq, Eq)] | ||
243 | /// A (possible) solution for a proposed goal. | ||
244 | pub enum Solution { | ||
245 | /// The goal indeed holds, and there is a unique value for all existential | ||
246 | /// variables. | ||
247 | Unique(SolutionVariables), | ||
248 | |||
249 | /// The goal may be provable in multiple ways, but regardless we may have some guidance | ||
250 | /// for type inference. In this case, we don't return any lifetime | ||
251 | /// constraints, since we have not "committed" to any particular solution | ||
252 | /// yet. | ||
253 | Ambig(Guidance), | ||
254 | } | ||
255 | |||
256 | #[derive(Clone, Debug, PartialEq, Eq)] | ||
257 | /// When a goal holds ambiguously (e.g., because there are multiple possible | ||
258 | /// solutions), we issue a set of *guidance* back to type inference. | ||
259 | pub enum Guidance { | ||
260 | /// The existential variables *must* have the given values if the goal is | ||
261 | /// ever to hold, but that alone isn't enough to guarantee the goal will | ||
262 | /// actually hold. | ||
263 | Definite(SolutionVariables), | ||
264 | |||
265 | /// There are multiple plausible values for the existentials, but the ones | ||
266 | /// here are suggested as the preferred choice heuristically. These should | ||
267 | /// be used for inference fallback only. | ||
268 | Suggested(SolutionVariables), | ||
269 | |||
270 | /// There's no useful information to feed back to type inference | ||
271 | Unknown, | ||
272 | } | ||
273 | |||
274 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] | ||
275 | pub enum FnTrait { | ||
276 | FnOnce, | ||
277 | FnMut, | ||
278 | Fn, | ||
279 | } | ||
280 | |||
281 | impl FnTrait { | ||
282 | fn lang_item_name(self) -> &'static str { | ||
283 | match self { | ||
284 | FnTrait::FnOnce => "fn_once", | ||
285 | FnTrait::FnMut => "fn_mut", | ||
286 | FnTrait::Fn => "fn", | ||
287 | } | ||
288 | } | ||
289 | } | ||
290 | |||
291 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
292 | pub struct ClosureFnTraitImplData { | ||
293 | def: DefWithBody, | ||
294 | expr: ExprId, | ||
295 | fn_trait: FnTrait, | ||
296 | } | ||
297 | |||
298 | /// An impl. Usually this comes from an impl block, but some built-in types get | ||
299 | /// synthetic impls. | ||
300 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
301 | pub enum Impl { | ||
302 | /// A normal impl from an impl block. | ||
303 | ImplBlock(ImplBlock), | ||
304 | /// Closure types implement the Fn traits synthetically. | ||
305 | ClosureFnTraitImpl(ClosureFnTraitImplData), | ||
306 | } | ||
307 | /// This exists just for Chalk, because our ImplIds are only unique per module. | ||
308 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
309 | pub struct GlobalImplId(salsa::InternId); | ||
310 | impl_intern_key!(GlobalImplId); | ||
311 | |||
312 | /// An associated type value. Usually this comes from a `type` declaration | ||
313 | /// inside an impl block, but for built-in impls we have to synthesize it. | ||
314 | /// (We only need this because Chalk wants a unique ID for each of these.) | ||
315 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] | ||
316 | pub enum AssocTyValue { | ||
317 | /// A normal assoc type value from an impl block. | ||
318 | TypeAlias(TypeAlias), | ||
319 | /// The output type of the Fn trait implementation. | ||
320 | ClosureFnTraitImplOutput(ClosureFnTraitImplData), | ||
321 | } | ||
322 | /// This exists just for Chalk, because it needs a unique ID for each associated | ||
323 | /// type value in an impl (even synthetic ones). | ||
324 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
325 | pub struct AssocTyValueId(salsa::InternId); | ||
326 | impl_intern_key!(AssocTyValueId); | ||
diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs deleted file mode 100644 index 1a93e5e50..000000000 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ /dev/null | |||
@@ -1,884 +0,0 @@ | |||
1 | //! Conversion code from/to Chalk. | ||
2 | use std::sync::Arc; | ||
3 | |||
4 | use log::debug; | ||
5 | |||
6 | use chalk_ir::{ | ||
7 | cast::Cast, family::ChalkIr, Identifier, ImplId, Parameter, PlaceholderIndex, TypeId, | ||
8 | TypeKindId, TypeName, UniverseIndex, | ||
9 | }; | ||
10 | use chalk_rust_ir::{AssociatedTyDatum, AssociatedTyValue, ImplDatum, StructDatum, TraitDatum}; | ||
11 | |||
12 | use hir_def::lang_item::LangItemTarget; | ||
13 | use hir_expand::name; | ||
14 | |||
15 | use ra_db::salsa::{InternId, InternKey}; | ||
16 | |||
17 | use super::{AssocTyValue, Canonical, ChalkContext, Impl, Obligation}; | ||
18 | use crate::{ | ||
19 | db::HirDatabase, | ||
20 | ty::display::HirDisplay, | ||
21 | ty::{ApplicationTy, GenericPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk}, | ||
22 | Crate, GenericDef, ImplBlock, Trait, TypeAlias, | ||
23 | }; | ||
24 | |||
25 | /// This represents a trait whose name we could not resolve. | ||
26 | const UNKNOWN_TRAIT: chalk_ir::TraitId = | ||
27 | chalk_ir::TraitId(chalk_ir::RawId { index: u32::max_value() }); | ||
28 | |||
29 | pub(super) trait ToChalk { | ||
30 | type Chalk; | ||
31 | fn to_chalk(self, db: &impl HirDatabase) -> Self::Chalk; | ||
32 | fn from_chalk(db: &impl HirDatabase, chalk: Self::Chalk) -> Self; | ||
33 | } | ||
34 | |||
35 | pub(super) fn from_chalk<T, ChalkT>(db: &impl HirDatabase, chalk: ChalkT) -> T | ||
36 | where | ||
37 | T: ToChalk<Chalk = ChalkT>, | ||
38 | { | ||
39 | T::from_chalk(db, chalk) | ||
40 | } | ||
41 | |||
42 | impl ToChalk for Ty { | ||
43 | type Chalk = chalk_ir::Ty<ChalkIr>; | ||
44 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Ty<ChalkIr> { | ||
45 | match self { | ||
46 | Ty::Apply(apply_ty) => { | ||
47 | let name = match apply_ty.ctor { | ||
48 | TypeCtor::AssociatedType(type_alias) => { | ||
49 | let type_id = type_alias.to_chalk(db); | ||
50 | TypeName::AssociatedType(type_id) | ||
51 | } | ||
52 | _ => { | ||
53 | // other TypeCtors get interned and turned into a chalk StructId | ||
54 | let struct_id = apply_ty.ctor.to_chalk(db); | ||
55 | TypeName::TypeKindId(struct_id.into()) | ||
56 | } | ||
57 | }; | ||
58 | let parameters = apply_ty.parameters.to_chalk(db); | ||
59 | chalk_ir::ApplicationTy { name, parameters }.cast().intern() | ||
60 | } | ||
61 | Ty::Projection(proj_ty) => { | ||
62 | let associated_ty_id = proj_ty.associated_ty.to_chalk(db); | ||
63 | let parameters = proj_ty.parameters.to_chalk(db); | ||
64 | chalk_ir::ProjectionTy { associated_ty_id, parameters }.cast().intern() | ||
65 | } | ||
66 | Ty::Param { idx, .. } => { | ||
67 | PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize }.to_ty::<ChalkIr>() | ||
68 | } | ||
69 | Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx as usize).intern(), | ||
70 | Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"), | ||
71 | Ty::Dyn(predicates) => { | ||
72 | let where_clauses = predicates.iter().cloned().map(|p| p.to_chalk(db)).collect(); | ||
73 | chalk_ir::TyData::Dyn(make_binders(where_clauses, 1)).intern() | ||
74 | } | ||
75 | Ty::Opaque(predicates) => { | ||
76 | let where_clauses = predicates.iter().cloned().map(|p| p.to_chalk(db)).collect(); | ||
77 | chalk_ir::TyData::Opaque(make_binders(where_clauses, 1)).intern() | ||
78 | } | ||
79 | Ty::Unknown => { | ||
80 | let parameters = Vec::new(); | ||
81 | let name = TypeName::Error; | ||
82 | chalk_ir::ApplicationTy { name, parameters }.cast().intern() | ||
83 | } | ||
84 | } | ||
85 | } | ||
86 | fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty<ChalkIr>) -> Self { | ||
87 | match chalk.data().clone() { | ||
88 | chalk_ir::TyData::Apply(apply_ty) => { | ||
89 | // FIXME this is kind of hacky due to the fact that | ||
90 | // TypeName::Placeholder is a Ty::Param on our side | ||
91 | match apply_ty.name { | ||
92 | TypeName::TypeKindId(TypeKindId::StructId(struct_id)) => { | ||
93 | let ctor = from_chalk(db, struct_id); | ||
94 | let parameters = from_chalk(db, apply_ty.parameters); | ||
95 | Ty::Apply(ApplicationTy { ctor, parameters }) | ||
96 | } | ||
97 | TypeName::AssociatedType(type_id) => { | ||
98 | let ctor = TypeCtor::AssociatedType(from_chalk(db, type_id)); | ||
99 | let parameters = from_chalk(db, apply_ty.parameters); | ||
100 | Ty::Apply(ApplicationTy { ctor, parameters }) | ||
101 | } | ||
102 | TypeName::Error => Ty::Unknown, | ||
103 | // FIXME handle TypeKindId::Trait/Type here | ||
104 | TypeName::TypeKindId(_) => unimplemented!(), | ||
105 | TypeName::Placeholder(idx) => { | ||
106 | assert_eq!(idx.ui, UniverseIndex::ROOT); | ||
107 | Ty::Param { idx: idx.idx as u32, name: crate::Name::missing() } | ||
108 | } | ||
109 | } | ||
110 | } | ||
111 | chalk_ir::TyData::Projection(proj) => { | ||
112 | let associated_ty = from_chalk(db, proj.associated_ty_id); | ||
113 | let parameters = from_chalk(db, proj.parameters); | ||
114 | Ty::Projection(ProjectionTy { associated_ty, parameters }) | ||
115 | } | ||
116 | chalk_ir::TyData::ForAll(_) => unimplemented!(), | ||
117 | chalk_ir::TyData::BoundVar(idx) => Ty::Bound(idx as u32), | ||
118 | chalk_ir::TyData::InferenceVar(_iv) => Ty::Unknown, | ||
119 | chalk_ir::TyData::Dyn(where_clauses) => { | ||
120 | assert_eq!(where_clauses.binders.len(), 1); | ||
121 | let predicates = | ||
122 | where_clauses.value.into_iter().map(|c| from_chalk(db, c)).collect(); | ||
123 | Ty::Dyn(predicates) | ||
124 | } | ||
125 | chalk_ir::TyData::Opaque(where_clauses) => { | ||
126 | assert_eq!(where_clauses.binders.len(), 1); | ||
127 | let predicates = | ||
128 | where_clauses.value.into_iter().map(|c| from_chalk(db, c)).collect(); | ||
129 | Ty::Opaque(predicates) | ||
130 | } | ||
131 | } | ||
132 | } | ||
133 | } | ||
134 | |||
135 | impl ToChalk for Substs { | ||
136 | type Chalk = Vec<chalk_ir::Parameter<ChalkIr>>; | ||
137 | |||
138 | fn to_chalk(self, db: &impl HirDatabase) -> Vec<Parameter<ChalkIr>> { | ||
139 | self.iter().map(|ty| ty.clone().to_chalk(db).cast()).collect() | ||
140 | } | ||
141 | |||
142 | fn from_chalk(db: &impl HirDatabase, parameters: Vec<chalk_ir::Parameter<ChalkIr>>) -> Substs { | ||
143 | let tys = parameters | ||
144 | .into_iter() | ||
145 | .map(|p| match p { | ||
146 | chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty), | ||
147 | chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(), | ||
148 | }) | ||
149 | .collect(); | ||
150 | Substs(tys) | ||
151 | } | ||
152 | } | ||
153 | |||
154 | impl ToChalk for TraitRef { | ||
155 | type Chalk = chalk_ir::TraitRef<ChalkIr>; | ||
156 | |||
157 | fn to_chalk(self: TraitRef, db: &impl HirDatabase) -> chalk_ir::TraitRef<ChalkIr> { | ||
158 | let trait_id = self.trait_.to_chalk(db); | ||
159 | let parameters = self.substs.to_chalk(db); | ||
160 | chalk_ir::TraitRef { trait_id, parameters } | ||
161 | } | ||
162 | |||
163 | fn from_chalk(db: &impl HirDatabase, trait_ref: chalk_ir::TraitRef<ChalkIr>) -> Self { | ||
164 | let trait_ = from_chalk(db, trait_ref.trait_id); | ||
165 | let substs = from_chalk(db, trait_ref.parameters); | ||
166 | TraitRef { trait_, substs } | ||
167 | } | ||
168 | } | ||
169 | |||
170 | impl ToChalk for Trait { | ||
171 | type Chalk = chalk_ir::TraitId; | ||
172 | |||
173 | fn to_chalk(self, _db: &impl HirDatabase) -> chalk_ir::TraitId { | ||
174 | chalk_ir::TraitId(id_to_chalk(self.id)) | ||
175 | } | ||
176 | |||
177 | fn from_chalk(_db: &impl HirDatabase, trait_id: chalk_ir::TraitId) -> Trait { | ||
178 | Trait { id: id_from_chalk(trait_id.0) } | ||
179 | } | ||
180 | } | ||
181 | |||
182 | impl ToChalk for TypeCtor { | ||
183 | type Chalk = chalk_ir::StructId; | ||
184 | |||
185 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::StructId { | ||
186 | db.intern_type_ctor(self).into() | ||
187 | } | ||
188 | |||
189 | fn from_chalk(db: &impl HirDatabase, struct_id: chalk_ir::StructId) -> TypeCtor { | ||
190 | db.lookup_intern_type_ctor(struct_id.into()) | ||
191 | } | ||
192 | } | ||
193 | |||
194 | impl ToChalk for Impl { | ||
195 | type Chalk = chalk_ir::ImplId; | ||
196 | |||
197 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ImplId { | ||
198 | db.intern_chalk_impl(self).into() | ||
199 | } | ||
200 | |||
201 | fn from_chalk(db: &impl HirDatabase, impl_id: chalk_ir::ImplId) -> Impl { | ||
202 | db.lookup_intern_chalk_impl(impl_id.into()) | ||
203 | } | ||
204 | } | ||
205 | |||
206 | impl ToChalk for TypeAlias { | ||
207 | type Chalk = chalk_ir::TypeId; | ||
208 | |||
209 | fn to_chalk(self, _db: &impl HirDatabase) -> chalk_ir::TypeId { | ||
210 | chalk_ir::TypeId(id_to_chalk(self.id)) | ||
211 | } | ||
212 | |||
213 | fn from_chalk(_db: &impl HirDatabase, type_alias_id: chalk_ir::TypeId) -> TypeAlias { | ||
214 | TypeAlias { id: id_from_chalk(type_alias_id.0) } | ||
215 | } | ||
216 | } | ||
217 | |||
218 | impl ToChalk for AssocTyValue { | ||
219 | type Chalk = chalk_rust_ir::AssociatedTyValueId; | ||
220 | |||
221 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_rust_ir::AssociatedTyValueId { | ||
222 | db.intern_assoc_ty_value(self).into() | ||
223 | } | ||
224 | |||
225 | fn from_chalk( | ||
226 | db: &impl HirDatabase, | ||
227 | assoc_ty_value_id: chalk_rust_ir::AssociatedTyValueId, | ||
228 | ) -> AssocTyValue { | ||
229 | db.lookup_intern_assoc_ty_value(assoc_ty_value_id.into()) | ||
230 | } | ||
231 | } | ||
232 | |||
233 | impl ToChalk for GenericPredicate { | ||
234 | type Chalk = chalk_ir::QuantifiedWhereClause<ChalkIr>; | ||
235 | |||
236 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::QuantifiedWhereClause<ChalkIr> { | ||
237 | match self { | ||
238 | GenericPredicate::Implemented(trait_ref) => { | ||
239 | make_binders(chalk_ir::WhereClause::Implemented(trait_ref.to_chalk(db)), 0) | ||
240 | } | ||
241 | GenericPredicate::Projection(projection_pred) => make_binders( | ||
242 | chalk_ir::WhereClause::ProjectionEq(chalk_ir::ProjectionEq { | ||
243 | projection: projection_pred.projection_ty.to_chalk(db), | ||
244 | ty: projection_pred.ty.to_chalk(db), | ||
245 | }), | ||
246 | 0, | ||
247 | ), | ||
248 | GenericPredicate::Error => { | ||
249 | let impossible_trait_ref = chalk_ir::TraitRef { | ||
250 | trait_id: UNKNOWN_TRAIT, | ||
251 | parameters: vec![Ty::Unknown.to_chalk(db).cast()], | ||
252 | }; | ||
253 | make_binders(chalk_ir::WhereClause::Implemented(impossible_trait_ref), 0) | ||
254 | } | ||
255 | } | ||
256 | } | ||
257 | |||
258 | fn from_chalk( | ||
259 | db: &impl HirDatabase, | ||
260 | where_clause: chalk_ir::QuantifiedWhereClause<ChalkIr>, | ||
261 | ) -> GenericPredicate { | ||
262 | match where_clause.value { | ||
263 | chalk_ir::WhereClause::Implemented(tr) => { | ||
264 | if tr.trait_id == UNKNOWN_TRAIT { | ||
265 | // FIXME we need an Error enum on the Chalk side to avoid this | ||
266 | return GenericPredicate::Error; | ||
267 | } | ||
268 | GenericPredicate::Implemented(from_chalk(db, tr)) | ||
269 | } | ||
270 | chalk_ir::WhereClause::ProjectionEq(projection_eq) => { | ||
271 | let projection_ty = from_chalk(db, projection_eq.projection); | ||
272 | let ty = from_chalk(db, projection_eq.ty); | ||
273 | GenericPredicate::Projection(super::ProjectionPredicate { projection_ty, ty }) | ||
274 | } | ||
275 | } | ||
276 | } | ||
277 | } | ||
278 | |||
279 | impl ToChalk for ProjectionTy { | ||
280 | type Chalk = chalk_ir::ProjectionTy<ChalkIr>; | ||
281 | |||
282 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ProjectionTy<ChalkIr> { | ||
283 | chalk_ir::ProjectionTy { | ||
284 | associated_ty_id: self.associated_ty.to_chalk(db), | ||
285 | parameters: self.parameters.to_chalk(db), | ||
286 | } | ||
287 | } | ||
288 | |||
289 | fn from_chalk( | ||
290 | db: &impl HirDatabase, | ||
291 | projection_ty: chalk_ir::ProjectionTy<ChalkIr>, | ||
292 | ) -> ProjectionTy { | ||
293 | ProjectionTy { | ||
294 | associated_ty: from_chalk(db, projection_ty.associated_ty_id), | ||
295 | parameters: from_chalk(db, projection_ty.parameters), | ||
296 | } | ||
297 | } | ||
298 | } | ||
299 | |||
300 | impl ToChalk for super::ProjectionPredicate { | ||
301 | type Chalk = chalk_ir::Normalize<ChalkIr>; | ||
302 | |||
303 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Normalize<ChalkIr> { | ||
304 | chalk_ir::Normalize { | ||
305 | projection: self.projection_ty.to_chalk(db), | ||
306 | ty: self.ty.to_chalk(db), | ||
307 | } | ||
308 | } | ||
309 | |||
310 | fn from_chalk(_db: &impl HirDatabase, _normalize: chalk_ir::Normalize<ChalkIr>) -> Self { | ||
311 | unimplemented!() | ||
312 | } | ||
313 | } | ||
314 | |||
315 | impl ToChalk for Obligation { | ||
316 | type Chalk = chalk_ir::DomainGoal<ChalkIr>; | ||
317 | |||
318 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::DomainGoal<ChalkIr> { | ||
319 | match self { | ||
320 | Obligation::Trait(tr) => tr.to_chalk(db).cast(), | ||
321 | Obligation::Projection(pr) => pr.to_chalk(db).cast(), | ||
322 | } | ||
323 | } | ||
324 | |||
325 | fn from_chalk(_db: &impl HirDatabase, _goal: chalk_ir::DomainGoal<ChalkIr>) -> Self { | ||
326 | unimplemented!() | ||
327 | } | ||
328 | } | ||
329 | |||
330 | impl<T> ToChalk for Canonical<T> | ||
331 | where | ||
332 | T: ToChalk, | ||
333 | { | ||
334 | type Chalk = chalk_ir::Canonical<T::Chalk>; | ||
335 | |||
336 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Canonical<T::Chalk> { | ||
337 | let parameter = chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex::ROOT); | ||
338 | let value = self.value.to_chalk(db); | ||
339 | let canonical = chalk_ir::Canonical { value, binders: vec![parameter; self.num_vars] }; | ||
340 | canonical | ||
341 | } | ||
342 | |||
343 | fn from_chalk(db: &impl HirDatabase, canonical: chalk_ir::Canonical<T::Chalk>) -> Canonical<T> { | ||
344 | Canonical { num_vars: canonical.binders.len(), value: from_chalk(db, canonical.value) } | ||
345 | } | ||
346 | } | ||
347 | |||
348 | impl ToChalk for Arc<super::TraitEnvironment> { | ||
349 | type Chalk = chalk_ir::Environment<ChalkIr>; | ||
350 | |||
351 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Environment<ChalkIr> { | ||
352 | let mut clauses = Vec::new(); | ||
353 | for pred in &self.predicates { | ||
354 | if pred.is_error() { | ||
355 | // for env, we just ignore errors | ||
356 | continue; | ||
357 | } | ||
358 | let program_clause: chalk_ir::ProgramClause<ChalkIr> = pred.clone().to_chalk(db).cast(); | ||
359 | clauses.push(program_clause.into_from_env_clause()); | ||
360 | } | ||
361 | chalk_ir::Environment::new().add_clauses(clauses) | ||
362 | } | ||
363 | |||
364 | fn from_chalk( | ||
365 | _db: &impl HirDatabase, | ||
366 | _env: chalk_ir::Environment<ChalkIr>, | ||
367 | ) -> Arc<super::TraitEnvironment> { | ||
368 | unimplemented!() | ||
369 | } | ||
370 | } | ||
371 | |||
372 | impl<T: ToChalk> ToChalk for super::InEnvironment<T> | ||
373 | where | ||
374 | T::Chalk: chalk_ir::family::HasTypeFamily<TypeFamily = ChalkIr>, | ||
375 | { | ||
376 | type Chalk = chalk_ir::InEnvironment<T::Chalk>; | ||
377 | |||
378 | fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::InEnvironment<T::Chalk> { | ||
379 | chalk_ir::InEnvironment { | ||
380 | environment: self.environment.to_chalk(db), | ||
381 | goal: self.value.to_chalk(db), | ||
382 | } | ||
383 | } | ||
384 | |||
385 | fn from_chalk( | ||
386 | db: &impl HirDatabase, | ||
387 | in_env: chalk_ir::InEnvironment<T::Chalk>, | ||
388 | ) -> super::InEnvironment<T> { | ||
389 | super::InEnvironment { | ||
390 | environment: from_chalk(db, in_env.environment), | ||
391 | value: from_chalk(db, in_env.goal), | ||
392 | } | ||
393 | } | ||
394 | } | ||
395 | |||
396 | fn make_binders<T>(value: T, num_vars: usize) -> chalk_ir::Binders<T> { | ||
397 | chalk_ir::Binders { | ||
398 | value, | ||
399 | binders: std::iter::repeat(chalk_ir::ParameterKind::Ty(())).take(num_vars).collect(), | ||
400 | } | ||
401 | } | ||
402 | |||
403 | fn convert_where_clauses( | ||
404 | db: &impl HirDatabase, | ||
405 | def: GenericDef, | ||
406 | substs: &Substs, | ||
407 | ) -> Vec<chalk_ir::QuantifiedWhereClause<ChalkIr>> { | ||
408 | let generic_predicates = db.generic_predicates(def); | ||
409 | let mut result = Vec::with_capacity(generic_predicates.len()); | ||
410 | for pred in generic_predicates.iter() { | ||
411 | if pred.is_error() { | ||
412 | // HACK: Return just the single predicate (which is always false | ||
413 | // anyway), otherwise Chalk can easily get into slow situations | ||
414 | return vec![pred.clone().subst(substs).to_chalk(db)]; | ||
415 | } | ||
416 | result.push(pred.clone().subst(substs).to_chalk(db)); | ||
417 | } | ||
418 | result | ||
419 | } | ||
420 | |||
421 | impl<'a, DB> chalk_solve::RustIrDatabase<ChalkIr> for ChalkContext<'a, DB> | ||
422 | where | ||
423 | DB: HirDatabase, | ||
424 | { | ||
425 | fn associated_ty_data(&self, id: TypeId) -> Arc<AssociatedTyDatum<ChalkIr>> { | ||
426 | self.db.associated_ty_data(id) | ||
427 | } | ||
428 | fn trait_datum(&self, trait_id: chalk_ir::TraitId) -> Arc<TraitDatum<ChalkIr>> { | ||
429 | self.db.trait_datum(self.krate, trait_id) | ||
430 | } | ||
431 | fn struct_datum(&self, struct_id: chalk_ir::StructId) -> Arc<StructDatum<ChalkIr>> { | ||
432 | self.db.struct_datum(self.krate, struct_id) | ||
433 | } | ||
434 | fn impl_datum(&self, impl_id: ImplId) -> Arc<ImplDatum<ChalkIr>> { | ||
435 | self.db.impl_datum(self.krate, impl_id) | ||
436 | } | ||
437 | fn impls_for_trait( | ||
438 | &self, | ||
439 | trait_id: chalk_ir::TraitId, | ||
440 | parameters: &[Parameter<ChalkIr>], | ||
441 | ) -> Vec<ImplId> { | ||
442 | debug!("impls_for_trait {:?}", trait_id); | ||
443 | if trait_id == UNKNOWN_TRAIT { | ||
444 | return Vec::new(); | ||
445 | } | ||
446 | let trait_: Trait = from_chalk(self.db, trait_id); | ||
447 | let mut result: Vec<_> = self | ||
448 | .db | ||
449 | .impls_for_trait(self.krate, trait_) | ||
450 | .iter() | ||
451 | .copied() | ||
452 | .map(Impl::ImplBlock) | ||
453 | .map(|impl_| impl_.to_chalk(self.db)) | ||
454 | .collect(); | ||
455 | |||
456 | let ty: Ty = from_chalk(self.db, parameters[0].assert_ty_ref().clone()); | ||
457 | if let Ty::Apply(ApplicationTy { ctor: TypeCtor::Closure { def, expr }, .. }) = ty { | ||
458 | for &fn_trait in | ||
459 | [super::FnTrait::FnOnce, super::FnTrait::FnMut, super::FnTrait::Fn].iter() | ||
460 | { | ||
461 | if let Some(actual_trait) = get_fn_trait(self.db, self.krate, fn_trait) { | ||
462 | if trait_ == actual_trait { | ||
463 | let impl_ = super::ClosureFnTraitImplData { def, expr, fn_trait }; | ||
464 | result.push(Impl::ClosureFnTraitImpl(impl_).to_chalk(self.db)); | ||
465 | } | ||
466 | } | ||
467 | } | ||
468 | } | ||
469 | |||
470 | debug!("impls_for_trait returned {} impls", result.len()); | ||
471 | result | ||
472 | } | ||
473 | fn impl_provided_for( | ||
474 | &self, | ||
475 | auto_trait_id: chalk_ir::TraitId, | ||
476 | struct_id: chalk_ir::StructId, | ||
477 | ) -> bool { | ||
478 | debug!("impl_provided_for {:?}, {:?}", auto_trait_id, struct_id); | ||
479 | false // FIXME | ||
480 | } | ||
481 | fn type_name(&self, _id: TypeKindId) -> Identifier { | ||
482 | unimplemented!() | ||
483 | } | ||
484 | fn associated_ty_value( | ||
485 | &self, | ||
486 | id: chalk_rust_ir::AssociatedTyValueId, | ||
487 | ) -> Arc<AssociatedTyValue<ChalkIr>> { | ||
488 | self.db.associated_ty_value(self.krate, id) | ||
489 | } | ||
490 | fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<ChalkIr>> { | ||
491 | vec![] | ||
492 | } | ||
493 | fn local_impls_to_coherence_check( | ||
494 | &self, | ||
495 | _trait_id: chalk_ir::TraitId, | ||
496 | ) -> Vec<chalk_ir::ImplId> { | ||
497 | // We don't do coherence checking (yet) | ||
498 | unimplemented!() | ||
499 | } | ||
500 | } | ||
501 | |||
502 | pub(crate) fn associated_ty_data_query( | ||
503 | db: &impl HirDatabase, | ||
504 | id: TypeId, | ||
505 | ) -> Arc<AssociatedTyDatum<ChalkIr>> { | ||
506 | debug!("associated_ty_data {:?}", id); | ||
507 | let type_alias: TypeAlias = from_chalk(db, id); | ||
508 | let trait_ = match type_alias.container(db) { | ||
509 | Some(crate::Container::Trait(t)) => t, | ||
510 | _ => panic!("associated type not in trait"), | ||
511 | }; | ||
512 | let generic_params = db.generic_params(type_alias.id.into()); | ||
513 | let bound_data = chalk_rust_ir::AssociatedTyDatumBound { | ||
514 | // FIXME add bounds and where clauses | ||
515 | bounds: vec![], | ||
516 | where_clauses: vec![], | ||
517 | }; | ||
518 | let datum = AssociatedTyDatum { | ||
519 | trait_id: trait_.to_chalk(db), | ||
520 | id, | ||
521 | name: lalrpop_intern::intern(&type_alias.name(db).to_string()), | ||
522 | binders: make_binders(bound_data, generic_params.count_params_including_parent()), | ||
523 | }; | ||
524 | Arc::new(datum) | ||
525 | } | ||
526 | |||
527 | pub(crate) fn trait_datum_query( | ||
528 | db: &impl HirDatabase, | ||
529 | krate: Crate, | ||
530 | trait_id: chalk_ir::TraitId, | ||
531 | ) -> Arc<TraitDatum<ChalkIr>> { | ||
532 | debug!("trait_datum {:?}", trait_id); | ||
533 | if trait_id == UNKNOWN_TRAIT { | ||
534 | let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses: Vec::new() }; | ||
535 | |||
536 | let flags = chalk_rust_ir::TraitFlags { | ||
537 | auto: false, | ||
538 | marker: false, | ||
539 | upstream: true, | ||
540 | fundamental: false, | ||
541 | non_enumerable: true, | ||
542 | coinductive: false, | ||
543 | }; | ||
544 | return Arc::new(TraitDatum { | ||
545 | id: trait_id, | ||
546 | binders: make_binders(trait_datum_bound, 1), | ||
547 | flags, | ||
548 | associated_ty_ids: vec![], | ||
549 | }); | ||
550 | } | ||
551 | let trait_: Trait = from_chalk(db, trait_id); | ||
552 | debug!("trait {:?} = {:?}", trait_id, trait_.name(db)); | ||
553 | let generic_params = db.generic_params(trait_.id.into()); | ||
554 | let bound_vars = Substs::bound_vars(&generic_params); | ||
555 | let flags = chalk_rust_ir::TraitFlags { | ||
556 | auto: trait_.is_auto(db), | ||
557 | upstream: trait_.module(db).krate() != krate, | ||
558 | non_enumerable: true, | ||
559 | coinductive: false, // only relevant for Chalk testing | ||
560 | // FIXME set these flags correctly | ||
561 | marker: false, | ||
562 | fundamental: false, | ||
563 | }; | ||
564 | let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars); | ||
565 | let associated_ty_ids = trait_ | ||
566 | .items(db) | ||
567 | .into_iter() | ||
568 | .filter_map(|trait_item| match trait_item { | ||
569 | crate::AssocItem::TypeAlias(type_alias) => Some(type_alias), | ||
570 | _ => None, | ||
571 | }) | ||
572 | .map(|type_alias| type_alias.to_chalk(db)) | ||
573 | .collect(); | ||
574 | let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses }; | ||
575 | let trait_datum = TraitDatum { | ||
576 | id: trait_id, | ||
577 | binders: make_binders(trait_datum_bound, bound_vars.len()), | ||
578 | flags, | ||
579 | associated_ty_ids, | ||
580 | }; | ||
581 | Arc::new(trait_datum) | ||
582 | } | ||
583 | |||
584 | pub(crate) fn struct_datum_query( | ||
585 | db: &impl HirDatabase, | ||
586 | krate: Crate, | ||
587 | struct_id: chalk_ir::StructId, | ||
588 | ) -> Arc<StructDatum<ChalkIr>> { | ||
589 | debug!("struct_datum {:?}", struct_id); | ||
590 | let type_ctor: TypeCtor = from_chalk(db, struct_id); | ||
591 | debug!("struct {:?} = {:?}", struct_id, type_ctor); | ||
592 | let num_params = type_ctor.num_ty_params(db); | ||
593 | let upstream = type_ctor.krate(db) != Some(krate); | ||
594 | let where_clauses = type_ctor | ||
595 | .as_generic_def() | ||
596 | .map(|generic_def| { | ||
597 | let generic_params = db.generic_params(generic_def.into()); | ||
598 | let bound_vars = Substs::bound_vars(&generic_params); | ||
599 | convert_where_clauses(db, generic_def, &bound_vars) | ||
600 | }) | ||
601 | .unwrap_or_else(Vec::new); | ||
602 | let flags = chalk_rust_ir::StructFlags { | ||
603 | upstream, | ||
604 | // FIXME set fundamental flag correctly | ||
605 | fundamental: false, | ||
606 | }; | ||
607 | let struct_datum_bound = chalk_rust_ir::StructDatumBound { | ||
608 | fields: Vec::new(), // FIXME add fields (only relevant for auto traits) | ||
609 | where_clauses, | ||
610 | }; | ||
611 | let struct_datum = | ||
612 | StructDatum { id: struct_id, binders: make_binders(struct_datum_bound, num_params), flags }; | ||
613 | Arc::new(struct_datum) | ||
614 | } | ||
615 | |||
616 | pub(crate) fn impl_datum_query( | ||
617 | db: &impl HirDatabase, | ||
618 | krate: Crate, | ||
619 | impl_id: ImplId, | ||
620 | ) -> Arc<ImplDatum<ChalkIr>> { | ||
621 | let _p = ra_prof::profile("impl_datum"); | ||
622 | debug!("impl_datum {:?}", impl_id); | ||
623 | let impl_: Impl = from_chalk(db, impl_id); | ||
624 | match impl_ { | ||
625 | Impl::ImplBlock(impl_block) => impl_block_datum(db, krate, impl_id, impl_block), | ||
626 | Impl::ClosureFnTraitImpl(data) => closure_fn_trait_impl_datum(db, krate, data), | ||
627 | } | ||
628 | .unwrap_or_else(invalid_impl_datum) | ||
629 | } | ||
630 | |||
631 | fn impl_block_datum( | ||
632 | db: &impl HirDatabase, | ||
633 | krate: Crate, | ||
634 | impl_id: ImplId, | ||
635 | impl_block: ImplBlock, | ||
636 | ) -> Option<Arc<ImplDatum<ChalkIr>>> { | ||
637 | let generic_params = db.generic_params(impl_block.id.into()); | ||
638 | let bound_vars = Substs::bound_vars(&generic_params); | ||
639 | let trait_ref = impl_block.target_trait_ref(db)?.subst(&bound_vars); | ||
640 | let trait_ = trait_ref.trait_; | ||
641 | let impl_type = if impl_block.krate(db) == krate { | ||
642 | chalk_rust_ir::ImplType::Local | ||
643 | } else { | ||
644 | chalk_rust_ir::ImplType::External | ||
645 | }; | ||
646 | let where_clauses = convert_where_clauses(db, impl_block.into(), &bound_vars); | ||
647 | let negative = impl_block.is_negative(db); | ||
648 | debug!( | ||
649 | "impl {:?}: {}{} where {:?}", | ||
650 | impl_id, | ||
651 | if negative { "!" } else { "" }, | ||
652 | trait_ref.display(db), | ||
653 | where_clauses | ||
654 | ); | ||
655 | let trait_ref = trait_ref.to_chalk(db); | ||
656 | |||
657 | let polarity = if negative { | ||
658 | chalk_rust_ir::Polarity::Negative | ||
659 | } else { | ||
660 | chalk_rust_ir::Polarity::Positive | ||
661 | }; | ||
662 | |||
663 | let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses }; | ||
664 | let associated_ty_value_ids = impl_block | ||
665 | .items(db) | ||
666 | .into_iter() | ||
667 | .filter_map(|item| match item { | ||
668 | crate::AssocItem::TypeAlias(type_alias) => Some(type_alias), | ||
669 | _ => None, | ||
670 | }) | ||
671 | .filter(|type_alias| { | ||
672 | // don't include associated types that don't exist in the trait | ||
673 | trait_.associated_type_by_name(db, &type_alias.name(db)).is_some() | ||
674 | }) | ||
675 | .map(|type_alias| AssocTyValue::TypeAlias(type_alias).to_chalk(db)) | ||
676 | .collect(); | ||
677 | debug!("impl_datum: {:?}", impl_datum_bound); | ||
678 | let impl_datum = ImplDatum { | ||
679 | binders: make_binders(impl_datum_bound, bound_vars.len()), | ||
680 | impl_type, | ||
681 | polarity, | ||
682 | associated_ty_value_ids, | ||
683 | }; | ||
684 | Some(Arc::new(impl_datum)) | ||
685 | } | ||
686 | |||
687 | fn invalid_impl_datum() -> Arc<ImplDatum<ChalkIr>> { | ||
688 | let trait_ref = chalk_ir::TraitRef { | ||
689 | trait_id: UNKNOWN_TRAIT, | ||
690 | parameters: vec![chalk_ir::TyData::BoundVar(0).cast().intern().cast()], | ||
691 | }; | ||
692 | let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses: Vec::new() }; | ||
693 | let impl_datum = ImplDatum { | ||
694 | binders: make_binders(impl_datum_bound, 1), | ||
695 | impl_type: chalk_rust_ir::ImplType::External, | ||
696 | polarity: chalk_rust_ir::Polarity::Positive, | ||
697 | associated_ty_value_ids: Vec::new(), | ||
698 | }; | ||
699 | Arc::new(impl_datum) | ||
700 | } | ||
701 | |||
702 | fn closure_fn_trait_impl_datum( | ||
703 | db: &impl HirDatabase, | ||
704 | krate: Crate, | ||
705 | data: super::ClosureFnTraitImplData, | ||
706 | ) -> Option<Arc<ImplDatum<ChalkIr>>> { | ||
707 | // for some closure |X, Y| -> Z: | ||
708 | // impl<T, U, V> Fn<(T, U)> for closure<fn(T, U) -> V> { Output = V } | ||
709 | |||
710 | let trait_ = get_fn_trait(db, krate, data.fn_trait)?; // get corresponding fn trait | ||
711 | |||
712 | // validate FnOnce trait, since we need it in the assoc ty value definition | ||
713 | // and don't want to return a valid value only to find out later that FnOnce | ||
714 | // is broken | ||
715 | let fn_once_trait = get_fn_trait(db, krate, super::FnTrait::FnOnce)?; | ||
716 | fn_once_trait.associated_type_by_name(db, &name::OUTPUT_TYPE)?; | ||
717 | |||
718 | let num_args: u16 = match &db.body(data.def.into())[data.expr] { | ||
719 | crate::expr::Expr::Lambda { args, .. } => args.len() as u16, | ||
720 | _ => { | ||
721 | log::warn!("closure for closure type {:?} not found", data); | ||
722 | 0 | ||
723 | } | ||
724 | }; | ||
725 | |||
726 | let arg_ty = Ty::apply( | ||
727 | TypeCtor::Tuple { cardinality: num_args }, | ||
728 | Substs::builder(num_args as usize).fill_with_bound_vars(0).build(), | ||
729 | ); | ||
730 | let sig_ty = Ty::apply( | ||
731 | TypeCtor::FnPtr { num_args }, | ||
732 | Substs::builder(num_args as usize + 1).fill_with_bound_vars(0).build(), | ||
733 | ); | ||
734 | |||
735 | let self_ty = Ty::apply_one(TypeCtor::Closure { def: data.def, expr: data.expr }, sig_ty); | ||
736 | |||
737 | let trait_ref = TraitRef { | ||
738 | trait_, | ||
739 | substs: Substs::build_for_def(db, trait_).push(self_ty).push(arg_ty).build(), | ||
740 | }; | ||
741 | |||
742 | let output_ty_id = AssocTyValue::ClosureFnTraitImplOutput(data.clone()).to_chalk(db); | ||
743 | |||
744 | let impl_type = chalk_rust_ir::ImplType::External; | ||
745 | |||
746 | let impl_datum_bound = chalk_rust_ir::ImplDatumBound { | ||
747 | trait_ref: trait_ref.to_chalk(db), | ||
748 | where_clauses: Vec::new(), | ||
749 | }; | ||
750 | let impl_datum = ImplDatum { | ||
751 | binders: make_binders(impl_datum_bound, num_args as usize + 1), | ||
752 | impl_type, | ||
753 | polarity: chalk_rust_ir::Polarity::Positive, | ||
754 | associated_ty_value_ids: vec![output_ty_id], | ||
755 | }; | ||
756 | Some(Arc::new(impl_datum)) | ||
757 | } | ||
758 | |||
759 | pub(crate) fn associated_ty_value_query( | ||
760 | db: &impl HirDatabase, | ||
761 | krate: Crate, | ||
762 | id: chalk_rust_ir::AssociatedTyValueId, | ||
763 | ) -> Arc<chalk_rust_ir::AssociatedTyValue<ChalkIr>> { | ||
764 | let data: AssocTyValue = from_chalk(db, id); | ||
765 | match data { | ||
766 | AssocTyValue::TypeAlias(type_alias) => { | ||
767 | type_alias_associated_ty_value(db, krate, type_alias) | ||
768 | } | ||
769 | AssocTyValue::ClosureFnTraitImplOutput(data) => { | ||
770 | closure_fn_trait_output_assoc_ty_value(db, krate, data) | ||
771 | } | ||
772 | } | ||
773 | } | ||
774 | |||
775 | fn type_alias_associated_ty_value( | ||
776 | db: &impl HirDatabase, | ||
777 | _krate: Crate, | ||
778 | type_alias: TypeAlias, | ||
779 | ) -> Arc<AssociatedTyValue<ChalkIr>> { | ||
780 | let impl_block = type_alias.impl_block(db).expect("assoc ty value should be in impl"); | ||
781 | let impl_id = Impl::ImplBlock(impl_block).to_chalk(db); | ||
782 | let trait_ = impl_block | ||
783 | .target_trait_ref(db) | ||
784 | .expect("assoc ty value should not exist") // we don't return any assoc ty values if the impl'd trait can't be resolved | ||
785 | .trait_; | ||
786 | let assoc_ty = trait_ | ||
787 | .associated_type_by_name(db, &type_alias.name(db)) | ||
788 | .expect("assoc ty value should not exist"); // validated when building the impl data as well | ||
789 | let generic_params = db.generic_params(impl_block.id.into()); | ||
790 | let bound_vars = Substs::bound_vars(&generic_params); | ||
791 | let ty = db.type_for_def(type_alias.into(), crate::ty::Namespace::Types).subst(&bound_vars); | ||
792 | let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: ty.to_chalk(db) }; | ||
793 | let value = chalk_rust_ir::AssociatedTyValue { | ||
794 | impl_id, | ||
795 | associated_ty_id: assoc_ty.to_chalk(db), | ||
796 | value: make_binders(value_bound, bound_vars.len()), | ||
797 | }; | ||
798 | Arc::new(value) | ||
799 | } | ||
800 | |||
801 | fn closure_fn_trait_output_assoc_ty_value( | ||
802 | db: &impl HirDatabase, | ||
803 | krate: Crate, | ||
804 | data: super::ClosureFnTraitImplData, | ||
805 | ) -> Arc<AssociatedTyValue<ChalkIr>> { | ||
806 | let impl_id = Impl::ClosureFnTraitImpl(data.clone()).to_chalk(db); | ||
807 | |||
808 | let num_args: u16 = match &db.body(data.def.into())[data.expr] { | ||
809 | crate::expr::Expr::Lambda { args, .. } => args.len() as u16, | ||
810 | _ => { | ||
811 | log::warn!("closure for closure type {:?} not found", data); | ||
812 | 0 | ||
813 | } | ||
814 | }; | ||
815 | |||
816 | let output_ty = Ty::Bound(num_args.into()); | ||
817 | |||
818 | let fn_once_trait = | ||
819 | get_fn_trait(db, krate, super::FnTrait::FnOnce).expect("assoc ty value should not exist"); | ||
820 | |||
821 | let output_ty_id = fn_once_trait | ||
822 | .associated_type_by_name(db, &name::OUTPUT_TYPE) | ||
823 | .expect("assoc ty value should not exist"); | ||
824 | |||
825 | let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: output_ty.to_chalk(db) }; | ||
826 | |||
827 | let value = chalk_rust_ir::AssociatedTyValue { | ||
828 | associated_ty_id: output_ty_id.to_chalk(db), | ||
829 | impl_id, | ||
830 | value: make_binders(value_bound, num_args as usize + 1), | ||
831 | }; | ||
832 | Arc::new(value) | ||
833 | } | ||
834 | |||
835 | fn get_fn_trait(db: &impl HirDatabase, krate: Crate, fn_trait: super::FnTrait) -> Option<Trait> { | ||
836 | let target = db.lang_item(krate.crate_id, fn_trait.lang_item_name().into())?; | ||
837 | match target { | ||
838 | LangItemTarget::TraitId(t) => Some(t.into()), | ||
839 | _ => None, | ||
840 | } | ||
841 | } | ||
842 | |||
843 | fn id_from_chalk<T: InternKey>(chalk_id: chalk_ir::RawId) -> T { | ||
844 | T::from_intern_id(InternId::from(chalk_id.index)) | ||
845 | } | ||
846 | fn id_to_chalk<T: InternKey>(salsa_id: T) -> chalk_ir::RawId { | ||
847 | chalk_ir::RawId { index: salsa_id.as_intern_id().as_u32() } | ||
848 | } | ||
849 | |||
850 | impl From<chalk_ir::StructId> for crate::ty::TypeCtorId { | ||
851 | fn from(struct_id: chalk_ir::StructId) -> Self { | ||
852 | id_from_chalk(struct_id.0) | ||
853 | } | ||
854 | } | ||
855 | |||
856 | impl From<crate::ty::TypeCtorId> for chalk_ir::StructId { | ||
857 | fn from(type_ctor_id: crate::ty::TypeCtorId) -> Self { | ||
858 | chalk_ir::StructId(id_to_chalk(type_ctor_id)) | ||
859 | } | ||
860 | } | ||
861 | |||
862 | impl From<chalk_ir::ImplId> for crate::ty::traits::GlobalImplId { | ||
863 | fn from(impl_id: chalk_ir::ImplId) -> Self { | ||
864 | id_from_chalk(impl_id.0) | ||
865 | } | ||
866 | } | ||
867 | |||
868 | impl From<crate::ty::traits::GlobalImplId> for chalk_ir::ImplId { | ||
869 | fn from(impl_id: crate::ty::traits::GlobalImplId) -> Self { | ||
870 | chalk_ir::ImplId(id_to_chalk(impl_id)) | ||
871 | } | ||
872 | } | ||
873 | |||
874 | impl From<chalk_rust_ir::AssociatedTyValueId> for crate::ty::traits::AssocTyValueId { | ||
875 | fn from(id: chalk_rust_ir::AssociatedTyValueId) -> Self { | ||
876 | id_from_chalk(id.0) | ||
877 | } | ||
878 | } | ||
879 | |||
880 | impl From<crate::ty::traits::AssocTyValueId> for chalk_rust_ir::AssociatedTyValueId { | ||
881 | fn from(assoc_ty_value_id: crate::ty::traits::AssocTyValueId) -> Self { | ||
882 | chalk_rust_ir::AssociatedTyValueId(id_to_chalk(assoc_ty_value_id)) | ||
883 | } | ||
884 | } | ||
diff --git a/crates/ra_hir/src/util.rs b/crates/ra_hir/src/util.rs deleted file mode 100644 index 0095ee45d..000000000 --- a/crates/ra_hir/src/util.rs +++ /dev/null | |||
@@ -1,12 +0,0 @@ | |||
1 | //! Internal utility functions. | ||
2 | |||
3 | use std::sync::Arc; | ||
4 | |||
5 | /// Helper for mutating `Arc<[T]>` (i.e. `Arc::make_mut` for Arc slices). | ||
6 | /// The underlying values are cloned if there are other strong references. | ||
7 | pub(crate) fn make_mut_slice<T: Clone>(a: &mut Arc<[T]>) -> &mut [T] { | ||
8 | if Arc::get_mut(a).is_none() { | ||
9 | *a = a.iter().cloned().collect(); | ||
10 | } | ||
11 | Arc::get_mut(a).unwrap() | ||
12 | } | ||