ide_diagnostics/handlers/
await_outside_of_async.rs1use crate::{Diagnostic, DiagnosticsContext, adjusted_display_range};
2
3pub(crate) fn await_outside_of_async(
7 ctx: &DiagnosticsContext<'_, '_>,
8 d: &hir::AwaitOutsideOfAsync,
9) -> Diagnostic {
10 let display_range =
11 adjusted_display_range(ctx, d.node, &|node| Some(node.await_token()?.text_range()));
12 Diagnostic::new(
13 crate::DiagnosticCode::RustcHardError("E0728"),
14 format!("`await` is used inside {}, which is not an `async` context", d.location),
15 display_range,
16 )
17 .stable()
18}
19
20#[cfg(test)]
21mod tests {
22 use crate::tests::check_diagnostics;
23
24 #[test]
25 fn await_inside_non_async_fn() {
26 check_diagnostics(
27 r#"
28async fn foo() {}
29
30fn bar() {
31 foo().await;
32 //^^^^^ error: `await` is used inside non-async function, which is not an `async` context
33}
34"#,
35 );
36 }
37
38 #[test]
39 fn await_inside_async_fn() {
40 check_diagnostics(
41 r#"
42async fn foo() {}
43
44async fn bar() {
45 foo().await;
46}
47"#,
48 );
49 }
50
51 #[test]
52 fn await_inside_closure() {
53 check_diagnostics(
54 r#"
55//- minicore: future
56async fn foo() {}
57
58async fn bar() {
59 let _a = || { foo().await };
60 //^^^^^ error: `await` is used inside non-async closure, which is not an `async` context
61}
62"#,
63 );
64 }
65
66 #[test]
67 fn await_inside_async_block() {
68 check_diagnostics(
69 r#"
70//- minicore: future
71async fn foo() {}
72
73fn bar() {
74 let _a = async { foo().await };
75}
76"#,
77 );
78 }
79
80 #[test]
81 fn await_in_complex_context() {
82 check_diagnostics(
83 r#"
84//- minicore: future
85async fn foo() {}
86
87fn bar() {
88 async fn baz() {
89 let a = foo().await;
90 }
91
92 let x = || {
93 let y = async {
94 baz().await;
95 let z = || {
96 baz().await;
97 //^^^^^ error: `await` is used inside non-async closure, which is not an `async` context
98 };
99 };
100 };
101}
102"#,
103 );
104 }
105}