Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion crates/hir-ty/src/infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ use hir_def::{
TupleFieldId, TupleId, VariantId,
attrs::AttrFlags,
expr_store::{Body, ExpressionStore, HygieneId, body::Param, path::Path},
hir::{BindingId, ExprId, ExprOrPatId, ExprOrPatIdPacked, LabelId, PatId},
hir::{BindingId, ExprId, ExprOrPatId, ExprOrPatIdPacked, LabelId, PatId, UnaryOp},
lang_item::LangItems,
layout::Integer,
resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs},
Expand Down Expand Up @@ -434,6 +434,13 @@ pub enum InferenceDiagnostic {
expr: ExprId,
found: StoredTy,
},
UnaryOperatorCannotBeApplied {
#[type_visitable(ignore)]
expr: ExprId,
#[type_visitable(ignore)]
op: UnaryOp,
found: StoredTy,
},
MutRefInImmRefPat {
#[type_visitable(ignore)]
pat: PatId,
Expand Down
8 changes: 6 additions & 2 deletions crates/hir-ty/src/infer/op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use syntax::ast::{ArithOp, BinaryOp, UnaryOp};
use tracing::debug;

use crate::{
Adjust, Adjustment, AutoBorrow,
Adjust, Adjustment, AutoBorrow, InferenceDiagnostic,
infer::{AllowTwoPhase, AutoBorrowMutability, Expectation, InferenceContext, expr::ExprIsRead},
method_resolution::{MethodCallee, TreatNotYetDefinedOpaques},
next_solver::{
Expand Down Expand Up @@ -271,7 +271,11 @@ impl<'db> InferenceContext<'db> {
method.sig.output()
}
Err(_errors) => {
// FIXME: Report diagnostic.
self.push_diagnostic(InferenceDiagnostic::UnaryOperatorCannotBeApplied {
expr: ex,
op,
found: operand_ty.store(),
});
self.types.types.error
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/hir-ty/src/infer/unify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,7 @@ pub(super) mod resolve_completely {
| InferenceDiagnostic::CannotIndexInto { found: ty, .. }
| InferenceDiagnostic::ExpectedFunction { found: ty, .. }
| InferenceDiagnostic::ExpectedArrayOrSlicePat { found: ty, .. }
| InferenceDiagnostic::UnaryOperatorCannotBeApplied { found: ty, .. }
| InferenceDiagnostic::UnresolvedField { receiver: ty, .. }
| InferenceDiagnostic::UnresolvedMethodCall { receiver: ty, .. } = diagnostic
&& ty.as_ref().references_non_lt_error()
Expand Down
12 changes: 12 additions & 0 deletions crates/hir/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ diagnostics![AnyDiagnostic<'db> ->
AwaitOutsideOfAsync,
BreakOutsideOfLoop,
CannotBeDereferenced<'db>,
UnaryOperatorCannotBeApplied<'db>,
CannotImplicitlyDerefTraitObject<'db>,
CannotIndexInto<'db>,
CastToUnsized<'db>,
Expand Down Expand Up @@ -338,6 +339,13 @@ pub struct CannotBeDereferenced<'db> {
pub found: Type<'db>,
}

#[derive(Debug)]
pub struct UnaryOperatorCannotBeApplied<'db> {
pub expr: InFile<ExprOrPatPtr>,
pub op: ast::UnaryOp,
pub found: Type<'db>,
}

#[derive(Debug)]
pub struct MutRefInImmRefPat {
pub pat: InFile<ExprOrPatPtr>,
Expand Down Expand Up @@ -985,6 +993,10 @@ impl<'db> AnyDiagnostic<'db> {
let expr = expr_syntax(*expr)?;
CannotBeDereferenced { expr, found: new_ty(found.as_ref()) }.into()
}
InferenceDiagnostic::UnaryOperatorCannotBeApplied { expr, op, found } => {
let expr = expr_syntax(*expr)?;
UnaryOperatorCannotBeApplied { expr, op: *op, found: new_ty(found.as_ref()) }.into()
}
InferenceDiagnostic::MutRefInImmRefPat { pat } => {
let pat = pat_syntax(*pat)?.map(Into::into);
MutRefInImmRefPat { pat }.into()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,7 @@ fn main() {
fn legacy_const_generics() {
check_diagnostics(
r#"
//- minicore: unary_ops, builtin_impls
#[rustc_legacy_const_generics(1, 3)]
fn mixed<const N1: &'static str, const N2: bool>(
_a: u8,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
use hir::HirDisplay;
use syntax::ast::UnaryOp;

use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext};

// Diagnostic: unary-operator-cannot-be-applied
//
// This diagnostic is triggered if a unary operator (`!` or `-`) is applied
// to a value whose type does not implement the corresponding trait
// (`Not` or `Neg`).
pub(crate) fn unary_operator_cannot_be_applied(
ctx: &DiagnosticsContext<'_, '_>,
d: &hir::UnaryOperatorCannotBeApplied<'_>,
) -> Diagnostic {
let op = match d.op {
UnaryOp::Not => "!",
UnaryOp::Neg => "-",
// `Deref` uses a different diagnostic (`CannotBeDereferenced`).
UnaryOp::Deref => "*",
};
Diagnostic::new_with_syntax_node_ptr(
ctx,
DiagnosticCode::RustcHardError("E0600"),
format!(
"cannot apply unary operator `{op}` to type `{}`",
d.found.display(ctx.sema.db, ctx.display_target)
),
d.expr.map(Into::into),
)
.stable()
}

#[cfg(test)]
mod tests {
use crate::tests::check_diagnostics;

#[test]
fn not_on_enum() {
check_diagnostics(
r#"
//- minicore: unary_ops, builtin_impls
enum Question { Yes, No }

fn f() {
let _ = !Question::Yes;
//^^^^^^^^^^^^^^ error: cannot apply unary operator `!` to type `Question`
}
"#,
);
}

#[test]
fn neg_on_struct() {
check_diagnostics(
r#"
//- minicore: unary_ops, builtin_impls
struct S;

fn f() {
let _ = -S;
//^^ error: cannot apply unary operator `-` to type `S`
}
"#,
);
}

#[test]
fn allows_not_on_bool() {
check_diagnostics(
r#"
//- minicore: unary_ops, builtin_impls
fn f() {
let _ = !true;
let _ = !false;
}
"#,
);
}

#[test]
fn allows_not_on_integer() {
check_diagnostics(
r#"
//- minicore: unary_ops, builtin_impls
fn f() {
let _ = !0u32;
let _ = !0i32;
}
"#,
);
}

#[test]
fn allows_neg_on_numeric() {
check_diagnostics(
r#"
//- minicore: unary_ops, builtin_impls
fn f() {
let _ = -1i32;
let _ = -1.0f64;
}
"#,
);
}

#[test]
fn neg_on_unsigned() {
check_diagnostics(
r#"
//- minicore: unary_ops, builtin_impls
fn f() {
let _ = -1u32;
//^^^^^ error: cannot apply unary operator `-` to type `u32`
}
"#,
);
}

#[test]
fn allows_not_with_impl() {
check_diagnostics(
r#"
//- minicore: unary_ops, builtin_impls
struct Bar;
struct Foo;

impl core::ops::Not for Bar {
type Output = Foo;
fn not(self) -> Foo { Foo }
}

fn f() {
let _ = !Bar;
}
"#,
);
}

#[test]
fn allows_neg_with_impl() {
check_diagnostics(
r#"
//- minicore: unary_ops, builtin_impls
struct Bar;
struct Foo;

impl core::ops::Neg for Bar {
type Output = Foo;
fn neg(self) -> Foo { Foo }
}

fn f() {
let _ = -Bar;
}
"#,
);
}
}
2 changes: 2 additions & 0 deletions crates/ide-diagnostics/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ mod handlers {
pub(crate) mod type_mismatch;
pub(crate) mod type_must_be_known;
pub(crate) mod typed_hole;
pub(crate) mod unary_operator_cannot_be_applied;
pub(crate) mod undeclared_label;
pub(crate) mod unimplemented_builtin_macro;
pub(crate) mod unimplemented_trait;
Expand Down Expand Up @@ -437,6 +438,7 @@ pub fn semantic_diagnostics(
let d = match diag {
AnyDiagnostic::AwaitOutsideOfAsync(d) => handlers::await_outside_of_async::await_outside_of_async(&ctx, &d),
AnyDiagnostic::CannotBeDereferenced(d) => handlers::cannot_be_dereferenced::cannot_be_dereferenced(&ctx, &d),
AnyDiagnostic::UnaryOperatorCannotBeApplied(d) => handlers::unary_operator_cannot_be_applied::unary_operator_cannot_be_applied(&ctx, &d),
AnyDiagnostic::CannotImplicitlyDerefTraitObject(d) => handlers::cannot_implicitly_deref_trait_object::cannot_implicitly_deref_trait_object(&ctx, &d),
AnyDiagnostic::CannotIndexInto(d) => handlers::cannot_index_into::cannot_index_into(&ctx, &d),
AnyDiagnostic::CastToUnsized(d) => handlers::invalid_cast::cast_to_unsized(&ctx, &d),
Expand Down
30 changes: 28 additions & 2 deletions crates/test-utils/src/minicore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@
//! discriminant:
//! drop: sized
//! env: option
//! eq: sized
//! eq: sized, unary_ops, builtin_impls
//! error: fmt
//! float_consts:
//! float_consts: unary_ops, builtin_impls
//! fmt: option, result, transmute, coerce_unsized, copy, clone, derive
//! fn: sized, tuple
//! from: sized, result
Expand Down Expand Up @@ -370,11 +370,13 @@ pub mod clone {
}
}

// region:index
impl<T: Clone> Clone for [T; 1] {
fn clone(&self) -> Self {
[self[0].clone()]
}
}
// endregion:index
// endregion:builtin_impls

// region:derive
Expand Down Expand Up @@ -1213,6 +1215,30 @@ pub mod ops {
#[must_use = "this returns the result of the operation, without modifying the original"]
fn neg(self) -> Self::Output;
}

// region:builtin_impls
macro_rules! not_impl {
($($t:ty)*) => ($(
impl const Not for $t {
type Output = $t;
fn not(self) -> $t { !self }
}
)*)
}

not_impl! { bool usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 }

macro_rules! neg_impl {
($($t:ty)*) => ($(
impl const Neg for $t {
type Output = $t;
fn neg(self) -> $t { -self }
}
)*)
}

neg_impl! { isize i8 i16 i32 i64 i128 f16 f32 f64 f128 }
// endregion:builtin_impls
// endregion:unary_ops

// region:coroutine
Expand Down