]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/keys.rs
Merge #8951
[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, MacroCallId, MacroDefId};
6 use rustc_hash::FxHashMap;
7 use syntax::{ast, AstNode, AstPtr};
8
9 use crate::{
10     dyn_map::{DynMap, Policy},
11     ConstId, ConstParamId, EnumId, EnumVariantId, FieldId, FunctionId, ImplId, LifetimeParamId,
12     StaticId, 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 pub const CONST_PARAM: Key<ast::ConstParam, ConstParamId> = Key::new();
33
34 pub const MACRO: Key<ast::MacroCall, MacroDefId> = Key::new();
35 pub const ATTR_MACRO: Key<ast::Item, MacroCallId> = Key::new();
36
37 /// XXX: AST Nodes and SyntaxNodes have identity equality semantics: nodes are
38 /// equal if they point to exactly the same object.
39 ///
40 /// In general, we do not guarantee that we have exactly one instance of a
41 /// syntax tree for each file. We probably should add such guarantee, but, for
42 /// the time being, we will use identity-less AstPtr comparison.
43 pub struct AstPtrPolicy<AST, ID> {
44     _phantom: PhantomData<(AST, ID)>,
45 }
46
47 impl<AST: AstNode + 'static, ID: 'static> Policy for AstPtrPolicy<AST, ID> {
48     type K = InFile<AST>;
49     type V = ID;
50     fn insert(map: &mut DynMap, key: InFile<AST>, value: ID) {
51         let key = key.as_ref().map(AstPtr::new);
52         map.map
53             .entry::<FxHashMap<InFile<AstPtr<AST>>, ID>>()
54             .or_insert_with(Default::default)
55             .insert(key, value);
56     }
57     fn get<'a>(map: &'a DynMap, key: &InFile<AST>) -> Option<&'a ID> {
58         let key = key.as_ref().map(AstPtr::new);
59         map.map.get::<FxHashMap<InFile<AstPtr<AST>>, ID>>()?.get(&key)
60     }
61 }