Merge pull request #19236 from BenjaminBrienen/rust-2024-and-1.85

Rust 2024 and 1.85
This commit is contained in:
Chayim Refael Friedman 2025-03-15 20:48:46 +00:00 committed by GitHub
commit 78aee2a424
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
582 changed files with 2282 additions and 2521 deletions

View file

@ -5,7 +5,7 @@ resolver = "2"
[workspace.package] [workspace.package]
rust-version = "1.85" rust-version = "1.85"
edition = "2021" edition = "2024"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
authors = ["rust-analyzer team"] authors = ["rust-analyzer team"]
repository = "https://github.com/rust-lang/rust-analyzer" repository = "https://github.com/rust-lang/rust-analyzer"

View file

@ -82,9 +82,5 @@ impl FileChange {
} }
fn durability(source_root: &SourceRoot) -> Durability { fn durability(source_root: &SourceRoot) -> Durability {
if source_root.is_library { if source_root.is_library { Durability::HIGH } else { Durability::LOW }
Durability::HIGH
} else {
Durability::LOW
}
} }

View file

@ -10,15 +10,15 @@ use std::hash::BuildHasherDefault;
use std::{fmt, mem, ops}; use std::{fmt, mem, ops};
use cfg::{CfgOptions, HashableCfgOptions}; use cfg::{CfgOptions, HashableCfgOptions};
use dashmap::mapref::entry::Entry;
use dashmap::DashMap; use dashmap::DashMap;
use dashmap::mapref::entry::Entry;
use intern::Symbol; use intern::Symbol;
use la_arena::{Arena, Idx, RawIdx}; use la_arena::{Arena, Idx, RawIdx};
use rustc_hash::{FxHashMap, FxHashSet, FxHasher}; use rustc_hash::{FxHashMap, FxHashSet, FxHasher};
use salsa::{Durability, Setter}; use salsa::{Durability, Setter};
use span::{Edition, EditionedFileId}; use span::{Edition, EditionedFileId};
use triomphe::Arc; use triomphe::Arc;
use vfs::{file_set::FileSet, AbsPathBuf, AnchoredPath, FileId, VfsPath}; use vfs::{AbsPathBuf, AnchoredPath, FileId, VfsPath, file_set::FileSet};
use crate::{CrateWorkspaceData, RootQueryDb}; use crate::{CrateWorkspaceData, RootQueryDb};
@ -110,11 +110,7 @@ impl CrateName {
/// Dashes are not allowed in the crate names, /// Dashes are not allowed in the crate names,
/// hence the input string is returned as `Err` for those cases. /// hence the input string is returned as `Err` for those cases.
pub fn new(name: &str) -> Result<CrateName, &str> { pub fn new(name: &str) -> Result<CrateName, &str> {
if name.contains('-') { if name.contains('-') { Err(name) } else { Ok(Self(Symbol::intern(name))) }
Err(name)
} else {
Ok(Self(Symbol::intern(name)))
}
} }
/// Creates a crate name, unconditionally replacing the dashes with underscores. /// Creates a crate name, unconditionally replacing the dashes with underscores.
@ -922,15 +918,21 @@ mod tests {
None, None,
empty_ws_data(), empty_ws_data(),
); );
assert!(graph assert!(
.add_dep(crate1, DependencyBuilder::new(CrateName::new("crate2").unwrap(), crate2,)) graph
.is_ok()); .add_dep(crate1, DependencyBuilder::new(CrateName::new("crate2").unwrap(), crate2,))
assert!(graph .is_ok()
.add_dep(crate2, DependencyBuilder::new(CrateName::new("crate3").unwrap(), crate3,)) );
.is_ok()); assert!(
assert!(graph graph
.add_dep(crate3, DependencyBuilder::new(CrateName::new("crate1").unwrap(), crate1,)) .add_dep(crate2, DependencyBuilder::new(CrateName::new("crate3").unwrap(), crate3,))
.is_err()); .is_ok()
);
assert!(
graph
.add_dep(crate3, DependencyBuilder::new(CrateName::new("crate1").unwrap(), crate1,))
.is_err()
);
} }
#[test] #[test]
@ -962,12 +964,16 @@ mod tests {
None, None,
empty_ws_data(), empty_ws_data(),
); );
assert!(graph assert!(
.add_dep(crate1, DependencyBuilder::new(CrateName::new("crate2").unwrap(), crate2,)) graph
.is_ok()); .add_dep(crate1, DependencyBuilder::new(CrateName::new("crate2").unwrap(), crate2,))
assert!(graph .is_ok()
.add_dep(crate2, DependencyBuilder::new(CrateName::new("crate2").unwrap(), crate2,)) );
.is_err()); assert!(
graph
.add_dep(crate2, DependencyBuilder::new(CrateName::new("crate2").unwrap(), crate2,))
.is_err()
);
} }
#[test] #[test]
@ -1012,12 +1018,16 @@ mod tests {
None, None,
empty_ws_data(), empty_ws_data(),
); );
assert!(graph assert!(
.add_dep(crate1, DependencyBuilder::new(CrateName::new("crate2").unwrap(), crate2,)) graph
.is_ok()); .add_dep(crate1, DependencyBuilder::new(CrateName::new("crate2").unwrap(), crate2,))
assert!(graph .is_ok()
.add_dep(crate2, DependencyBuilder::new(CrateName::new("crate3").unwrap(), crate3,)) );
.is_ok()); assert!(
graph
.add_dep(crate2, DependencyBuilder::new(CrateName::new("crate3").unwrap(), crate3,))
.is_ok()
);
} }
#[test] #[test]
@ -1049,15 +1059,17 @@ mod tests {
None, None,
empty_ws_data(), empty_ws_data(),
); );
assert!(graph assert!(
.add_dep( graph
crate1, .add_dep(
DependencyBuilder::new( crate1,
CrateName::normalize_dashes("crate-name-with-dashes"), DependencyBuilder::new(
crate2, CrateName::normalize_dashes("crate-name-with-dashes"),
crate2,
)
) )
) .is_ok()
.is_ok()); );
assert_eq!( assert_eq!(
graph.arena[crate1].basic.dependencies, graph.arena[crate1].basic.dependencies,
vec![ vec![

View file

@ -14,15 +14,15 @@ pub use crate::{
SourceRoot, SourceRootId, TargetLayoutLoadResult, UniqueCrateData, SourceRoot, SourceRootId, TargetLayoutLoadResult, UniqueCrateData,
}, },
}; };
use dashmap::{mapref::entry::Entry, DashMap}; use dashmap::{DashMap, mapref::entry::Entry};
pub use query_group::{self}; pub use query_group::{self};
use rustc_hash::{FxHashSet, FxHasher}; use rustc_hash::{FxHashSet, FxHasher};
pub use salsa::{self}; pub use salsa::{self};
use salsa::{Durability, Setter}; use salsa::{Durability, Setter};
pub use semver::{BuildMetadata, Prerelease, Version, VersionReq}; pub use semver::{BuildMetadata, Prerelease, Version, VersionReq};
use syntax::{ast, Parse, SyntaxError}; use syntax::{Parse, SyntaxError, ast};
use triomphe::Arc; use triomphe::Arc;
pub use vfs::{file_set::FileSet, AnchoredPath, AnchoredPathBuf, FileId, VfsPath}; pub use vfs::{AnchoredPath, AnchoredPathBuf, FileId, VfsPath, file_set::FileSet};
#[macro_export] #[macro_export]
macro_rules! impl_intern_key { macro_rules! impl_intern_key {

View file

@ -9,7 +9,7 @@ use std::fmt;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use intern::{sym, Symbol}; use intern::{Symbol, sym};
pub use cfg_expr::{CfgAtom, CfgExpr}; pub use cfg_expr::{CfgAtom, CfgExpr};
pub use dnf::DnfExpr; pub use dnf::DnfExpr;

View file

@ -1,10 +1,11 @@
use arbitrary::{Arbitrary, Unstructured}; use arbitrary::{Arbitrary, Unstructured};
use expect_test::{expect, Expect}; use expect_test::{Expect, expect};
use intern::Symbol; use intern::Symbol;
use syntax::{ast, AstNode, Edition}; use syntax::{AstNode, Edition, ast};
use syntax_bridge::{ use syntax_bridge::{
dummy_test_span_utils::{DummyTestSpanMap, DUMMY}, DocCommentDesugarMode,
syntax_node_to_token_tree, DocCommentDesugarMode, dummy_test_span_utils::{DUMMY, DummyTestSpanMap},
syntax_node_to_token_tree,
}; };
use crate::{CfgAtom, CfgExpr, CfgOptions, DnfExpr}; use crate::{CfgAtom, CfgExpr, CfgOptions, DnfExpr};

View file

@ -6,28 +6,28 @@ use base_db::Crate;
use cfg::{CfgExpr, CfgOptions}; use cfg::{CfgExpr, CfgOptions};
use either::Either; use either::Either;
use hir_expand::{ use hir_expand::{
attrs::{collect_attrs, Attr, AttrId, RawAttrs},
HirFileId, InFile, HirFileId, InFile,
attrs::{Attr, AttrId, RawAttrs, collect_attrs},
}; };
use intern::{sym, Symbol}; use intern::{Symbol, sym};
use la_arena::{ArenaMap, Idx, RawIdx}; use la_arena::{ArenaMap, Idx, RawIdx};
use mbe::DelimiterKind; use mbe::DelimiterKind;
use rustc_abi::ReprOptions; use rustc_abi::ReprOptions;
use syntax::{ use syntax::{
ast::{self, HasAttrs},
AstPtr, AstPtr,
ast::{self, HasAttrs},
}; };
use triomphe::Arc; use triomphe::Arc;
use tt::iter::{TtElement, TtIter}; use tt::iter::{TtElement, TtIter};
use crate::{ use crate::{
AdtId, AttrDefId, GenericParamId, HasModule, ItemTreeLoc, LocalFieldId, Lookup, MacroId,
VariantId,
db::DefDatabase, db::DefDatabase,
item_tree::{AttrOwner, FieldParent, ItemTreeNode}, item_tree::{AttrOwner, FieldParent, ItemTreeNode},
lang_item::LangItem, lang_item::LangItem,
nameres::{ModuleOrigin, ModuleSource}, nameres::{ModuleOrigin, ModuleSource},
src::{HasChildSource, HasSource}, src::{HasChildSource, HasSource},
AdtId, AttrDefId, GenericParamId, HasModule, ItemTreeLoc, LocalFieldId, Lookup, MacroId,
VariantId,
}; };
/// Desugared attributes of an item post `cfg_attr` expansion. /// Desugared attributes of an item post `cfg_attr` expansion.
@ -770,8 +770,8 @@ mod tests {
use hir_expand::span_map::{RealSpanMap, SpanMap}; use hir_expand::span_map::{RealSpanMap, SpanMap};
use span::FileId; use span::FileId;
use syntax::{ast, AstNode, TextRange}; use syntax::{AstNode, TextRange, ast};
use syntax_bridge::{syntax_node_to_token_tree, DocCommentDesugarMode}; use syntax_bridge::{DocCommentDesugarMode, syntax_node_to_token_tree};
use crate::attr::{DocAtom, DocExpr}; use crate::attr::{DocAtom, DocExpr};

View file

@ -6,7 +6,7 @@
use std::fmt; use std::fmt;
use hir_expand::name::{AsName, Name}; use hir_expand::name::{AsName, Name};
use intern::{sym, Symbol}; use intern::{Symbol, sym};
/// Different signed int types. /// Different signed int types.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BuiltinInt { pub enum BuiltinInt {

View file

@ -4,19 +4,19 @@ pub mod adt;
use base_db::Crate; use base_db::Crate;
use hir_expand::name::Name; use hir_expand::name::Name;
use intern::{sym, Symbol}; use intern::{Symbol, sym};
use la_arena::{Idx, RawIdx}; use la_arena::{Idx, RawIdx};
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
ConstId, ExternCrateId, FunctionId, HasModule, ImplId, ItemContainerId, ItemLoc, Lookup,
Macro2Id, MacroRulesId, ProcMacroId, StaticId, TraitAliasId, TraitId, TypeAliasId,
db::DefDatabase, db::DefDatabase,
item_tree::{self, FnFlags, ModItem}, item_tree::{self, FnFlags, ModItem},
nameres::proc_macro::{parse_macro_name_and_helper_attrs, ProcMacroKind}, nameres::proc_macro::{ProcMacroKind, parse_macro_name_and_helper_attrs},
path::ImportAlias, path::ImportAlias,
type_ref::{TraitRef, TypeBound, TypeRefId, TypesMap}, type_ref::{TraitRef, TypeBound, TypeRefId, TypesMap},
visibility::RawVisibility, visibility::RawVisibility,
ConstId, ExternCrateId, FunctionId, HasModule, ImplId, ItemContainerId, ItemLoc, Lookup,
Macro2Id, MacroRulesId, ProcMacroId, StaticId, TraitAliasId, TraitId, TypeAliasId,
}; };
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
@ -431,11 +431,7 @@ impl ExternCrateDeclData {
Some(krate) Some(krate)
} else { } else {
krate.data(db).dependencies.iter().find_map(|dep| { krate.data(db).dependencies.iter().find_map(|dep| {
if dep.name.symbol() == name.symbol() { if dep.name.symbol() == name.symbol() { Some(dep.crate_id) } else { None }
Some(dep.crate_id)
} else {
None
}
}) })
}; };

View file

@ -11,6 +11,7 @@ use rustc_abi::{IntegerType, ReprOptions};
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
EnumId, EnumVariantId, LocalFieldId, LocalModuleId, Lookup, StructId, UnionId, VariantId,
db::DefDatabase, db::DefDatabase,
hir::Expr, hir::Expr,
item_tree::{ item_tree::{
@ -20,7 +21,6 @@ use crate::{
nameres::diagnostics::{DefDiagnostic, DefDiagnostics}, nameres::diagnostics::{DefDiagnostic, DefDiagnostics},
type_ref::{TypeRefId, TypesMap}, type_ref::{TypeRefId, TypesMap},
visibility::RawVisibility, visibility::RawVisibility,
EnumId, EnumVariantId, LocalFieldId, LocalModuleId, Lookup, StructId, UnionId, VariantId,
}; };
/// Note that we use `StructData` for unions as well! /// Note that we use `StructData` for unions as well!

View file

@ -1,33 +1,14 @@
//! Defines database & queries for name resolution. //! Defines database & queries for name resolution.
use base_db::{Crate, RootQueryDb, SourceDatabase, Upcast}; use base_db::{Crate, RootQueryDb, SourceDatabase, Upcast};
use either::Either; use either::Either;
use hir_expand::{db::ExpandDatabase, HirFileId, MacroDefId}; use hir_expand::{HirFileId, MacroDefId, db::ExpandDatabase};
use intern::sym; use intern::sym;
use la_arena::ArenaMap; use la_arena::ArenaMap;
use span::{EditionedFileId, MacroCallId}; use span::{EditionedFileId, MacroCallId};
use syntax::{ast, AstPtr}; use syntax::{AstPtr, ast};
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
attr::{Attrs, AttrsWithOwner},
data::{
adt::{EnumData, EnumVariantData, EnumVariants, StructData, VariantData},
ConstData, ExternCrateDeclData, FunctionData, ImplData, Macro2Data, MacroRulesData,
ProcMacroData, StaticData, TraitAliasData, TraitData, TypeAliasData,
},
expr_store::{scope::ExprScopes, Body, BodySourceMap},
generics::GenericParams,
import_map::ImportMap,
item_tree::{AttrOwner, ItemTree, ItemTreeSourceMaps},
lang_item::{self, LangItem, LangItemTarget, LangItems},
nameres::{
assoc::{ImplItems, TraitItems},
diagnostics::DefDiagnostics,
DefMap, LocalDefMap,
},
tt,
type_ref::TypesSourceMap,
visibility::{self, Visibility},
AttrDefId, BlockId, BlockLoc, ConstBlockId, ConstBlockLoc, ConstId, ConstLoc, DefWithBodyId, AttrDefId, BlockId, BlockLoc, ConstBlockId, ConstBlockLoc, ConstId, ConstLoc, DefWithBodyId,
EnumId, EnumLoc, EnumVariantId, EnumVariantLoc, ExternBlockId, ExternBlockLoc, ExternCrateId, EnumId, EnumLoc, EnumVariantId, EnumVariantLoc, ExternBlockId, ExternBlockLoc, ExternCrateId,
ExternCrateLoc, FunctionId, FunctionLoc, GenericDefId, ImplId, ImplLoc, InTypeConstId, ExternCrateLoc, FunctionId, FunctionLoc, GenericDefId, ImplId, ImplLoc, InTypeConstId,
@ -35,6 +16,25 @@ use crate::{
MacroRulesLocFlags, ProcMacroId, ProcMacroLoc, StaticId, StaticLoc, StructId, StructLoc, MacroRulesLocFlags, ProcMacroId, ProcMacroLoc, StaticId, StaticLoc, StructId, StructLoc,
TraitAliasId, TraitAliasLoc, TraitId, TraitLoc, TypeAliasId, TypeAliasLoc, UnionId, UnionLoc, TraitAliasId, TraitAliasLoc, TraitId, TraitLoc, TypeAliasId, TypeAliasLoc, UnionId, UnionLoc,
UseId, UseLoc, VariantId, UseId, UseLoc, VariantId,
attr::{Attrs, AttrsWithOwner},
data::{
ConstData, ExternCrateDeclData, FunctionData, ImplData, Macro2Data, MacroRulesData,
ProcMacroData, StaticData, TraitAliasData, TraitData, TypeAliasData,
adt::{EnumData, EnumVariantData, EnumVariants, StructData, VariantData},
},
expr_store::{Body, BodySourceMap, scope::ExprScopes},
generics::GenericParams,
import_map::ImportMap,
item_tree::{AttrOwner, ItemTree, ItemTreeSourceMaps},
lang_item::{self, LangItem, LangItemTarget, LangItems},
nameres::{
DefMap, LocalDefMap,
assoc::{ImplItems, TraitItems},
diagnostics::DefDiagnostics,
},
tt,
type_ref::TypesSourceMap,
visibility::{self, Visibility},
}; };
use salsa::plumbing::AsId; use salsa::plumbing::AsId;
@ -337,7 +337,7 @@ fn crate_supports_no_std(db: &dyn DefDatabase, crate_id: Crate) -> bool {
for output in segments.skip(1) { for output in segments.skip(1) {
match output.flat_tokens() { match output.flat_tokens() {
[tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.sym == sym::no_std => { [tt::TokenTree::Leaf(tt::Leaf::Ident(ident))] if ident.sym == sym::no_std => {
return true return true;
} }
_ => {} _ => {}
} }

View file

@ -27,15 +27,15 @@
pub mod keys { pub mod keys {
use std::marker::PhantomData; use std::marker::PhantomData;
use hir_expand::{attrs::AttrId, MacroCallId}; use hir_expand::{MacroCallId, attrs::AttrId};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use syntax::{ast, AstNode, AstPtr}; use syntax::{AstNode, AstPtr, ast};
use crate::{ use crate::{
dyn_map::{DynMap, Policy},
BlockId, ConstId, EnumId, EnumVariantId, ExternBlockId, ExternCrateId, FieldId, FunctionId, BlockId, ConstId, EnumId, EnumVariantId, ExternBlockId, ExternCrateId, FieldId, FunctionId,
ImplId, LifetimeParamId, Macro2Id, MacroRulesId, ProcMacroId, StaticId, StructId, ImplId, LifetimeParamId, Macro2Id, MacroRulesId, ProcMacroId, StaticId, StructId,
TraitAliasId, TraitId, TypeAliasId, TypeOrConstParamId, UnionId, UseId, TraitAliasId, TraitId, TypeAliasId, TypeOrConstParamId, UnionId, UseId,
dyn_map::{DynMap, Policy},
}; };
pub type Key<K, V> = crate::dyn_map::Key<AstPtr<K>, V, AstPtrPolicy<K, V>>; pub type Key<K, V> = crate::dyn_map::Key<AstPtr<K>, V, AstPtrPolicy<K, V>>;

View file

@ -6,17 +6,17 @@ use base_db::Crate;
use cfg::CfgOptions; use cfg::CfgOptions;
use drop_bomb::DropBomb; use drop_bomb::DropBomb;
use hir_expand::{ use hir_expand::{
attrs::RawAttrs, mod_path::ModPath, span_map::SpanMap, ExpandError, ExpandErrorKind, ExpandError, ExpandErrorKind, ExpandResult, HirFileId, InFile, Lookup, MacroCallId,
ExpandResult, HirFileId, InFile, Lookup, MacroCallId, attrs::RawAttrs, mod_path::ModPath, span_map::SpanMap,
}; };
use span::{Edition, SyntaxContext}; use span::{Edition, SyntaxContext};
use syntax::{ast, Parse}; use syntax::{Parse, ast};
use triomphe::Arc; use triomphe::Arc;
use crate::type_ref::{TypesMap, TypesSourceMap}; use crate::type_ref::{TypesMap, TypesSourceMap};
use crate::{ use crate::{
attr::Attrs, db::DefDatabase, lower::LowerCtx, path::Path, AsMacroCall, MacroId, ModuleId, AsMacroCall, MacroId, ModuleId, UnresolvedMacro, attr::Attrs, db::DefDatabase, lower::LowerCtx,
UnresolvedMacro, path::Path,
}; };
#[derive(Debug)] #[derive(Debug)]
@ -84,11 +84,7 @@ impl Expander {
} }
}); });
if let Some(err) = unresolved_macro_err { if let Some(err) = unresolved_macro_err { Err(err) } else { Ok(result) }
Err(err)
} else {
Ok(result)
}
} }
pub fn enter_expand_id<T: ast::AstNode>( pub fn enter_expand_id<T: ast::AstNode>(

View file

@ -12,16 +12,17 @@ use std::ops::{Deref, Index};
use cfg::{CfgExpr, CfgOptions}; use cfg::{CfgExpr, CfgOptions};
use either::Either; use either::Either;
use hir_expand::{name::Name, ExpandError, InFile}; use hir_expand::{ExpandError, InFile, name::Name};
use la_arena::{Arena, ArenaMap}; use la_arena::{Arena, ArenaMap};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use smallvec::SmallVec; use smallvec::SmallVec;
use span::{Edition, MacroFileId, SyntaxContext}; use span::{Edition, MacroFileId, SyntaxContext};
use syntax::{ast, AstPtr, SyntaxNodePtr}; use syntax::{AstPtr, SyntaxNodePtr, ast};
use triomphe::Arc; use triomphe::Arc;
use tt::TextRange; use tt::TextRange;
use crate::{ use crate::{
BlockId, DefWithBodyId, Lookup, SyntheticSyntax,
db::DefDatabase, db::DefDatabase,
hir::{ hir::{
Array, AsmOperand, Binding, BindingId, Expr, ExprId, ExprOrPatId, Label, LabelId, Pat, Array, AsmOperand, Binding, BindingId, Expr, ExprId, ExprOrPatId, Label, LabelId, Pat,
@ -30,7 +31,6 @@ use crate::{
nameres::DefMap, nameres::DefMap,
path::{ModPath, Path}, path::{ModPath, Path},
type_ref::{TypeRef, TypeRefId, TypesMap, TypesSourceMap}, type_ref::{TypeRef, TypeRefId, TypesMap, TypesSourceMap},
BlockId, DefWithBodyId, Lookup, SyntheticSyntax,
}; };
pub use self::body::{Body, BodySourceMap}; pub use self::body::{Body, BodySourceMap};

View file

@ -9,13 +9,13 @@ use syntax::ast;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
DefWithBodyId, HasModule,
db::DefDatabase, db::DefDatabase,
expander::Expander, expander::Expander,
expr_store::{lower, pretty, ExpressionStore, ExpressionStoreSourceMap, SelfParamPtr}, expr_store::{ExpressionStore, ExpressionStoreSourceMap, SelfParamPtr, lower, pretty},
hir::{BindingId, ExprId, PatId}, hir::{BindingId, ExprId, PatId},
item_tree::AttrOwner, item_tree::AttrOwner,
src::HasSource, src::HasSource,
DefWithBodyId, HasModule,
}; };
/// The body of an item (function, const etc.). /// The body of an item (function, const etc.).

View file

@ -8,26 +8,27 @@ use std::mem;
use base_db::Crate; use base_db::Crate;
use either::Either; use either::Either;
use hir_expand::{ use hir_expand::{
InFile, MacroDefId,
mod_path::tool_path, mod_path::tool_path,
name::{AsName, Name}, name::{AsName, Name},
span_map::{ExpansionSpanMap, SpanMap}, span_map::{ExpansionSpanMap, SpanMap},
InFile, MacroDefId,
}; };
use intern::{sym, Symbol}; use intern::{Symbol, sym};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use span::AstIdMap; use span::AstIdMap;
use stdx::never; use stdx::never;
use syntax::{ use syntax::{
AstNode, AstPtr, AstToken as _, SyntaxNodePtr,
ast::{ ast::{
self, ArrayExprKind, AstChildren, BlockExpr, HasArgList, HasAttrs, HasGenericArgs, self, ArrayExprKind, AstChildren, BlockExpr, HasArgList, HasAttrs, HasGenericArgs,
HasLoopBody, HasName, RangeItem, SlicePatComponents, HasLoopBody, HasName, RangeItem, SlicePatComponents,
}, },
AstNode, AstPtr, AstToken as _, SyntaxNodePtr,
}; };
use text_size::TextSize; use text_size::TextSize;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
AdtId, BlockId, BlockLoc, ConstBlockLoc, DefWithBodyId, MacroId, ModuleDefId, UnresolvedMacro,
attr::Attrs, attr::Attrs,
builtin_type::BuiltinUint, builtin_type::BuiltinUint,
data::adt::StructKind, data::adt::StructKind,
@ -38,14 +39,14 @@ use crate::{
ExpressionStoreDiagnostics, ExpressionStoreSourceMap, HygieneId, LabelPtr, PatPtr, ExpressionStoreDiagnostics, ExpressionStoreSourceMap, HygieneId, LabelPtr, PatPtr,
}, },
hir::{ hir::{
Array, Binding, BindingAnnotation, BindingId, BindingProblems, CaptureBy, ClosureKind,
Expr, ExprId, Item, Label, LabelId, Literal, MatchArm, Movability, OffsetOf, Pat, PatId,
RecordFieldPat, RecordLitField, Statement,
format_args::{ format_args::{
self, FormatAlignment, FormatArgs, FormatArgsPiece, FormatArgument, FormatArgumentKind, self, FormatAlignment, FormatArgs, FormatArgsPiece, FormatArgument, FormatArgumentKind,
FormatArgumentsCollector, FormatCount, FormatDebugHex, FormatOptions, FormatArgumentsCollector, FormatCount, FormatDebugHex, FormatOptions,
FormatPlaceholder, FormatSign, FormatTrait, FormatPlaceholder, FormatSign, FormatTrait,
}, },
Array, Binding, BindingAnnotation, BindingId, BindingProblems, CaptureBy, ClosureKind,
Expr, ExprId, Item, Label, LabelId, Literal, MatchArm, Movability, OffsetOf, Pat, PatId,
RecordFieldPat, RecordLitField, Statement,
}, },
item_scope::BuiltinShadowMode, item_scope::BuiltinShadowMode,
lang_item::LangItem, lang_item::LangItem,
@ -53,7 +54,6 @@ use crate::{
nameres::{DefMap, LocalDefMap, MacroSubNs}, nameres::{DefMap, LocalDefMap, MacroSubNs},
path::{GenericArgs, Path}, path::{GenericArgs, Path},
type_ref::{Mutability, Rawness, TypeRef}, type_ref::{Mutability, Rawness, TypeRef},
AdtId, BlockId, BlockLoc, ConstBlockLoc, DefWithBodyId, MacroId, ModuleDefId, UnresolvedMacro,
}; };
type FxIndexSet<K> = indexmap::IndexSet<K, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>; type FxIndexSet<K> = indexmap::IndexSet<K, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;
@ -641,11 +641,7 @@ impl ExprCollector<'_> {
let expr = self.collect_expr_opt(e.expr()); let expr = self.collect_expr_opt(e.expr());
let raw_tok = e.raw_token().is_some(); let raw_tok = e.raw_token().is_some();
let mutability = if raw_tok { let mutability = if raw_tok {
if e.mut_token().is_some() { if e.mut_token().is_some() { Mutability::Mut } else { Mutability::Shared }
Mutability::Mut
} else {
Mutability::Shared
}
} else { } else {
Mutability::from_mutable(e.mut_token().is_some()) Mutability::from_mutable(e.mut_token().is_some())
}; };
@ -2041,7 +2037,7 @@ impl ExprCollector<'_> {
return match l.kind() { return match l.kind() {
ast::LiteralKind::String(s) => Some((s, true)), ast::LiteralKind::String(s) => Some((s, true)),
_ => None, _ => None,
} };
} }
_ => return None, _ => return None,
}; };

View file

@ -3,8 +3,8 @@ use hir_expand::name::Name;
use intern::Symbol; use intern::Symbol;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use syntax::{ use syntax::{
ast::{self, HasName, IsString},
AstNode, AstPtr, AstToken, T, AstNode, AstPtr, AstToken, T,
ast::{self, HasName, IsString},
}; };
use tt::TextRange; use tt::TextRange;

View file

@ -1,13 +1,13 @@
//! Name resolution for expressions. //! Name resolution for expressions.
use hir_expand::{name::Name, MacroDefId}; use hir_expand::{MacroDefId, name::Name};
use la_arena::{Arena, ArenaMap, Idx, IdxRange, RawIdx}; use la_arena::{Arena, ArenaMap, Idx, IdxRange, RawIdx};
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
BlockId, ConstBlockId, DefWithBodyId,
db::DefDatabase, db::DefDatabase,
expr_store::{Body, ExpressionStore, HygieneId}, expr_store::{Body, ExpressionStore, HygieneId},
hir::{Binding, BindingId, Expr, ExprId, Item, LabelId, Pat, PatId, Statement}, hir::{Binding, BindingId, Expr, ExprId, Item, LabelId, Pat, PatId, Statement},
BlockId, ConstBlockId, DefWithBodyId,
}; };
pub type ScopeId = Idx<ScopeData>; pub type ScopeId = Idx<ScopeData>;
@ -325,14 +325,14 @@ fn compute_expr_scopes(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use base_db::RootQueryDb; use base_db::RootQueryDb;
use hir_expand::{name::AsName, InFile}; use hir_expand::{InFile, name::AsName};
use salsa::AsDynDatabase; use salsa::AsDynDatabase;
use span::FileId; use span::FileId;
use syntax::{algo::find_node_at_offset, ast, AstNode}; use syntax::{AstNode, algo::find_node_at_offset, ast};
use test_fixture::WithFixture; use test_fixture::WithFixture;
use test_utils::{assert_eq_text, extract_offset}; use test_utils::{assert_eq_text, extract_offset};
use crate::{db::DefDatabase, test_db::TestDB, FunctionId, ModuleDefId}; use crate::{FunctionId, ModuleDefId, db::DefDatabase, test_db::TestDB};
fn find_function(db: &TestDB, file_id: FileId) -> FunctionId { fn find_function(db: &TestDB, file_id: FileId) -> FunctionId {
let krate = db.test_crate(); let krate = db.test_crate();

View file

@ -1,7 +1,7 @@
mod block; mod block;
use crate::{hir::MatchArm, test_db::TestDB, ModuleDefId}; use crate::{ModuleDefId, hir::MatchArm, test_db::TestDB};
use expect_test::{expect, Expect}; use expect_test::{Expect, expect};
use la_arena::RawIdx; use la_arena::RawIdx;
use test_fixture::WithFixture; use test_fixture::WithFixture;

View file

@ -4,19 +4,19 @@ use std::{cell::Cell, cmp::Ordering, iter};
use base_db::{Crate, CrateOrigin, LangCrateOrigin}; use base_db::{Crate, CrateOrigin, LangCrateOrigin};
use hir_expand::{ use hir_expand::{
name::{AsName, Name},
Lookup, Lookup,
name::{AsName, Name},
}; };
use intern::sym; use intern::sym;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use crate::{ use crate::{
ImportPathConfig, ModuleDefId, ModuleId,
db::DefDatabase, db::DefDatabase,
item_scope::ItemInNs, item_scope::ItemInNs,
nameres::DefMap, nameres::DefMap,
path::{ModPath, PathKind}, path::{ModPath, PathKind},
visibility::{Visibility, VisibilityExplicitness}, visibility::{Visibility, VisibilityExplicitness},
ImportPathConfig, ModuleDefId, ModuleId,
}; };
/// Find a path that can be used to refer to a certain item. This can depend on /// Find a path that can be used to refer to a certain item. This can depend on
@ -651,7 +651,7 @@ fn find_local_import_locations(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use expect_test::{expect, Expect}; use expect_test::{Expect, expect};
use hir_expand::db::ExpandDatabase; use hir_expand::db::ExpandDatabase;
use itertools::Itertools; use itertools::Itertools;
use span::Edition; use span::Edition;

View file

@ -7,8 +7,8 @@ use std::{ops, sync::LazyLock};
use either::Either; use either::Either;
use hir_expand::{ use hir_expand::{
name::{AsName, Name},
ExpandResult, ExpandResult,
name::{AsName, Name},
}; };
use intern::sym; use intern::sym;
use la_arena::{Arena, RawIdx}; use la_arena::{Arena, RawIdx};
@ -20,6 +20,8 @@ use syntax::ast::{self, HasGenericParams, HasName, HasTypeBounds};
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
AdtId, ConstParamId, GenericDefId, HasModule, ItemTreeLoc, LifetimeParamId,
LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup, TypeOrConstParamId, TypeParamId,
db::DefDatabase, db::DefDatabase,
expander::Expander, expander::Expander,
item_tree::{AttrOwner, FileItemTreeId, GenericModItem, GenericsItemTreeNode, ItemTree}, item_tree::{AttrOwner, FileItemTreeId, GenericModItem, GenericsItemTreeNode, ItemTree},
@ -30,8 +32,6 @@ use crate::{
ArrayType, ConstRef, FnType, LifetimeRef, PathId, RefType, TypeBound, TypeRef, TypeRefId, ArrayType, ConstRef, FnType, LifetimeRef, PathId, RefType, TypeBound, TypeRef, TypeRefId,
TypesMap, TypesSourceMap, TypesMap, TypesSourceMap,
}, },
AdtId, ConstParamId, GenericDefId, HasModule, ItemTreeLoc, LifetimeParamId,
LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup, TypeOrConstParamId, TypeParamId,
}; };
/// The index of the self param in the generic of the non-parent definition. /// The index of the self param in the generic of the non-parent definition.
@ -292,11 +292,7 @@ impl GenericParams {
parent: GenericDefId, parent: GenericDefId,
) -> Option<LifetimeParamId> { ) -> Option<LifetimeParamId> {
self.lifetimes.iter().find_map(|(id, p)| { self.lifetimes.iter().find_map(|(id, p)| {
if &p.name == name { if &p.name == name { Some(LifetimeParamId { local_id: id, parent }) } else { None }
Some(LifetimeParamId { local_id: id, parent })
} else {
None
}
}) })
} }

View file

@ -17,7 +17,7 @@ pub mod type_ref;
use std::fmt; use std::fmt;
use hir_expand::{name::Name, MacroDefId}; use hir_expand::{MacroDefId, name::Name};
use intern::Symbol; use intern::Symbol;
use la_arena::Idx; use la_arena::Idx;
use rustc_apfloat::ieee::{Half as f16, Quad as f128}; use rustc_apfloat::ieee::{Half as f16, Quad as f128};
@ -25,10 +25,10 @@ use syntax::ast;
use type_ref::TypeRefId; use type_ref::TypeRefId;
use crate::{ use crate::{
BlockId, ConstBlockId,
builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint}, builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint},
path::{GenericArgs, Path}, path::{GenericArgs, Path},
type_ref::{Mutability, Rawness}, type_ref::{Mutability, Rawness},
BlockId, ConstBlockId,
}; };
pub use syntax::ast::{ArithOp, BinaryOp, CmpOp, LogicOp, Ordering, RangeOp, UnaryOp}; pub use syntax::ast::{ArithOp, BinaryOp, CmpOp, LogicOp, Ordering, RangeOp, UnaryOp};
@ -137,11 +137,7 @@ pub enum LiteralOrConst {
impl Literal { impl Literal {
pub fn negate(self) -> Option<Self> { pub fn negate(self) -> Option<Self> {
if let Literal::Int(i, k) = self { if let Literal::Int(i, k) = self { Some(Literal::Int(-i, k)) } else { None }
Some(Literal::Int(-i, k))
} else {
None
}
} }
} }

View file

@ -7,8 +7,8 @@ use rustc_parse_format as parse;
use span::SyntaxContext; use span::SyntaxContext;
use stdx::TupleExt; use stdx::TupleExt;
use syntax::{ use syntax::{
ast::{self, IsString},
TextRange, TextRange,
ast::{self, IsString},
}; };
use crate::hir::ExprId; use crate::hir::ExprId;

View file

@ -5,25 +5,25 @@ use core::fmt;
use std::{fmt::Write, ops::Index}; use std::{fmt::Write, ops::Index};
use hir_expand::{ use hir_expand::{
AstId, InFile,
db::ExpandDatabase, db::ExpandDatabase,
name::{AsName, Name}, name::{AsName, Name},
AstId, InFile,
}; };
use intern::{sym, Symbol}; use intern::{Symbol, sym};
use la_arena::{Arena, ArenaMap, Idx}; use la_arena::{Arena, ArenaMap, Idx};
use span::Edition; use span::Edition;
use stdx::thin_vec::{thin_vec_with_header_struct, EmptyOptimizedThinVec, ThinVec}; use stdx::thin_vec::{EmptyOptimizedThinVec, ThinVec, thin_vec_with_header_struct};
use syntax::{ use syntax::{
ast::{self, HasGenericArgs, HasName, IsString},
AstPtr, AstPtr,
ast::{self, HasGenericArgs, HasName, IsString},
}; };
use crate::{ use crate::{
SyntheticSyntax,
builtin_type::{BuiltinInt, BuiltinType, BuiltinUint}, builtin_type::{BuiltinInt, BuiltinType, BuiltinUint},
hir::Literal, hir::Literal,
lower::LowerCtx, lower::LowerCtx,
path::{GenericArg, Path}, path::{GenericArg, Path},
SyntheticSyntax,
}; };
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
@ -34,11 +34,7 @@ pub enum Mutability {
impl Mutability { impl Mutability {
pub fn from_mutable(mutable: bool) -> Mutability { pub fn from_mutable(mutable: bool) -> Mutability {
if mutable { if mutable { Mutability::Mut } else { Mutability::Shared }
Mutability::Mut
} else {
Mutability::Shared
}
} }
pub fn as_keyword_for_ref(self) -> &'static str { pub fn as_keyword_for_ref(self) -> &'static str {
@ -80,11 +76,7 @@ pub enum Rawness {
impl Rawness { impl Rawness {
pub fn from_raw(is_raw: bool) -> Rawness { pub fn from_raw(is_raw: bool) -> Rawness {
if is_raw { if is_raw { Rawness::RawPtr } else { Rawness::Ref }
Rawness::RawPtr
} else {
Rawness::Ref
}
} }
pub fn is_raw(&self) -> bool { pub fn is_raw(&self) -> bool {

View file

@ -3,21 +3,21 @@
use std::fmt; use std::fmt;
use base_db::Crate; use base_db::Crate;
use fst::{raw::IndexedValue, Automaton, Streamer}; use fst::{Automaton, Streamer, raw::IndexedValue};
use hir_expand::name::Name; use hir_expand::name::Name;
use itertools::Itertools; use itertools::Itertools;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use smallvec::SmallVec; use smallvec::SmallVec;
use span::Edition; use span::Edition;
use stdx::{format_to, TupleExt}; use stdx::{TupleExt, format_to};
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
AssocItemId, FxIndexMap, ModuleDefId, ModuleId, TraitId,
db::DefDatabase, db::DefDatabase,
item_scope::{ImportOrExternCrate, ItemInNs}, item_scope::{ImportOrExternCrate, ItemInNs},
nameres::DefMap, nameres::DefMap,
visibility::Visibility, visibility::Visibility,
AssocItemId, FxIndexMap, ModuleDefId, ModuleId, TraitId,
}; };
/// Item import details stored in the `ImportMap`. /// Item import details stored in the `ImportMap`.
@ -155,11 +155,7 @@ impl ImportMap {
let visible_items = mod_data.scope.entries().filter_map(|(name, per_ns)| { let visible_items = mod_data.scope.entries().filter_map(|(name, per_ns)| {
let per_ns = per_ns.filter_visibility(|vis| vis == Visibility::Public); let per_ns = per_ns.filter_visibility(|vis| vis == Visibility::Public);
if per_ns.is_none() { if per_ns.is_none() { None } else { Some((name, per_ns)) }
None
} else {
Some((name, per_ns))
}
}); });
for (name, per_ns) in visible_items { for (name, per_ns) in visible_items {
@ -474,10 +470,10 @@ fn search_maps(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use base_db::{RootQueryDb, Upcast}; use base_db::{RootQueryDb, Upcast};
use expect_test::{expect, Expect}; use expect_test::{Expect, expect};
use test_fixture::WithFixture; use test_fixture::WithFixture;
use crate::{test_db::TestDB, ItemContainerId, Lookup}; use crate::{ItemContainerId, Lookup, test_db::TestDB};
use super::*; use super::*;

View file

@ -4,22 +4,22 @@
use std::sync::LazyLock; use std::sync::LazyLock;
use base_db::Crate; use base_db::Crate;
use hir_expand::{attrs::AttrId, db::ExpandDatabase, name::Name, AstId, MacroCallId}; use hir_expand::{AstId, MacroCallId, attrs::AttrId, db::ExpandDatabase, name::Name};
use indexmap::map::Entry; use indexmap::map::Entry;
use itertools::Itertools; use itertools::Itertools;
use la_arena::Idx; use la_arena::Idx;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::{smallvec, SmallVec}; use smallvec::{SmallVec, smallvec};
use span::Edition; use span::Edition;
use stdx::format_to; use stdx::format_to;
use syntax::ast; use syntax::ast;
use crate::{ use crate::{
AdtId, BuiltinType, ConstId, ExternBlockId, ExternCrateId, FxIndexMap, HasModule, ImplId,
LocalModuleId, Lookup, MacroId, ModuleDefId, ModuleId, TraitId, UseId,
db::DefDatabase, db::DefDatabase,
per_ns::{Item, MacrosItem, PerNs, TypesItem, ValuesItem}, per_ns::{Item, MacrosItem, PerNs, TypesItem, ValuesItem},
visibility::{Visibility, VisibilityExplicitness}, visibility::{Visibility, VisibilityExplicitness},
AdtId, BuiltinType, ConstId, ExternBlockId, ExternCrateId, FxIndexMap, HasModule, ImplId,
LocalModuleId, Lookup, MacroId, ModuleDefId, ModuleId, TraitId, UseId,
}; };
#[derive(Debug, Default)] #[derive(Debug, Default)]

View file

@ -46,24 +46,24 @@ use std::{
use ast::{AstNode, StructKind}; use ast::{AstNode, StructKind};
use base_db::Crate; use base_db::Crate;
use either::Either; use either::Either;
use hir_expand::{attrs::RawAttrs, name::Name, ExpandTo, HirFileId, InFile}; use hir_expand::{ExpandTo, HirFileId, InFile, attrs::RawAttrs, name::Name};
use intern::{Interned, Symbol}; use intern::{Interned, Symbol};
use la_arena::{Arena, Idx, RawIdx}; use la_arena::{Arena, Idx, RawIdx};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use smallvec::SmallVec; use smallvec::SmallVec;
use span::{AstIdNode, Edition, FileAstId, SyntaxContext}; use span::{AstIdNode, Edition, FileAstId, SyntaxContext};
use stdx::never; use stdx::never;
use syntax::{ast, match_ast, SyntaxKind}; use syntax::{SyntaxKind, ast, match_ast};
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
BlockId, LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup,
attr::Attrs, attr::Attrs,
db::DefDatabase, db::DefDatabase,
generics::GenericParams, generics::GenericParams,
path::{GenericArgs, ImportAlias, ModPath, Path, PathKind}, path::{GenericArgs, ImportAlias, ModPath, Path, PathKind},
type_ref::{Mutability, TraitRef, TypeBound, TypeRefId, TypesMap, TypesSourceMap}, type_ref::{Mutability, TraitRef, TypeBound, TypeRefId, TypesMap, TypesSourceMap},
visibility::{RawVisibility, VisibilityExplicitness}, visibility::{RawVisibility, VisibilityExplicitness},
BlockId, LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup,
}; };
#[derive(Copy, Clone, Eq, PartialEq)] #[derive(Copy, Clone, Eq, PartialEq)]

View file

@ -3,23 +3,24 @@
use std::{cell::OnceCell, collections::hash_map::Entry}; use std::{cell::OnceCell, collections::hash_map::Entry};
use hir_expand::{ use hir_expand::{
HirFileId,
mod_path::path, mod_path::path,
name::AsName, name::AsName,
span_map::{SpanMap, SpanMapRef}, span_map::{SpanMap, SpanMapRef},
HirFileId,
}; };
use intern::{sym, Symbol}; use intern::{Symbol, sym};
use la_arena::Arena; use la_arena::Arena;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use span::{AstIdMap, SyntaxContext}; use span::{AstIdMap, SyntaxContext};
use stdx::thin_vec::ThinVec; use stdx::thin_vec::ThinVec;
use syntax::{ use syntax::{
ast::{self, HasModuleItem, HasName, HasTypeBounds, IsString},
AstNode, AstNode,
ast::{self, HasModuleItem, HasName, HasTypeBounds, IsString},
}; };
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
LocalLifetimeParamId, LocalTypeOrConstParamId,
db::DefDatabase, db::DefDatabase,
generics::{GenericParams, GenericParamsCollector}, generics::{GenericParams, GenericParamsCollector},
item_tree::{ item_tree::{
@ -38,7 +39,6 @@ use crate::{
TypesMap, TypesSourceMap, TypesMap, TypesSourceMap,
}, },
visibility::RawVisibility, visibility::RawVisibility,
LocalLifetimeParamId, LocalTypeOrConstParamId,
}; };
fn id<N>(index: Idx<N>) -> FileItemTreeId<N> { fn id<N>(index: Idx<N>) -> FileItemTreeId<N> {
@ -931,8 +931,7 @@ impl<'a> Ctx<'a> {
fn desugar_future_path(ctx: &mut LowerCtx<'_>, orig: TypeRefId) -> PathId { fn desugar_future_path(ctx: &mut LowerCtx<'_>, orig: TypeRefId) -> PathId {
let path = path![core::future::Future]; let path = path![core::future::Future];
let mut generic_args: Vec<_> = let mut generic_args: Vec<_> = std::iter::repeat_n(None, path.segments().len() - 1).collect();
std::iter::repeat(None).take(path.segments().len() - 1).collect();
let binding = AssociatedTypeBinding { let binding = AssociatedTypeBinding {
name: Name::new_symbol_root(sym::Output.clone()), name: Name::new_symbol_root(sym::Output.clone()),
args: None, args: None,

View file

@ -1,4 +1,4 @@
use expect_test::{expect, Expect}; use expect_test::{Expect, expect};
use span::Edition; use span::Edition;
use test_fixture::WithFixture; use test_fixture::WithFixture;

View file

@ -3,13 +3,13 @@
//! This attribute to tell the compiler about semi built-in std library //! This attribute to tell the compiler about semi built-in std library
//! features, such as Fn family of traits. //! features, such as Fn family of traits.
use hir_expand::name::Name; use hir_expand::name::Name;
use intern::{sym, Symbol}; use intern::{Symbol, sym};
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
db::DefDatabase, path::Path, AdtId, AssocItemId, AttrDefId, Crate, EnumId, EnumVariantId, AdtId, AssocItemId, AttrDefId, Crate, EnumId, EnumVariantId, FunctionId, ImplId, ModuleDefId,
FunctionId, ImplId, ModuleDefId, StaticId, StructId, TraitId, TypeAliasId, UnionId, StaticId, StructId, TraitId, TypeAliasId, UnionId, db::DefDatabase, path::Path,
}; };
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@ -164,11 +164,7 @@ impl LangItems {
} }
} }
if lang_items.items.is_empty() { if lang_items.items.is_empty() { None } else { Some(Arc::new(lang_items)) }
None
} else {
Some(Arc::new(lang_items))
}
} }
/// Salsa query. Look for a lang item, starting from the specified crate and recursively /// Salsa query. Look for a lang item, starting from the specified crate and recursively
@ -230,11 +226,7 @@ pub(crate) fn crate_notable_traits(db: &dyn DefDatabase, krate: Crate) -> Option
} }
} }
if traits.is_empty() { if traits.is_empty() { None } else { Some(traits.into_iter().collect()) }
None
} else {
Some(traits.into_iter().collect())
}
} }
pub enum GenericRequirement { pub enum GenericRequirement {

View file

@ -71,25 +71,25 @@ mod test_db;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use base_db::{impl_intern_key, Crate}; use base_db::{Crate, impl_intern_key};
use hir_expand::{ use hir_expand::{
AstId, ExpandError, ExpandResult, ExpandTo, HirFileId, InFile, MacroCallId, MacroCallKind,
MacroDefId, MacroDefKind,
builtin::{BuiltinAttrExpander, BuiltinDeriveExpander, BuiltinFnLikeExpander, EagerExpander}, builtin::{BuiltinAttrExpander, BuiltinDeriveExpander, BuiltinFnLikeExpander, EagerExpander},
db::ExpandDatabase, db::ExpandDatabase,
eager::expand_eager_macro_input, eager::expand_eager_macro_input,
impl_intern_lookup, impl_intern_lookup,
name::Name, name::Name,
proc_macro::{CustomProcMacroExpander, ProcMacroKind}, proc_macro::{CustomProcMacroExpander, ProcMacroKind},
AstId, ExpandError, ExpandResult, ExpandTo, HirFileId, InFile, MacroCallId, MacroCallKind,
MacroDefId, MacroDefKind,
}; };
use item_tree::ExternBlock; use item_tree::ExternBlock;
use la_arena::Idx; use la_arena::Idx;
use nameres::DefMap; use nameres::DefMap;
use span::{AstIdNode, Edition, FileAstId, SyntaxContext}; use span::{AstIdNode, Edition, FileAstId, SyntaxContext};
use stdx::impl_from; use stdx::impl_from;
use syntax::{ast, AstNode}; use syntax::{AstNode, ast};
pub use hir_expand::{tt, Intern, Lookup}; pub use hir_expand::{Intern, Lookup, tt};
use crate::{ use crate::{
builtin_type::BuiltinType, builtin_type::BuiltinType,
@ -438,11 +438,7 @@ impl ModuleId {
let def_map = self.def_map(db); let def_map = self.def_map(db);
let parent = def_map[self.local_id].parent?; let parent = def_map[self.local_id].parent?;
def_map[parent].children.iter().find_map(|(name, module_id)| { def_map[parent].children.iter().find_map(|(name, module_id)| {
if *module_id == self.local_id { if *module_id == self.local_id { Some(name.clone()) } else { None }
Some(name.clone())
} else {
None
}
}) })
} }

View file

@ -1,7 +1,7 @@
//! Context for lowering paths. //! Context for lowering paths.
use std::{cell::OnceCell, mem}; use std::{cell::OnceCell, mem};
use hir_expand::{span_map::SpanMap, AstId, HirFileId, InFile}; use hir_expand::{AstId, HirFileId, InFile, span_map::SpanMap};
use span::{AstIdMap, AstIdNode, Edition, EditionedFileId, FileId, RealSpanMap}; use span::{AstIdMap, AstIdNode, Edition, EditionedFileId, FileId, RealSpanMap};
use stdx::thin_vec::ThinVec; use stdx::thin_vec::ThinVec;
use syntax::ast; use syntax::ast;

View file

@ -19,10 +19,10 @@ use std::{iter, ops::Range, sync};
use base_db::RootQueryDb; use base_db::RootQueryDb;
use expect_test::Expect; use expect_test::Expect;
use hir_expand::{ use hir_expand::{
InFile, MacroCallKind, MacroFileId, MacroFileIdExt, MacroKind,
db::ExpandDatabase, db::ExpandDatabase,
proc_macro::{ProcMacro, ProcMacroExpander, ProcMacroExpansionError, ProcMacroKind}, proc_macro::{ProcMacro, ProcMacroExpander, ProcMacroExpansionError, ProcMacroKind},
span_map::SpanMapRef, span_map::SpanMapRef,
InFile, MacroCallKind, MacroFileId, MacroFileIdExt, MacroKind,
}; };
use intern::Symbol; use intern::Symbol;
use itertools::Itertools; use itertools::Itertools;
@ -30,21 +30,21 @@ use salsa::AsDynDatabase;
use span::{Edition, Span}; use span::{Edition, Span};
use stdx::{format_to, format_to_acc}; use stdx::{format_to, format_to_acc};
use syntax::{ use syntax::{
ast::{self, edit::IndentLevel},
AstNode, AstNode,
SyntaxKind::{COMMENT, EOF, IDENT, LIFETIME_IDENT}, SyntaxKind::{COMMENT, EOF, IDENT, LIFETIME_IDENT},
SyntaxNode, T, SyntaxNode, T,
ast::{self, edit::IndentLevel},
}; };
use test_fixture::WithFixture; use test_fixture::WithFixture;
use crate::{ use crate::{
AdtId, AsMacroCall, Lookup, ModuleDefId,
db::DefDatabase, db::DefDatabase,
nameres::{DefMap, MacroSubNs, ModuleSource}, nameres::{DefMap, MacroSubNs, ModuleSource},
resolver::HasResolver, resolver::HasResolver,
src::HasSource, src::HasSource,
test_db::TestDB, test_db::TestDB,
tt::TopSubtree, tt::TopSubtree,
AdtId, AsMacroCall, Lookup, ModuleDefId,
}; };
#[track_caller] #[track_caller]

View file

@ -62,7 +62,7 @@ use std::ops::Deref;
use base_db::Crate; use base_db::Crate;
use hir_expand::{ use hir_expand::{
name::Name, proc_macro::ProcMacroKind, ErasedAstId, HirFileId, InFile, MacroCallId, MacroDefId, ErasedAstId, HirFileId, InFile, MacroCallId, MacroDefId, name::Name, proc_macro::ProcMacroKind,
}; };
use intern::Symbol; use intern::Symbol;
use itertools::Itertools; use itertools::Itertools;
@ -70,11 +70,13 @@ use la_arena::Arena;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use span::{Edition, EditionedFileId, FileAstId, FileId, ROOT_ERASED_FILE_AST_ID}; use span::{Edition, EditionedFileId, FileAstId, FileId, ROOT_ERASED_FILE_AST_ID};
use stdx::format_to; use stdx::format_to;
use syntax::{ast, AstNode, SmolStr, SyntaxNode, ToSmolStr}; use syntax::{AstNode, SmolStr, SyntaxNode, ToSmolStr, ast};
use triomphe::Arc; use triomphe::Arc;
use tt::TextRange; use tt::TextRange;
use crate::{ use crate::{
AstId, BlockId, BlockLoc, CrateRootModuleId, EnumId, EnumVariantId, ExternCrateId, FunctionId,
FxIndexMap, LocalModuleId, Lookup, MacroExpander, MacroId, ModuleId, ProcMacroId, UseId,
db::DefDatabase, db::DefDatabase,
item_scope::{BuiltinShadowMode, ItemScope}, item_scope::{BuiltinShadowMode, ItemScope},
item_tree::{ItemTreeId, Mod, TreeId}, item_tree::{ItemTreeId, Mod, TreeId},
@ -82,8 +84,6 @@ use crate::{
path::ModPath, path::ModPath,
per_ns::PerNs, per_ns::PerNs,
visibility::{Visibility, VisibilityExplicitness}, visibility::{Visibility, VisibilityExplicitness},
AstId, BlockId, BlockLoc, CrateRootModuleId, EnumId, EnumVariantId, ExternCrateId, FunctionId,
FxIndexMap, LocalModuleId, Lookup, MacroExpander, MacroId, ModuleId, ProcMacroId, UseId,
}; };
pub use self::path_resolution::ResolvePathResultPrefixInfo; pub use self::path_resolution::ResolvePathResultPrefixInfo;

View file

@ -1,25 +1,25 @@
//! Expansion of associated items //! Expansion of associated items
use hir_expand::{ use hir_expand::{
name::Name, AstId, ExpandResult, InFile, Intern, Lookup, MacroCallKind, MacroDefKind, AstId, ExpandResult, InFile, Intern, Lookup, MacroCallKind, MacroDefKind, name::Name,
}; };
use smallvec::SmallVec; use smallvec::SmallVec;
use span::{HirFileId, MacroCallId}; use span::{HirFileId, MacroCallId};
use syntax::{ast, Parse}; use syntax::{Parse, ast};
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
AssocItemId, AstIdWithPath, ConstLoc, FunctionId, FunctionLoc, ImplId, ItemContainerId,
ItemLoc, ModuleId, TraitId, TypeAliasId, TypeAliasLoc,
db::DefDatabase, db::DefDatabase,
expander::{Expander, Mark}, expander::{Expander, Mark},
item_tree::{self, AssocItem, ItemTree, ItemTreeId, MacroCall, ModItem, TreeId}, item_tree::{self, AssocItem, ItemTree, ItemTreeId, MacroCall, ModItem, TreeId},
macro_call_as_call_id, macro_call_as_call_id,
nameres::{ nameres::{
DefMap, LocalDefMap, MacroSubNs,
attr_resolution::ResolvedAttr, attr_resolution::ResolvedAttr,
diagnostics::{DefDiagnostic, DefDiagnostics}, diagnostics::{DefDiagnostic, DefDiagnostics},
DefMap, LocalDefMap, MacroSubNs,
}, },
AssocItemId, AstIdWithPath, ConstLoc, FunctionId, FunctionLoc, ImplId, ItemContainerId,
ItemLoc, ModuleId, TraitId, TypeAliasId, TypeAliasLoc,
}; };
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]

View file

@ -2,20 +2,20 @@
use base_db::Crate; use base_db::Crate;
use hir_expand::{ use hir_expand::{
MacroCallId, MacroCallKind, MacroDefId,
attrs::{Attr, AttrId, AttrInput}, attrs::{Attr, AttrId, AttrInput},
inert_attr_macro::find_builtin_attr_idx, inert_attr_macro::find_builtin_attr_idx,
MacroCallId, MacroCallKind, MacroDefId,
}; };
use span::SyntaxContext; use span::SyntaxContext;
use syntax::ast; use syntax::ast;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
AstIdWithPath, LocalModuleId, MacroId, UnresolvedMacro,
db::DefDatabase, db::DefDatabase,
item_scope::BuiltinShadowMode, item_scope::BuiltinShadowMode,
nameres::{path_resolution::ResolveMode, LocalDefMap}, nameres::{LocalDefMap, path_resolution::ResolveMode},
path::{self, ModPath, PathKind}, path::{self, ModPath, PathKind},
AstIdWithPath, LocalModuleId, MacroId, UnresolvedMacro,
}; };
use super::{DefMap, MacroSubNs}; use super::{DefMap, MacroSubNs};

View file

@ -9,15 +9,15 @@ use base_db::{BuiltDependency, Crate, CrateOrigin, LangCrateOrigin};
use cfg::{CfgAtom, CfgExpr, CfgOptions}; use cfg::{CfgAtom, CfgExpr, CfgOptions};
use either::Either; use either::Either;
use hir_expand::{ use hir_expand::{
ExpandTo, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
MacroFileIdExt,
attrs::{Attr, AttrId}, attrs::{Attr, AttrId},
builtin::{find_builtin_attr, find_builtin_derive, find_builtin_macro}, builtin::{find_builtin_attr, find_builtin_derive, find_builtin_macro},
name::{AsName, Name}, name::{AsName, Name},
proc_macro::CustomProcMacroExpander, proc_macro::CustomProcMacroExpander,
ExpandTo, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
MacroFileIdExt,
}; };
use intern::{sym, Interned}; use intern::{Interned, sym};
use itertools::{izip, Itertools}; use itertools::{Itertools, izip};
use la_arena::Idx; use la_arena::Idx;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use span::{Edition, EditionedFileId, FileAstId, SyntaxContext}; use span::{Edition, EditionedFileId, FileAstId, SyntaxContext};
@ -25,6 +25,12 @@ use syntax::ast;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
AdtId, AstId, AstIdWithPath, ConstLoc, CrateRootModuleId, EnumLoc, EnumVariantLoc,
ExternBlockLoc, ExternCrateId, ExternCrateLoc, FunctionId, FunctionLoc, ImplLoc, Intern,
ItemContainerId, LocalModuleId, Lookup, Macro2Id, Macro2Loc, MacroExpander, MacroId,
MacroRulesId, MacroRulesLoc, MacroRulesLocFlags, ModuleDefId, ModuleId, ProcMacroId,
ProcMacroLoc, StaticLoc, StructLoc, TraitAliasLoc, TraitLoc, TypeAliasLoc, UnionLoc,
UnresolvedMacro, UseId, UseLoc,
attr::Attrs, attr::Attrs,
db::DefDatabase, db::DefDatabase,
item_scope::{GlobId, ImportId, ImportOrExternCrate, PerNsGlobImports}, item_scope::{GlobId, ImportId, ImportOrExternCrate, PerNsGlobImports},
@ -34,24 +40,18 @@ use crate::{
}, },
macro_call_as_call_id, macro_call_as_call_id_with_eager, macro_call_as_call_id, macro_call_as_call_id_with_eager,
nameres::{ nameres::{
BuiltinShadowMode, DefMap, LocalDefMap, MacroSubNs, ModuleData, ModuleOrigin, ResolveMode,
attr_resolution::{attr_macro_as_call_id, derive_macro_as_call_id}, attr_resolution::{attr_macro_as_call_id, derive_macro_as_call_id},
diagnostics::DefDiagnostic, diagnostics::DefDiagnostic,
mod_resolution::ModDir, mod_resolution::ModDir,
path_resolution::ReachedFixedPoint, path_resolution::ReachedFixedPoint,
proc_macro::{parse_macro_name_and_helper_attrs, ProcMacroDef, ProcMacroKind}, proc_macro::{ProcMacroDef, ProcMacroKind, parse_macro_name_and_helper_attrs},
sub_namespace_match, BuiltinShadowMode, DefMap, LocalDefMap, MacroSubNs, ModuleData, sub_namespace_match,
ModuleOrigin, ResolveMode,
}, },
path::{ImportAlias, ModPath, PathKind}, path::{ImportAlias, ModPath, PathKind},
per_ns::{Item, PerNs}, per_ns::{Item, PerNs},
tt, tt,
visibility::{RawVisibility, Visibility}, visibility::{RawVisibility, Visibility},
AdtId, AstId, AstIdWithPath, ConstLoc, CrateRootModuleId, EnumLoc, EnumVariantLoc,
ExternBlockLoc, ExternCrateId, ExternCrateLoc, FunctionId, FunctionLoc, ImplLoc, Intern,
ItemContainerId, LocalModuleId, Lookup, Macro2Id, Macro2Loc, MacroExpander, MacroId,
MacroRulesId, MacroRulesLoc, MacroRulesLocFlags, ModuleDefId, ModuleId, ProcMacroId,
ProcMacroLoc, StaticLoc, StructLoc, TraitAliasLoc, TraitLoc, TypeAliasLoc, UnionLoc,
UnresolvedMacro, UseId, UseLoc,
}; };
const GLOB_RECURSION_LIMIT: usize = 100; const GLOB_RECURSION_LIMIT: usize = 100;

View file

@ -3,15 +3,15 @@
use std::ops::Not; use std::ops::Not;
use cfg::{CfgExpr, CfgOptions}; use cfg::{CfgExpr, CfgOptions};
use hir_expand::{attrs::AttrId, ExpandErrorKind, MacroCallKind}; use hir_expand::{ExpandErrorKind, MacroCallKind, attrs::AttrId};
use la_arena::Idx; use la_arena::Idx;
use syntax::ast; use syntax::ast;
use crate::{ use crate::{
AstId,
item_tree::{self, AttrOwner, ItemTreeId, TreeId}, item_tree::{self, AttrOwner, ItemTreeId, TreeId},
nameres::LocalModuleId, nameres::LocalModuleId,
path::ModPath, path::ModPath,
AstId,
}; };
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]

View file

@ -1,10 +1,10 @@
//! This module resolves `mod foo;` declaration to file. //! This module resolves `mod foo;` declaration to file.
use arrayvec::ArrayVec; use arrayvec::ArrayVec;
use base_db::{AnchoredPath, RootQueryDb}; use base_db::{AnchoredPath, RootQueryDb};
use hir_expand::{name::Name, HirFileIdExt}; use hir_expand::{HirFileIdExt, name::Name};
use span::EditionedFileId; use span::EditionedFileId;
use crate::{db::DefDatabase, HirFileId}; use crate::{HirFileId, db::DefDatabase};
const MOD_DEPTH_LIMIT: usize = 32; const MOD_DEPTH_LIMIT: usize = 32;

View file

@ -11,19 +11,19 @@
//! `ReachedFixedPoint` signals about this. //! `ReachedFixedPoint` signals about this.
use either::Either; use either::Either;
use hir_expand::{name::Name, Lookup}; use hir_expand::{Lookup, name::Name};
use span::Edition; use span::Edition;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
AdtId, LocalModuleId, ModuleDefId,
db::DefDatabase, db::DefDatabase,
item_scope::{ImportOrExternCrate, BUILTIN_SCOPE}, item_scope::{BUILTIN_SCOPE, ImportOrExternCrate},
item_tree::FieldsShape, item_tree::FieldsShape,
nameres::{sub_namespace_match, BlockInfo, BuiltinShadowMode, DefMap, LocalDefMap, MacroSubNs}, nameres::{BlockInfo, BuiltinShadowMode, DefMap, LocalDefMap, MacroSubNs, sub_namespace_match},
path::{ModPath, PathKind}, path::{ModPath, PathKind},
per_ns::PerNs, per_ns::PerNs,
visibility::{RawVisibility, Visibility}, visibility::{RawVisibility, Visibility},
AdtId, LocalModuleId, ModuleDefId,
}; };
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@ -356,7 +356,7 @@ impl DefMap {
PathKind::Abs => match self.resolve_path_abs(local_def_map, &mut segments, path) { PathKind::Abs => match self.resolve_path_abs(local_def_map, &mut segments, path) {
Either::Left(it) => it, Either::Left(it) => it,
Either::Right(reached_fixed_point) => { Either::Right(reached_fixed_point) => {
return ResolvePathResult::empty(reached_fixed_point) return ResolvePathResult::empty(reached_fixed_point);
} }
}, },
}; };
@ -402,11 +402,11 @@ impl DefMap {
PathKind::Abs => match self.resolve_path_abs(local_def_map, &mut segments, path) { PathKind::Abs => match self.resolve_path_abs(local_def_map, &mut segments, path) {
Either::Left(it) => it, Either::Left(it) => it,
Either::Right(reached_fixed_point) => { Either::Right(reached_fixed_point) => {
return ResolvePathResult::empty(reached_fixed_point) return ResolvePathResult::empty(reached_fixed_point);
} }
}, },
PathKind::DollarCrate(_) | PathKind::Crate | PathKind::Super(_) => { PathKind::DollarCrate(_) | PathKind::Crate | PathKind::Super(_) => {
return ResolvePathResult::empty(ReachedFixedPoint::Yes) return ResolvePathResult::empty(ReachedFixedPoint::Yes);
} }
}; };

View file

@ -5,7 +5,7 @@ mod mod_resolution;
mod primitives; mod primitives;
use base_db::RootQueryDb; use base_db::RootQueryDb;
use expect_test::{expect, Expect}; use expect_test::{Expect, expect};
use test_fixture::WithFixture; use test_fixture::WithFixture;
use triomphe::Arc; use triomphe::Arc;

View file

@ -7,7 +7,7 @@ use span::Edition;
use test_fixture::WithFixture; use test_fixture::WithFixture;
use triomphe::Arc; use triomphe::Arc;
use crate::{db::DefDatabase, nameres::tests::TestDB, AdtId, ModuleDefId}; use crate::{AdtId, ModuleDefId, db::DefDatabase, nameres::tests::TestDB};
fn check_def_map_is_not_recomputed(ra_fixture_initial: &str, ra_fixture_change: &str) { fn check_def_map_is_not_recomputed(ra_fixture_initial: &str, ra_fixture_change: &str) {
let (mut db, pos) = TestDB::with_position(ra_fixture_initial); let (mut db, pos) = TestDB::with_position(ra_fixture_initial);

View file

@ -19,7 +19,7 @@ use span::Edition;
use stdx::thin_vec::thin_vec_with_header_struct; use stdx::thin_vec::thin_vec_with_header_struct;
use syntax::ast; use syntax::ast;
pub use hir_expand::mod_path::{path, ModPath, PathKind}; pub use hir_expand::mod_path::{ModPath, PathKind, path};
pub use lower::hir_segment_to_ast_segment; pub use lower::hir_segment_to_ast_segment;

View file

@ -8,7 +8,7 @@ use hir_expand::{
mod_path::resolve_crate_root, mod_path::resolve_crate_root,
name::{AsName, Name}, name::{AsName, Name},
}; };
use intern::{sym, Interned}; use intern::{Interned, sym};
use stdx::thin_vec::EmptyOptimizedThinVec; use stdx::thin_vec::EmptyOptimizedThinVec;
use syntax::ast::{self, AstNode, HasGenericArgs, HasTypeBounds}; use syntax::ast::{self, AstNode, HasGenericArgs, HasTypeBounds};

View file

@ -1,4 +1,4 @@
use expect_test::{expect, Expect}; use expect_test::{Expect, expect};
use span::Edition; use span::Edition;
use syntax::ast::{self, make}; use syntax::ast::{self, make};
use test_fixture::WithFixture; use test_fixture::WithFixture;
@ -6,8 +6,8 @@ use test_fixture::WithFixture;
use crate::{ use crate::{
lower::LowerCtx, lower::LowerCtx,
path::{ path::{
lower::{hir_segment_to_ast_segment, SEGMENT_LOWERING_MAP},
Path, Path,
lower::{SEGMENT_LOWERING_MAP, hir_segment_to_ast_segment},
}, },
pretty, pretty,
test_db::TestDB, test_db::TestDB,

View file

@ -6,9 +6,9 @@
use bitflags::bitflags; use bitflags::bitflags;
use crate::{ use crate::{
MacroId, ModuleDefId,
item_scope::{ImportId, ImportOrExternCrate, ImportOrGlob, ItemInNs}, item_scope::{ImportId, ImportOrExternCrate, ImportOrGlob, ItemInNs},
visibility::Visibility, visibility::Visibility,
MacroId, ModuleDefId,
}; };
#[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)] #[derive(PartialEq, Eq, Hash, Copy, Clone, Debug)]
@ -146,11 +146,7 @@ impl PerNs {
} }
pub fn or_else(self, f: impl FnOnce() -> PerNs) -> PerNs { pub fn or_else(self, f: impl FnOnce() -> PerNs) -> PerNs {
if self.is_full() { if self.is_full() { self } else { self.or(f()) }
self
} else {
self.or(f())
}
} }
pub fn iter_items(self) -> impl Iterator<Item = (ItemInNs, Option<ImportOrExternCrate>)> { pub fn iter_items(self) -> impl Iterator<Item = (ItemInNs, Option<ImportOrExternCrate>)> {

View file

@ -2,36 +2,36 @@
use std::{fmt, iter, mem}; use std::{fmt, iter, mem};
use base_db::Crate; use base_db::Crate;
use hir_expand::{name::Name, MacroDefId}; use hir_expand::{MacroDefId, name::Name};
use intern::{sym, Symbol}; use intern::{Symbol, sym};
use itertools::Itertools as _; use itertools::Itertools as _;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use smallvec::{smallvec, SmallVec}; use smallvec::{SmallVec, smallvec};
use span::SyntaxContext; use span::SyntaxContext;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
AdtId, ConstId, ConstParamId, CrateRootModuleId, DefWithBodyId, EnumId, EnumVariantId,
ExternBlockId, ExternCrateId, FunctionId, FxIndexMap, GenericDefId, GenericParamId, HasModule,
ImplId, ItemContainerId, ItemTreeLoc, LifetimeParamId, LocalModuleId, Lookup, Macro2Id,
MacroId, MacroRulesId, ModuleDefId, ModuleId, ProcMacroId, StaticId, StructId, TraitAliasId,
TraitId, TypeAliasId, TypeOrConstParamId, TypeOwnerId, TypeParamId, UseId, VariantId,
builtin_type::BuiltinType, builtin_type::BuiltinType,
data::ExternCrateDeclData, data::ExternCrateDeclData,
db::DefDatabase, db::DefDatabase,
expr_store::{ expr_store::{
scope::{ExprScopes, ScopeId},
HygieneId, HygieneId,
scope::{ExprScopes, ScopeId},
}, },
generics::{GenericParams, TypeOrConstParamData}, generics::{GenericParams, TypeOrConstParamData},
hir::{BindingId, ExprId, LabelId}, hir::{BindingId, ExprId, LabelId},
item_scope::{BuiltinShadowMode, ImportOrExternCrate, ImportOrGlob, BUILTIN_SCOPE}, item_scope::{BUILTIN_SCOPE, BuiltinShadowMode, ImportOrExternCrate, ImportOrGlob},
lang_item::LangItemTarget, lang_item::LangItemTarget,
nameres::{DefMap, LocalDefMap, MacroSubNs, ResolvePathResultPrefixInfo}, nameres::{DefMap, LocalDefMap, MacroSubNs, ResolvePathResultPrefixInfo},
path::{ModPath, Path, PathKind}, path::{ModPath, Path, PathKind},
per_ns::PerNs, per_ns::PerNs,
type_ref::{LifetimeRef, TypesMap}, type_ref::{LifetimeRef, TypesMap},
visibility::{RawVisibility, Visibility}, visibility::{RawVisibility, Visibility},
AdtId, ConstId, ConstParamId, CrateRootModuleId, DefWithBodyId, EnumId, EnumVariantId,
ExternBlockId, ExternCrateId, FunctionId, FxIndexMap, GenericDefId, GenericParamId, HasModule,
ImplId, ItemContainerId, ItemTreeLoc, LifetimeParamId, LocalModuleId, Lookup, Macro2Id,
MacroId, MacroRulesId, ModuleDefId, ModuleId, ProcMacroId, StaticId, StructId, TraitAliasId,
TraitId, TypeAliasId, TypeOrConstParamId, TypeOwnerId, TypeParamId, UseId, VariantId,
}; };
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -209,11 +209,7 @@ impl Resolver {
} }
let remaining_idx = || { let remaining_idx = || {
if path.segments().len() == 1 { if path.segments().len() == 1 { None } else { Some(1) }
None
} else {
Some(1)
}
}; };
for scope in self.scopes() { for scope in self.scopes() {

View file

@ -3,13 +3,13 @@
use either::Either; use either::Either;
use hir_expand::InFile; use hir_expand::InFile;
use la_arena::ArenaMap; use la_arena::ArenaMap;
use syntax::{ast, AstNode, AstPtr}; use syntax::{AstNode, AstPtr, ast};
use crate::{ use crate::{
db::DefDatabase,
item_tree::{AttrOwner, FieldParent, ItemTreeNode},
GenericDefId, ItemTreeLoc, LocalFieldId, LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup, GenericDefId, ItemTreeLoc, LocalFieldId, LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup,
UseId, VariantId, UseId, VariantId,
db::DefDatabase,
item_tree::{AttrOwner, FieldParent, ItemTreeNode},
}; };
pub trait HasSource { pub trait HasSource {

View file

@ -6,17 +6,17 @@ use base_db::{
Crate, CrateGraphBuilder, CratesMap, FileSourceRootInput, FileText, RootQueryDb, Crate, CrateGraphBuilder, CratesMap, FileSourceRootInput, FileText, RootQueryDb,
SourceDatabase, SourceRoot, SourceRootId, SourceRootInput, Upcast, SourceDatabase, SourceRoot, SourceRootId, SourceRootInput, Upcast,
}; };
use hir_expand::{db::ExpandDatabase, files::FilePosition, InFile}; use hir_expand::{InFile, db::ExpandDatabase, files::FilePosition};
use salsa::{AsDynDatabase, Durability}; use salsa::{AsDynDatabase, Durability};
use span::{EditionedFileId, FileId}; use span::{EditionedFileId, FileId};
use syntax::{algo, ast, AstNode}; use syntax::{AstNode, algo, ast};
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
LocalModuleId, Lookup, ModuleDefId, ModuleId,
db::DefDatabase, db::DefDatabase,
nameres::{DefMap, ModuleSource}, nameres::{DefMap, ModuleSource},
src::HasSource, src::HasSource,
LocalModuleId, Lookup, ModuleDefId, ModuleId,
}; };
#[salsa::db] #[salsa::db]
@ -281,9 +281,9 @@ impl TestDB {
let editioned_file_id_wrapper = let editioned_file_id_wrapper =
base_db::EditionedFileId::new(db.as_dyn_database(), position.file_id); base_db::EditionedFileId::new(db.as_dyn_database(), position.file_id);
let root = db.parse(editioned_file_id_wrapper); let root_syntax_node = db.parse(editioned_file_id_wrapper).syntax_node();
let scope_iter = algo::ancestors_at_offset(&root.syntax_node(), position.offset) let scope_iter =
.filter_map(|node| { algo::ancestors_at_offset(&root_syntax_node, position.offset).filter_map(|node| {
let block = ast::BlockExpr::cast(node)?; let block = ast::BlockExpr::cast(node)?;
let expr = ast::Expr::from(block); let expr = ast::Expr::from(block);
let expr_id = source_map let expr_id = source_map

View file

@ -9,11 +9,11 @@ use syntax::ast;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
ConstId, FunctionId, HasModule, LocalFieldId, LocalModuleId, ModuleId, VariantId,
db::DefDatabase, db::DefDatabase,
nameres::DefMap, nameres::DefMap,
path::{ModPath, PathKind}, path::{ModPath, PathKind},
resolver::HasResolver, resolver::HasResolver,
ConstId, FunctionId, HasModule, LocalFieldId, LocalModuleId, ModuleId, VariantId,
}; };
/// Visibility of an item, not yet resolved. /// Visibility of an item, not yet resolved.

View file

@ -4,23 +4,23 @@ use std::{borrow::Cow, fmt, ops};
use base_db::Crate; use base_db::Crate;
use cfg::CfgExpr; use cfg::CfgExpr;
use either::Either; use either::Either;
use intern::{sym, Interned, Symbol}; use intern::{Interned, Symbol, sym};
use mbe::{DelimiterKind, Punct}; use mbe::{DelimiterKind, Punct};
use smallvec::{smallvec, SmallVec}; use smallvec::{SmallVec, smallvec};
use span::{Span, SyntaxContext}; use span::{Span, SyntaxContext};
use syntax::unescape; use syntax::unescape;
use syntax::{ast, match_ast, AstNode, AstToken, SyntaxNode}; use syntax::{AstNode, AstToken, SyntaxNode, ast, match_ast};
use syntax_bridge::{desugar_doc_comment_text, syntax_node_to_token_tree, DocCommentDesugarMode}; use syntax_bridge::{DocCommentDesugarMode, desugar_doc_comment_text, syntax_node_to_token_tree};
use triomphe::ThinArc; use triomphe::ThinArc;
use crate::name::Name; use crate::name::Name;
use crate::{ use crate::{
InFile,
db::ExpandDatabase, db::ExpandDatabase,
mod_path::ModPath, mod_path::ModPath,
span_map::SpanMapRef, span_map::SpanMapRef,
tt::{self, token_to_literal, TopSubtree}, tt::{self, TopSubtree, token_to_literal},
InFile,
}; };
/// Syntactical attributes, without filtering of `cfg_attr`s. /// Syntactical attributes, without filtering of `cfg_attr`s.

View file

@ -7,9 +7,9 @@ mod derive_macro;
mod fn_macro; mod fn_macro;
pub use self::{ pub use self::{
attr_macro::{find_builtin_attr, pseudo_derive_attr_expansion, BuiltinAttrExpander}, attr_macro::{BuiltinAttrExpander, find_builtin_attr, pseudo_derive_attr_expansion},
derive_macro::{find_builtin_derive, BuiltinDeriveExpander}, derive_macro::{BuiltinDeriveExpander, find_builtin_derive},
fn_macro::{ fn_macro::{
find_builtin_macro, include_input_to_file_id, BuiltinFnLikeExpander, EagerExpander, BuiltinFnLikeExpander, EagerExpander, find_builtin_macro, include_input_to_file_id,
}, },
}; };

View file

@ -2,7 +2,7 @@
use intern::sym; use intern::sym;
use span::{MacroCallId, Span}; use span::{MacroCallId, Span};
use crate::{db::ExpandDatabase, name, tt, ExpandResult, MacroCallKind}; use crate::{ExpandResult, MacroCallKind, db::ExpandDatabase, name, tt};
use super::quote; use super::quote;
@ -130,7 +130,7 @@ fn derive_expand(
return ExpandResult::ok(tt::TopSubtree::empty(tt::DelimSpan { return ExpandResult::ok(tt::TopSubtree::empty(tt::DelimSpan {
open: span, open: span,
close: span, close: span,
})) }));
} }
}; };
pseudo_derive_attr_expansion(tt, derives, span) pseudo_derive_attr_expansion(tt, derives, span)

View file

@ -1,7 +1,7 @@
//! Builtin derives. //! Builtin derives.
use intern::sym; use intern::sym;
use itertools::{izip, Itertools}; use itertools::{Itertools, izip};
use parser::SyntaxKind; use parser::SyntaxKind;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use span::{Edition, MacroCallId, Span, SyntaxContext}; use span::{Edition, MacroCallId, Span, SyntaxContext};
@ -10,17 +10,18 @@ use syntax_bridge::DocCommentDesugarMode;
use tracing::debug; use tracing::debug;
use crate::{ use crate::{
ExpandError, ExpandResult,
builtin::quote::{dollar_crate, quote}, builtin::quote::{dollar_crate, quote},
db::ExpandDatabase, db::ExpandDatabase,
hygiene::span_with_def_site_ctxt, hygiene::span_with_def_site_ctxt,
name::{self, AsName, Name}, name::{self, AsName, Name},
span_map::ExpansionSpanMap, span_map::ExpansionSpanMap,
tt, ExpandError, ExpandResult, tt,
}; };
use syntax::{ use syntax::{
ast::{ ast::{
self, edit_in_place::GenericParamsOwnerEdit, make, AstNode, FieldList, HasAttrs, self, AstNode, FieldList, HasAttrs, HasGenericArgs, HasGenericParams, HasModuleItem,
HasGenericArgs, HasGenericParams, HasModuleItem, HasName, HasTypeBounds, HasName, HasTypeBounds, edit_in_place::GenericParamsOwnerEdit, make,
}, },
ted, ted,
}; };
@ -117,7 +118,7 @@ impl VariantShape {
quote! {span => #it : #mapped , } quote! {span => #it : #mapped , }
}); });
quote! {span => quote! {span =>
#path { ##fields } #path { # #fields }
} }
} }
&VariantShape::Tuple(n) => { &VariantShape::Tuple(n) => {
@ -128,7 +129,7 @@ impl VariantShape {
} }
}); });
quote! {span => quote! {span =>
#path ( ##fields ) #path ( # #fields )
} }
} }
VariantShape::Unit => path, VariantShape::Unit => path,
@ -464,7 +465,7 @@ fn expand_simple_derive(
return ExpandResult::new( return ExpandResult::new(
tt::TopSubtree::empty(tt::DelimSpan { open: invoc_span, close: invoc_span }), tt::TopSubtree::empty(tt::DelimSpan { open: invoc_span, close: invoc_span }),
e, e,
) );
} }
}; };
ExpandResult::ok(expand_simple_derive_with_parsed( ExpandResult::ok(expand_simple_derive_with_parsed(
@ -523,7 +524,7 @@ fn expand_simple_derive_with_parsed(
let name = info.name; let name = info.name;
quote! {invoc_span => quote! {invoc_span =>
impl < ##params #extra_impl_params > #trait_path for #name < ##args > where ##where_block { #trait_body } impl < # #params #extra_impl_params > #trait_path for #name < # #args > where # #where_block { #trait_body }
} }
} }
@ -572,7 +573,7 @@ fn clone_expand(
quote! {span => quote! {span =>
fn clone(&self) -> Self { fn clone(&self) -> Self {
match self { match self {
##arms # #arms
} }
} }
} }
@ -650,7 +651,7 @@ fn debug_expand(
} }
}); });
quote! {span => quote! {span =>
f.debug_struct(#name) ##for_fields .finish() f.debug_struct(#name) # #for_fields .finish()
} }
} }
VariantShape::Tuple(n) => { VariantShape::Tuple(n) => {
@ -660,7 +661,7 @@ fn debug_expand(
} }
}); });
quote! {span => quote! {span =>
f.debug_tuple(#name) ##for_fields .finish() f.debug_tuple(#name) # #for_fields .finish()
} }
} }
VariantShape::Unit => quote! {span => VariantShape::Unit => quote! {span =>
@ -703,7 +704,7 @@ fn debug_expand(
quote! {span => quote! {span =>
fn fmt(&self, f: &mut #krate::fmt::Formatter) -> #krate::fmt::Result { fn fmt(&self, f: &mut #krate::fmt::Formatter) -> #krate::fmt::Result {
match self { match self {
##arms # #arms
} }
} }
} }
@ -736,7 +737,7 @@ fn hash_expand(
let it = let it =
names.iter().map(|it| quote! {span => #it . hash(ra_expand_state); }); names.iter().map(|it| quote! {span => #it . hash(ra_expand_state); });
quote! {span => { quote! {span => {
##it # #it
} } } }
}; };
let fat_arrow = fat_arrow(span); let fat_arrow = fat_arrow(span);
@ -754,7 +755,7 @@ fn hash_expand(
fn hash<H: #krate::hash::Hasher>(&self, ra_expand_state: &mut H) { fn hash<H: #krate::hash::Hasher>(&self, ra_expand_state: &mut H) {
#check_discriminant #check_discriminant
match self { match self {
##arms # #arms
} }
} }
} }
@ -803,7 +804,7 @@ fn partial_eq_expand(
let t2 = tt::Ident::new(&format!("{}_other", first.sym), first.span); let t2 = tt::Ident::new(&format!("{}_other", first.sym), first.span);
quote!(span =>#t1 .eq( #t2 )) quote!(span =>#t1 .eq( #t2 ))
}; };
quote!(span =>#first ##rest) quote!(span =>#first # #rest)
} }
}; };
quote! {span => ( #pat1 , #pat2 ) #fat_arrow #body , } quote! {span => ( #pat1 , #pat2 ) #fat_arrow #body , }
@ -814,7 +815,7 @@ fn partial_eq_expand(
quote! {span => quote! {span =>
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
match (self, other) { match (self, other) {
##arms # #arms
_unused #fat_arrow false _unused #fat_arrow false
} }
} }
@ -891,7 +892,7 @@ fn ord_expand(
let fat_arrow = fat_arrow(span); let fat_arrow = fat_arrow(span);
let mut body = quote! {span => let mut body = quote! {span =>
match (self, other) { match (self, other) {
##arms # #arms
_unused #fat_arrow #krate::cmp::Ordering::Equal _unused #fat_arrow #krate::cmp::Ordering::Equal
} }
}; };
@ -961,7 +962,7 @@ fn partial_ord_expand(
right, right,
quote! {span => quote! {span =>
match (self, other) { match (self, other) {
##arms # #arms
_unused #fat_arrow #krate::option::Option::Some(#krate::cmp::Ordering::Equal) _unused #fat_arrow #krate::option::Option::Some(#krate::cmp::Ordering::Equal)
} }
}, },
@ -1072,7 +1073,7 @@ fn coerce_pointee_expand(
"exactly one generic type parameter must be marked \ "exactly one generic type parameter must be marked \
as `#[pointee]` to derive `CoercePointee` traits", as `#[pointee]` to derive `CoercePointee` traits",
), ),
) );
} }
(Some(_), Some(_)) => { (Some(_), Some(_)) => {
return ExpandResult::new( return ExpandResult::new(
@ -1082,7 +1083,7 @@ fn coerce_pointee_expand(
"only one type parameter can be marked as `#[pointee]` \ "only one type parameter can be marked as `#[pointee]` \
when deriving `CoercePointee` traits", when deriving `CoercePointee` traits",
), ),
) );
} }
} }
}; };
@ -1120,7 +1121,9 @@ fn coerce_pointee_expand(
tt::TopSubtree::empty(tt::DelimSpan::from_single(span)), tt::TopSubtree::empty(tt::DelimSpan::from_single(span)),
ExpandError::other( ExpandError::other(
span, span,
format!("`derive(CoercePointee)` requires `{pointee_param_name}` to be marked `?Sized`"), format!(
"`derive(CoercePointee)` requires `{pointee_param_name}` to be marked `?Sized`"
),
), ),
); );
} }
@ -1335,7 +1338,7 @@ fn coerce_pointee_expand(
let info = match parse_adt_from_syntax(&adt, &span_map, span) { let info = match parse_adt_from_syntax(&adt, &span_map, span) {
Ok(it) => it, Ok(it) => it,
Err(err) => { Err(err) => {
return ExpandResult::new(tt::TopSubtree::empty(tt::DelimSpan::from_single(span)), err) return ExpandResult::new(tt::TopSubtree::empty(tt::DelimSpan::from_single(span)), err);
} }
}; };

View file

@ -4,26 +4,26 @@ use base_db::AnchoredPath;
use cfg::CfgExpr; use cfg::CfgExpr;
use either::Either; use either::Either;
use intern::{ use intern::{
sym::{self},
Symbol, Symbol,
sym::{self},
}; };
use mbe::{expect_fragment, DelimiterKind}; use mbe::{DelimiterKind, expect_fragment};
use span::{Edition, EditionedFileId, FileId, Span}; use span::{Edition, EditionedFileId, FileId, Span};
use stdx::format_to; use stdx::format_to;
use syntax::{ use syntax::{
format_smolstr, format_smolstr,
unescape::{unescape_byte, unescape_char, unescape_unicode, Mode}, unescape::{Mode, unescape_byte, unescape_char, unescape_unicode},
}; };
use syntax_bridge::syntax_node_to_token_tree; use syntax_bridge::syntax_node_to_token_tree;
use crate::{ use crate::{
builtin::quote::{dollar_crate, quote, WithDelimiter}, ExpandError, ExpandResult, HirFileIdExt, Lookup as _, MacroCallId,
builtin::quote::{WithDelimiter, dollar_crate, quote},
db::ExpandDatabase, db::ExpandDatabase,
hygiene::{span_with_call_site_ctxt, span_with_def_site_ctxt}, hygiene::{span_with_call_site_ctxt, span_with_def_site_ctxt},
name, name,
span_map::SpanMap, span_map::SpanMap,
tt::{self, DelimSpan, TtElement, TtIter}, tt::{self, DelimSpan, TtElement, TtIter},
ExpandError, ExpandResult, HirFileIdExt, Lookup as _, MacroCallId,
}; };
macro_rules! register_builtin { macro_rules! register_builtin {
@ -240,9 +240,9 @@ fn assert_expand(
let dollar_crate = dollar_crate(span); let dollar_crate = dollar_crate(span);
let panic_args = rest.iter(); let panic_args = rest.iter();
let mac = if use_panic_2021(db, span) { let mac = if use_panic_2021(db, span) {
quote! {call_site_span => #dollar_crate::panic::panic_2021!(##panic_args) } quote! {call_site_span => #dollar_crate::panic::panic_2021!(# #panic_args) }
} else { } else {
quote! {call_site_span => #dollar_crate::panic!(##panic_args) } quote! {call_site_span => #dollar_crate::panic!(# #panic_args) }
}; };
let value = cond.value; let value = cond.value;
let expanded = quote! {call_site_span =>{ let expanded = quote! {call_site_span =>{
@ -427,12 +427,15 @@ fn compile_error_expand(
span: Span, span: Span,
) -> ExpandResult<tt::TopSubtree> { ) -> ExpandResult<tt::TopSubtree> {
let err = match &*tt.0 { let err = match &*tt.0 {
[_, tt::TokenTree::Leaf(tt::Leaf::Literal(tt::Literal { [
symbol: text, _,
span: _, tt::TokenTree::Leaf(tt::Leaf::Literal(tt::Literal {
kind: tt::LitKind::Str | tt::LitKind::StrRaw(_), symbol: text,
suffix: _, span: _,
}))] => ExpandError::other(span, Box::from(unescape_str(text).as_str())), kind: tt::LitKind::Str | tt::LitKind::StrRaw(_),
suffix: _,
})),
] => ExpandError::other(span, Box::from(unescape_str(text).as_str())),
_ => ExpandError::other(span, "`compile_error!` argument must be a string"), _ => ExpandError::other(span, "`compile_error!` argument must be a string"),
}; };
@ -736,7 +739,7 @@ fn include_expand(
return ExpandResult::new( return ExpandResult::new(
tt::TopSubtree::empty(DelimSpan { open: span, close: span }), tt::TopSubtree::empty(DelimSpan { open: span, close: span }),
e, e,
) );
} }
}; };
let span_map = db.real_span_map(editioned_file_id); let span_map = db.real_span_map(editioned_file_id);
@ -789,7 +792,7 @@ fn include_str_expand(
return ExpandResult::new( return ExpandResult::new(
tt::TopSubtree::empty(DelimSpan { open: span, close: span }), tt::TopSubtree::empty(DelimSpan { open: span, close: span }),
e, e,
) );
} }
}; };
@ -827,7 +830,7 @@ fn env_expand(
return ExpandResult::new( return ExpandResult::new(
tt::TopSubtree::empty(DelimSpan { open: span, close: span }), tt::TopSubtree::empty(DelimSpan { open: span, close: span }),
e, e,
) );
} }
}; };
@ -865,7 +868,7 @@ fn option_env_expand(
return ExpandResult::new( return ExpandResult::new(
tt::TopSubtree::empty(DelimSpan { open: call_site, close: call_site }), tt::TopSubtree::empty(DelimSpan { open: call_site, close: call_site }),
e, e,
) );
} }
}; };
let dollar_crate = dollar_crate(call_site); let dollar_crate = dollar_crate(call_site);

View file

@ -1,7 +1,7 @@
//! A simplified version of quote-crate like quasi quote macro //! A simplified version of quote-crate like quasi quote macro
#![allow(clippy::crate_in_macro_def)] #![allow(clippy::crate_in_macro_def)]
use intern::{sym, Symbol}; use intern::{Symbol, sym};
use span::Span; use span::Span;
use syntax::ToSmolStr; use syntax::ToSmolStr;
use tt::IdentIsRaw; use tt::IdentIsRaw;
@ -61,7 +61,7 @@ macro_rules! quote_impl__ {
$crate::builtin::quote::__quote!($span $builder $($tail)*); $crate::builtin::quote::__quote!($span $builder $($tail)*);
}; };
($span:ident $builder:ident ## $first:ident $($tail:tt)* ) => {{ ($span:ident $builder:ident # # $first:ident $($tail:tt)* ) => {{
::std::iter::IntoIterator::into_iter($first).for_each(|it| $crate::builtin::quote::ToTokenTree::to_tokens(it, $span, $builder)); ::std::iter::IntoIterator::into_iter($first).for_each(|it| $crate::builtin::quote::ToTokenTree::to_tokens(it, $span, $builder));
$crate::builtin::quote::__quote!($span $builder $($tail)*); $crate::builtin::quote::__quote!($span $builder $($tail)*);
}}; }};
@ -226,7 +226,7 @@ mod tests {
use ::tt::IdentIsRaw; use ::tt::IdentIsRaw;
use expect_test::expect; use expect_test::expect;
use intern::Symbol; use intern::Symbol;
use span::{Edition, SpanAnchor, SyntaxContext, ROOT_ERASED_FILE_AST_ID}; use span::{Edition, ROOT_ERASED_FILE_AST_ID, SpanAnchor, SyntaxContext};
use syntax::{TextRange, TextSize}; use syntax::{TextRange, TextSize};
use super::quote; use super::quote;
@ -324,6 +324,9 @@ mod tests {
} }
}; };
assert_eq!(quoted.to_string(), "impl Clone for Foo {fn clone (& self) -> Self {Self {name : self . name . clone () , id : self . id . clone () ,}}}"); assert_eq!(
quoted.to_string(),
"impl Clone for Foo {fn clone (& self) -> Self {Self {name : self . name . clone () , id : self . id . clone () ,}}}"
);
} }
} }

View file

@ -3,15 +3,15 @@ use std::iter::Peekable;
use base_db::Crate; use base_db::Crate;
use cfg::{CfgAtom, CfgExpr}; use cfg::{CfgAtom, CfgExpr};
use intern::{sym, Symbol}; use intern::{Symbol, sym};
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use syntax::{ use syntax::{
ast::{self, Attr, HasAttrs, Meta, TokenTree, VariantList},
AstNode, NodeOrToken, SyntaxElement, SyntaxKind, SyntaxNode, T, AstNode, NodeOrToken, SyntaxElement, SyntaxKind, SyntaxNode, T,
ast::{self, Attr, HasAttrs, Meta, TokenTree, VariantList},
}; };
use tracing::{debug, warn}; use tracing::{debug, warn};
use crate::{db::ExpandDatabase, proc_macro::ProcMacroKind, MacroCallLoc, MacroDefKind}; use crate::{MacroCallLoc, MacroDefKind, db::ExpandDatabase, proc_macro::ProcMacroKind};
fn check_cfg(db: &dyn ExpandDatabase, attr: &Attr, krate: Crate) -> Option<bool> { fn check_cfg(db: &dyn ExpandDatabase, attr: &Attr, krate: Crate) -> Option<bool> {
if !attr.simple_name().as_deref().map(|v| v == "cfg")? { if !attr.simple_name().as_deref().map(|v| v == "cfg")? {
@ -344,8 +344,8 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use cfg::DnfExpr; use cfg::DnfExpr;
use expect_test::{expect, Expect}; use expect_test::{Expect, expect};
use syntax::{ast::Attr, AstNode, SourceFile}; use syntax::{AstNode, SourceFile, ast::Attr};
use crate::cfg_process::parse_from_attr_token_tree; use crate::cfg_process::parse_from_attr_token_tree;

View file

@ -9,25 +9,26 @@ use span::{
AstIdMap, Edition, EditionedFileId, HirFileId, HirFileIdRepr, MacroCallId, MacroFileId, Span, AstIdMap, Edition, EditionedFileId, HirFileId, HirFileIdRepr, MacroCallId, MacroFileId, Span,
SyntaxContext, SyntaxContext,
}; };
use syntax::{ast, AstNode, Parse, SyntaxElement, SyntaxError, SyntaxNode, SyntaxToken, T}; use syntax::{AstNode, Parse, SyntaxElement, SyntaxError, SyntaxNode, SyntaxToken, T, ast};
use syntax_bridge::{syntax_node_to_token_tree, DocCommentDesugarMode}; use syntax_bridge::{DocCommentDesugarMode, syntax_node_to_token_tree};
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
attrs::{collect_attrs, AttrId}, AstId, BuiltinAttrExpander, BuiltinDeriveExpander, BuiltinFnLikeExpander, EagerCallInfo,
EagerExpander, ExpandError, ExpandResult, ExpandTo, MacroCallKind, MacroCallLoc, MacroDefId,
MacroDefKind,
attrs::{AttrId, collect_attrs},
builtin::pseudo_derive_attr_expansion, builtin::pseudo_derive_attr_expansion,
cfg_process, cfg_process,
declarative::DeclarativeMacroExpander, declarative::DeclarativeMacroExpander,
fixup::{self, SyntaxFixupUndoInfo}, fixup::{self, SyntaxFixupUndoInfo},
hygiene::{ hygiene::{
span_with_call_site_ctxt, span_with_def_site_ctxt, span_with_mixed_site_ctxt, SyntaxContextExt as _, span_with_call_site_ctxt, span_with_def_site_ctxt,
SyntaxContextExt as _, span_with_mixed_site_ctxt,
}, },
proc_macro::{CrateProcMacros, CustomProcMacroExpander, ProcMacros}, proc_macro::{CrateProcMacros, CustomProcMacroExpander, ProcMacros},
span_map::{ExpansionSpanMap, RealSpanMap, SpanMap, SpanMapRef}, span_map::{ExpansionSpanMap, RealSpanMap, SpanMap, SpanMapRef},
tt, AstId, BuiltinAttrExpander, BuiltinDeriveExpander, BuiltinFnLikeExpander, EagerCallInfo, tt,
EagerExpander, ExpandError, ExpandResult, ExpandTo, MacroCallKind, MacroCallLoc, MacroDefId,
MacroDefKind,
}; };
/// This is just to ensure the types of smart_macro_arg and macro_arg are the same /// This is just to ensure the types of smart_macro_arg and macro_arg are the same
type MacroArgResult = (Arc<tt::TopSubtree>, SyntaxFixupUndoInfo, Span); type MacroArgResult = (Arc<tt::TopSubtree>, SyntaxFixupUndoInfo, Span);
@ -397,11 +398,7 @@ fn parse_macro_expansion_error(
) -> Option<Arc<ExpandResult<Arc<[SyntaxError]>>>> { ) -> Option<Arc<ExpandResult<Arc<[SyntaxError]>>>> {
let e: ExpandResult<Arc<[SyntaxError]>> = let e: ExpandResult<Arc<[SyntaxError]>> =
db.parse_macro_expansion(MacroFileId { macro_call_id }).map(|it| Arc::from(it.0.errors())); db.parse_macro_expansion(MacroFileId { macro_call_id }).map(|it| Arc::from(it.0.errors()));
if e.value.is_empty() && e.err.is_none() { if e.value.is_empty() && e.err.is_none() { None } else { Some(Arc::new(e)) }
None
} else {
Some(Arc::new(e))
}
} }
pub(crate) fn parse_with_map( pub(crate) fn parse_with_map(

View file

@ -4,15 +4,16 @@ use base_db::Crate;
use intern::sym; use intern::sym;
use span::{Edition, HirFileIdRepr, MacroCallId, Span, SyntaxContext}; use span::{Edition, HirFileIdRepr, MacroCallId, Span, SyntaxContext};
use stdx::TupleExt; use stdx::TupleExt;
use syntax::{ast, AstNode}; use syntax::{AstNode, ast};
use syntax_bridge::DocCommentDesugarMode; use syntax_bridge::DocCommentDesugarMode;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
AstId, ExpandError, ExpandErrorKind, ExpandResult, Lookup,
attrs::RawAttrs, attrs::RawAttrs,
db::ExpandDatabase, db::ExpandDatabase,
hygiene::{apply_mark, Transparency}, hygiene::{Transparency, apply_mark},
tt, AstId, ExpandError, ExpandErrorKind, ExpandResult, Lookup, tt,
}; };
/// Old-style `macro_rules` or the new macros 2.0 /// Old-style `macro_rules` or the new macros 2.0

View file

@ -20,16 +20,16 @@
//! See the full discussion : <https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Eager.20expansion.20of.20built-in.20macros> //! See the full discussion : <https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Eager.20expansion.20of.20built-in.20macros>
use base_db::Crate; use base_db::Crate;
use span::SyntaxContext; use span::SyntaxContext;
use syntax::{ted, Parse, SyntaxElement, SyntaxNode, TextSize, WalkEvent}; use syntax::{Parse, SyntaxElement, SyntaxNode, TextSize, WalkEvent, ted};
use syntax_bridge::DocCommentDesugarMode; use syntax_bridge::DocCommentDesugarMode;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
AstId, EagerCallInfo, ExpandError, ExpandResult, ExpandTo, ExpansionSpanMap, InFile,
MacroCallId, MacroCallKind, MacroCallLoc, MacroDefId, MacroDefKind,
ast::{self, AstNode}, ast::{self, AstNode},
db::ExpandDatabase, db::ExpandDatabase,
mod_path::ModPath, mod_path::ModPath,
AstId, EagerCallInfo, ExpandError, ExpandResult, ExpandTo, ExpansionSpanMap, InFile,
MacroCallId, MacroCallKind, MacroCallLoc, MacroDefId, MacroDefKind,
}; };
pub fn expand_eager_macro_input( pub fn expand_eager_macro_input(

View file

@ -9,8 +9,9 @@ use span::{
use syntax::{AstNode, AstPtr, SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange, TextSize}; use syntax::{AstNode, AstPtr, SyntaxNode, SyntaxNodePtr, SyntaxToken, TextRange, TextSize};
use crate::{ use crate::{
MacroFileIdExt, MacroKind,
db::{self, ExpandDatabase}, db::{self, ExpandDatabase},
map_node_range_up, map_node_range_up_rooted, span_for_offset, MacroFileIdExt, MacroKind, map_node_range_up, map_node_range_up_rooted, span_for_offset,
}; };
/// `InFile<T>` stores a value of `T` inside a particular file/syntax tree. /// `InFile<T>` stores a value of `T` inside a particular file/syntax tree.
@ -365,11 +366,7 @@ impl InFile<SyntaxToken> {
// FIXME: Figure out an API that makes proper use of ctx, this only exists to // FIXME: Figure out an API that makes proper use of ctx, this only exists to
// keep pre-token map rewrite behaviour. // keep pre-token map rewrite behaviour.
if ctxt.is_root() { if ctxt.is_root() { Some(range) } else { None }
Some(range)
} else {
None
}
} }
} }
} }

View file

@ -4,13 +4,14 @@
use intern::sym; use intern::sym;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use span::{ use span::{
ErasedFileAstId, Span, SpanAnchor, SyntaxContext, FIXUP_ERASED_FILE_AST_ID_MARKER, ErasedFileAstId, FIXUP_ERASED_FILE_AST_ID_MARKER, ROOT_ERASED_FILE_AST_ID, Span, SpanAnchor,
ROOT_ERASED_FILE_AST_ID, SyntaxContext,
}; };
use stdx::never; use stdx::never;
use syntax::{ use syntax::{
SyntaxElement, SyntaxKind, SyntaxNode, TextRange, TextSize,
ast::{self, AstNode, HasLoopBody}, ast::{self, AstNode, HasLoopBody},
match_ast, SyntaxElement, SyntaxKind, SyntaxNode, TextRange, TextSize, match_ast,
}; };
use syntax_bridge::DocCommentDesugarMode; use syntax_bridge::DocCommentDesugarMode;
use triomphe::Arc; use triomphe::Arc;
@ -465,7 +466,7 @@ fn reverse_fixups_(tt: &mut TopSubtree, undo_info: &[TopSubtree]) {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use expect_test::{expect, Expect}; use expect_test::{Expect, expect};
use span::{Edition, EditionedFileId, FileId}; use span::{Edition, EditionedFileId, FileId};
use syntax::TextRange; use syntax::TextRange;
use syntax_bridge::DocCommentDesugarMode; use syntax_bridge::DocCommentDesugarMode;

View file

@ -147,7 +147,7 @@ pub trait SyntaxContextExt {
fn normalize_to_macros_2_0(self, db: &dyn ExpandDatabase) -> span::SyntaxContext; fn normalize_to_macros_2_0(self, db: &dyn ExpandDatabase) -> span::SyntaxContext;
fn parent_ctxt(self, db: &dyn ExpandDatabase) -> span::SyntaxContext; fn parent_ctxt(self, db: &dyn ExpandDatabase) -> span::SyntaxContext;
fn remove_mark(&mut self, db: &dyn ExpandDatabase) fn remove_mark(&mut self, db: &dyn ExpandDatabase)
-> (Option<span::MacroCallId>, Transparency); -> (Option<span::MacroCallId>, Transparency);
fn outer_mark(self, db: &dyn ExpandDatabase) -> (Option<span::MacroCallId>, Transparency); fn outer_mark(self, db: &dyn ExpandDatabase) -> (Option<span::MacroCallId>, Transparency);
fn marks(self, db: &dyn ExpandDatabase) -> Vec<(span::MacroCallId, Transparency)>; fn marks(self, db: &dyn ExpandDatabase) -> Vec<(span::MacroCallId, Transparency)>;
fn is_opaque(self, db: &dyn ExpandDatabase) -> bool; fn is_opaque(self, db: &dyn ExpandDatabase) -> bool;

View file

@ -40,15 +40,15 @@ use span::{
SyntaxContext, SyntaxContext,
}; };
use syntax::{ use syntax::{
ast::{self, AstNode},
SyntaxNode, SyntaxToken, TextRange, TextSize, SyntaxNode, SyntaxToken, TextRange, TextSize,
ast::{self, AstNode},
}; };
use crate::{ use crate::{
attrs::AttrId, attrs::AttrId,
builtin::{ builtin::{
include_input_to_file_id, BuiltinAttrExpander, BuiltinDeriveExpander, BuiltinAttrExpander, BuiltinDeriveExpander, BuiltinFnLikeExpander, EagerExpander,
BuiltinFnLikeExpander, EagerExpander, include_input_to_file_id,
}, },
db::ExpandDatabase, db::ExpandDatabase,
mod_path::ModPath, mod_path::ModPath,
@ -67,7 +67,7 @@ pub use span::{HirFileId, MacroCallId, MacroFileId};
pub mod tt { pub mod tt {
pub use span::Span; pub use span::Span;
pub use tt::{token_to_literal, DelimiterKind, IdentIsRaw, LitKind, Spacing}; pub use tt::{DelimiterKind, IdentIsRaw, LitKind, Spacing, token_to_literal};
pub type Delimiter = ::tt::Delimiter<Span>; pub type Delimiter = ::tt::Delimiter<Span>;
pub type DelimSpan = ::tt::DelimSpan<Span>; pub type DelimSpan = ::tt::DelimSpan<Span>;
@ -207,7 +207,9 @@ impl ExpandErrorKind {
kind: RenderedExpandError::GENERAL_KIND, kind: RenderedExpandError::GENERAL_KIND,
}, },
None => RenderedExpandError { None => RenderedExpandError {
message: format!("internal error: proc-macro map is missing error entry for crate {def_crate:?}"), message: format!(
"internal error: proc-macro map is missing error entry for crate {def_crate:?}"
),
error: true, error: true,
kind: RenderedExpandError::GENERAL_KIND, kind: RenderedExpandError::GENERAL_KIND,
}, },
@ -389,7 +391,7 @@ impl HirFileIdExt for HirFileId {
loop { loop {
match call.file_id.repr() { match call.file_id.repr() {
HirFileIdRepr::FileId(file_id) => { HirFileIdRepr::FileId(file_id) => {
break Some(InRealFile { file_id, value: call.value }) break Some(InRealFile { file_id, value: call.value });
} }
HirFileIdRepr::MacroFile(MacroFileId { macro_call_id }) => { HirFileIdRepr::MacroFile(MacroFileId { macro_call_id }) => {
call = db.lookup_intern_macro_call(macro_call_id).to_node(db); call = db.lookup_intern_macro_call(macro_call_id).to_node(db);

View file

@ -7,7 +7,7 @@ use std::{
use crate::{ use crate::{
db::ExpandDatabase, db::ExpandDatabase,
hygiene::{marks_rev, SyntaxContextExt, Transparency}, hygiene::{SyntaxContextExt, Transparency, marks_rev},
name::{AsName, Name}, name::{AsName, Name},
tt, tt,
}; };
@ -15,7 +15,7 @@ use base_db::Crate;
use intern::sym; use intern::sym;
use smallvec::SmallVec; use smallvec::SmallVec;
use span::{Edition, SyntaxContext}; use span::{Edition, SyntaxContext};
use syntax::{ast, AstNode}; use syntax::{AstNode, ast};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ModPath { pub struct ModPath {

View file

@ -2,7 +2,7 @@
use std::fmt; use std::fmt;
use intern::{sym, Symbol}; use intern::{Symbol, sym};
use span::{Edition, SyntaxContext}; use span::{Edition, SyntaxContext};
use syntax::utils::is_raw_identifier; use syntax::utils::is_raw_identifier;
use syntax::{ast, format_smolstr}; use syntax::{ast, format_smolstr};

View file

@ -3,7 +3,7 @@
use base_db::Crate; use base_db::Crate;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use syntax::NodeOrToken; use syntax::NodeOrToken;
use syntax::{ast::make, SyntaxNode}; use syntax::{SyntaxNode, ast::make};
use crate::{db::ExpandDatabase, span_map::ExpansionSpanMap}; use crate::{db::ExpandDatabase, span_map::ExpansionSpanMap};

View file

@ -10,7 +10,7 @@ use rustc_hash::FxHashMap;
use span::Span; use span::Span;
use triomphe::Arc; use triomphe::Arc;
use crate::{db::ExpandDatabase, tt, ExpandError, ExpandErrorKind, ExpandResult}; use crate::{ExpandError, ExpandErrorKind, ExpandResult, db::ExpandDatabase, tt};
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Hash)] #[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Hash)]
pub enum ProcMacroKind { pub enum ProcMacroKind {
@ -298,7 +298,7 @@ impl CustomProcMacroExpander {
call_site, call_site,
"internal error: no proc macros for crate", "internal error: no proc macros for crate",
), ),
) );
} }
}; };
let proc_macro = match proc_macros.get(id, call_site) { let proc_macro = match proc_macros.get(id, call_site) {
@ -310,7 +310,7 @@ impl CustomProcMacroExpander {
close: call_site, close: call_site,
}), }),
e, e,
) );
} }
}; };

View file

@ -2,7 +2,7 @@
use span::{EditionedFileId, HirFileId, HirFileIdRepr, MacroFileId, Span, SyntaxContext}; use span::{EditionedFileId, HirFileId, HirFileIdRepr, MacroFileId, Span, SyntaxContext};
use stdx::TupleExt; use stdx::TupleExt;
use syntax::{ast, AstNode, TextRange}; use syntax::{AstNode, TextRange, ast};
use triomphe::Arc; use triomphe::Arc;
pub use span::RealSpanMap; pub use span::RealSpanMap;

View file

@ -12,8 +12,8 @@ use intern::sym;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
db::HirDatabase, infer::unify::InferenceTable, Canonical, Goal, Interner, ProjectionTyExt, Canonical, Goal, Interner, ProjectionTyExt, TraitEnvironment, Ty, TyBuilder, TyKind,
TraitEnvironment, Ty, TyBuilder, TyKind, db::HirDatabase, infer::unify::InferenceTable,
}; };
const AUTODEREF_RECURSION_LIMIT: usize = 20; const AUTODEREF_RECURSION_LIMIT: usize = 20;

View file

@ -3,21 +3,21 @@
use std::iter; use std::iter;
use chalk_ir::{ use chalk_ir::{
AdtId, DebruijnIndex, Scalar,
cast::{Cast, CastTo, Caster}, cast::{Cast, CastTo, Caster},
fold::TypeFoldable, fold::TypeFoldable,
interner::HasInterner, interner::HasInterner,
AdtId, DebruijnIndex, Scalar,
}; };
use hir_def::{ use hir_def::{
builtin_type::BuiltinType, DefWithBodyId, GenericDefId, GenericParamId, TraitId, TypeAliasId, DefWithBodyId, GenericDefId, GenericParamId, TraitId, TypeAliasId, builtin_type::BuiltinType,
}; };
use smallvec::SmallVec; use smallvec::SmallVec;
use crate::{ use crate::{
consteval::unknown_const_as_generic, db::HirDatabase, error_lifetime, generics::generics, Binders, BoundVar, CallableSig, GenericArg, GenericArgData, Interner, ProjectionTy,
infer::unify::InferenceTable, primitive, to_assoc_type_id, to_chalk_trait_id, Binders, Substitution, TraitRef, Ty, TyDefId, TyExt, TyKind, consteval::unknown_const_as_generic,
BoundVar, CallableSig, GenericArg, GenericArgData, Interner, ProjectionTy, Substitution, db::HirDatabase, error_lifetime, generics::generics, infer::unify::InferenceTable, primitive,
TraitRef, Ty, TyDefId, TyExt, TyKind, to_assoc_type_id, to_chalk_trait_id,
}; };
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
@ -263,7 +263,7 @@ impl TyBuilder<()> {
.as_generic_def_id(db.upcast()) .as_generic_def_id(db.upcast())
.map(|p| generics(db.upcast(), p).placeholder_subst(db)); .map(|p| generics(db.upcast(), p).placeholder_subst(db));
// These represent resume type, yield type, and return type of coroutine. // These represent resume type, yield type, and return type of coroutine.
let params = std::iter::repeat(ParamKind::Type).take(3).collect(); let params = std::iter::repeat_n(ParamKind::Type, 3).collect();
TyBuilder::new((), params, parent_subst) TyBuilder::new((), params, parent_subst)
} }
@ -340,7 +340,7 @@ impl TyBuilder<hir_def::AdtId> {
pub struct Tuple(usize); pub struct Tuple(usize);
impl TyBuilder<Tuple> { impl TyBuilder<Tuple> {
pub fn tuple(size: usize) -> TyBuilder<Tuple> { pub fn tuple(size: usize) -> TyBuilder<Tuple> {
TyBuilder::new(Tuple(size), iter::repeat(ParamKind::Type).take(size).collect(), None) TyBuilder::new(Tuple(size), std::iter::repeat_n(ParamKind::Type, size).collect(), None)
} }
pub fn build(self) -> Ty { pub fn build(self) -> Ty {
@ -356,7 +356,7 @@ impl TyBuilder<Tuple> {
let elements = elements.into_iter(); let elements = elements.into_iter();
let len = elements.len(); let len = elements.len();
let mut b = let mut b =
TyBuilder::new(Tuple(len), iter::repeat(ParamKind::Type).take(len).collect(), None); TyBuilder::new(Tuple(len), std::iter::repeat_n(ParamKind::Type, len).collect(), None);
for e in elements { for e in elements {
b = b.push(e); b = b.push(e);
} }

View file

@ -8,31 +8,32 @@ use intern::sym;
use span::Edition; use span::Edition;
use tracing::debug; use tracing::debug;
use chalk_ir::{cast::Caster, fold::shift::Shift, CanonicalVarKinds}; use chalk_ir::{CanonicalVarKinds, cast::Caster, fold::shift::Shift};
use chalk_solve::rust_ir::{self, OpaqueTyDatumBound, WellKnownTrait}; use chalk_solve::rust_ir::{self, OpaqueTyDatumBound, WellKnownTrait};
use base_db::Crate; use base_db::Crate;
use hir_def::{ use hir_def::{
data::{adt::StructFlags, TraitFlags},
hir::Movability,
lang_item::{LangItem, LangItemTarget},
AssocItemId, BlockId, CallableDefId, GenericDefId, HasModule, ItemContainerId, Lookup, AssocItemId, BlockId, CallableDefId, GenericDefId, HasModule, ItemContainerId, Lookup,
TypeAliasId, VariantId, TypeAliasId, VariantId,
data::{TraitFlags, adt::StructFlags},
hir::Movability,
lang_item::{LangItem, LangItemTarget},
}; };
use crate::{ use crate::{
AliasEq, AliasTy, BoundVar, DebruijnIndex, FnDefId, Interner, ProjectionTy, ProjectionTyExt,
QuantifiedWhereClause, Substitution, TraitRef, TraitRefExt, Ty, TyBuilder, TyExt, TyKind,
WhereClause,
db::{HirDatabase, InternedCoroutine}, db::{HirDatabase, InternedCoroutine},
from_assoc_type_id, from_chalk_trait_id, from_foreign_def_id, from_assoc_type_id, from_chalk_trait_id, from_foreign_def_id,
generics::generics, generics::generics,
make_binders, make_single_type_binders, make_binders, make_single_type_binders,
mapping::{from_chalk, ToChalk, TypeAliasAsValue}, mapping::{ToChalk, TypeAliasAsValue, from_chalk},
method_resolution::{TraitImpls, TyFingerprint, ALL_FLOAT_FPS, ALL_INT_FPS}, method_resolution::{ALL_FLOAT_FPS, ALL_INT_FPS, TraitImpls, TyFingerprint},
to_assoc_type_id, to_chalk_trait_id, to_assoc_type_id, to_chalk_trait_id,
traits::ChalkContext, traits::ChalkContext,
utils::ClosureSubst, utils::ClosureSubst,
wrap_empty_binders, AliasEq, AliasTy, BoundVar, DebruijnIndex, FnDefId, Interner, ProjectionTy, wrap_empty_binders,
ProjectionTyExt, QuantifiedWhereClause, Substitution, TraitRef, TraitRefExt, Ty, TyBuilder,
TyExt, TyKind, WhereClause,
}; };
pub(crate) type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>; pub(crate) type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>;

View file

@ -1,22 +1,22 @@
//! Various extensions traits for Chalk types. //! Various extensions traits for Chalk types.
use chalk_ir::{ use chalk_ir::{
cast::Cast, FloatTy, IntTy, Mutability, Scalar, TyVariableKind, TypeOutlives, UintTy, FloatTy, IntTy, Mutability, Scalar, TyVariableKind, TypeOutlives, UintTy, cast::Cast,
}; };
use hir_def::{ use hir_def::{
DefWithBodyId, FunctionId, GenericDefId, HasModule, ItemContainerId, Lookup, TraitId,
builtin_type::{BuiltinFloat, BuiltinInt, BuiltinType, BuiltinUint}, builtin_type::{BuiltinFloat, BuiltinInt, BuiltinType, BuiltinUint},
generics::TypeOrConstParamData, generics::TypeOrConstParamData,
lang_item::LangItem, lang_item::LangItem,
type_ref::Rawness, type_ref::Rawness,
DefWithBodyId, FunctionId, GenericDefId, HasModule, ItemContainerId, Lookup, TraitId,
}; };
use crate::{ use crate::{
db::HirDatabase, from_assoc_type_id, from_chalk_trait_id, from_foreign_def_id, AdtId, AliasEq, AliasTy, Binders, CallableDefId, CallableSig, Canonical, CanonicalVarKinds,
from_placeholder_idx, generics::generics, to_chalk_trait_id, utils::ClosureSubst, AdtId, ClosureId, DynTy, FnPointer, ImplTraitId, InEnvironment, Interner, Lifetime, ProjectionTy,
AliasEq, AliasTy, Binders, CallableDefId, CallableSig, Canonical, CanonicalVarKinds, ClosureId,
DynTy, FnPointer, ImplTraitId, InEnvironment, Interner, Lifetime, ProjectionTy,
QuantifiedWhereClause, Substitution, TraitRef, Ty, TyBuilder, TyKind, TypeFlags, WhereClause, QuantifiedWhereClause, Substitution, TraitRef, Ty, TyBuilder, TyKind, TypeFlags, WhereClause,
db::HirDatabase, from_assoc_type_id, from_chalk_trait_id, from_foreign_def_id,
from_placeholder_idx, generics::generics, to_chalk_trait_id, utils::ClosureSubst,
}; };
pub trait TyExt { pub trait TyExt {

View file

@ -1,14 +1,14 @@
//! Constant evaluation details //! Constant evaluation details
use base_db::Crate; use base_db::Crate;
use chalk_ir::{cast::Cast, BoundVar, DebruijnIndex}; use chalk_ir::{BoundVar, DebruijnIndex, cast::Cast};
use hir_def::{ use hir_def::{
ConstBlockLoc, EnumVariantId, GeneralConstId, HasModule as _, StaticId,
expr_store::{Body, HygieneId}, expr_store::{Body, HygieneId},
hir::{Expr, ExprId}, hir::{Expr, ExprId},
path::Path, path::Path,
resolver::{Resolver, ValueNs}, resolver::{Resolver, ValueNs},
type_ref::LiteralConstRef, type_ref::LiteralConstRef,
ConstBlockLoc, EnumVariantId, GeneralConstId, HasModule as _, StaticId,
}; };
use hir_expand::Lookup; use hir_expand::Lookup;
use salsa::Cycle; use salsa::Cycle;
@ -16,17 +16,18 @@ use stdx::never;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
Const, ConstData, ConstScalar, ConstValue, GenericArg, Interner, MemoryMap, Substitution,
TraitEnvironment, Ty, TyBuilder,
db::{HirDatabase, HirDatabaseData}, db::{HirDatabase, HirDatabaseData},
display::DisplayTarget, display::DisplayTarget,
generics::Generics, generics::Generics,
infer::InferenceContext, infer::InferenceContext,
lower::ParamLoweringMode, lower::ParamLoweringMode,
mir::monomorphize_mir_body_bad, mir::monomorphize_mir_body_bad,
to_placeholder_idx, Const, ConstData, ConstScalar, ConstValue, GenericArg, Interner, MemoryMap, to_placeholder_idx,
Substitution, TraitEnvironment, Ty, TyBuilder,
}; };
use super::mir::{interpret_mir, lower_to_mir, pad16, MirEvalError, MirLowerError}; use super::mir::{MirEvalError, MirLowerError, interpret_mir, lower_to_mir, pad16};
/// Extension trait for [`Const`] /// Extension trait for [`Const`]
pub trait ConstExt { pub trait ConstExt {

View file

@ -2,16 +2,16 @@ use base_db::RootQueryDb;
use chalk_ir::Substitution; use chalk_ir::Substitution;
use hir_def::db::DefDatabase; use hir_def::db::DefDatabase;
use rustc_apfloat::{ use rustc_apfloat::{
ieee::{Half as f16, Quad as f128},
Float, Float,
ieee::{Half as f16, Quad as f128},
}; };
use span::EditionedFileId; use span::EditionedFileId;
use test_fixture::WithFixture; use test_fixture::WithFixture;
use test_utils::skip_slow_tests; use test_utils::skip_slow_tests;
use crate::{ use crate::{
consteval::try_const_usize, db::HirDatabase, display::DisplayTarget, mir::pad16, Const, ConstScalar, Interner, MemoryMap, consteval::try_const_usize, db::HirDatabase,
test_db::TestDB, Const, ConstScalar, Interner, MemoryMap, display::DisplayTarget, mir::pad16, test_db::TestDB,
}; };
use super::{ use super::{

View file

@ -3,11 +3,12 @@
use std::sync; use std::sync;
use base_db::{impl_intern_key, Crate, Upcast}; use base_db::{Crate, Upcast, impl_intern_key};
use hir_def::{ use hir_def::{
db::DefDatabase, hir::ExprId, layout::TargetDataLayout, AdtId, BlockId, CallableDefId, AdtId, BlockId, CallableDefId, ConstParamId, DefWithBodyId, EnumVariantId, FunctionId,
ConstParamId, DefWithBodyId, EnumVariantId, FunctionId, GeneralConstId, GenericDefId, ImplId, GeneralConstId, GenericDefId, ImplId, LifetimeParamId, LocalFieldId, StaticId, TraitId,
LifetimeParamId, LocalFieldId, StaticId, TraitId, TypeAliasId, TypeOrConstParamId, VariantId, TypeAliasId, TypeOrConstParamId, VariantId, db::DefDatabase, hir::ExprId,
layout::TargetDataLayout,
}; };
use hir_expand::name::Name; use hir_expand::name::Name;
use la_arena::ArenaMap; use la_arena::ArenaMap;
@ -16,7 +17,8 @@ use smallvec::SmallVec;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
chalk_db, Binders, ClosureId, Const, FnDefId, ImplTraitId, ImplTraits, InferenceResult, Interner,
PolyFnSig, Substitution, TraitEnvironment, TraitRef, Ty, TyDefId, ValueTyDefId, chalk_db,
consteval::ConstEvalError, consteval::ConstEvalError,
drop::DropGlue, drop::DropGlue,
dyn_compatibility::DynCompatibilityViolation, dyn_compatibility::DynCompatibilityViolation,
@ -24,8 +26,6 @@ use crate::{
lower::{Diagnostics, GenericDefaults, GenericPredicates}, lower::{Diagnostics, GenericDefaults, GenericPredicates},
method_resolution::{InherentImpls, TraitImpls, TyFingerprint}, method_resolution::{InherentImpls, TraitImpls, TyFingerprint},
mir::{BorrowckResult, MirBody, MirLowerError}, mir::{BorrowckResult, MirBody, MirLowerError},
Binders, ClosureId, Const, FnDefId, ImplTraitId, ImplTraits, InferenceResult, Interner,
PolyFnSig, Substitution, TraitEnvironment, TraitRef, Ty, TyDefId, ValueTyDefId,
}; };
#[query_group::query_group] #[query_group::query_group]
@ -262,7 +262,7 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> + std::fmt::Debug {
#[salsa::invoke(chalk_db::impl_datum_query)] #[salsa::invoke(chalk_db::impl_datum_query)]
fn impl_datum(&self, krate: Crate, impl_id: chalk_db::ImplId) fn impl_datum(&self, krate: Crate, impl_id: chalk_db::ImplId)
-> sync::Arc<chalk_db::ImplDatum>; -> sync::Arc<chalk_db::ImplDatum>;
#[salsa::invoke(chalk_db::fn_def_datum_query)] #[salsa::invoke(chalk_db::fn_def_datum_query)]
fn fn_def_datum(&self, fn_def_id: FnDefId) -> sync::Arc<chalk_db::FnDefDatum>; fn fn_def_datum(&self, fn_def_id: FnDefId) -> sync::Arc<chalk_db::FnDefDatum>;

View file

@ -5,12 +5,12 @@ mod match_check;
mod unsafe_check; mod unsafe_check;
pub use crate::diagnostics::{ pub use crate::diagnostics::{
decl_check::{incorrect_case, CaseType, IncorrectCase}, decl_check::{CaseType, IncorrectCase, incorrect_case},
expr::{ expr::{
record_literal_missing_fields, record_pattern_missing_fields, BodyValidationDiagnostic, BodyValidationDiagnostic, record_literal_missing_fields, record_pattern_missing_fields,
}, },
unsafe_check::{ unsafe_check::{
missing_unsafe, unsafe_operations, unsafe_operations_for_body, InsideUnsafeBlock, InsideUnsafeBlock, UnsafetyReason, missing_unsafe, unsafe_operations,
UnsafetyReason, unsafe_operations_for_body,
}, },
}; };

View file

@ -16,20 +16,20 @@ mod case_conv;
use std::fmt; use std::fmt;
use hir_def::{ use hir_def::{
data::adt::VariantData, db::DefDatabase, hir::Pat, src::HasSource, AdtId, ConstId, EnumId, AdtId, ConstId, EnumId, EnumVariantId, FunctionId, HasModule, ItemContainerId, Lookup,
EnumVariantId, FunctionId, HasModule, ItemContainerId, Lookup, ModuleDefId, ModuleId, StaticId, ModuleDefId, ModuleId, StaticId, StructId, TraitId, TypeAliasId, data::adt::VariantData,
StructId, TraitId, TypeAliasId, db::DefDatabase, hir::Pat, src::HasSource,
}; };
use hir_expand::{ use hir_expand::{
name::{AsName, Name},
HirFileId, HirFileIdExt, HirFileId, HirFileIdExt,
name::{AsName, Name},
}; };
use intern::sym; use intern::sym;
use stdx::{always, never}; use stdx::{always, never};
use syntax::{ use syntax::{
AstNode, AstPtr, ToSmolStr,
ast::{self, HasName}, ast::{self, HasName},
utils::is_raw_identifier, utils::is_raw_identifier,
AstNode, AstPtr, ToSmolStr,
}; };
use crate::db::HirDatabase; use crate::db::HirDatabase;

View file

@ -97,7 +97,7 @@ fn is_snake_case<F: Fn(char) -> bool>(ident: &str, wrong_case: F) -> bool {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use expect_test::{expect, Expect}; use expect_test::{Expect, expect};
fn check<F: Fn(&str) -> Option<String>>(fun: F, input: &str, expect: Expect) { fn check<F: Fn(&str) -> Option<String>>(fun: F, input: &str, expect: Expect) {
// `None` is translated to empty string, meaning that there is nothing to fix. // `None` is translated to empty string, meaning that there is nothing to fix.

View file

@ -8,36 +8,36 @@ use base_db::Crate;
use chalk_solve::rust_ir::AdtKind; use chalk_solve::rust_ir::AdtKind;
use either::Either; use either::Either;
use hir_def::{ use hir_def::{
AdtId, AssocItemId, DefWithBodyId, HasModule, ItemContainerId, Lookup,
lang_item::LangItem, lang_item::LangItem,
resolver::{HasResolver, ValueNs}, resolver::{HasResolver, ValueNs},
AdtId, AssocItemId, DefWithBodyId, HasModule, ItemContainerId, Lookup,
}; };
use intern::sym; use intern::sym;
use itertools::Itertools; use itertools::Itertools;
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use rustc_pattern_analysis::constructor::Constructor; use rustc_pattern_analysis::constructor::Constructor;
use syntax::{ use syntax::{
ast::{self, UnaryOp},
AstNode, AstNode,
ast::{self, UnaryOp},
}; };
use tracing::debug; use tracing::debug;
use triomphe::Arc; use triomphe::Arc;
use typed_arena::Arena; use typed_arena::Arena;
use crate::{ use crate::{
Adjust, InferenceResult, Interner, Ty, TyExt, TyKind,
db::HirDatabase, db::HirDatabase,
diagnostics::match_check::{ diagnostics::match_check::{
self, self,
pat_analysis::{self, DeconstructedPat, MatchCheckCtx, WitnessPat}, pat_analysis::{self, DeconstructedPat, MatchCheckCtx, WitnessPat},
}, },
display::{DisplayTarget, HirDisplay}, display::{DisplayTarget, HirDisplay},
Adjust, InferenceResult, Interner, Ty, TyExt, TyKind,
}; };
pub(crate) use hir_def::{ pub(crate) use hir_def::{
LocalFieldId, VariantId,
expr_store::Body, expr_store::Body,
hir::{Expr, ExprId, MatchArm, Pat, PatId, Statement}, hir::{Expr, ExprId, MatchArm, Pat, PatId, Statement},
LocalFieldId, VariantId,
}; };
pub enum BodyValidationDiagnostic { pub enum BodyValidationDiagnostic {

View file

@ -11,19 +11,19 @@ pub(crate) mod pat_analysis;
use chalk_ir::Mutability; use chalk_ir::Mutability;
use hir_def::{ use hir_def::{
data::adt::VariantData, expr_store::Body, hir::PatId, AdtId, EnumVariantId, LocalFieldId, AdtId, EnumVariantId, LocalFieldId, VariantId, data::adt::VariantData, expr_store::Body,
VariantId, hir::PatId,
}; };
use hir_expand::name::Name; use hir_expand::name::Name;
use span::Edition; use span::Edition;
use stdx::{always, never}; use stdx::{always, never};
use crate::{ use crate::{
InferenceResult, Interner, Substitution, Ty, TyExt, TyKind,
db::HirDatabase, db::HirDatabase,
display::{HirDisplay, HirDisplayError, HirFormatter}, display::{HirDisplay, HirDisplayError, HirFormatter},
infer::BindingMode, infer::BindingMode,
lang_items::is_box, lang_items::is_box,
InferenceResult, Interner, Substitution, Ty, TyExt, TyKind,
}; };
use self::pat_util::EnumerateAndAdjustIterator; use self::pat_util::EnumerateAndAdjustIterator;

View file

@ -6,21 +6,21 @@ use std::fmt;
use hir_def::{DefWithBodyId, EnumId, EnumVariantId, HasModule, LocalFieldId, ModuleId, VariantId}; use hir_def::{DefWithBodyId, EnumId, EnumVariantId, HasModule, LocalFieldId, ModuleId, VariantId};
use intern::sym; use intern::sym;
use rustc_pattern_analysis::{ use rustc_pattern_analysis::{
constructor::{Constructor, ConstructorSet, VariantVisibility},
usefulness::{compute_match_usefulness, PlaceValidity, UsefulnessReport},
Captures, IndexVec, PatCx, PrivateUninhabitedField, Captures, IndexVec, PatCx, PrivateUninhabitedField,
constructor::{Constructor, ConstructorSet, VariantVisibility},
usefulness::{PlaceValidity, UsefulnessReport, compute_match_usefulness},
}; };
use smallvec::{smallvec, SmallVec}; use smallvec::{SmallVec, smallvec};
use stdx::never; use stdx::never;
use crate::{ use crate::{
AdtId, Interner, Scalar, Ty, TyExt, TyKind,
db::HirDatabase, db::HirDatabase,
infer::normalize, infer::normalize,
inhabitedness::{is_enum_variant_uninhabited_from, is_ty_uninhabited_from}, inhabitedness::{is_enum_variant_uninhabited_from, is_ty_uninhabited_from},
AdtId, Interner, Scalar, Ty, TyExt, TyKind,
}; };
use super::{is_box, FieldPat, Pat, PatKind}; use super::{FieldPat, Pat, PatKind, is_box};
use Constructor::*; use Constructor::*;

View file

@ -5,18 +5,18 @@ use std::mem;
use either::Either; use either::Either;
use hir_def::{ use hir_def::{
AdtId, DefWithBodyId, FieldId, FunctionId, VariantId,
expr_store::Body, expr_store::Body,
hir::{Expr, ExprId, ExprOrPatId, Pat, PatId, Statement, UnaryOp}, hir::{Expr, ExprId, ExprOrPatId, Pat, PatId, Statement, UnaryOp},
path::Path, path::Path,
resolver::{HasResolver, ResolveValueResult, Resolver, ValueNs}, resolver::{HasResolver, ResolveValueResult, Resolver, ValueNs},
type_ref::Rawness, type_ref::Rawness,
AdtId, DefWithBodyId, FieldId, FunctionId, VariantId,
}; };
use span::Edition; use span::Edition;
use crate::{ use crate::{
db::HirDatabase, utils::is_fn_unsafe_to_call, InferenceResult, Interner, TargetFeatures, TyExt, InferenceResult, Interner, TargetFeatures, TyExt, TyKind, db::HirDatabase,
TyKind, utils::is_fn_unsafe_to_call,
}; };
#[derive(Debug, Default)] #[derive(Debug, Default)]

View file

@ -11,6 +11,8 @@ use base_db::Crate;
use chalk_ir::{BoundVar, Safety, TyKind}; use chalk_ir::{BoundVar, Safety, TyKind};
use either::Either; use either::Either;
use hir_def::{ use hir_def::{
GenericDefId, HasModule, ImportPathConfig, ItemContainerId, LocalFieldId, Lookup, ModuleDefId,
ModuleId, TraitId,
data::adt::VariantData, data::adt::VariantData,
db::DefDatabase, db::DefDatabase,
find_path::{self, PrefixKind}, find_path::{self, PrefixKind},
@ -23,16 +25,14 @@ use hir_def::{
TraitBoundModifier, TypeBound, TypeRef, TypeRefId, TypesMap, TypesSourceMap, UseArgRef, TraitBoundModifier, TypeBound, TypeRef, TypeRefId, TypesMap, TypesSourceMap, UseArgRef,
}, },
visibility::Visibility, visibility::Visibility,
GenericDefId, HasModule, ImportPathConfig, ItemContainerId, LocalFieldId, Lookup, ModuleDefId,
ModuleId, TraitId,
}; };
use hir_expand::name::Name; use hir_expand::name::Name;
use intern::{sym, Internable, Interned}; use intern::{Internable, Interned, sym};
use itertools::Itertools; use itertools::Itertools;
use la_arena::ArenaMap; use la_arena::ArenaMap;
use rustc_apfloat::{ use rustc_apfloat::{
ieee::{Half as f16, Quad as f128},
Float, Float,
ieee::{Half as f16, Quad as f128},
}; };
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use smallvec::SmallVec; use smallvec::SmallVec;
@ -41,6 +41,11 @@ use stdx::never;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
AdtId, AliasEq, AliasTy, Binders, CallableDefId, CallableSig, ConcreteConst, Const,
ConstScalar, ConstValue, DomainGoal, FnAbi, GenericArg, ImplTraitId, Interner, Lifetime,
LifetimeData, LifetimeOutlives, MemoryMap, Mutability, OpaqueTy, ProjectionTy, ProjectionTyExt,
QuantifiedWhereClause, Scalar, Substitution, TraitEnvironment, TraitRef, TraitRefExt, Ty,
TyExt, WhereClause,
consteval::try_const_usize, consteval::try_const_usize,
db::{HirDatabase, InternedClosure}, db::{HirDatabase, InternedClosure},
from_assoc_type_id, from_foreign_def_id, from_placeholder_idx, from_assoc_type_id, from_foreign_def_id, from_placeholder_idx,
@ -51,12 +56,7 @@ use crate::{
mapping::from_chalk, mapping::from_chalk,
mir::pad16, mir::pad16,
primitive, to_assoc_type_id, primitive, to_assoc_type_id,
utils::{self, detect_variant_from_bytes, ClosureSubst}, utils::{self, ClosureSubst, detect_variant_from_bytes},
AdtId, AliasEq, AliasTy, Binders, CallableDefId, CallableSig, ConcreteConst, Const,
ConstScalar, ConstValue, DomainGoal, FnAbi, GenericArg, ImplTraitId, Interner, Lifetime,
LifetimeData, LifetimeOutlives, MemoryMap, Mutability, OpaqueTy, ProjectionTy, ProjectionTyExt,
QuantifiedWhereClause, Scalar, Substitution, TraitEnvironment, TraitRef, TraitRefExt, Ty,
TyExt, WhereClause,
}; };
pub trait HirWrite: fmt::Write { pub trait HirWrite: fmt::Write {
@ -529,7 +529,9 @@ where
Err(HirDisplayError::FmtError) => Err(fmt::Error), Err(HirDisplayError::FmtError) => Err(fmt::Error),
Err(HirDisplayError::DisplaySourceCodeError(_)) => { Err(HirDisplayError::DisplaySourceCodeError(_)) => {
// This should never happen // This should never happen
panic!("HirDisplay::hir_fmt failed with DisplaySourceCodeError when calling Display::fmt!") panic!(
"HirDisplay::hir_fmt failed with DisplaySourceCodeError when calling Display::fmt!"
)
} }
} }
} }
@ -1381,7 +1383,7 @@ impl HirDisplay for Ty {
match f.closure_style { match f.closure_style {
ClosureStyle::Hide => return write!(f, "{TYPE_HINT_TRUNCATION}"), ClosureStyle::Hide => return write!(f, "{TYPE_HINT_TRUNCATION}"),
ClosureStyle::ClosureWithId => { ClosureStyle::ClosureWithId => {
return write!(f, "{{closure#{:?}}}", id.0.as_u32()) return write!(f, "{{closure#{:?}}}", id.0.as_u32());
} }
ClosureStyle::ClosureWithSubst => { ClosureStyle::ClosureWithSubst => {
write!(f, "{{closure#{:?}}}", id.0.as_u32())?; write!(f, "{{closure#{:?}}}", id.0.as_u32())?;

View file

@ -1,16 +1,16 @@
//! Utilities for computing drop info about types. //! Utilities for computing drop info about types.
use chalk_ir::cast::Cast; use chalk_ir::cast::Cast;
use hir_def::AdtId;
use hir_def::data::adt::StructFlags; use hir_def::data::adt::StructFlags;
use hir_def::lang_item::LangItem; use hir_def::lang_item::LangItem;
use hir_def::AdtId;
use stdx::never; use stdx::never;
use triomphe::Arc; use triomphe::Arc;
use crate::db::HirDatabaseData; use crate::db::HirDatabaseData;
use crate::{ use crate::{
db::HirDatabase, method_resolution::TyFingerprint, AliasTy, Canonical, CanonicalVarKinds, AliasTy, Canonical, CanonicalVarKinds, InEnvironment, Interner, ProjectionTy, TraitEnvironment,
InEnvironment, Interner, ProjectionTy, TraitEnvironment, Ty, TyBuilder, TyKind, Ty, TyBuilder, TyKind, db::HirDatabase, method_resolution::TyFingerprint,
}; };
use crate::{ConcreteConst, ConstScalar, ConstValue}; use crate::{ConcreteConst, ConstScalar, ConstValue};
@ -176,11 +176,7 @@ fn projection_has_drop_glue(
let normalized = db.normalize_projection(projection, env.clone()); let normalized = db.normalize_projection(projection, env.clone());
match normalized.kind(Interner) { match normalized.kind(Interner) {
TyKind::Alias(AliasTy::Projection(_)) | TyKind::AssociatedType(..) => { TyKind::Alias(AliasTy::Projection(_)) | TyKind::AssociatedType(..) => {
if is_copy(db, ty, env) { if is_copy(db, ty, env) { DropGlue::None } else { DropGlue::DependOnParams }
DropGlue::None
} else {
DropGlue::DependOnParams
}
} }
_ => db.has_drop_glue(normalized, env), _ => db.has_drop_glue(normalized, env),
} }

View file

@ -3,28 +3,27 @@
use std::ops::ControlFlow; use std::ops::ControlFlow;
use chalk_ir::{ use chalk_ir::{
DebruijnIndex,
cast::Cast, cast::Cast,
visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor}, visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor},
DebruijnIndex,
}; };
use chalk_solve::rust_ir::InlineBound; use chalk_solve::rust_ir::InlineBound;
use hir_def::{ use hir_def::{
data::TraitFlags, lang_item::LangItem, AssocItemId, ConstId, FunctionId, GenericDefId, AssocItemId, ConstId, FunctionId, GenericDefId, HasModule, TraitId, TypeAliasId,
HasModule, TraitId, TypeAliasId, data::TraitFlags, lang_item::LangItem,
}; };
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use smallvec::SmallVec; use smallvec::SmallVec;
use crate::{ use crate::{
all_super_traits, AliasEq, AliasTy, Binders, BoundVar, CallableSig, GoalData, ImplTraitId, Interner, OpaqueTyId,
ProjectionTyExt, Solution, Substitution, TraitRef, Ty, TyKind, WhereClause, all_super_traits,
db::HirDatabase, db::HirDatabase,
from_assoc_type_id, from_chalk_trait_id, from_assoc_type_id, from_chalk_trait_id,
generics::{generics, trait_self_param_idx}, generics::{generics, trait_self_param_idx},
lower::callable_item_sig, lower::callable_item_sig,
to_assoc_type_id, to_chalk_trait_id, to_assoc_type_id, to_chalk_trait_id,
utils::elaborate_clause_supertraits, utils::elaborate_clause_supertraits,
AliasEq, AliasTy, Binders, BoundVar, CallableSig, GoalData, ImplTraitId, Interner, OpaqueTyId,
ProjectionTyExt, Solution, Substitution, TraitRef, Ty, TyKind, WhereClause,
}; };
#[derive(Debug, Clone, PartialEq, Eq, Hash)] #[derive(Debug, Clone, PartialEq, Eq, Hash)]
@ -558,11 +557,7 @@ fn receiver_for_self_ty(db: &dyn HirDatabase, func: FunctionId, ty: Ty) -> Optio
let subst = Substitution::from_iter( let subst = Substitution::from_iter(
Interner, Interner,
subst.iter(Interner).enumerate().map(|(idx, arg)| { subst.iter(Interner).enumerate().map(|(idx, arg)| {
if idx == trait_self_idx { if idx == trait_self_idx { ty.clone().cast(Interner) } else { arg.clone() }
ty.clone().cast(Interner)
} else {
arg.clone()
}
}), }),
); );
let sig = callable_item_sig(db, func.into()); let sig = callable_item_sig(db, func.into());

View file

@ -9,22 +9,22 @@
//! where parent follows the same scheme. //! where parent follows the same scheme.
use std::ops; use std::ops;
use chalk_ir::{cast::Cast as _, BoundVar, DebruijnIndex}; use chalk_ir::{BoundVar, DebruijnIndex, cast::Cast as _};
use hir_def::{ use hir_def::{
ConstParamId, GenericDefId, GenericParamId, ItemContainerId, LifetimeParamId,
LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup, TypeOrConstParamId, TypeParamId,
db::DefDatabase, db::DefDatabase,
generics::{ generics::{
GenericParamDataRef, GenericParams, LifetimeParamData, TypeOrConstParamData, GenericParamDataRef, GenericParams, LifetimeParamData, TypeOrConstParamData,
TypeParamProvenance, TypeParamProvenance,
}, },
type_ref::TypesMap, type_ref::TypesMap,
ConstParamId, GenericDefId, GenericParamId, ItemContainerId, LifetimeParamId,
LocalLifetimeParamId, LocalTypeOrConstParamId, Lookup, TypeOrConstParamId, TypeParamId,
}; };
use itertools::chain; use itertools::chain;
use stdx::TupleExt; use stdx::TupleExt;
use triomphe::Arc; use triomphe::Arc;
use crate::{db::HirDatabase, lt_to_placeholder_idx, to_placeholder_idx, Interner, Substitution}; use crate::{Interner, Substitution, db::HirDatabase, lt_to_placeholder_idx, to_placeholder_idx};
pub fn generics(db: &dyn DefDatabase, def: GenericDefId) -> Generics { pub fn generics(db: &dyn DefDatabase, def: GenericDefId) -> Generics {
let parent_generics = parent_generic_def(db, def).map(|def| Box::new(generics(db, def))); let parent_generics = parent_generic_def(db, def).map(|def| Box::new(generics(db, def)));

View file

@ -26,14 +26,16 @@ pub(crate) mod unify;
use std::{cell::OnceCell, convert::identity, iter, ops::Index}; use std::{cell::OnceCell, convert::identity, iter, ops::Index};
use chalk_ir::{ use chalk_ir::{
DebruijnIndex, Mutability, Safety, Scalar, TyKind, TypeFlags, Variance,
cast::Cast, cast::Cast,
fold::TypeFoldable, fold::TypeFoldable,
interner::HasInterner, interner::HasInterner,
visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor}, visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor},
DebruijnIndex, Mutability, Safety, Scalar, TyKind, TypeFlags, Variance,
}; };
use either::Either; use either::Either;
use hir_def::{ use hir_def::{
AdtId, AssocItemId, DefWithBodyId, FieldId, FunctionId, ImplId, ItemContainerId, Lookup,
TraitId, TupleFieldId, TupleId, TypeAliasId, VariantId,
builtin_type::{BuiltinInt, BuiltinType, BuiltinUint}, builtin_type::{BuiltinInt, BuiltinType, BuiltinUint},
data::{ConstData, StaticData}, data::{ConstData, StaticData},
expr_store::{Body, HygieneId}, expr_store::{Body, HygieneId},
@ -43,8 +45,6 @@ use hir_def::{
path::{ModPath, Path}, path::{ModPath, Path},
resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs}, resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs},
type_ref::{LifetimeRef, TypeRefId, TypesMap}, type_ref::{LifetimeRef, TypeRefId, TypesMap},
AdtId, AssocItemId, DefWithBodyId, FieldId, FunctionId, ImplId, ItemContainerId, Lookup,
TraitId, TupleFieldId, TupleId, TypeAliasId, VariantId,
}; };
use hir_expand::name::Name; use hir_expand::name::Name;
use indexmap::IndexSet; use indexmap::IndexSet;
@ -55,6 +55,9 @@ use stdx::{always, never};
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
AliasEq, AliasTy, Binders, ClosureId, Const, DomainGoal, GenericArg, Goal, ImplTraitId,
ImplTraitIdx, InEnvironment, Interner, Lifetime, OpaqueTyId, ParamLoweringMode,
PathLoweringDiagnostic, ProjectionTy, Substitution, TraitEnvironment, Ty, TyBuilder, TyExt,
db::HirDatabase, db::HirDatabase,
fold_tys, fold_tys,
generics::Generics, generics::Generics,
@ -64,14 +67,11 @@ use crate::{
expr::ExprIsRead, expr::ExprIsRead,
unify::InferenceTable, unify::InferenceTable,
}, },
lower::{diagnostics::TyLoweringDiagnostic, ImplTraitLoweringMode}, lower::{ImplTraitLoweringMode, diagnostics::TyLoweringDiagnostic},
mir::MirSpan, mir::MirSpan,
to_assoc_type_id, to_assoc_type_id,
traits::FnTrait, traits::FnTrait,
utils::{InTypeConstIdMetadata, UnevaluatedConstEvaluatorFolder}, utils::{InTypeConstIdMetadata, UnevaluatedConstEvaluatorFolder},
AliasEq, AliasTy, Binders, ClosureId, Const, DomainGoal, GenericArg, Goal, ImplTraitId,
ImplTraitIdx, InEnvironment, Interner, Lifetime, OpaqueTyId, ParamLoweringMode,
PathLoweringDiagnostic, ProjectionTy, Substitution, TraitEnvironment, Ty, TyBuilder, TyExt,
}; };
// This lint has a false positive here. See the link below for details. // This lint has a false positive here. See the link below for details.
@ -1190,11 +1190,7 @@ impl<'a> InferenceContext<'a> {
if let Some(impl_id) = impl_id { if let Some(impl_id) = impl_id {
taits.extend(collector.assocs.into_iter().filter_map(|(id, (impl_, ty))| { taits.extend(collector.assocs.into_iter().filter_map(|(id, (impl_, ty))| {
if impl_ == impl_id { if impl_ == impl_id { Some((id, ty)) } else { None }
Some((id, ty))
} else {
None
}
})); }));
} }
@ -1914,11 +1910,7 @@ impl Expectation {
match self { match self {
Expectation::HasType(ety) => { Expectation::HasType(ety) => {
let ety = table.resolve_ty_shallow(ety); let ety = table.resolve_ty_shallow(ety);
if ety.is_ty_var() { if ety.is_ty_var() { Expectation::None } else { Expectation::HasType(ety) }
Expectation::None
} else {
Expectation::HasType(ety)
}
} }
Expectation::RValueLikeUnsized(ety) => Expectation::RValueLikeUnsized(ety.clone()), Expectation::RValueLikeUnsized(ety) => Expectation::RValueLikeUnsized(ety.clone()),
_ => Expectation::None, _ => Expectation::None,
@ -2044,7 +2036,7 @@ impl chalk_ir::zip::Zipper<Interner> for UnknownMismatch<'_> {
| (_, TyKind::Error) | (_, TyKind::Error)
| (TyKind::Alias(AliasTy::Projection(_)) | TyKind::AssociatedType(_, _), _) | (TyKind::Alias(AliasTy::Projection(_)) | TyKind::AssociatedType(_, _), _)
| (_, TyKind::Alias(AliasTy::Projection(_)) | TyKind::AssociatedType(_, _)) => { | (_, TyKind::Alias(AliasTy::Projection(_)) | TyKind::AssociatedType(_, _)) => {
return Err(chalk_ir::NoSolution) return Err(chalk_ir::NoSolution);
} }
_ => (), _ => (),
} }

View file

@ -1,13 +1,13 @@
//! Type cast logic. Basically coercion + additional casts. //! Type cast logic. Basically coercion + additional casts.
use chalk_ir::{Mutability, Scalar, TyVariableKind, UintTy}; use chalk_ir::{Mutability, Scalar, TyVariableKind, UintTy};
use hir_def::{hir::ExprId, AdtId}; use hir_def::{AdtId, hir::ExprId};
use stdx::never; use stdx::never;
use crate::{ use crate::{
infer::{coerce::CoerceNever, unify::InferenceTable},
Adjustment, Binders, DynTy, InferenceDiagnostic, Interner, PlaceholderIndex, Adjustment, Binders, DynTy, InferenceDiagnostic, Interner, PlaceholderIndex,
QuantifiedWhereClauses, Ty, TyExt, TyKind, TypeFlags, WhereClause, QuantifiedWhereClauses, Ty, TyExt, TyKind, TypeFlags, WhereClause,
infer::{coerce::CoerceNever, unify::InferenceTable},
}; };
#[derive(Debug)] #[derive(Debug)]
@ -431,8 +431,8 @@ fn contains_dyn_trait(ty: &Ty) -> bool {
use std::ops::ControlFlow; use std::ops::ControlFlow;
use chalk_ir::{ use chalk_ir::{
visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor},
DebruijnIndex, DebruijnIndex,
visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor},
}; };
struct DynTraitVisitor; struct DynTraitVisitor;

View file

@ -3,12 +3,13 @@
use std::{cmp, convert::Infallible, mem}; use std::{cmp, convert::Infallible, mem};
use chalk_ir::{ use chalk_ir::{
BoundVar, DebruijnIndex, FnSubst, Mutability, TyKind,
cast::Cast, cast::Cast,
fold::{FallibleTypeFolder, TypeFoldable}, fold::{FallibleTypeFolder, TypeFoldable},
BoundVar, DebruijnIndex, FnSubst, Mutability, TyKind,
}; };
use either::Either; use either::Either;
use hir_def::{ use hir_def::{
DefWithBodyId, FieldId, HasModule, TupleFieldId, TupleId, VariantId,
data::adt::VariantData, data::adt::VariantData,
hir::{ hir::{
Array, AsmOperand, BinaryOp, BindingId, CaptureBy, Expr, ExprId, ExprOrPatId, Pat, PatId, Array, AsmOperand, BinaryOp, BindingId, CaptureBy, Expr, ExprId, ExprOrPatId, Pat, PatId,
@ -17,16 +18,18 @@ use hir_def::{
lang_item::LangItem, lang_item::LangItem,
path::Path, path::Path,
resolver::ValueNs, resolver::ValueNs,
DefWithBodyId, FieldId, HasModule, TupleFieldId, TupleId, VariantId,
}; };
use hir_expand::name::Name; use hir_expand::name::Name;
use intern::sym; use intern::sym;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
use smallvec::{smallvec, SmallVec}; use smallvec::{SmallVec, smallvec};
use stdx::{format_to, never}; use stdx::{format_to, never};
use syntax::utils::is_raw_identifier; use syntax::utils::is_raw_identifier;
use crate::{ use crate::{
Adjust, Adjustment, AliasEq, AliasTy, Binders, BindingMode, ChalkTraitId, ClosureId, DynTy,
DynTyExt, FnAbi, FnPointer, FnSig, Interner, OpaqueTy, ProjectionTyExt, Substitution, Ty,
TyExt, WhereClause,
db::{HirDatabase, InternedClosure}, db::{HirDatabase, InternedClosure},
error_lifetime, from_chalk_trait_id, from_placeholder_idx, error_lifetime, from_chalk_trait_id, from_placeholder_idx,
generics::Generics, generics::Generics,
@ -36,9 +39,6 @@ use crate::{
to_chalk_trait_id, to_chalk_trait_id,
traits::FnTrait, traits::FnTrait,
utils::{self, elaborate_clause_supertraits}, utils::{self, elaborate_clause_supertraits},
Adjust, Adjustment, AliasEq, AliasTy, Binders, BindingMode, ChalkTraitId, ClosureId, DynTy,
DynTyExt, FnAbi, FnPointer, FnSig, Interner, OpaqueTy, ProjectionTyExt, Substitution, Ty,
TyExt, WhereClause,
}; };
use super::{Expectation, InferenceContext}; use super::{Expectation, InferenceContext};

View file

@ -7,7 +7,7 @@
use std::iter; use std::iter;
use chalk_ir::{cast::Cast, BoundVar, Goal, Mutability, TyKind, TyVariableKind}; use chalk_ir::{BoundVar, Goal, Mutability, TyKind, TyVariableKind, cast::Cast};
use hir_def::{ use hir_def::{
hir::ExprId, hir::ExprId,
lang_item::{LangItem, LangItemTarget}, lang_item::{LangItem, LangItemTarget},
@ -16,6 +16,8 @@ use stdx::always;
use triomphe::Arc; use triomphe::Arc;
use crate::{ use crate::{
Canonical, DomainGoal, FnAbi, FnPointer, FnSig, Guidance, InEnvironment, Interner, Lifetime,
Solution, Substitution, TraitEnvironment, Ty, TyBuilder, TyExt,
autoderef::{Autoderef, AutoderefKind}, autoderef::{Autoderef, AutoderefKind},
db::HirDatabase, db::HirDatabase,
infer::{ infer::{
@ -23,8 +25,6 @@ use crate::{
TypeError, TypeMismatch, TypeError, TypeMismatch,
}, },
utils::ClosureSubst, utils::ClosureSubst,
Canonical, DomainGoal, FnAbi, FnPointer, FnSig, Guidance, InEnvironment, Interner, Lifetime,
Solution, Substitution, TraitEnvironment, Ty, TyBuilder, TyExt,
}; };
use super::unify::InferenceTable; use super::unify::InferenceTable;

View file

@ -6,13 +6,13 @@ use std::cell::RefCell;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use either::Either; use either::Either;
use hir_def::{hir::ExprOrPatId, path::Path, resolver::Resolver, type_ref::TypesMap, TypeOwnerId}; use hir_def::{TypeOwnerId, hir::ExprOrPatId, path::Path, resolver::Resolver, type_ref::TypesMap};
use la_arena::{Idx, RawIdx}; use la_arena::{Idx, RawIdx};
use crate::{ use crate::{
InferenceDiagnostic, InferenceTyDiagnosticSource, TyLoweringContext, TyLoweringDiagnostic,
db::HirDatabase, db::HirDatabase,
lower::path::{PathDiagnosticCallback, PathLoweringContext}, lower::path::{PathDiagnosticCallback, PathLoweringContext},
InferenceDiagnostic, InferenceTyDiagnosticSource, TyLoweringContext, TyLoweringDiagnostic,
}; };
// Unfortunately, this struct needs to use interior mutability (but we encapsulate it) // Unfortunately, this struct needs to use interior mutability (but we encapsulate it)

View file

@ -5,9 +5,10 @@ use std::{
mem, mem,
}; };
use chalk_ir::{cast::Cast, fold::Shift, DebruijnIndex, Mutability, TyVariableKind}; use chalk_ir::{DebruijnIndex, Mutability, TyVariableKind, cast::Cast, fold::Shift};
use either::Either; use either::Either;
use hir_def::{ use hir_def::{
BlockId, FieldId, GenericDefId, GenericParamId, ItemContainerId, Lookup, TupleFieldId, TupleId,
hir::{ hir::{
ArithOp, Array, AsmOperand, AsmOptions, BinaryOp, ClosureKind, Expr, ExprId, ExprOrPatId, ArithOp, Array, AsmOperand, AsmOptions, BinaryOp, ClosureKind, Expr, ExprId, ExprOrPatId,
LabelId, Literal, Pat, PatId, Statement, UnaryOp, LabelId, Literal, Pat, PatId, Statement, UnaryOp,
@ -15,7 +16,6 @@ use hir_def::{
lang_item::{LangItem, LangItemTarget}, lang_item::{LangItem, LangItemTarget},
path::{GenericArg, GenericArgs, Path}, path::{GenericArg, GenericArgs, Path},
resolver::ValueNs, resolver::ValueNs,
BlockId, FieldId, GenericDefId, GenericParamId, ItemContainerId, Lookup, TupleFieldId, TupleId,
}; };
use hir_expand::name::Name; use hir_expand::name::Name;
use intern::sym; use intern::sym;
@ -23,34 +23,34 @@ use stdx::always;
use syntax::ast::RangeOp; use syntax::ast::RangeOp;
use crate::{ use crate::{
autoderef::{builtin_deref, deref_by_trait, Autoderef}, Adjust, Adjustment, AdtId, AutoBorrow, Binders, CallableDefId, CallableSig, DeclContext,
DeclOrigin, FnAbi, FnPointer, FnSig, FnSubst, Interner, Rawness, Scalar, Substitution,
TraitEnvironment, TraitRef, Ty, TyBuilder, TyExt, TyKind,
autoderef::{Autoderef, builtin_deref, deref_by_trait},
consteval, consteval,
db::{InternedClosure, InternedCoroutine}, db::{InternedClosure, InternedCoroutine},
error_lifetime, error_lifetime,
generics::{generics, Generics}, generics::{Generics, generics},
infer::{ infer::{
BreakableKind,
coerce::{CoerceMany, CoerceNever, CoercionCause}, coerce::{CoerceMany, CoerceNever, CoercionCause},
find_continuable, find_continuable,
pat::contains_explicit_ref_binding, pat::contains_explicit_ref_binding,
BreakableKind,
}, },
lang_items::lang_items_for_bin_op, lang_items::lang_items_for_bin_op,
lower::{ lower::{
const_or_path_to_chalk, generic_arg_to_chalk, lower_to_chalk_mutability, ParamLoweringMode, ParamLoweringMode, const_or_path_to_chalk, generic_arg_to_chalk, lower_to_chalk_mutability,
}, },
mapping::{from_chalk, ToChalk}, mapping::{ToChalk, from_chalk},
method_resolution::{self, VisibleFromModule}, method_resolution::{self, VisibleFromModule},
primitive::{self, UintTy}, primitive::{self, UintTy},
static_lifetime, to_chalk_trait_id, static_lifetime, to_chalk_trait_id,
traits::FnTrait, traits::FnTrait,
Adjust, Adjustment, AdtId, AutoBorrow, Binders, CallableDefId, CallableSig, DeclContext,
DeclOrigin, FnAbi, FnPointer, FnSig, FnSubst, Interner, Rawness, Scalar, Substitution,
TraitEnvironment, TraitRef, Ty, TyBuilder, TyExt, TyKind,
}; };
use super::{ use super::{
cast::CastCheck, coerce::auto_deref_adjust_steps, find_breakable, BreakableContext, Diverges, BreakableContext, Diverges, Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch,
Expectation, InferenceContext, InferenceDiagnostic, TypeMismatch, cast::CastCheck, coerce::auto_deref_adjust_steps, find_breakable,
}; };
#[derive(Clone, Copy, PartialEq, Eq)] #[derive(Clone, Copy, PartialEq, Eq)]
@ -1556,11 +1556,7 @@ impl InferenceContext<'_> {
target_is_read, target_is_read,
) )
}; };
if type_ref.is_some() { if type_ref.is_some() { decl_ty } else { ty }
decl_ty
} else {
ty
}
} else { } else {
decl_ty decl_ty
}; };
@ -2402,11 +2398,7 @@ impl InferenceContext<'_> {
BinaryOp::Assignment { .. } => unreachable!("handled above"), BinaryOp::Assignment { .. } => unreachable!("handled above"),
}; };
if is_assign { if is_assign { self.result.standard_types.unit.clone() } else { output_ty }
self.result.standard_types.unit.clone()
} else {
output_ty
}
} }
fn is_builtin_binop(&mut self, lhs: &Ty, rhs: &Ty, op: BinaryOp) -> bool { fn is_builtin_binop(&mut self, lhs: &Ty, rhs: &Ty, op: BinaryOp) -> bool {

View file

@ -1,7 +1,7 @@
//! Finds if an expression is an immutable context or a mutable context, which is used in selecting //! Finds if an expression is an immutable context or a mutable context, which is used in selecting
//! between `Deref` and `DerefMut` or `Index` and `IndexMut` or similar. //! between `Deref` and `DerefMut` or `Index` and `IndexMut` or similar.
use chalk_ir::{cast::Cast, Mutability}; use chalk_ir::{Mutability, cast::Cast};
use hir_def::{ use hir_def::{
hir::{ hir::{
Array, AsmOperand, BinaryOp, BindingAnnotation, Expr, ExprId, Pat, PatId, Statement, Array, AsmOperand, BinaryOp, BindingAnnotation, Expr, ExprId, Pat, PatId, Statement,
@ -13,9 +13,9 @@ use hir_expand::name::Name;
use intern::sym; use intern::sym;
use crate::{ use crate::{
infer::{expr::ExprIsRead, Expectation, InferenceContext},
lower::lower_to_chalk_mutability,
Adjust, Adjustment, AutoBorrow, Interner, OverloadedDeref, TyBuilder, TyKind, Adjust, Adjustment, AutoBorrow, Interner, OverloadedDeref, TyBuilder, TyKind,
infer::{Expectation, InferenceContext, expr::ExprIsRead},
lower::lower_to_chalk_mutability,
}; };
impl InferenceContext<'_> { impl InferenceContext<'_> {

View file

@ -3,24 +3,25 @@
use std::iter::repeat_with; use std::iter::repeat_with;
use hir_def::{ use hir_def::{
HasModule,
expr_store::Body, expr_store::Body,
hir::{Binding, BindingAnnotation, BindingId, Expr, ExprId, Literal, Pat, PatId}, hir::{Binding, BindingAnnotation, BindingId, Expr, ExprId, Literal, Pat, PatId},
path::Path, path::Path,
HasModule,
}; };
use hir_expand::name::Name; use hir_expand::name::Name;
use stdx::TupleExt; use stdx::TupleExt;
use crate::{ use crate::{
DeclContext, DeclOrigin, InferenceDiagnostic, Interner, Mutability, Scalar, Substitution, Ty,
TyBuilder, TyExt, TyKind,
consteval::{self, try_const_usize, usize_const}, consteval::{self, try_const_usize, usize_const},
infer::{ infer::{
coerce::CoerceNever, expr::ExprIsRead, BindingMode, Expectation, InferenceContext, BindingMode, Expectation, InferenceContext, TypeMismatch, coerce::CoerceNever,
TypeMismatch, expr::ExprIsRead,
}, },
lower::lower_to_chalk_mutability, lower::lower_to_chalk_mutability,
primitive::UintTy, primitive::UintTy,
static_lifetime, DeclContext, DeclOrigin, InferenceDiagnostic, Interner, Mutability, Scalar, static_lifetime,
Substitution, Ty, TyBuilder, TyExt, TyKind,
}; };
impl InferenceContext<'_> { impl InferenceContext<'_> {

View file

@ -2,21 +2,22 @@
use chalk_ir::cast::Cast; use chalk_ir::cast::Cast;
use hir_def::{ use hir_def::{
AdtId, AssocItemId, GenericDefId, ItemContainerId, Lookup,
path::{Path, PathSegment}, path::{Path, PathSegment},
resolver::{ResolveValueResult, TypeNs, ValueNs}, resolver::{ResolveValueResult, TypeNs, ValueNs},
AdtId, AssocItemId, GenericDefId, ItemContainerId, Lookup,
}; };
use hir_expand::name::Name; use hir_expand::name::Name;
use stdx::never; use stdx::never;
use crate::{ use crate::{
InferenceDiagnostic, Interner, Substitution, TraitRef, TraitRefExt, Ty, TyBuilder, TyExt,
TyKind, ValueTyDefId,
builder::ParamKind, builder::ParamKind,
consteval, error_lifetime, consteval, error_lifetime,
generics::generics, generics::generics,
infer::diagnostics::InferenceTyLoweringContext as TyLoweringContext, infer::diagnostics::InferenceTyLoweringContext as TyLoweringContext,
method_resolution::{self, VisibleFromModule}, method_resolution::{self, VisibleFromModule},
to_chalk_trait_id, InferenceDiagnostic, Interner, Substitution, TraitRef, TraitRefExt, Ty, to_chalk_trait_id,
TyBuilder, TyExt, TyKind, ValueTyDefId,
}; };
use super::{ExprOrPatId, InferenceContext, InferenceTyDiagnosticSource}; use super::{ExprOrPatId, InferenceContext, InferenceTyDiagnosticSource};
@ -63,7 +64,7 @@ impl InferenceContext<'_> {
never!("uninferred pattern?"); never!("uninferred pattern?");
None None
} }
} };
} }
ValueNs::ImplSelf(impl_id) => { ValueNs::ImplSelf(impl_id) => {
let generics = crate::generics::generics(self.db.upcast(), impl_id.into()); let generics = crate::generics::generics(self.db.upcast(), impl_id.into());
@ -81,7 +82,7 @@ impl InferenceContext<'_> {
}; };
} }
ValueNs::GenericParam(it) => { ValueNs::GenericParam(it) => {
return Some(ValuePathResolution::NonGeneric(self.db.const_param_ty(it))) return Some(ValuePathResolution::NonGeneric(self.db.const_param_ty(it)));
} }
}; };

View file

@ -1,15 +1,15 @@
//! Unification and canonicalization logic. //! Unification and canonicalization logic.
use std::{fmt, iter, mem}; use std::{fmt, mem};
use chalk_ir::{ use chalk_ir::{
cast::Cast, fold::TypeFoldable, interner::HasInterner, zip::Zip, CanonicalVarKind, FloatTy, CanonicalVarKind, FloatTy, IntTy, TyVariableKind, UniverseIndex, cast::Cast,
IntTy, TyVariableKind, UniverseIndex, fold::TypeFoldable, interner::HasInterner, zip::Zip,
}; };
use chalk_solve::infer::ParameterEnaVariableExt; use chalk_solve::infer::ParameterEnaVariableExt;
use either::Either; use either::Either;
use ena::unify::UnifyKey; use ena::unify::UnifyKey;
use hir_def::{lang_item::LangItem, AdtId}; use hir_def::{AdtId, lang_item::LangItem};
use hir_expand::name::Name; use hir_expand::name::Name;
use intern::sym; use intern::sym;
use rustc_hash::FxHashMap; use rustc_hash::FxHashMap;
@ -18,12 +18,12 @@ use triomphe::Arc;
use super::{InferOk, InferResult, InferenceContext, TypeError}; use super::{InferOk, InferResult, InferenceContext, TypeError};
use crate::{ use crate::{
AliasEq, AliasTy, BoundVar, Canonical, Const, ConstValue, DebruijnIndex, DomainGoal,
GenericArg, GenericArgData, Goal, GoalData, Guidance, InEnvironment, InferenceVar, Interner,
Lifetime, OpaqueTyId, ParamKind, ProjectionTy, ProjectionTyExt, Scalar, Solution, Substitution,
TraitEnvironment, TraitRef, Ty, TyBuilder, TyExt, TyKind, VariableKind, WhereClause,
consteval::unknown_const, db::HirDatabase, fold_generic_args, fold_tys_and_consts, consteval::unknown_const, db::HirDatabase, fold_generic_args, fold_tys_and_consts,
to_chalk_trait_id, traits::FnTrait, AliasEq, AliasTy, BoundVar, Canonical, Const, ConstValue, to_chalk_trait_id, traits::FnTrait,
DebruijnIndex, DomainGoal, GenericArg, GenericArgData, Goal, GoalData, Guidance, InEnvironment,
InferenceVar, Interner, Lifetime, OpaqueTyId, ParamKind, ProjectionTy, ProjectionTyExt, Scalar,
Solution, Substitution, TraitEnvironment, TraitRef, Ty, TyBuilder, TyExt, TyKind, VariableKind,
WhereClause,
}; };
impl InferenceContext<'_> { impl InferenceContext<'_> {
@ -386,7 +386,7 @@ impl<'a> InferenceTable<'a> {
} }
fn extend_type_variable_table(&mut self, to_index: usize) { fn extend_type_variable_table(&mut self, to_index: usize) {
let count = to_index - self.type_variable_table.len() + 1; let count = to_index - self.type_variable_table.len() + 1;
self.type_variable_table.extend(iter::repeat(TypeVariableFlags::default()).take(count)); self.type_variable_table.extend(std::iter::repeat_n(TypeVariableFlags::default(), count));
} }
fn new_var(&mut self, kind: TyVariableKind, diverging: bool) -> Ty { fn new_var(&mut self, kind: TyVariableKind, diverging: bool) -> Ty {
@ -890,11 +890,7 @@ impl<'a> InferenceTable<'a> {
TyKind::Error => self.new_type_var(), TyKind::Error => self.new_type_var(),
TyKind::InferenceVar(..) => { TyKind::InferenceVar(..) => {
let ty_resolved = self.resolve_ty_shallow(&ty); let ty_resolved = self.resolve_ty_shallow(&ty);
if ty_resolved.is_unknown() { if ty_resolved.is_unknown() { self.new_type_var() } else { ty }
self.new_type_var()
} else {
ty
}
} }
_ => ty, _ => ty,
} }

View file

@ -2,14 +2,14 @@
use std::ops::ControlFlow::{self, Break, Continue}; use std::ops::ControlFlow::{self, Break, Continue};
use chalk_ir::{ use chalk_ir::{
visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor},
DebruijnIndex, DebruijnIndex,
visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor},
}; };
use hir_def::{visibility::Visibility, AdtId, EnumVariantId, ModuleId, VariantId}; use hir_def::{AdtId, EnumVariantId, ModuleId, VariantId, visibility::Visibility};
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use crate::{ use crate::{
consteval::try_const_usize, db::HirDatabase, Binders, Interner, Substitution, Ty, TyKind, Binders, Interner, Substitution, Ty, TyKind, consteval::try_const_usize, db::HirDatabase,
}; };
// FIXME: Turn this into a query, it can be quite slow // FIXME: Turn this into a query, it can be quite slow

View file

@ -2,15 +2,15 @@
//! representation of the various objects Chalk deals with (types, goals etc.). //! representation of the various objects Chalk deals with (types, goals etc.).
use crate::{ use crate::{
chalk_db, tls, AliasTy, CanonicalVarKind, CanonicalVarKinds, ClosureId, Const, ConstData, AliasTy, CanonicalVarKind, CanonicalVarKinds, ClosureId, Const, ConstData, ConstScalar,
ConstScalar, Constraint, Constraints, FnAbi, FnDefId, GenericArg, GenericArgData, Goal, Constraint, Constraints, FnAbi, FnDefId, GenericArg, GenericArgData, Goal, GoalData, Goals,
GoalData, Goals, InEnvironment, Lifetime, LifetimeData, OpaqueTy, OpaqueTyId, ProgramClause, InEnvironment, Lifetime, LifetimeData, OpaqueTy, OpaqueTyId, ProgramClause, ProgramClauseData,
ProgramClauseData, ProgramClauses, ProjectionTy, QuantifiedWhereClause, QuantifiedWhereClauses, ProgramClauses, ProjectionTy, QuantifiedWhereClause, QuantifiedWhereClauses, Substitution, Ty,
Substitution, Ty, TyData, TyKind, VariableKind, VariableKinds, TyData, TyKind, VariableKind, VariableKinds, chalk_db, tls,
}; };
use chalk_ir::{ProgramClauseImplication, SeparatorTraitRef, Variance}; use chalk_ir::{ProgramClauseImplication, SeparatorTraitRef, Variance};
use hir_def::TypeAliasId; use hir_def::TypeAliasId;
use intern::{impl_internable, Interned}; use intern::{Interned, impl_internable};
use smallvec::SmallVec; use smallvec::SmallVec;
use std::fmt; use std::fmt;
use triomphe::Arc; use triomphe::Arc;

View file

@ -1,6 +1,6 @@
//! Functions to detect special lang items //! Functions to detect special lang items
use hir_def::{data::adt::StructFlags, lang_item::LangItem, AdtId}; use hir_def::{AdtId, data::adt::StructFlags, lang_item::LangItem};
use hir_expand::name::Name; use hir_expand::name::Name;
use intern::sym; use intern::sym;

Some files were not shown because too many files have changed in this diff Show more