Repository: rust-analyzer/rust-analyzer
Pull request #5064 (2020-06-25 16:20:41)

Add NotificationDispatcher


bors r+
🤖


Patch:
diff --git a/crates/flycheck/src/lib.rs b/crates/flycheck/src/lib.rs
index 9e8205ae79..4dcab7a61f 100644
--- a/crates/flycheck/src/lib.rs
+++ b/crates/flycheck/src/lib.rs
@@ -120,7 +120,13 @@ impl FlycheckActor {
     ) -> FlycheckActor {
         FlycheckActor { sender, config, workspace_root, last_update_req: None, check_process: None }
     }
-
+    fn next_event(&self, inbox: &Receiver<Restart>) -> Option<Event> {
+        let check_chan = self.check_process.as_ref().map(|(chan, _thread)| chan);
+        select! {
+            recv(inbox) -> msg => msg.ok().map(Event::Restart),
+            recv(check_chan.unwrap_or(&never())) -> msg => Some(Event::CheckEvent(msg.ok())),
+        }
+    }
     fn run(&mut self, inbox: Receiver<Restart>) {
         // If we rerun the thread, we need to discard the previous check results first
         self.send(Message::ClearDiagnostics);
@@ -167,15 +173,6 @@ impl FlycheckActor {
             }
         }
     }
-
-    fn next_event(&self, inbox: &Receiver<Restart>) -> Option<Event> {
-        let check_chan = self.check_process.as_ref().map(|(chan, _thread)| chan);
-        select! {
-            recv(inbox) -> msg => msg.ok().map(Event::Restart),
-            recv(check_chan.unwrap_or(&never())) -> msg => Some(Event::CheckEvent(msg.ok())),
-        }
-    }
-
     fn should_recheck(&mut self) -> bool {
         if let Some(_last_update_req) = &self.last_update_req {
             // We currently only request an update on save, as we need up to
diff --git a/crates/ra_hir_def/src/adt.rs b/crates/ra_hir_def/src/adt.rs
index 4994a21253..2bc34d449f 100644
--- a/crates/ra_hir_def/src/adt.rs
+++ b/crates/ra_hir_def/src/adt.rs
@@ -8,12 +8,12 @@ use hir_expand::{
     InFile,
 };
 use ra_arena::{map::ArenaMap, Arena};
+use ra_prof::profile;
 use ra_syntax::ast::{self, NameOwner, TypeAscriptionOwner, VisibilityOwner};
 
 use crate::{
     body::{CfgExpander, LowerCtx},
     db::DefDatabase,
-    item_tree::{Field, Fields, ItemTree},
     src::HasChildSource,
     src::HasSource,
     trace::Trace,
@@ -22,7 +22,6 @@ use crate::{
     EnumId, HasModule, LocalEnumVariantId, LocalFieldId, Lookup, ModuleId, StructId, UnionId,
     VariantId,
 };
-use ra_cfg::CfgOptions;
 
 /// Note that we use `StructData` for unions as well!
 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -60,48 +59,39 @@ pub struct FieldData {
 
 impl StructData {
     pub(crate) fn struct_data_query(db: &dyn DefDatabase, id: StructId) -> Arc<StructData> {
-        let loc = id.lookup(db);
-        let item_tree = db.item_tree(loc.id.file_id);
-        let cfg_options = db.crate_graph()[loc.container.module(db).krate].cfg_options.clone();
+        let src = id.lookup(db).source(db);
 
-        let strukt = &item_tree[loc.id.value];
-        let variant_data = lower_fields(&item_tree, &cfg_options, &strukt.fields);
-
-        Arc::new(StructData { name: strukt.name.clone(), variant_data: Arc::new(variant_data) })
+        let name = src.value.name().map_or_else(Name::missing, |n| n.as_name());
+        let variant_data =
+            VariantData::new(db, src.map(|s| s.kind()), id.lookup(db).container.module(db));
+        let variant_data = Arc::new(variant_data);
+        Arc::new(StructData { name, variant_data })
     }
     pub(crate) fn union_data_query(db: &dyn DefDatabase, id: UnionId) -> Arc<StructData> {
-        let loc = id.lookup(db);
-        let item_tree = db.item_tree(loc.id.file_id);
-        let cfg_options = db.crate_graph()[loc.container.module(db).krate].cfg_options.clone();
-
-        let union = &item_tree[loc.id.value];
-        let variant_data = lower_fields(&item_tree, &cfg_options, &union.fields);
-
-        Arc::new(StructData { name: union.name.clone(), variant_data: Arc::new(variant_data) })
+        let src = id.lookup(db).source(db);
+        let name = src.value.name().map_or_else(Name::missing, |n| n.as_name());
+        let variant_data = VariantData::new(
+            db,
+            src.map(|s| {
+                s.record_field_def_list()
+                    .map(ast::StructKind::Record)
+                    .unwrap_or(ast::StructKind::Unit)
+            }),
+            id.lookup(db).container.module(db),
+        );
+        let variant_data = Arc::new(variant_data);
+        Arc::new(StructData { name, variant_data })
     }
 }
 
 impl EnumData {
     pub(crate) fn enum_data_query(db: &dyn DefDatabase, e: EnumId) -> Arc<EnumData> {
-        let loc = e.lookup(db);
-        let item_tree = db.item_tree(loc.id.file_id);
-        let cfg_options = db.crate_graph()[loc.container.module(db).krate].cfg_options.clone();
-
-        let enum_ = &item_tree[loc.id.value];
-        let mut variants = Arena::new();
-        for var_id in enum_.variants.clone() {
-            if item_tree.attrs(var_id.into()).is_cfg_enabled(&cfg_options) {
-                let var = &item_tree[var_id];
-                let var_data = lower_fields(&item_tree, &cfg_options, &var.fields);
-
-                variants.alloc(EnumVariantData {
-                    name: var.name.clone(),
-                    variant_data: Arc::new(var_data),
-                });
-            }
-        }
-
-        Arc::new(EnumData { name: enum_.name.clone(), variants })
+        let _p = profile("enum_data_query");
+        let src = e.lookup(db).source(db);
+        let name = src.value.name().map_or_else(Name::missing, |n| n.as_name());
+        let mut trace = Trace::new_for_arena();
+        lower_enum(db, &mut trace, &src, e.lookup(db).container.module(db));
+        Arc::new(EnumData { name, variants: trace.into_arena() })
     }
 
     pub fn variant(&self, name: &Name) -> Option<LocalEnumVariantId> {
@@ -261,35 +251,3 @@ fn lower_struct(
         ast::StructKind::Unit => StructKind::Unit,
     }
 }
-
-fn lower_fields(item_tree: &ItemTree, cfg_options: &CfgOptions, fields: &Fields) -> VariantData {
-    match fields {
-        Fields::Record(flds) => {
-            let mut arena = Arena::new();
-            for field_id in flds.clone() {
-                if item_tree.attrs(field_id.into()).is_cfg_enabled(cfg_options) {
-                    arena.alloc(lower_field(item_tree, &item_tree[field_id]));
-                }
-            }
-            VariantData::Record(arena)
-        }
-        Fields::Tuple(flds) => {
-            let mut arena = Arena::new();
-            for field_id in flds.clone() {
-                if item_tree.attrs(field_id.into()).is_cfg_enabled(cfg_options) {
-                    arena.alloc(lower_field(item_tree, &item_tree[field_id]));
-                }
-            }
-            VariantData::Tuple(arena)
-        }
-        Fields::Unit => VariantData::Unit,
-    }
-}
-
-fn lower_field(item_tree: &ItemTree, field: &Field) -> FieldData {
-    FieldData {
-        name: field.name.clone(),
-        type_ref: field.type_ref.clone(),
-        visibility: item_tree[field.visibility].clone(),
-    }
-}
diff --git a/crates/ra_hir_def/src/attr.rs b/crates/ra_hir_def/src/attr.rs
index e228e2145b..197737ffce 100644
--- a/crates/ra_hir_def/src/attr.rs
+++ b/crates/ra_hir_def/src/attr.rs
@@ -208,5 +208,5 @@ where
 fn attrs_from_item_tree<N: ItemTreeNode>(id: ItemTreeId<N>, db: &dyn DefDatabase) -> Attrs {
     let tree = db.item_tree(id.file_id);
     let mod_item = N::id_to_mod_item(id.value);
-    tree.attrs(mod_item.into()).clone()
+    tree.attrs(mod_item).clone()
 }
diff --git a/crates/ra_hir_def/src/data.rs b/crates/ra_hir_def/src/data.rs
index 282ade2a3a..f9e5701db2 100644
--- a/crates/ra_hir_def/src/data.rs
+++ b/crates/ra_hir_def/src/data.rs
@@ -40,7 +40,7 @@ impl FunctionData {
             name: func.name.clone(),
             params: func.params.to_vec(),
             ret_type: func.ret_type.clone(),
-            attrs: item_tree.attrs(ModItem::from(loc.id.value).into()).clone(),
+            attrs: item_tree.attrs(loc.id.value.into()).clone(),
             has_self_param: func.has_self_param,
             is_unsafe: func.is_unsafe,
             visibility: item_tree[func.visibility].clone(),
@@ -224,7 +224,7 @@ fn collect_items(
         match item {
             AssocItem::Function(id) => {
                 let item = &item_tree[id];
-                let attrs = item_tree.attrs(ModItem::from(id).into());
+                let attrs = item_tree.attrs(id.into());
                 if !attrs.is_cfg_enabled(&cfg_options) {
                     continue;
                 }
diff --git a/crates/ra_hir_def/src/item_tree.rs b/crates/ra_hir_def/src/item_tree.rs
index 3e603bd558..d7bc64e6ca 100644
--- a/crates/ra_hir_def/src/item_tree.rs
+++ b/crates/ra_hir_def/src/item_tree.rs
@@ -5,7 +5,6 @@ mod lower;
 mod tests;
 
 use std::{
-    any::type_name,
     fmt::{self, Debug},
     hash::{Hash, Hasher},
     marker::PhantomData,
@@ -179,8 +178,8 @@ impl ItemTree {
         self.attrs.get(&AttrOwner::TopLevel).unwrap_or(&Attrs::EMPTY)
     }
 
-    pub fn attrs(&self, of: AttrOwner) -> &Attrs {
-        self.attrs.get(&of).unwrap_or(&Attrs::EMPTY)
+    pub fn attrs(&self, of: ModItem) -> &Attrs {
+        self.attrs.get(&AttrOwner::ModItem(of)).unwrap_or(&Attrs::EMPTY)
     }
 
     /// Returns the lowered inner items that `ast` corresponds to.
@@ -283,32 +282,15 @@ struct ItemTreeData {
 }
 
 #[derive(Debug, Eq, PartialEq, Hash)]
-pub enum AttrOwner {
+enum AttrOwner {
     /// Attributes on an item.
     ModItem(ModItem),
     /// Inner attributes of the source file.
     TopLevel,
-
-    Variant(Idx<Variant>),
-    Field(Idx<Field>),
     // FIXME: Store variant and field attrs, and stop reparsing them in `attrs_query`.
 }
 
-macro_rules! from_attrs {
-    ( $( $var:ident($t:ty) ),+ ) => {
-        $(
-            impl From<$t> for AttrOwner {
-                fn from(t: $t) -> AttrOwner {
-                    AttrOwner::$var(t)
-                }
-            }
-        )+
-    };
-}
-
-from_attrs!(ModItem(ModItem), Variant(Idx<Variant>), Field(Idx<Field>));
-
-/// Trait implemented by all item nodes in the item tree.
+/// Trait implemented by all nodes in the item tree.
 pub trait ItemTreeNode: Clone {
     type Source: AstNode + Into<ast::ModuleItem>;
 
@@ -541,7 +523,7 @@ pub struct Enum {
     pub name: Name,
     pub visibility: RawVisibilityId,
     pub generic_params: GenericParamsId,
-    pub variants: IdRange<Variant>,
+    pub variants: Range<Idx<Variant>>,
     pub ast_id: FileAstId<ast::EnumDef>,
 }
 
@@ -699,48 +681,10 @@ pub struct Variant {
     pub fields: Fields,
 }
 
-pub struct IdRange<T> {
-    range: Range<u32>,
-    _p: PhantomData<T>,
-}
-
-impl<T> IdRange<T> {
-    fn new(range: Range<Idx<T>>) -> Self {
-        Self { range: range.start.into_raw().into()..range.end.into_raw().into(), _p: PhantomData }
-    }
-}
-
-impl<T> Iterator for IdRange<T> {
-    type Item = Idx<T>;
-    fn next(&mut self) -> Option<Self::Item> {
-        self.range.next().map(|raw| Idx::from_raw(raw.into()))
-    }
-}
-
-impl<T> fmt::Debug for IdRange<T> {
-    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
-        f.debug_tuple(&format!("IdRange::<{}>", type_name::<T>())).field(&self.range).finish()
-    }
-}
-
-impl<T> Clone for IdRange<T> {
-    fn clone(&self) -> Self {
-        Self { range: self.range.clone(), _p: PhantomData }
-    }
-}
-
-impl<T> PartialEq for IdRange<T> {
-    fn eq(&self, other: &Self) -> bool {
-        self.range == other.range
-    }
-}
-
-impl<T> Eq for IdRange<T> {}
-
 #[derive(Debug, Clone, PartialEq, Eq)]
 pub enum Fields {
-    Record(IdRange<Field>),
-    Tuple(IdRange<Field>),
+    Record(Range<Idx<Field>>),
+    Tuple(Range<Idx<Field>>),
     Unit,
 }
 
diff --git a/crates/ra_hir_def/src/item_tree/lower.rs b/crates/ra_hir_def/src/item_tree/lower.rs
index 5149dd141f..f10ad25f70 100644
--- a/crates/ra_hir_def/src/item_tree/lower.rs
+++ b/crates/ra_hir_def/src/item_tree/lower.rs
@@ -126,15 +126,15 @@ impl Ctx {
 
         if !attrs.is_empty() {
             for item in items.iter().flat_map(|items| &items.0) {
-                self.add_attrs((*item).into(), attrs.clone());
+                self.add_attrs(*item, attrs.clone());
             }
         }
 
         items
     }
 
-    fn add_attrs(&mut self, item: AttrOwner, attrs: Attrs) {
-        match self.tree.attrs.entry(item) {
+    fn add_attrs(&mut self, item: ModItem, attrs: Attrs) {
+        match self.tree.attrs.entry(AttrOwner::ModItem(item)) {
             Entry::Occupied(mut entry) => {
                 *entry.get_mut() = entry.get().merge(attrs);
             }
@@ -196,16 +196,15 @@ impl Ctx {
         }
     }
 
-    fn lower_record_fields(&mut self, fields: &ast::RecordFieldDefList) -> IdRange<Field> {
+    fn lower_record_fields(&mut self, fields: &ast::RecordFieldDefList) -> Range<Idx<Field>> {
         let start = self.next_field_idx();
         for field in fields.fields() {
             if let Some(data) = self.lower_record_field(&field) {
-                let idx = self.data().fields.alloc(data);
-                self.add_attrs(idx.into(), Attrs::new(&field, &self.hygiene));
+                self.data().fields.alloc(data);
             }
         }
         let end = self.next_field_idx();
-        IdRange::new(start..end)
+        start..end
     }
 
     fn lower_record_field(&mut self, field: &ast::RecordFieldDef) -> Option<Field> {
@@ -216,16 +215,15 @@ impl Ctx {
         Some(res)
     }
 
-    fn lower_tuple_fields(&mut self, fields: &ast::TupleFieldDefList) -> IdRange<Field> {
+    fn lower_tuple_fields(&mut self, fields: &ast::TupleFieldDefList) -> Range<Idx<Field>> {
         let start = self.next_field_idx();
         for (i, field) in fields.fields().enumerate() {
             if let Some(data) = self.lower_tuple_field(i, &field) {
-                let idx = self.data().fields.alloc(data);
-                self.add_attrs(idx.into(), Attrs::new(&field, &self.hygiene));
+                self.data().fields.alloc(data);
             }
         }
         let end = self.next_field_idx();
-        IdRange::new(start..end)
+        start..end
     }
 
     fn lower_tuple_field(&mut self, idx: usize, field: &ast::TupleFieldDef) -> Option<Field> {
@@ -244,7 +242,7 @@ impl Ctx {
             Some(record_field_def_list) => {
                 self.lower_fields(&StructKind::Record(record_field_def_list))
             }
-            None => Fields::Record(IdRange::new(self.next_field_idx()..self.next_field_idx())),
+            None => Fields::Record(self.next_field_idx()..self.next_field_idx()),
         };
         let ast_id = self.source_ast_id_map.ast_id(union);
         let res = Union { name, visibility, generic_params, fields, ast_id };
@@ -257,23 +255,22 @@ impl Ctx {
         let generic_params = self.lower_generic_params(GenericsOwner::Enum, enum_);
         let variants = match &enum_.variant_list() {
             Some(variant_list) => self.lower_variants(variant_list),
-            None => IdRange::new(self.next_variant_idx()..self.next_variant_idx()),
+            None => self.next_variant_idx()..self.next_variant_idx(),
         };
         let ast_id = self.source_ast_id_map.ast_id(enum_);
         let res = Enum { name, visibility, generic_params, variants, ast_id };
         Some(id(self.data().enums.alloc(res)))
     }
 
-    fn lower_variants(&mut self, variants: &ast::EnumVariantList) -> IdRange<Variant> {
+    fn lower_variants(&mut self, variants: &ast::EnumVariantList) -> Range<Idx<Variant>> {
         let start = self.next_variant_idx();
         for variant in variants.variants() {
             if let Some(data) = self.lower_variant(&variant) {
-                let idx = self.data().variants.alloc(data);
-                self.add_attrs(idx.into(), Attrs::new(&variant, &self.hygiene));
+                self.data().variants.alloc(data);
             }
         }
         let end = self.next_variant_idx();
-        IdRange::new(start..end)
+        start..end
     }
 
     fn lower_variant(&mut self, variant: &ast::EnumVariant) -> Option<Variant> {
@@ -422,7 +419,7 @@ impl Ctx {
                         let attrs = Attrs::new(&item, &this.hygiene);
                         this.collect_inner_items(item.syntax());
                         this.lower_assoc_item(&item).map(|item| {
-                            this.add_attrs(ModItem::from(item).into(), attrs);
+                            this.add_attrs(item.into(), attrs);
                             item
                         })
                     })
@@ -456,7 +453,7 @@ impl Ctx {
                 self.collect_inner_items(item.syntax());
                 let assoc = self.lower_assoc_item(&item)?;
                 let attrs = Attrs::new(&item, &self.hygiene);
-                self.add_attrs(ModItem::from(assoc).into(), attrs);
+                self.add_attrs(assoc.into(), attrs);
                 Some(assoc)
             })
             .collect();
@@ -542,7 +539,7 @@ impl Ctx {
                 .filter_map(|item| {
                     self.collect_inner_items(item.syntax());
                     let attrs = Attrs::new(&item, &self.hygiene);
-                    let id: ModItem = match item {
+                    let id = match item {
                         ast::ExternItem::FnDef(ast) => {
                             let func = self.lower_function(&ast)?;
                             func.into()
@@ -552,7 +549,7 @@ impl Ctx {
                             statik.into()
                         }
                     };
-                    self.add_attrs(id.into(), attrs);
+                    self.add_attrs(id, attrs);
                     Some(id)
                 })
                 .collect()
diff --git a/crates/ra_hir_def/src/nameres/collector.rs b/crates/ra_hir_def/src/nameres/collector.rs
index 2ced4f66bb..94da700ad3 100644
--- a/crates/ra_hir_def/src/nameres/collector.rs
+++ b/crates/ra_hir_def/src/nameres/collector.rs
@@ -742,7 +742,7 @@ impl ModCollector<'_, '_> {
         // `#[macro_use] extern crate` is hoisted to imports macros before collecting
         // any other items.
         for item in items {
-            if self.is_cfg_enabled(self.item_tree.attrs((*item).into())) {
+            if self.is_cfg_enabled(self.item_tree.attrs(*item)) {
                 if let ModItem::ExternCrate(id) = item {
                     let import = self.item_tree[*id].clone();
                     if import.is_macro_use {
@@ -753,7 +753,7 @@ impl ModCollector<'_, '_> {
         }
 
         for &item in items {
-            let attrs = self.item_tree.attrs(item.into());
+            let attrs = self.item_tree.attrs(item);
             if self.is_cfg_enabled(attrs) {
                 let module =
                     ModuleId { krate: self.def_collector.def_map.krate, local_id: self.module_id };
diff --git a/crates/rust-analyzer/src/dispatch.rs b/crates/rust-analyzer/src/dispatch.rs
new file mode 100644
index 0000000000..5fdbed8ef3
--- /dev/null
+++ b/crates/rust-analyzer/src/dispatch.rs
@@ -0,0 +1,176 @@
+//! A visitor for downcasting arbitrary request (JSON) into a specific type.
+use std::{panic, time::Instant};
+
+use serde::{de::DeserializeOwned, Serialize};
+
+use crate::{
+    global_state::{GlobalState, GlobalStateSnapshot},
+    lsp_utils::is_canceled,
+    main_loop::Task,
+    LspError, Result,
+};
+
+pub(crate) struct RequestDispatcher<'a> {
+    pub(crate) req: Option<lsp_server::Request>,
+    pub(crate) global_state: &'a mut GlobalState,
+    pub(crate) request_received: Instant,
+}
+
+impl<'a> RequestDispatcher<'a> {
+    /// Dispatches the request onto the current thread
+    pub(crate) fn on_sync<R>(
+        &mut self,
+        f: fn(&mut GlobalState, R::Params) -> Result<R::Result>,
+    ) -> Result<&mut Self>
+    where
+        R: lsp_types::request::Request + 'static,
+        R::Params: DeserializeOwned + panic::UnwindSafe + 'static,
+        R::Result: Serialize + 'static,
+    {
+        let (id, params) = match self.parse::<R>() {
+            Some(it) => it,
+            None => {
+                return Ok(self);
+            }
+        };
+        let world = panic::AssertUnwindSafe(&mut *self.global_state);
+        let task = panic::catch_unwind(move || {
+            let result = f(world.0, params);
+            result_to_task::<R>(id, result)
+        })
+        .map_err(|_| format!("sync task {:?} panicked", R::METHOD))?;
+        self.global_state.on_task(task);
+        Ok(self)
+    }
+
+    /// Dispatches the request onto thread pool
+    pub(crate) fn on<R>(
+        &mut self,
+        f: fn(GlobalStateSnapshot, R::Params) -> Result<R::Result>,
+    ) -> Result<&mut Self>
+    where
+        R: lsp_types::request::Request + 'static,
+        R::Params: DeserializeOwned + Send + 'static,
+        R::Result: Serialize + 'static,
+    {
+        let (id, params) = match self.parse::<R>() {
+            Some(it) => it,
+            None => {
+                return Ok(self);
+            }
+        };
+
+        self.global_state.task_pool.0.spawn({
+            let world = self.global_state.snapshot();
+            move || {
+                let result = f(world, params);
+                result_to_task::<R>(id, result)
+            }
+        });
+
+        Ok(self)
+    }
+
+    pub(crate) fn finish(&mut self) {
+        match self.req.take() {
+            None => (),
+            Some(req) => {
+                log::error!("unknown request: {:?}", req);
+                let resp = lsp_server::Response::new_err(
+                    req.id,
+                    lsp_server::ErrorCode::MethodNotFound as i32,
+                    "unknown request".to_string(),
+                );
+                self.global_state.send(resp.into());
+            }
+        }
+    }
+
+    fn parse<R>(&mut self) -> Option<(lsp_server::RequestId, R::Params)>
+    where
+        R: lsp_types::request::Request + 'static,
+        R::Params: DeserializeOwned + 'static,
+    {
+        let req = self.req.take()?;
+        let (id, params) = match req.extract::<R::Params>(R::METHOD) {
+            Ok(it) => it,
+            Err(req) => {
+                self.req = Some(req);
+                return None;
+            }
+        };
+        self.global_state
+            .req_queue
+            .incoming
+            .register(id.clone(), (R::METHOD, self.request_received));
+        Some((id, params))
+    }
+}
+
+fn result_to_task<R>(id: lsp_server::RequestId, result: Result<R::Result>) -> Task
+where
+    R: lsp_types::request::Request + 'static,
+    R::Params: DeserializeOwned + 'static,
+    R::Result: Serialize + 'static,
+{
+    let response = match result {
+        Ok(resp) => lsp_server::Response::new_ok(id, &resp),
+        Err(e) => match e.downcast::<LspError>() {
+            Ok(lsp_error) => lsp_server::Response::new_err(id, lsp_error.code, lsp_error.message),
+            Err(e) => {
+                if is_canceled(&*e) {
+                    lsp_server::Response::new_err(
+                        id,
+                        lsp_server::ErrorCode::ContentModified as i32,
+                        "content modified".to_string(),
+                    )
+                } else {
+                    lsp_server::Response::new_err(
+                        id,
+                        lsp_server::ErrorCode::InternalError as i32,
+                        e.to_string(),
+                    )
+                }
+            }
+        },
+    };
+    Task::Respond(response)
+}
+
+pub(crate) struct NotificationDispatcher<'a> {
+    pub(crate) not: Option<lsp_server::Notification>,
+    pub(crate) global_state: &'a mut GlobalState,
+}
+
+impl<'a> NotificationDispatcher<'a> {
+    pub(crate) fn on<N>(
+        &mut self,
+        f: fn(&mut GlobalState, N::Params) -> Result<()>,
+    ) -> Result<&mut Self>
+    where
+        N: lsp_types::notification::Notification + 'static,
+        N::Params: DeserializeOwned + Send + 'static,
+    {
+        let not = match self.not.take() {
+            Some(it) => it,
+            None => return Ok(self),
+        };
+        let params = match not.extract::<N::Params>(N::METHOD) {
+            Ok(it) => it,
+            Err(not) => {
+                self.not = Some(not);
+                return Ok(self);
+            }
+        };
+        f(self.global_state, params)?;
+        Ok(self)
+    }
+
+    pub(crate) fn finish(&mut self) {
+        if let Some(not) = &self.not {
+            if !not.method.starts_with("$/") {
+                log::error!("unhandled notification: {:?}", not);
+            }
+        }
+    }
+}
diff --git a/crates/rust-analyzer/src/global_state.rs b/crates/rust-analyzer/src/global_state.rs
index de6b956866..56d50c7899 100644
--- a/crates/rust-analyzer/src/global_state.rs
+++ b/crates/rust-analyzer/src/global_state.rs
@@ -5,7 +5,7 @@
 
 use std::{convert::TryFrom, sync::Arc};
 
-use crossbeam_channel::{unbounded, Receiver};
+use crossbeam_channel::{unbounded, Receiver, Sender};
 use flycheck::{FlycheckConfig, FlycheckHandle};
 use lsp_types::Url;
 use parking_lot::RwLock;
@@ -22,6 +22,7 @@ use crate::{
     line_endings::LineEndings,
     main_loop::{ReqQueue, Task},
     request_metrics::{LatestRequests, RequestMetrics},
+    show_message,
     thread_pool::TaskPool,
     to_proto::url_from_abs_path,
     Result,
@@ -66,6 +67,7 @@ impl Default for Status {
 /// snapshot of the file systems, and `analysis_host`, which stores our
 /// incremental salsa database.
 pub(crate) struct GlobalState {
+    sender: Sender<lsp_server::Message>,
     pub(crate) config: Config,
     pub(crate) task_pool: (TaskPool<Task>, Receiver<Task>),
     pub(crate) analysis_host: AnalysisHost,
@@ -95,6 +97,7 @@ pub(crate) struct GlobalStateSnapshot {
 
 impl GlobalState {
     pub(crate) fn new(
+        sender: Sender<lsp_server::Message>,
         workspaces: Vec<ProjectWorkspace>,
         lru_capacity: Option<usize>,
         config: Config,
@@ -162,6 +165,7 @@ impl GlobalState {
         };
 
         let mut res = GlobalState {
+            sender,
             config,
             task_pool,
             analysis_host,
@@ -252,6 +256,19 @@ impl GlobalState {
     pub(crate) fn complete_request(&mut self, request: RequestMetrics) {
         self.latest_requests.write().record(request)
     }
+
+    pub(crate) fn send(&mut self, message: lsp_server::Message) {
+        self.sender.send(message).unwrap()
+    }
+    pub(crate) fn show_message(&mut self, typ: lsp_types::MessageType, message: String) {
+        show_message(typ, message, &self.sender)
+    }
+}
+
+impl Drop for GlobalState {
+    fn drop(&mut self) {
+        self.analysis_host.request_cancellation()
+    }
 }
 
 impl GlobalStateSnapshot {
diff --git a/crates/rust-analyzer/src/lib.rs b/crates/rust-analyzer/src/lib.rs
index ca788dd3cf..d503fe96e2 100644
--- a/crates/rust-analyzer/src/lib.rs
+++ b/crates/rust-analyzer/src/lib.rs
@@ -19,6 +19,7 @@ macro_rules! eprintln {
 
 mod global_state;
 mod main_loop;
+mod dispatch;
 mod handlers;
 mod caps;
 mod cargo_target_spec;
diff --git a/crates/rust-analyzer/src/lsp_utils.rs b/crates/rust-analyzer/src/lsp_utils.rs
index 14adb8ae73..35917030c8 100644
--- a/crates/rust-analyzer/src/lsp_utils.rs
+++ b/crates/rust-analyzer/src/lsp_utils.rs
@@ -1,12 +1,13 @@
 //! Utilities for LSP-related boilerplate code.
 use std::{error::Error, ops::Range};
 
-use crate::from_proto;
 use crossbeam_channel::Sender;
 use lsp_server::{Message, Notification};
 use ra_db::Canceled;
 use ra_ide::LineIndex;
-use serde::{de::DeserializeOwned, Serialize};
+use serde::Serialize;
+
+use crate::from_proto;
 
 pub fn show_message(
     typ: lsp_types::MessageType,
@@ -29,14 +30,6 @@ pub(crate) fn notification_is<N: lsp_types::notification::Notification>(
     notification.method == N::METHOD
 }
 
-pub(crate) fn notification_cast<N>(notification: Notification) -> Result<N::Params, Notification>
-where
-    N: lsp_types::notification::Notification,
-    N::Params: DeserializeOwned,
-{
-    notification.extract(N::METHOD)
-}
-
 pub(crate) fn notification_new<N>(params: N::Params) -> Notification
 where
     N: lsp_types::notification::Notification,
diff --git a/crates/rust-analyzer/src/main_loop.rs b/crates/rust-analyzer/src/main_loop.rs
index 1a9c5ee2ce..c2f43df1d0 100644
--- a/crates/rust-analyzer/src/main_loop.rs
+++ b/crates/rust-analyzer/src/main_loop.rs
@@ -5,27 +5,26 @@ use std::{
     time::{Duration, Instant},
 };
 
-use crossbeam_channel::{never, select, RecvError, Sender};
-use lsp_server::{Connection, ErrorCode, Notification, Request, RequestId, Response};
-use lsp_types::{request::Request as _, NumberOrString};
+use crossbeam_channel::{never, select, Receiver};
+use lsp_server::{Connection, Notification, Request, Response};
+use lsp_types::{notification::Notification as _, request::Request as _};
 use ra_db::VfsPath;
 use ra_ide::{Canceled, FileId};
 use ra_prof::profile;
 use ra_project_model::{PackageRoot, ProjectWorkspace};
-use serde::{de::DeserializeOwned, Serialize};
 
 use crate::{
     config::{Config, FilesWatcher, LinkedProject},
     diagnostics::DiagnosticTask,
+    dispatch::{NotificationDispatcher, RequestDispatcher},
     from_proto,
-    global_state::{file_id_to_url, GlobalState, GlobalStateSnapshot, Status},
+    global_state::{file_id_to_url, GlobalState, Status},
     handlers, lsp_ext,
     lsp_utils::{
-        apply_document_changes, is_canceled, notification_cast, notification_is, notification_new,
-        show_message,
+        apply_document_changes, is_canceled, notification_is, notification_new, show_message,
     },
     request_metrics::RequestMetrics,
-    LspError, Result,
+    Result,
 };
 
 pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
@@ -50,7 +49,7 @@ pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
         SetThreadPriority(thread, thread_priority_above_normal);
     }
 
-    let mut global_state = {
+    let global_state = {
         let workspaces = {
             if config.linked_projects.is_empty() && config.notifications.cargo_toml_not_found {
                 show_message(
@@ -113,40 +112,346 @@ pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
             connection.sender.send(request.into()).unwrap();
         }
 
-        GlobalState::new(workspaces, config.lru_capacity, config, req_queue)
+        GlobalState::new(
+            connection.sender.clone(),
+            workspaces,
+            config.lru_capacity,
+            config,
+            req_queue,
+        )
     };
 
     log::info!("server initialized, serving requests");
-    {
-        loop {
-            log::trace!("selecting");
-            let event = select! {
-                recv(&connection.receiver) -> msg => match msg {
-                    Ok(msg) => Event::Lsp(msg),
-                    Err(RecvError) => return Err("client exited without shutdown".into()),
-                },
-                recv(&global_state.task_pool.1) -> task => Event::Task(task.unwrap()),
-                recv(global_state.task_receiver) -> task => match task {
-                    Ok(task) => Event::Vfs(task),
-                    Err(RecvError) => return Err("vfs died".into()),
+    global_state.run(connection.receiver)?;
+    Ok(())
+}
+
+impl GlobalState {
+    fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {
+        select! {
+            recv(inbox) -> msg =>
+                msg.ok().map(Event::Lsp),
+
+            recv(self.task_pool.1) -> task =>
+                Some(Event::Task(task.unwrap())),
+
+            recv(self.task_receiver) -> task =>
+                Some(Event::Vfs(task.unwrap())),
+
+            recv(self.flycheck.as_ref().map_or(&never(), |it| &it.1)) -> task =>
+                Some(Event::Flycheck(task.unwrap())),
+        }
+    }
+
+    fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
+        while let Some(event) = self.next_event(&inbox) {
+            let loop_start = Instant::now();
+            // NOTE: don't count blocking select! call as a loop-turn time
+            let _p = profile("main_loop_inner/loop-turn");
+
+            log::info!("loop turn = {:?}", event);
+            let queue_count = self.task_pool.0.len();
+            if queue_count > 0 {
+                log::info!("queued count = {}", queue_count);
+            }
+
+            let mut became_ready = false;
+            match event {
+                Event::Lsp(msg) => match msg {
+                    lsp_server::Message::Request(req) => self.on_request(loop_start, req)?,
+                    lsp_server::Message::Notification(not) => {
+                        if not.method == lsp_types::notification::Exit::METHOD {
+                            return Ok(());
+                        }
+                        self.on_notification(not)?;
+                    }
+                    lsp_server::Message::Response(resp) => {
+                        let handler = self.req_queue.outgoing.complete(resp.id.clone());
+                        handler(&mut self, resp)
+                    }
                 },
-                recv(global_state.flycheck.as_ref().map_or(&never(), |it| &it.1)) -> task => match task {
-                    Ok(task) => Event::Flycheck(task),
-                    Err(RecvError) => return Err("check watcher died".into()),
+                Event::Task(task) => {
+                    self.on_task(task);
+                    self.maybe_collect_garbage();
+                }
+                Event::Vfs(task) => match task {
+                    vfs::loader::Message::Loaded { files } => {
+                        let vfs = &mut self.vfs.write().0;
+                        for (path, contents) in files {
+                            let path = VfsPath::from(path);
+                            if !self.mem_docs.contains(&path) {
+                                vfs.set_file_contents(path, contents)
+                            }
+                        }
+                    }
+                    vfs::loader::Message::Progress { n_total, n_done } => {
+                        let state = if n_done == 0 {
+                            Progress::Begin
+                        } else if n_done < n_total {
+                            Progress::Report
+                        } else {
+                            assert_eq!(n_done, n_total);
+                            self.status = Status::Ready;
+                            became_ready = true;
+                            Progress::End
+                        };
+                        report_progress(
+                            &mut self,
+                            "roots scanned",
+                            state,
+                            Some(format!("{}/{}", n_done, n_total)),
+                            Some(percentage(n_done, n_total)),
+                        )
+                    }
                 },
-            };
-            if let Event::Lsp(lsp_server::Message::Request(req)) = &event {
-                if connection.handle_shutdown(&req)? {
-                    break;
+                Event::Flycheck(task) => on_check_task(task, &mut self)?,
+            }
+
+            let state_changed = self.process_changes();
+            if became_ready {
+                if let Some(flycheck) = &self.flycheck {
+                    flycheck.0.update();
+                }
+            }
+
+            if self.status == Status::Ready && (state_changed || became_ready) {
+                let subscriptions = self
+                    .mem_docs
+                    .iter()
+                    .map(|path| self.vfs.read().0.file_id(&path).unwrap())
+                    .collect::<Vec<_>>();
+
+                self.update_file_notifications_on_threadpool(subscriptions);
+            }
+
+            let loop_duration = loop_start.elapsed();
+            if loop_duration > Duration::from_millis(100) {
+                log::error!("overly long loop turn: {:?}", loop_duration);
+                if env::var("RA_PROFILE").is_ok() {
+                    self.show_message(
+                        lsp_types::MessageType::Error,
+                        format!("overly long loop turn: {:?}", loop_duration),
+                    )
+                }
+            }
+        }
+        Err("client exited without proper shutdown sequence")?
+    }
+
+    fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
+        RequestDispatcher { req: Some(req), global_state: self, request_received }
+            .on_sync::<lsp_ext::CollectGarbage>(|s, ()| Ok(s.collect_garbage()))?
+            .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
+            .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
+            .on_sync::<lsp_types::request::Shutdown>(|_, ()| Ok(()))?
+            .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
+                handlers::handle_selection_range(s.snapshot(), p)
+            })?
+            .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
+                handlers::handle_matching_brace(s.snapshot(), p)
+            })?
+            .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)?
+            .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)?
+            .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)?
+            .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)?
+            .on::<lsp_ext::Runnables>(handlers::handle_runnables)?
+            .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)?
+            .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)?
+            .on::<lsp_ext::ResolveCodeActionRequest>(handlers::handle_resolve_code_action)?
+            .on::<lsp_ext::HoverRequest>(handlers::handle_hover)?
+            .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)?
+            .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)?
+            .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)?
+            .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)?
+            .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)?
+            .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)?
+            .on::<lsp_types::request::Completion>(handlers::handle_completion)?
+            .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)?
+            .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)?
+            .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)?
+            .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)?
+            .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)?
+            .on::<lsp_types::request::Rename>(handlers::handle_rename)?
+            .on::<lsp_types::request::References>(handlers::handle_references)?
+            .on::<lsp_types::request::Formatting>(handlers::handle_formatting)?
+            .on::<lsp_types::request::DocumentHighlightRequest>(
+                handlers::handle_document_highlight,
+            )?
+            .on::<lsp_types::request::CallHierarchyPrepare>(
+                handlers::handle_call_hierarchy_prepare,
+            )?
+            .on::<lsp_types::request::CallHierarchyIncomingCalls>(
+                handlers::handle_call_hierarchy_incoming,
+            )?
+            .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
+                handlers::handle_call_hierarchy_outgoing,
+            )?
+            .on::<lsp_types::request::SemanticTokensRequest>(handlers::handle_semantic_tokens)?
+            .on::<lsp_types::request::SemanticTokensRangeRequest>(
+                handlers::handle_semantic_tokens_range,
+            )?
+            .on::<lsp_ext::Ssr>(handlers::handle_ssr)?
+            .finish();
+        Ok(())
+    }
+    fn on_notification(&mut self, not: Notification) -> Result<()> {
+        NotificationDispatcher { not: Some(not), global_state: self }
+            .on::<lsp_types::notification::Cancel>(|this, params| {
+                let id: lsp_server::RequestId = match params.id {
+                    lsp_types::NumberOrString::Number(id) => id.into(),
+                    lsp_types::NumberOrString::String(id) => id.into(),
+                };
+                if let Some(response) = this.req_queue.incoming.cancel(id) {
+                    this.send(response.into());
+                }
+                Ok(())
+            })?
+            .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
+                if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
+                    if !this.mem_docs.insert(path.clone()) {
+                        log::error!("duplicate DidOpenTextDocument: {}", path)
+                    }
+                    this.vfs
+                        .write()
+                        .0
+                        .set_file_contents(path, Some(params.text_document.text.into_bytes()));
+                }
+                Ok(())
+            })?
+            .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
+                if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
+                    assert!(this.mem_docs.contains(&path));
+                    let vfs = &mut this.vfs.write().0;
+                    let file_id = vfs.file_id(&path).unwrap();
+                    let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
+                    apply_document_changes(&mut text, params.content_changes);
+                    vfs.set_file_contents(path, Some(text.into_bytes()))
+                }
+                Ok(())
+            })?
+            .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
+                if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
+                    if !this.mem_docs.remove(&path) {
+                        log::error!("orphan DidCloseTextDocument: {}", path)
+                    }
+                    if let Some(path) = path.as_path() {
+                        this.loader.invalidate(path.to_path_buf());
+                    }
+                }
+                let params = lsp_types::PublishDiagnosticsParams {
+                    uri: params.text_document.uri,
+                    diagnostics: Vec::new(),
+                    version: None,
                 };
+                let not = notification_new::<lsp_types::notification::PublishDiagnostics>(params);
+                this.send(not.into());
+                Ok(())
+            })?
+            .on::<lsp_types::notification::DidSaveTextDocument>(|this, _params| {
+                if let Some(flycheck) = &this.flycheck {
+                    flycheck.0.update();
+                }
+                Ok(())
+            })?
+            .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
+                // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
+                // this notification's parameters should be ignored and the actual config queried separately.
+                let request = this.req_queue.outgoing.register(
+                    lsp_types::request::WorkspaceConfiguration::METHOD.to_string(),
+                    lsp_types::ConfigurationParams {
+                        items: vec![lsp_types::ConfigurationItem {
+                            scope_uri: None,
+                            section: Some("rust-analyzer".to_string()),
+                        }],
+                    },
+                    |this, resp| {
+                        log::debug!("config update response: '{:?}", resp);
+                        let Response { error, result, .. } = resp;
+
+                        match (error, result) {
+                            (Some(err), _) => {
+                                log::error!("failed to fetch the server settings: {:?}", err)
+                            }
+                            (None, Some(configs)) => {
+                                if let Some(new_config) = configs.get(0) {
+                                    let mut config = this.config.clone();
+                                    config.update(&new_config);
+                                    this.update_configuration(config);
+                                }
+                            }
+                            (None, None) => log::error!(
+                                "received empty server settings response from the client"
+                            ),
+                        }
+                    },
+                );
+                this.send(request.into());
+
+                return Ok(());
+            })?
+            .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
+                for change in params.changes {
+                    if let Ok(path) = from_proto::abs_path(&change.uri) {
+                        this.loader.invalidate(path);
+                    }
+                }
+                Ok(())
+            })?
+            .finish();
+        Ok(())
+    }
+    pub(crate) fn on_task(&mut self, task: Task) {
+        match task {
+            Task::Respond(response) => {
+                if let Some((method, start)) = self.req_queue.incoming.complete(response.id.clone())
+                {
+                    let duration = start.elapsed();
+                    log::info!("handled req#{} in {:?}", response.id, duration);
+                    self.complete_request(RequestMetrics {
+                        id: response.id.clone(),
+                        method: method.to_string(),
+                        duration,
+                    });
+                    self.send(response.into());
+                }
             }
-            assert!(!global_state.vfs.read().0.has_changes());
-            loop_turn(&connection, &mut global_state, event)?;
-            assert!(!global_state.vfs.read().0.has_changes());
+            Task::Diagnostics(tasks) => {
+                tasks.into_iter().for_each(|task| on_diagnostic_task(task, self))
+            }
+            Task::Unit => (),
         }
     }
-    global_state.analysis_host.request_cancellation();
-    Ok(())
+    fn update_file_notifications_on_threadpool(&mut self, subscriptions: Vec<FileId>) {
+        log::trace!("updating notifications for {:?}", subscriptions);
+        if self.config.publish_diagnostics {
+            let snapshot = self.snapshot();
+            let subscriptions = subscriptions.clone();
+            self.task_pool.0.spawn(move || {
+                let diagnostics = subscriptions
+                    .into_iter()
+                    .filter_map(|file_id| {
+                        handlers::publish_diagnostics(&snapshot, file_id)
+                            .map_err(|err| {
+                                if !is_canceled(&*err) {
+                                    log::error!("failed to compute diagnostics: {:?}", err);
+                                }
+                                ()
+                            })
+                            .ok()
+                    })
+                    .collect::<Vec<_>>();
+                Task::Diagnostics(diagnostics)
+            })
+        }
+        self.task_pool.0.spawn({
+            let subs = subscriptions;
+            let snap = self.snapshot();
+            move || {
+                snap.analysis.prime_caches(subs).unwrap_or_else(|_: Canceled| ());
+                Task::Unit
+            }
+        });
+    }
 }
 
 #[derive(Debug)]
@@ -199,333 +504,10 @@ pub(crate) type ReqHandler = fn(&mut GlobalState, Response);
 pub(crate) type ReqQueue = lsp_server::ReqQueue<(&'static str, Instant), ReqHandler>;
 const DO_NOTHING: ReqHandler = |_, _| ();
 
-fn loop_turn(connection: &Connection, global_state: &mut GlobalState, event: Event) -> Result<()> {
-    let loop_start = Instant::now();
-
-    // NOTE: don't count blocking select! call as a loop-turn time
-    let _p = profile("main_loop_inner/loop-turn");
-    log::info!("loop turn = {:?}", event);
-    let queue_count = global_state.task_pool.0.len();
-    if queue_count > 0 {
-        log::info!("queued count = {}", queue_count);
-    }
-
-    let mut became_ready = false;
-    match event {
-        Event::Task(task) => {
-            on_task(task, &connection.sender, global_state);
-            global_state.maybe_collect_garbage();
-        }
-        Event::Vfs(task) => match task {
-            vfs::loader::Message::Loaded { files } => {
-                let vfs = &mut global_state.vfs.write().0;
-                for (path, contents) in files {
-                    let path = VfsPath::from(path);
-                    if !global_state.mem_docs.contains(&path) {
-                        vfs.set_file_contents(path, contents)
-                    }
-                }
-            }
-            vfs::loader::Message::Progress { n_total, n_done } => {
-                let state = if n_done == 0 {
-                    Progress::Begin
-                } else if n_done < n_total {
-                    Progress::Report
-                } else {
-                    assert_eq!(n_done, n_total);
-                    global_state.status = Status::Ready;
-                    became_ready = true;
-                    Progress::End
-                };
-                report_progress(
-                    global_state,
-                    &connection.sender,
-                    "roots scanned",
-                    state,
-                    Some(format!("{}/{}", n_done, n_total)),
-                    Some(percentage(n_done, n_total)),
-                )
-            }
-        },
-        Event::Flycheck(task) => on_check_task(task, global_state, &connection.sender)?,
-        Event::Lsp(msg) => match msg {
-            lsp_server::Message::Request(req) => {
-                on_request(global_state, &connection.sender, loop_start, req)?
-            }
-            lsp_server::Message::Notification(not) => {
-                on_notification(&connection.sender, global_state, not)?;
-            }
-            lsp_server::Message::Response(resp) => {
-                let handler = global_state.req_queue.outgoing.complete(resp.id.clone());
-                handler(global_state, resp)
-            }
-        },
-    };
-
-    let state_changed = global_state.process_changes();
-
-    if became_ready {
-        if let Some(flycheck) = &global_state.flycheck {
-            flycheck.0.update();
-        }
-    }
-
-    if global_state.status == Status::Ready && (state_changed || became_ready) {
-        let subscriptions = global_state
-            .mem_docs
-            .iter()
-            .map(|path| global_state.vfs.read().0.file_id(&path).unwrap())
-            .collect::<Vec<_>>();
-
-        update_file_notifications_on_threadpool(global_state, subscriptions.clone());
-        global_state.task_pool.0.spawn({
-            let subs = subscriptions;
-            let snap = global_state.snapshot();
-            move || {
-                snap.analysis.prime_caches(subs).unwrap_or_else(|_: Canceled| ());
-                Task::Unit
-            }
-        });
-    }
-
-    let loop_duration = loop_start.elapsed();
-    if loop_duration > Duration::from_millis(100) {
-        log::error!("overly long loop turn: {:?}", loop_duration);
-        if env::var("RA_PROFILE").is_ok() {
-            show_message(
-                lsp_types::MessageType::Error,
-                format!("overly long loop turn: {:?}", loop_duration),
-                &connection.sender,
-            );
-        }
-    }
-
-    Ok(())
-}
-
-fn on_task(task: Task, msg_sender: &Sender<lsp_server::Message>, global_state: &mut GlobalState) {
-    match task {
-        Task::Respond(response) => {
-            if let Some((method, start)) =
-                global_state.req_queue.incoming.complete(response.id.clone())
-            {
-                let duration = start.elapsed();
-                log::info!("handled req#{} in {:?}", response.id, duration);
-                global_state.complete_request(RequestMetrics {
-                    id: response.id.clone(),
-                    method: method.to_string(),
-                    duration,
-                });
-                msg_sender.send(response.into()).unwrap();
-            }
-        }
-        Task::Diagnostics(tasks) => {
-            tasks.into_iter().for_each(|task| on_diagnostic_task(task, msg_sender, global_state))
-        }
-        Task::Unit => (),
-    }
-}
-
-fn on_request(
-    global_state: &mut GlobalState,
-    msg_sender: &Sender<lsp_server::Message>,
-    request_received: Instant,
-    req: Request,
-) -> Result<()> {
-    let mut pool_dispatcher =
-        PoolDispatcher { req: Some(req), global_state, msg_sender, request_received };
-    pool_dispatcher
-        .on_sync::<lsp_ext::CollectGarbage>(|s, ()| Ok(s.collect_garbage()))?
-        .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
-        .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
-        .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
-            handlers::handle_selection_range(s.snapshot(), p)
-        })?
-        .on_sync::<lsp_ext::MatchingBrace>(|s, p| handlers::handle_matching_brace(s.snapshot(), p))?
-        .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)?
-        .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)?
-        .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)?
-        .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)?
-        .on::<lsp_ext::Runnables>(handlers::handle_runnables)?
-        .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)?
-        .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)?
-        .on::<lsp_ext::ResolveCodeActionRequest>(handlers::handle_resolve_code_action)?
-        .on::<lsp_ext::HoverRequest>(handlers::handle_hover)?
-        .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)?
-        .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)?
-        .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)?
-        .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)?
-        .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)?
-        .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)?
-        .on::<lsp_types::request::Completion>(handlers::handle_completion)?
-        .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)?
-        .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)?
-        .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)?
-        .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)?
-        .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)?
-        .on::<lsp_types::request::Rename>(handlers::handle_rename)?
-        .on::<lsp_types::request::References>(handlers::handle_references)?
-        .on::<lsp_types::request::Formatting>(handlers::handle_formatting)?
-        .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)?
-        .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)?
-        .on::<lsp_types::request::CallHierarchyIncomingCalls>(
-            handlers::handle_call_hierarchy_incoming,
-        )?
-        .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
-            handlers::handle_call_hierarchy_outgoing,
-        )?
-        .on::<lsp_types::request::SemanticTokensRequest>(handlers::handle_semantic_tokens)?
-        .on::<lsp_types::request::SemanticTokensRangeRequest>(
-            handlers::handle_semantic_tokens_range,
-        )?
-        .on::<lsp_ext::Ssr>(handlers::handle_ssr)?
-        .finish();
-    Ok(())
-}
-
-fn on_notification(
-    msg_sender: &Sender<lsp_server::Message>,
-    global_state: &mut GlobalState,
-    not: Notification,
-) -> Result<()> {
-    let not = match notification_cast::<lsp_types::notification::Cancel>(not) {
-        Ok(params) => {
-            let id: RequestId = match params.id {
-                NumberOrString::Number(id) => id.into(),
-                NumberOrString::String(id) => id.into(),
-            };
-            if let Some(response) = global_state.req_queue.incoming.cancel(id) {
-                msg_sender.send(response.into()).unwrap()
-            }
-            return Ok(());
-        }
-        Err(not) => not,
-    };
-    let not = match notification_cast::<lsp_types::notification::DidOpenTextDocument>(not) {
-        Ok(params) => {
-            if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
-                if !global_state.mem_docs.insert(path.clone()) {
-                    log::error!("duplicate DidOpenTextDocument: {}", path)
-                }
-                global_state
-                    .vfs
-                    .write()
-                    .0
-                    .set_file_contents(path, Some(params.text_document.text.into_bytes()));
-            }
-            return Ok(());
-        }
-        Err(not) => not,
-    };
-    let not = match notification_cast::<lsp_types::notification::DidChangeTextDocument>(not) {
-        Ok(params) => {
-            if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
-                assert!(global_state.mem_docs.contains(&path));
-                let vfs = &mut global_state.vfs.write().0;
-                let file_id = vfs.file_id(&path).unwrap();
-                let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
-                apply_document_changes(&mut text, params.content_changes);
-                vfs.set_file_contents(path, Some(text.into_bytes()))
-            }
-            return Ok(());
-        }
-        Err(not) => not,
-    };
-    let not = match notification_cast::<lsp_types::notification::DidCloseTextDocument>(not) {
-        Ok(params) => {
-            if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
-                if !global_state.mem_docs.remove(&path) {
-                    log::error!("orphan DidCloseTextDocument: {}", path)
-                }
-                if let Some(path) = path.as_path() {
-                    global_state.loader.invalidate(path.to_path_buf());
-                }
-            }
-            let params = lsp_types::PublishDiagnosticsParams {
-                uri: params.text_document.uri,
-                diagnostics: Vec::new(),
-                version: None,
-            };
-            let not = notification_new::<lsp_types::notification::PublishDiagnostics>(params);
-            msg_sender.send(not.into()).unwrap();
-            return Ok(());
-        }
-        Err(not) => not,
-    };
-    let not = match notification_cast::<lsp_types::notification::DidSaveTextDocument>(not) {
-        Ok(_params) => {
-            if let Some(flycheck) = &global_state.flycheck {
-                flycheck.0.update();
-            }
-            return Ok(());
-        }
-        Err(not) => not,
-    };
-    let not = match notification_cast::<lsp_types::notification::DidChangeConfiguration>(not) {
-        Ok(_) => {
-            // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
-            // this notification's parameters should be ignored and the actual config queried separately.
-            let request = global_state.req_queue.outgoing.register(
-                lsp_types::request::WorkspaceConfiguration::METHOD.to_string(),
-                lsp_types::ConfigurationParams {
-                    items: vec![lsp_types::ConfigurationItem {
-                        scope_uri: None,
-                        section: Some("rust-analyzer".to_string()),
-                    }],
-                },
-                |global_state, resp| {
-                    log::debug!("config update response: '{:?}", resp);
-                    let Response { error, result, .. } = resp;
-
-                    match (error, result) {
-                        (Some(err), _) => {
-                            log::error!("failed to fetch the server settings: {:?}", err)
-                        }
-                        (None, Some(configs)) => {
-                            if let Some(new_config) = configs.get(0) {
-                                let mut config = global_state.config.clone();
-                                config.update(&new_config);
-                                global_state.update_configuration(config);
-                            }
-                        }
-                        (None, None) => {
-                            log::error!("received empty server settings response from the client")
-                        }
-                    }
-                },
-            );
-            msg_sender.send(request.into())?;
-
-            return Ok(());
-        }
-        Err(not) => not,
-    };
-    let not = match notification_cast::<lsp_types::notification::DidChangeWatchedFiles>(not) {
-        Ok(params) => {
-            for change in params.changes {
-                if let Ok(path) = from_proto::abs_path(&change.uri) {
-                    global_state.loader.invalidate(path)
-                }
-            }
-            return Ok(());
-        }
-        Err(not) => not,
-    };
-    if not.method.starts_with("$/") {
-        return Ok(());
-    }
-    log::error!("unhandled notification: {:?}", not);
-    Ok(())
-}
-
-fn on_check_task(
-    task: flycheck::Message,
-    global_state: &mut GlobalState,
-    msg_sender: &Sender<lsp_server::Message>,
-) -> Result<()> {
+fn on_check_task(task: flycheck::Message, global_state: &mut GlobalState) -> Result<()> {
     match task {
         flycheck::Message::ClearDiagnostics => {
-            on_diagnostic_task(DiagnosticTask::ClearCheck, msg_sender, global_state)
+            on_diagnostic_task(DiagnosticTask::ClearCheck, global_state)
         }
 
         flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
@@ -550,7 +532,6 @@ fn on_check_task(
                         diag.diagnostic,
                         diag.fixes.into_iter().map(|it| it.into()).collect(),
                     ),
-                    msg_sender,
                     global_state,
                 )
             }
@@ -563,26 +544,22 @@ fn on_check_task(
                 flycheck::Progress::End => (Progress::End, None),
             };
 
-            report_progress(global_state, msg_sender, "cargo check", state, message, None);
+            report_progress(global_state, "cargo check", state, message, None);
         }
     };
 
     Ok(())
 }
 
-fn on_diagnostic_task(
-    task: DiagnosticTask,
-    msg_sender: &Sender<lsp_server::Message>,
-    state: &mut GlobalState,
-) {
-    let subscriptions = state.diagnostics.handle_task(task);
+fn on_diagnostic_task(task: DiagnosticTask, global_state: &mut GlobalState) {
+    let subscriptions = global_state.diagnostics.handle_task(task);
 
     for file_id in subscriptions {
-        let url = file_id_to_url(&state.vfs.read().0, file_id);
-        let diagnostics = state.diagnostics.diagnostics_for(file_id).cloned().collect();
+        let url = file_id_to_url(&global_state.vfs.read().0, file_id);
+        let diagnostics = global_state.diagnostics.diagnostics_for(file_id).cloned().collect();
         let params = lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version: None };
         let not = notification_new::<lsp_types::notification::PublishDiagnostics>(params);
-        msg_sender.send(not.into()).unwrap();
+        global_state.send(not.into());
     }
 }
 
@@ -599,7 +576,6 @@ fn percentage(done: usize, total: usize) -> f64 {
 
 fn report_progress(
     global_state: &mut GlobalState,
-    sender: &Sender<lsp_server::Message>,
     title: &str,
     state: Progress,
     message: Option<String>,
@@ -616,7 +592,7 @@ fn report_progress(
                 lsp_types::WorkDoneProgressCreateParams { token: token.clone() },
                 DO_NOTHING,
             );
-            sender.send(work_done_progress_create.into()).unwrap();
+            global_state.send(work_done_progress_create.into());
 
             lsp_types::WorkDoneProgress::Begin(lsp_types::WorkDoneProgressBegin {
                 title: title.into(),
@@ -641,155 +617,5 @@ fn report_progress(
             token,
             value: lsp_types::ProgressParamsValue::WorkDone(work_done_progress),
         });
-    sender.send(notification.into()).unwrap();
-}
-
-struct PoolDispatcher<'a> {
-    req: Option<Request>,
-    global_state: &'a mut GlobalState,
-    msg_sender: &'a Sender<lsp_server::Message>,
-    request_received: Instant,
-}
-
-impl<'a> PoolDispatcher<'a> {
-    /// Dispatches the request onto the current thread
-    fn on_sync<R>(
-        &mut self,
-        f: fn(&mut GlobalState, R::Params) -> Result<R::Result>,
-    ) -> Result<&mut Self>
-    where
-        R: lsp_types::request::Request + 'static,
-        R::Params: DeserializeOwned + panic::UnwindSafe + 'static,
-        R::Result: Serialize + 'static,
-    {
-        let (id, params) = match self.parse::<R>() {
-            Some(it) => it,
-            None => {
-                return Ok(self);
-            }
-        };
-        let world = panic::AssertUnwindSafe(&mut *self.global_state);
-        let task = panic::catch_unwind(move || {
-            let result = f(world.0, params);
-            result_to_task::<R>(id, result)
-        })
-        .map_err(|_| format!("sync task {:?} panicked", R::METHOD))?;
-        on_task(task, self.msg_sender, self.global_state);
-        Ok(self)
-    }
-
-    /// Dispatches the request onto thread pool
-    fn on<R>(
-        &mut self,
-        f: fn(GlobalStateSnapshot, R::Params) -> Result<R::Result>,
-    ) -> Result<&mut Self>
-    where
-        R: lsp_types::request::Request + 'static,
-        R::Params: DeserializeOwned + Send + 'static,
-        R::Result: Serialize + 'static,
-    {
-        let (id, params) = match self.parse::<R>() {
-            Some(it) => it,
-            None => {
-                return Ok(self);
-            }
-        };
-
-        self.global_state.task_pool.0.spawn({
-            let world = self.global_state.snapshot();
-            move || {
-                let result = f(world, params);
-                result_to_task::<R>(id, result)
-            }
-        });
-
-        Ok(self)
-    }
-
-    fn parse<R>(&mut self) -> Option<(RequestId, R::Params)>
-    where
-        R: lsp_types::request::Request + 'static,
-        R::Params: DeserializeOwned + 'static,
-    {
-        let req = self.req.take()?;
-        let (id, params) = match req.extract::<R::Params>(R::METHOD) {
-            Ok(it) => it,
-            Err(req) => {
-                self.req = Some(req);
-                return None;
-            }
-        };
-        self.global_state
-            .req_queue
-            .incoming
-            .register(id.clone(), (R::METHOD, self.request_received));
-        Some((id, params))
-    }
-
-    fn finish(&mut self) {
-        match self.req.take() {
-            None => (),
-            Some(req) => {
-                log::error!("unknown request: {:?}", req);
-                let resp = Response::new_err(
-                    req.id,
-                    ErrorCode::MethodNotFound as i32,
-                    "unknown request".to_string(),
-                );
-                self.msg_sender.send(resp.into()).unwrap();
-            }
-        }
-    }
-}
-
-fn result_to_task<R>(id: RequestId, result: Result<R::Result>) -> Task
-where
-    R: lsp_types::request::Request + 'static,
-    R::Params: DeserializeOwned + 'static,
-    R::Result: Serialize + 'static,
-{
-    let response = match result {
-        Ok(resp) => Response::new_ok(id, &resp),
-        Err(e) => match e.downcast::<LspError>() {
-            Ok(lsp_error) => Response::new_err(id, lsp_error.code, lsp_error.message),
-            Err(e) => {
-                if is_canceled(&*e) {
-                    Response::new_err(
-                        id,
-                        ErrorCode::ContentModified as i32,
-                        "content modified".to_string(),
-                    )
-                } else {
-                    Response::new_err(id, ErrorCode::InternalError as i32, e.to_string())
-                }
-            }
-        },
-    };
-    Task::Respond(response)
-}
-
-fn update_file_notifications_on_threadpool(
-    global_state: &mut GlobalState,
-    subscriptions: Vec<FileId>,
-) {
-    log::trace!("updating notifications for {:?}", subscriptions);
-    if global_state.config.publish_diagnostics {
-        let snapshot = global_state.snapshot();
-        global_state.task_pool.0.spawn(move || {
-            let diagnostics = subscriptions
-                .into_iter()
-                .filter_map(|file_id| {
-                    handlers::publish_diagnostics(&snapshot, file_id)
-                        .map_err(|err| {
-                            if !is_canceled(&*err) {
-                                log::error!("failed to compute diagnostics: {:?}", err);
-                            }
-                            ()
-                        })
-                        .ok()
-                })
-                .collect::<Vec<_>>();
-            Task::Diagnostics(diagnostics)
-        })
-    }
+    global_state.send(notification.into());
 }
diff --git a/crates/vfs-notify/src/lib.rs b/crates/vfs-notify/src/lib.rs
index 68fdb8cb09..25ba8d7982 100644
--- a/crates/vfs-notify/src/lib.rs
+++ b/crates/vfs-notify/src/lib.rs
@@ -82,7 +82,12 @@ impl NotifyActor {
             watcher_receiver,
         }
     }
-
+    fn next_event(&self, receiver: &Receiver<Message>) -> Option<Event> {
+        select! {
+            recv(receiver) -> it => it.ok().map(Event::Message),
+            recv(&self.watcher_receiver) -> it => Some(Event::NotifyEvent(it.unwrap())),
+        }
+    }
     fn run(mut self, inbox: Receiver<Message>) {
         while let Some(event) = self.next_event(&inbox) {
             log::debug!("vfs-notify event: {:?}", event);
@@ -154,12 +159,6 @@ impl NotifyActor {
             }
         }
     }
-    fn next_event(&self, receiver: &Receiver<Message>) -> Option<Event> {
-        select! {
-            recv(receiver) -> it => it.ok().map(Event::Message),
-            recv(&self.watcher_receiver) -> it => Some(Event::NotifyEvent(it.unwrap())),
-        }
-    }
     fn load_entry(
         &mut self,
         entry: loader::Entry,


Test patch:
diff --git a/crates/ra_hir_def/src/item_tree/tests.rs b/crates/ra_hir_def/src/item_tree/tests.rs
index 08559fb92b..dc035d809e 100644
--- a/crates/ra_hir_def/src/item_tree/tests.rs
+++ b/crates/ra_hir_def/src/item_tree/tests.rs
@@ -92,7 +92,7 @@ fn print_item_tree(ra_fixture: &str) -> String {
 }
 
 fn fmt_mod_item(out: &mut String, tree: &ItemTree, item: ModItem) {
-    let attrs = tree.attrs(item.into());
+    let attrs = tree.attrs(item);
     if !attrs.is_empty() {
         format_to!(out, "#[{:?}]\n", attrs);
     }
@@ -237,13 +237,13 @@ Trait { name: Name(Text("Tr")), visibility: RawVisibilityId("pub(self)"), generi
 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("struct0"))] }, input: None }]) }]
 Struct { name: Name(Text("Struct0")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(1), fields: Unit, ast_id: FileAstId::<ra_syntax::ast::generated::nodes::StructDef>(3), kind: Unit }
 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("struct1"))] }, input: None }]) }]
-Struct { name: Name(Text("Struct1")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(2), fields: Tuple(IdRange::<ra_hir_def::item_tree::Field>(0..1)), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::StructDef>(4), kind: Tuple }
+Struct { name: Name(Text("Struct1")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(2), fields: Tuple(Idx::<Field>(0)..Idx::<Field>(1)), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::StructDef>(4), kind: Tuple }
 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("struct2"))] }, input: None }]) }]
-Struct { name: Name(Text("Struct2")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(3), fields: Record(IdRange::<ra_hir_def::item_tree::Field>(1..2)), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::StructDef>(5), kind: Record }
+Struct { name: Name(Text("Struct2")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(3), fields: Record(Idx::<Field>(1)..Idx::<Field>(2)), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::StructDef>(5), kind: Record }
 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("en"))] }, input: None }]) }]
-Enum { name: Name(Text("En")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), variants: IdRange::<ra_hir_def::item_tree::Variant>(0..1), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::EnumDef>(6) }
+Enum { name: Name(Text("En")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), variants: Idx::<Variant>(0)..Idx::<Variant>(1), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::EnumDef>(6) }
 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("un"))] }, input: None }]) }]
-Union { name: Name(Text("Un")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), fields: Record(IdRange::<ra_hir_def::item_tree::Field>(3..4)), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::UnionDef>(7) }
+Union { name: Name(Text("Un")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), fields: Record(Idx::<Field>(3)..Idx::<Field>(4)), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::UnionDef>(7) }
     "###);
 }