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