Skip to content

Commit cff40ff

Browse files
committed
patch 8.2.2320: Vim9: no error for comparing bool with string
Problem: Vim9: no error for comparing bool with string. Solution: Check for wrong types when comparing. (closes #7639)
1 parent 657137c commit cff40ff

4 files changed

Lines changed: 40 additions & 0 deletions

File tree

src/errors.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,3 +341,5 @@ EXTERN char e_mismatched_endfunction[]
341341
INIT(= N_("E1151: Mismatched endfunction"));
342342
EXTERN char e_mismatched_enddef[]
343343
INIT(= N_("E1152: Mismatched enddef"));
344+
EXTERN char e_invalid_operation_for_bool[]
345+
INIT(= N_("E1153: Invalid operation for bool"));

src/testdir/test_vim9_expr.vim

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -597,6 +597,18 @@ def Test_expr4_equal()
597597
CheckDefFailure(["var x = 'a' == "], 'E1097:', 3)
598598

599599
CheckDefExecFailure(['var items: any', 'eval 1', 'eval 2', 'if items == []', 'endif'], 'E691:', 4)
600+
601+
CheckDefExecFailure(['var x: any = "a"', 'echo x == true'], 'E1072: Cannot compare string with bool', 2)
602+
CheckDefExecFailure(["var x: any = true", 'echo x == ""'], 'E1072: Cannot compare bool with string', 2)
603+
CheckDefExecFailure(["var x: any = 99", 'echo x == true'], 'E1138', 2)
604+
CheckDefExecFailure(["var x: any = 'a'", 'echo x == 99'], 'E1030:', 2)
605+
606+
for op in ['>', '>=', '<', '<=', '=~', '!~']
607+
CheckDefExecFailure([
608+
"var a: any = 'a'",
609+
'var b: any = true',
610+
'echo a ' .. op .. ' b'], 'E1072:', 3)
611+
endfor
600612
enddef
601613

602614
" test != comperator

src/typval.c

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -834,6 +834,30 @@ typval_compare(
834834
default: break; // avoid gcc warning
835835
}
836836
}
837+
else if (in_vim9script() && (typ1->v_type == VAR_BOOL
838+
|| typ2->v_type == VAR_BOOL))
839+
{
840+
if (typ1->v_type != typ2->v_type)
841+
{
842+
semsg(_(e_cannot_compare_str_with_str),
843+
vartype_name(typ1->v_type), vartype_name(typ2->v_type));
844+
clear_tv(typ1);
845+
return FAIL;
846+
}
847+
n1 = typ1->vval.v_number;
848+
n2 = typ2->vval.v_number;
849+
switch (type)
850+
{
851+
case EXPR_IS:
852+
case EXPR_EQUAL: n1 = (n1 == n2); break;
853+
case EXPR_ISNOT:
854+
case EXPR_NEQUAL: n1 = (n1 != n2); break;
855+
default:
856+
emsg(_(e_invalid_operation_for_bool));
857+
clear_tv(typ1);
858+
return FAIL;
859+
}
860+
}
837861
else
838862
{
839863
s1 = tv_get_string_buf(typ1, buf1);

src/version.c

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -750,6 +750,8 @@ static char *(features[]) =
750750

751751
static int included_patches[] =
752752
{ /* Add new patch number below this line */
753+
/**/
754+
2320,
753755
/**/
754756
2319,
755757
/**/

0 commit comments

Comments
 (0)