]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/keys.rs
Merge #6888
[rust.git] / crates / hir_def / src / keys.rs
1 //! keys to be used with `DynMap`
2
3 use std::marker::PhantomData;
4
5 use hir_expand::{InFile, MacroDefId};
6 use rustc_hash::FxHashMap;
7 use syntax::{ast, AstNode, AstPtr};
8
9 use crate::{
10     dyn_map::{DynMap, Policy},
11     ConstId, EnumId, EnumVariantId, FieldId, FunctionId, ImplId, LifetimeParamId, StaticId,
12     StructId, TraitId, TypeAliasId, TypeParamId, UnionId,
13 };
14
15 pub type Key<K, V> = crate::dyn_map::Key<InFile<K>, V, AstPtrPolicy<K, V>>;
16
17 pub const FUNCTION: Key<ast::Fn, FunctionId> = Key::new();
18 pub const CONST: Key<ast::Const, ConstId> = Key::new();
19 pub const STATIC: Key<ast::Static, StaticId> = Key::new();
20 pub const TYPE_ALIAS: Key<ast::TypeAlias, TypeAliasId> = Key::new();
21 pub const IMPL: Key<ast::Impl, ImplId> = Key::new();
22 pub const TRAIT: Key<ast::Trait, TraitId> = Key::new();
23 pub const STRUCT: Key<ast::Struct, StructId> = Key::new();
24 pub const UNION: Key<ast::Union, UnionId> = Key::new();
25 pub const ENUM: Key<ast::Enum, EnumId> = Key::new();
26
27 pub const VARIANT: Key<ast::Variant, EnumVariantId> = Key::new();
28 pub const TUPLE_FIELD: Key<ast::TupleField, FieldId> = Key::new();
29 pub const RECORD_FIELD: Key<ast::RecordField, FieldId> = Key::new();
30 pub const TYPE_PARAM: Key<ast::TypeParam, TypeParamId> = Key::new();
31 pub const LIFETIME_PARAM: Key<ast::LifetimeParam, LifetimeParamId> = Key::new();
32
33 pub const MACRO: Key<ast::MacroCall, MacroDefId> = Key::new();
34
35 /// XXX: AST Nodes and SyntaxNodes have identity equality semantics: nodes are
36 /// equal if they point to exactly the same object.
37 ///
38 /// In general, we do not guarantee that we have exactly one instance of a
39 /// syntax tree for each file. We probably should add such guarantee, but, for
40 /// the time being, we will use identity-less AstPtr comparison.
41 pub struct AstPtrPolicy<AST, ID> {
42     _phantom: PhantomData<(AST, ID)>,
43 }
44
45 impl<AST: AstNode + 'static, ID: 'static> Policy for AstPtrPolicy<AST, ID> {
46     type K = InFile<AST>;
47     type V = ID;
48     fn insert(map: &mut DynMap, key: InFile<AST>, value: ID) {
49         let key = key.as_ref().map(AstPtr::new);
50         map.map
51             .entry::<FxHashMap<InFile<AstPtr<AST>>, ID>>()
52             .or_insert_with(Default::default)
53             .insert(key, value);
54     }
55     fn get<'a>(map: &'a DynMap, key: &InFile<AST>) -> Option<&'a ID> {
56         let key = key.as_ref().map(AstPtr::new);
57         map.map.get::<FxHashMap<InFile<AstPtr<AST>>, ID>>()?.get(&key)
58     }
59 }