rust-analyzer/crates/ra_hir_ty/src/expr.rs

229 lines
7.9 KiB
Rust
Raw Normal View History

//! FIXME: write short doc here
2019-11-12 15:46:57 +00:00
use std::sync::Arc;
2019-01-05 15:32:07 +00:00
2019-11-27 14:46:02 +00:00
use hir_def::{
2019-12-13 21:32:44 +00:00
path::{path, Path},
2019-11-27 14:46:02 +00:00
resolver::HasResolver,
AdtId, FunctionId,
};
use hir_expand::{diagnostics::DiagnosticSink, name::Name};
2019-11-15 11:53:09 +00:00
use ra_syntax::ast;
2019-11-14 14:37:22 +00:00
use ra_syntax::AstPtr;
2019-11-15 11:53:09 +00:00
use rustc_hash::FxHashSet;
2019-01-05 15:32:07 +00:00
2019-11-15 11:53:09 +00:00
use crate::{
db::HirDatabase,
2020-03-24 11:40:58 +00:00
diagnostics::{MissingFields, MissingMatchArms, MissingOkInTailExpr},
2020-02-19 16:53:32 +00:00
utils::variant_data,
2019-11-27 14:46:02 +00:00
ApplicationTy, InferenceResult, Ty, TypeCtor,
2020-03-24 11:40:58 +00:00
_match::{is_useful, MatchCheckCtx, Matrix, PatStack, Usefulness},
2019-11-15 11:53:09 +00:00
};
2019-01-05 15:32:07 +00:00
2019-11-12 15:46:57 +00:00
pub use hir_def::{
2019-11-14 08:56:13 +00:00
body::{
scope::{ExprScopes, ScopeEntry, ScopeId},
Body, BodySourceMap, ExprPtr, ExprSource, PatPtr, PatSource,
},
2019-11-12 15:46:57 +00:00
expr::{
ArithOp, Array, BinaryOp, BindingAnnotation, CmpOp, Expr, ExprId, Literal, LogicOp,
MatchArm, Ordering, Pat, PatId, RecordFieldPat, RecordLitField, Statement, UnaryOp,
},
2020-02-19 16:53:32 +00:00
VariantId,
2019-11-12 12:09:25 +00:00
};
2019-09-03 05:56:36 +00:00
2019-11-27 14:46:02 +00:00
pub struct ExprValidator<'a, 'b: 'a> {
func: FunctionId,
2019-11-15 11:53:09 +00:00
infer: Arc<InferenceResult>,
sink: &'a mut DiagnosticSink<'b>,
}
impl<'a, 'b> ExprValidator<'a, 'b> {
2019-11-27 14:46:02 +00:00
pub fn new(
func: FunctionId,
2019-11-15 11:53:09 +00:00
infer: Arc<InferenceResult>,
sink: &'a mut DiagnosticSink<'b>,
) -> ExprValidator<'a, 'b> {
ExprValidator { func, infer, sink }
}
pub fn validate_body(&mut self, db: &dyn HirDatabase) {
2019-11-27 14:46:02 +00:00
let body = db.body(self.func.into());
2019-11-15 11:53:09 +00:00
2019-11-24 15:48:29 +00:00
for e in body.exprs.iter() {
2019-11-15 11:53:09 +00:00
if let (id, Expr::RecordLit { path, fields, spread }) = e {
self.validate_record_literal(id, path, fields, *spread, db);
2020-03-24 11:40:58 +00:00
} else if let (id, Expr::Match { expr, arms }) = e {
self.validate_match(id, *expr, arms, db, self.infer.clone());
2019-11-15 11:53:09 +00:00
}
}
2019-11-24 15:48:29 +00:00
let body_expr = &body[body.body_expr];
2020-03-24 11:40:58 +00:00
if let Expr::Block { tail: Some(t), .. } = body_expr {
2019-11-24 15:48:29 +00:00
self.validate_results_in_tail_expr(body.body_expr, *t, db);
2019-11-15 11:53:09 +00:00
}
}
2020-03-24 11:40:58 +00:00
fn validate_match(
&mut self,
id: ExprId,
2020-04-05 17:16:34 +00:00
match_expr: ExprId,
2020-03-24 11:40:58 +00:00
arms: &[MatchArm],
db: &dyn HirDatabase,
infer: Arc<InferenceResult>,
) {
let (body, source_map): (Arc<Body>, Arc<BodySourceMap>) =
db.body_with_source_map(self.func.into());
2020-04-05 17:16:34 +00:00
let match_expr_ty = match infer.type_of_expr.get(match_expr) {
Some(ty) => ty,
// If we can't resolve the type of the match expression
// we cannot perform exhaustiveness checks.
None => return,
};
2020-03-24 11:40:58 +00:00
2020-04-05 17:16:34 +00:00
let cx = MatchCheckCtx { body, infer: infer.clone(), db };
2020-03-24 11:40:58 +00:00
let pats = arms.iter().map(|arm| arm.pat);
let mut seen = Matrix::empty();
for pat in pats {
2020-04-05 17:16:34 +00:00
// We skip any patterns whose type we cannot resolve.
if let Some(pat_ty) = infer.type_of_pat.get(pat) {
// We only include patterns whose type matches the type
// of the match expression. If we had a InvalidMatchArmPattern
// diagnostic or similar we could raise that in an else
// block here.
2020-04-05 19:42:24 +00:00
//
// When comparing the types, we also have to consider that rustc
// will automatically de-reference the match expression type if
// necessary.
if pat_ty == match_expr_ty
|| match_expr_ty
.as_reference()
.map(|(match_expr_ty, _)| match_expr_ty == pat_ty)
.unwrap_or(false)
{
2020-04-05 17:16:34 +00:00
// If we had a NotUsefulMatchArm diagnostic, we could
// check the usefulness of each pattern as we added it
// to the matrix here.
let v = PatStack::from_pattern(pat);
seen.push(&cx, v);
}
}
2020-03-24 11:40:58 +00:00
}
match is_useful(&cx, &seen, &PatStack::from_wild()) {
2020-04-05 01:02:27 +00:00
Ok(Usefulness::Useful) => (),
2020-03-24 11:40:58 +00:00
// if a wildcard pattern is not useful, then all patterns are covered
2020-04-05 01:02:27 +00:00
Ok(Usefulness::NotUseful) => return,
// this path is for unimplemented checks, so we err on the side of not
// reporting any errors
_ => return,
2020-03-24 11:40:58 +00:00
}
if let Ok(source_ptr) = source_map.expr_syntax(id) {
if let Some(expr) = source_ptr.value.left() {
let root = source_ptr.file_syntax(db.upcast());
if let ast::Expr::MatchExpr(match_expr) = expr.to_node(&root) {
if let (Some(match_expr), Some(arms)) =
(match_expr.expr(), match_expr.match_arm_list())
{
2020-03-24 11:40:58 +00:00
self.sink.push(MissingMatchArms {
file: source_ptr.file_id,
match_expr: AstPtr::new(&match_expr),
2020-03-24 11:40:58 +00:00
arms: AstPtr::new(&arms),
})
}
}
}
}
}
2019-11-15 11:53:09 +00:00
fn validate_record_literal(
&mut self,
id: ExprId,
_path: &Option<Path>,
fields: &[RecordLitField],
spread: Option<ExprId>,
db: &dyn HirDatabase,
2019-11-15 11:53:09 +00:00
) {
if spread.is_some() {
return;
2020-02-19 16:53:32 +00:00
};
let variant_def: VariantId = match self.infer.variant_resolution_for_expr(id) {
Some(VariantId::UnionId(_)) | None => return,
Some(it) => it,
};
if let VariantId::UnionId(_) = variant_def {
return;
2019-11-15 11:53:09 +00:00
}
let variant_data = variant_data(db.upcast(), variant_def);
2019-11-15 11:53:09 +00:00
let lit_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect();
2020-02-19 16:53:32 +00:00
let missed_fields: Vec<Name> = variant_data
2019-11-27 14:46:02 +00:00
.fields()
2019-11-15 11:53:09 +00:00
.iter()
2019-11-27 14:46:02 +00:00
.filter_map(|(_f, d)| {
let name = d.name.clone();
2019-11-15 11:53:09 +00:00
if lit_fields.contains(&name) {
None
} else {
Some(name)
}
})
.collect();
if missed_fields.is_empty() {
return;
}
2019-11-27 14:46:02 +00:00
let (_, source_map) = db.body_with_source_map(self.func.into());
2019-11-15 11:53:09 +00:00
2020-03-06 13:44:44 +00:00
if let Ok(source_ptr) = source_map.expr_syntax(id) {
if let Some(expr) = source_ptr.value.left() {
let root = source_ptr.file_syntax(db.upcast());
2019-11-15 11:53:09 +00:00
if let ast::Expr::RecordLit(record_lit) = expr.to_node(&root) {
if let Some(field_list) = record_lit.record_field_list() {
self.sink.push(MissingFields {
file: source_ptr.file_id,
field_list: AstPtr::new(&field_list),
missed_fields,
})
}
}
}
}
}
fn validate_results_in_tail_expr(&mut self, body_id: ExprId, id: ExprId, db: &dyn HirDatabase) {
2019-11-15 11:53:09 +00:00
// the mismatch will be on the whole block currently
let mismatch = match self.infer.type_mismatch_for_expr(body_id) {
Some(m) => m,
None => return,
};
2019-12-13 21:32:44 +00:00
let std_result_path = path![std::result::Result];
2019-11-15 11:53:09 +00:00
let resolver = self.func.resolver(db.upcast());
let std_result_enum = match resolver.resolve_known_enum(db.upcast(), &std_result_path) {
2019-11-15 11:53:09 +00:00
Some(it) => it,
_ => return,
};
2019-11-26 11:29:12 +00:00
let std_result_ctor = TypeCtor::Adt(AdtId::EnumId(std_result_enum));
2019-11-15 11:53:09 +00:00
let params = match &mismatch.expected {
Ty::Apply(ApplicationTy { ctor, parameters }) if ctor == &std_result_ctor => parameters,
_ => return,
};
2020-02-18 13:32:19 +00:00
if params.len() == 2 && params[0] == mismatch.actual {
2019-11-27 14:46:02 +00:00
let (_, source_map) = db.body_with_source_map(self.func.into());
2019-11-15 11:53:09 +00:00
2020-03-06 13:44:44 +00:00
if let Ok(source_ptr) = source_map.expr_syntax(id) {
if let Some(expr) = source_ptr.value.left() {
2019-11-15 11:53:09 +00:00
self.sink.push(MissingOkInTailExpr { file: source_ptr.file_id, expr });
}
}
}
}
}