Implemented basic enum const eval

This commit is contained in:
OleStrohm 2022-08-06 18:50:21 +02:00
parent f64c95600c
commit 997fc46efa
14 changed files with 227 additions and 17 deletions

View file

@ -2,7 +2,9 @@
use std::fmt::Display;
use either::Either;
use hir::{AsAssocItem, AttributeTemplate, HasAttrs, HasSource, HirDisplay, Semantics, TypeInfo};
use hir::{
db::HirDatabase, AsAssocItem, AttributeTemplate, HasAttrs, HasSource, HirDisplay, Semantics, TypeInfo,
};
use ide_db::{
base_db::SourceDatabase,
defs::Definition,
@ -346,7 +348,14 @@ pub(super) fn definition(
Definition::Module(it) => label_and_docs(db, it),
Definition::Function(it) => label_and_docs(db, it),
Definition::Adt(it) => label_and_docs(db, it),
Definition::Variant(it) => label_and_docs(db, it),
Definition::Variant(it) => label_value_and_docs(db, it, |&it| {
let hir_db: &dyn HirDatabase = db;
let body = hir_db.const_eval_variant(it.into());
match body {
Ok(x) => Some(format!("{}", x)),
Err(_) => it.value(db).map(|s| format!("{}", s)),
}
}),
Definition::Const(it) => label_value_and_docs(db, it, |it| {
let body = it.eval(db);
match body {

View file

@ -3527,6 +3527,86 @@ impl<const LEN: usize> Foo<LEN$0> {}
);
}
#[test]
fn hover_const_eval_variant() {
// show hex for <10
check(
r#"
#[repr(u8)]
enum E {
/// This is a doc
A$0 = 1 << 3,
}
"#,
expect![[r#"
*A*
```rust
test::E
```
```rust
A = 8
```
---
This is a doc
"#]],
);
// show hex for >10
check(
r#"
#[repr(u8)]
enum E {
/// This is a doc
A$0 = (1 << 3) + (1 << 2),
}
"#,
expect![[r#"
*A*
```rust
test::E
```
```rust
A = 12 (0xC)
```
---
This is a doc
"#]],
);
// enums in const eval
check(
r#"
#[repr(u8)]
enum E {
A = 1,
/// This is a doc
B$0 = E::A + 1,
}
"#,
expect![[r#"
*B*
```rust
test::E
```
```rust
B = 2
```
---
This is a doc
"#]],
);
}
#[test]
fn hover_const_eval() {
// show hex for <10
@ -3820,6 +3900,35 @@ fn foo() {
---
This is a doc
"#]],
);
check(
r#"
enum E {
/// This is a doc
A = 3,
}
fn foo(e: E) {
match e {
E::A$0 => (),
_ => ()
}
}
"#,
expect![[r#"
*A*
```rust
test::E
```
```rust
A = 3
```
---
This is a doc
"#]],
);