Repository: rust-analyzer/rust-analyzer
Pull request #3492 (2020-03-06 14:39:04)

Simplify creation of `T[,]`


bors r+
🤖


Patch:
diff --git a/crates/ra_db/src/fixture.rs b/crates/ra_db/src/fixture.rs
index da7af110c9..17cd138c20 100644
--- a/crates/ra_db/src/fixture.rs
+++ b/crates/ra_db/src/fixture.rs
@@ -21,9 +21,9 @@ pub trait WithFixture: Default + SourceDatabaseExt + 'static {
         (db, file_id)
     }
 
-    fn with_files(ra_fixture: &str) -> Self {
+    fn with_files(fixture: &str) -> Self {
         let mut db = Self::default();
-        let pos = with_files(&mut db, ra_fixture);
+        let pos = with_files(&mut db, fixture);
         assert!(pos.is_none());
         db
     }
diff --git a/crates/ra_hir/src/source_analyzer.rs b/crates/ra_hir/src/source_analyzer.rs
index 331ecdd9cc..f3f1ed05a3 100644
--- a/crates/ra_hir/src/source_analyzer.rs
+++ b/crates/ra_hir/src/source_analyzer.rs
@@ -261,7 +261,7 @@ fn scope_for_offset(
         .scope_by_expr()
         .iter()
         .filter_map(|(id, scope)| {
-            let source = source_map.expr_syntax(*id).ok()?;
+            let source = source_map.expr_syntax(*id)?;
             // FIXME: correctly handle macro expansion
             if source.file_id != offset.file_id {
                 return None;
@@ -337,7 +337,7 @@ fn adjust(
         .scope_by_expr()
         .iter()
         .filter_map(|(id, scope)| {
-            let source = source_map.expr_syntax(*id).ok()?;
+            let source = source_map.expr_syntax(*id)?;
             // FIXME: correctly handle macro expansion
             if source.file_id != file_id {
                 return None;
diff --git a/crates/ra_hir_def/src/body.rs b/crates/ra_hir_def/src/body.rs
index 57ba45b455..010d35e55b 100644
--- a/crates/ra_hir_def/src/body.rs
+++ b/crates/ra_hir_def/src/body.rs
@@ -149,16 +149,13 @@ pub type PatSource = InFile<PatPtr>;
 #[derive(Default, Debug, Eq, PartialEq)]
 pub struct BodySourceMap {
     expr_map: FxHashMap<ExprSource, ExprId>,
-    expr_map_back: ArenaMap<ExprId, Result<ExprSource, SyntheticSyntax>>,
+    expr_map_back: ArenaMap<ExprId, ExprSource>,
     pat_map: FxHashMap<PatSource, PatId>,
-    pat_map_back: ArenaMap<PatId, Result<PatSource, SyntheticSyntax>>,
+    pat_map_back: ArenaMap<PatId, PatSource>,
     field_map: FxHashMap<(ExprId, usize), AstPtr<ast::RecordField>>,
     expansions: FxHashMap<InFile<AstPtr<ast::MacroCall>>, HirFileId>,
 }
 
-#[derive(Default, Debug, Eq, PartialEq, Clone, Copy)]
-pub struct SyntheticSyntax;
-
 impl Body {
     pub(crate) fn body_with_source_map_query(
         db: &impl DefDatabase,
@@ -222,8 +219,8 @@ impl Index<PatId> for Body {
 }
 
 impl BodySourceMap {
-    pub fn expr_syntax(&self, expr: ExprId) -> Result<ExprSource, SyntheticSyntax> {
-        self.expr_map_back[expr]
+    pub fn expr_syntax(&self, expr: ExprId) -> Option<ExprSource> {
+        self.expr_map_back.get(expr).copied()
     }
 
     pub fn node_expr(&self, node: InFile<&ast::Expr>) -> Option<ExprId> {
@@ -241,8 +238,8 @@ impl BodySourceMap {
         self.expr_map.get(&src).cloned()
     }
 
-    pub fn pat_syntax(&self, pat: PatId) -> Result<PatSource, SyntheticSyntax> {
-        self.pat_map_back[pat]
+    pub fn pat_syntax(&self, pat: PatId) -> Option<PatSource> {
+        self.pat_map_back.get(pat).copied()
     }
 
     pub fn node_pat(&self, node: InFile<&ast::Pat>) -> Option<PatId> {
diff --git a/crates/ra_hir_def/src/body/lower.rs b/crates/ra_hir_def/src/body/lower.rs
index ec1b0c2e70..c18e6879ba 100644
--- a/crates/ra_hir_def/src/body/lower.rs
+++ b/crates/ra_hir_def/src/body/lower.rs
@@ -14,10 +14,9 @@ use ra_syntax::{
 };
 use test_utils::tested_by;
 
-use super::{ExprSource, PatSource};
 use crate::{
     adt::StructKind,
-    body::{Body, BodySourceMap, Expander, PatPtr, SyntheticSyntax},
+    body::{Body, BodySourceMap, Expander, PatPtr},
     builtin_type::{BuiltinFloat, BuiltinInt},
     db::DefDatabase,
     expr::{
@@ -103,48 +102,44 @@ where
 
     fn alloc_expr(&mut self, expr: Expr, ptr: AstPtr<ast::Expr>) -> ExprId {
         let ptr = Either::Left(ptr);
+        let id = self.body.exprs.alloc(expr);
         let src = self.expander.to_source(ptr);
-        let id = self.make_expr(expr, Ok(src));
         self.source_map.expr_map.insert(src, id);
+        self.source_map.expr_map_back.insert(id, src);
         id
     }
     // desugared exprs don't have ptr, that's wrong and should be fixed
     // somehow.
     fn alloc_expr_desugared(&mut self, expr: Expr) -> ExprId {
-        self.make_expr(expr, Err(SyntheticSyntax))
+        self.body.exprs.alloc(expr)
     }
     fn alloc_expr_field_shorthand(&mut self, expr: Expr, ptr: AstPtr<ast::RecordField>) -> ExprId {
         let ptr = Either::Right(ptr);
+        let id = self.body.exprs.alloc(expr);
         let src = self.expander.to_source(ptr);
-        let id = self.make_expr(expr, Ok(src));
         self.source_map.expr_map.insert(src, id);
-        id
-    }
-    fn empty_block(&mut self) -> ExprId {
-        self.alloc_expr_desugared(Expr::Block { statements: Vec::new(), tail: None })
-    }
-    fn missing_expr(&mut self) -> ExprId {
-        self.alloc_expr_desugared(Expr::Missing)
-    }
-    fn make_expr(&mut self, expr: Expr, src: Result<ExprSource, SyntheticSyntax>) -> ExprId {
-        let id = self.body.exprs.alloc(expr);
         self.source_map.expr_map_back.insert(id, src);
         id
     }
-
     fn alloc_pat(&mut self, pat: Pat, ptr: PatPtr) -> PatId {
+        let id = self.body.pats.alloc(pat);
         let src = self.expander.to_source(ptr);
-        let id = self.make_pat(pat, Ok(src));
         self.source_map.pat_map.insert(src, id);
+        self.source_map.pat_map_back.insert(id, src);
         id
     }
-    fn missing_pat(&mut self) -> PatId {
-        self.make_pat(Pat::Missing, Err(SyntheticSyntax))
+
+    fn empty_block(&mut self) -> ExprId {
+        let block = Expr::Block { statements: Vec::new(), tail: None };
+        self.body.exprs.alloc(block)
     }
-    fn make_pat(&mut self, pat: Pat, src: Result<PatSource, SyntheticSyntax>) -> PatId {
-        let id = self.body.pats.alloc(pat);
-        self.source_map.pat_map_back.insert(id, src);
-        id
+
+    fn missing_expr(&mut self) -> ExprId {
+        self.body.exprs.alloc(Expr::Missing)
+    }
+
+    fn missing_pat(&mut self) -> PatId {
+        self.body.pats.alloc(Pat::Missing)
     }
 
     fn collect_expr(&mut self, expr: ast::Expr) -> ExprId {
diff --git a/crates/ra_hir_ty/src/expr.rs b/crates/ra_hir_ty/src/expr.rs
index d8cdf5266e..22f24890d4 100644
--- a/crates/ra_hir_ty/src/expr.rs
+++ b/crates/ra_hir_ty/src/expr.rs
@@ -100,7 +100,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
         }
         let (_, source_map) = db.body_with_source_map(self.func.into());
 
-        if let Ok(source_ptr) = source_map.expr_syntax(id) {
+        if let Some(source_ptr) = source_map.expr_syntax(id) {
             if let Some(expr) = source_ptr.value.left() {
                 let root = source_ptr.file_syntax(db);
                 if let ast::Expr::RecordLit(record_lit) = expr.to_node(&root) {
@@ -145,7 +145,7 @@ impl<'a, 'b> ExprValidator<'a, 'b> {
         if params.len() == 2 && params[0] == mismatch.actual {
             let (_, source_map) = db.body_with_source_map(self.func.into());
 
-            if let Ok(source_ptr) = source_map.expr_syntax(id) {
+            if let Some(source_ptr) = source_map.expr_syntax(id) {
                 if let Some(expr) = source_ptr.value.left() {
                     self.sink.push(MissingOkInTailExpr { file: source_ptr.file_id, expr });
                 }
diff --git a/crates/ra_syntax/src/ast/edit.rs b/crates/ra_syntax/src/ast/edit.rs
index e4cdccdb43..40a04b9c5b 100644
--- a/crates/ra_syntax/src/ast/edit.rs
+++ b/crates/ra_syntax/src/ast/edit.rs
@@ -139,7 +139,7 @@ impl ast::RecordFieldList {
         let mut to_insert: ArrayVec<[SyntaxElement; 4]> = ArrayVec::new();
         to_insert.push(space.into());
         to_insert.push(field.syntax().clone().into());
-        to_insert.push(tokens::comma().into());
+        to_insert.push(make::token(T![,]).into());
 
         macro_rules! after_l_curly {
             () => {{
@@ -160,7 +160,7 @@ impl ast::RecordFieldList {
                 {
                     InsertPosition::After(comma)
                 } else {
-                    to_insert.insert(0, tokens::comma().into());
+                    to_insert.insert(0, make::token(T![,]).into());
                     InsertPosition::After($anchor.syntax().clone().into())
                 }
             };
diff --git a/crates/ra_syntax/src/ast/make.rs b/crates/ra_syntax/src/ast/make.rs
index 22c54f363e..f25b526b67 100644
--- a/crates/ra_syntax/src/ast/make.rs
+++ b/crates/ra_syntax/src/ast/make.rs
@@ -240,22 +240,13 @@ fn unroot(n: SyntaxNode) -> SyntaxNode {
 }
 
 pub mod tokens {
-    use crate::{ast, AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken, T};
     use once_cell::sync::Lazy;
 
+    use crate::{ast, AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken};
+
     pub(super) static SOURCE_FILE: Lazy<Parse<SourceFile>> =
         Lazy::new(|| SourceFile::parse("const C: <()>::Item = (1 != 1, 2 == 2, !true)\n;"));
 
-    pub fn comma() -> SyntaxToken {
-        SOURCE_FILE
-            .tree()
-            .syntax()
-            .descendants_with_tokens()
-            .filter_map(|it| it.into_token())
-            .find(|it| it.kind() == T![,])
-            .unwrap()
-    }
-
     pub fn single_space() -> SyntaxToken {
         SOURCE_FILE
             .tree()
diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs
index 643c54a9df..6bf0be5656 100644
--- a/crates/rust-analyzer/src/cli/analysis_stats.rs
+++ b/crates/rust-analyzer/src/cli/analysis_stats.rs
@@ -158,7 +158,7 @@ pub fn analysis_stats(
                 // in super-verbose mode for just one function, we print every single expression
                 let (_, sm) = db.body_with_source_map(f_id.into());
                 let src = sm.expr_syntax(expr_id);
-                if let Ok(src) = src {
+                if let Some(src) = src {
                     let original_file = src.file_id.original_file(db);
                     let line_index = host.analysis().file_line_index(original_file).unwrap();
                     let text_range = src.value.either(
@@ -186,7 +186,7 @@ pub fn analysis_stats(
                 if verbosity.is_verbose() {
                     let (_, sm) = db.body_with_source_map(f_id.into());
                     let src = sm.expr_syntax(expr_id);
-                    if let Ok(src) = src {
+                    if let Some(src) = src {
                         // FIXME: it might be nice to have a function (on Analysis?) that goes from Source<T> -> (LineCol, LineCol) directly
                         // But also, we should just turn the type mismatches into diagnostics and provide these
                         let root = db.parse_or_expand(src.file_id).unwrap();


Test patch:
diff --git a/crates/ra_hir_ty/src/tests.rs b/crates/ra_hir_ty/src/tests.rs
index 7e95473408..087edcc922 100644
--- a/crates/ra_hir_ty/src/tests.rs
+++ b/crates/ra_hir_ty/src/tests.rs
@@ -11,13 +11,8 @@ use std::fmt::Write;
 use std::sync::Arc;
 
 use hir_def::{
-    body::{BodySourceMap, SyntheticSyntax},
-    child_by_source::ChildBySource,
-    db::DefDatabase,
-    item_scope::ItemScope,
-    keys,
-    nameres::CrateDefMap,
-    AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId,
+    body::BodySourceMap, child_by_source::ChildBySource, db::DefDatabase, item_scope::ItemScope,
+    keys, nameres::CrateDefMap, AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId,
 };
 use hir_expand::InFile;
 use insta::assert_snapshot;
@@ -72,20 +67,20 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
 
         for (pat, ty) in inference_result.type_of_pat.iter() {
             let syntax_ptr = match body_source_map.pat_syntax(pat) {
-                Ok(sp) => {
+                Some(sp) => {
                     sp.map(|ast| ast.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr()))
                 }
-                Err(SyntheticSyntax) => continue,
+                None => continue,
             };
             types.push((syntax_ptr, ty));
         }
 
         for (expr, ty) in inference_result.type_of_expr.iter() {
             let syntax_ptr = match body_source_map.expr_syntax(expr) {
-                Ok(sp) => {
+                Some(sp) => {
                     sp.map(|ast| ast.either(|it| it.syntax_node_ptr(), |it| it.syntax_node_ptr()))
                 }
-                Err(SyntheticSyntax) => continue,
+                None => continue,
             };
             types.push((syntax_ptr, ty));
             if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr) {