Skip to content

Commit 37b9eb8

Browse files
authored
Merge pull request EmmyLuaLs#384 from ribru17/impossible_assert
feat: diagnostics for "impossible" assertions
2 parents 47438bd + 553ad9b commit 37b9eb8

File tree

3 files changed

+58
-4
lines changed

3 files changed

+58
-4
lines changed

crates/emmylua_code_analysis/locales/lint.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,10 @@ Cannot use `...` outside a vararg function.:
209209
en: 'Unnecessary assert: this expression is always truthy'
210210
zh_CN: '不必要的断言: 这个表达式始终为真'
211211
zh_HK: '不必要的斷言: 這個表達式始終為真'
212+
'Impossible assert: this expression is always falsy; prefer `error()`':
213+
en: 'Impossible assert: this expression is always falsy; prefer `error()`'
214+
zh_CN: '不可能的断言: 该表达式始终为假;建议使用 `error()`'
215+
zh_HK: '不可能的斷言: 該表達式始終為假;建議使用 `error()`'
212216
"`...` should be the last arg.":
213217
en: "`...` should be the last arg."
214218
zh_CN: "`...`必须是最后一个参数。"

crates/emmylua_code_analysis/src/diagnostic/checker/unnecessary_assert.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,14 @@ fn check_assert_rule(
4040
t!("Unnecessary assert: this expression is always truthy").to_string(),
4141
None,
4242
);
43+
} else if first_type.is_always_falsy() {
44+
context.add_diagnostic(
45+
DiagnosticCode::UnnecessaryAssert,
46+
call_expr.get_range(),
47+
t!("Impossible assert: this expression is always falsy; prefer `error()`")
48+
.to_string(),
49+
None,
50+
);
4351
}
4452
}
4553
Some(())

crates/emmylua_code_analysis/src/diagnostic/test/unnecessary_assert_test.rs

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,6 @@ mod test {
3232
local f
3333
assert(f)
3434
35-
assert(false)
36-
37-
assert(nil and 5)
38-
3935
---@type integer[]
4036
local ints = {1, 2}
4137
assert(ints[3])
@@ -85,4 +81,50 @@ mod test {
8581
"#
8682
));
8783
}
84+
85+
#[test]
86+
fn test_impossible_assert() {
87+
let mut ws = VirtualWorkspace::new();
88+
89+
assert!(!ws.check_code_for(
90+
DiagnosticCode::UnnecessaryAssert,
91+
r#"
92+
assert(false)
93+
"#
94+
));
95+
96+
assert!(!ws.check_code_for(
97+
DiagnosticCode::UnnecessaryAssert,
98+
r#"
99+
assert(nil)
100+
"#
101+
));
102+
103+
assert!(!ws.check_code_for(
104+
DiagnosticCode::UnnecessaryAssert,
105+
r#"
106+
assert(nil and 5)
107+
"#
108+
));
109+
110+
assert!(!ws.check_code_for(
111+
DiagnosticCode::UnnecessaryAssert,
112+
r#"
113+
local a = false ---@type false
114+
assert(a)
115+
"#
116+
));
117+
118+
assert!(!ws.check_code_for(
119+
DiagnosticCode::UnnecessaryAssert,
120+
r#"
121+
---@type integer[]
122+
local a = {1,2,3}
123+
local b = a[2] ---@type integer|nil
124+
if not b then
125+
assert(b, "No second element!")
126+
end
127+
"#
128+
));
129+
}
88130
}

0 commit comments

Comments
 (0)