Skip to content

Commit 5bbcfbc

Browse files
yegappanchrisbra
authored andcommitted
patch 9.0.1824: Vim9: private members may be modifiable
Problem: Vim9: private members may be modifiable Solution: prevent modification for def function closes: #12963 Signed-off-by: Christian Brabandt <[email protected]> Co-authored-by: Yegappan Lakshmanan <[email protected]>
1 parent 9d8ef7c commit 5bbcfbc

3 files changed

Lines changed: 44 additions & 0 deletions

File tree

src/testdir/test_vim9_class.vim

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3653,4 +3653,37 @@ def Test_dup_member_variable()
36533653
v9.CheckScriptFailure(lines, 'E1369: Duplicate member: val')
36543654
enddef
36553655

3656+
" Test for accessing a private member outside a class in a def function
3657+
def Test_private_member_access_outside_class()
3658+
# private object member variable
3659+
var lines =<< trim END
3660+
vim9script
3661+
class A
3662+
this._val = 10
3663+
def GetVal(): number
3664+
return this._val
3665+
enddef
3666+
endclass
3667+
def T()
3668+
var a = A.new()
3669+
a._val = 20
3670+
enddef
3671+
T()
3672+
END
3673+
v9.CheckScriptFailure(lines, 'E1333: Cannot access private member: _val')
3674+
3675+
# private class member variable
3676+
lines =<< trim END
3677+
vim9script
3678+
class A
3679+
static _val: number = 10
3680+
endclass
3681+
def T()
3682+
A._val = 20
3683+
enddef
3684+
T()
3685+
END
3686+
v9.CheckScriptFailure(lines, 'E1333: Cannot access private member: _val')
3687+
enddef
3688+
36563689
" vim: ts=8 sw=2 sts=2 expandtab tw=80 fdm=marker

src/version.c

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

700700
static int included_patches[] =
701701
{ /* Add new patch number below this line */
702+
/**/
703+
1824,
702704
/**/
703705
1823,
704706
/**/

src/vim9compile.c

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1866,6 +1866,15 @@ compile_lhs(
18661866
{
18671867
// for an object or class member get the type of the member
18681868
class_T *cl = lhs->lhs_type->tt_class;
1869+
// If it is private member variable, then accessing it outside the
1870+
// class is not allowed.
1871+
if (*(after + 1) == '_' && !inside_class(cctx, cl))
1872+
{
1873+
char_u *m_name = vim_strnsave(after + 1, lhs->lhs_end - after);
1874+
semsg(_(e_cannot_access_private_member_str), m_name);
1875+
vim_free(m_name);
1876+
return FAIL;
1877+
}
18691878
lhs->lhs_member_type = class_member_type(cl, after + 1,
18701879
lhs->lhs_end, &lhs->lhs_member_idx);
18711880
if (lhs->lhs_member_idx < 0)

0 commit comments

Comments
 (0)