Only allow &optional in records

There was some confusing behavior with &optional and locals, so this
should get rid of that by making it an error. However, there is a case
where function parameters are still allowed to have &optional - this is
because there are checks for &default in parameters as well.
This commit is contained in:
Evan Typanski 2025-08-14 09:29:50 -04:00
parent a2680d5eca
commit 4e5a56c5e0
4 changed files with 19 additions and 4 deletions

View file

@ -297,10 +297,10 @@ bool Attributes::CheckAttr(Attr* a) {
case ATTR_IS_USED: break;
case ATTR_OPTIONAL:
if ( global_var )
return AttrError("&optional is not valid for global variables");
if ( ! in_record )
return AttrError("&optional is only valid for record fields");
if ( in_record && Find(ATTR_DEFAULT) )
if ( Find(ATTR_DEFAULT) )
return AttrError("Using &default and &optional together results in &default behavior");
break;

View file

@ -2,5 +2,5 @@
error in <...>/attr-default-global-set-error.zeek, line 4: &default is not valid for global variables except for tables (&default=0)
error in <...>/attr-default-global-set-error.zeek, line 9: &default is not valid for global variables except for tables (&default=10)
error in <...>/attr-default-global-set-error.zeek, line 9: &default is not valid for global variables except for tables (&default=9)
error in <...>/attr-default-global-set-error.zeek, line 9: &optional is not valid for global variables (&optional)
error in <...>/attr-default-global-set-error.zeek, line 9: &optional is only valid for record fields (&optional)
error in <...>/attr-default-global-set-error.zeek, line 10: &default is not valid for global variables except for tables (&default=set())

View file

@ -0,0 +1,3 @@
### BTest baseline data generated by btest-diff. Do not edit. Use "btest -U/-u" to update. Requires BTest >= 0.63.
error in <...>/invalid-optional-attr.zeek, line 5: &optional is only valid for record fields (&optional)
error in <...>/invalid-optional-attr.zeek, line 11: &optional is only valid for record fields (&optional)

View file

@ -0,0 +1,12 @@
# @TEST-EXEC-FAIL: zeek -b %INPUT >out 2>&1
# @TEST-EXEC: TEST_DIFF_CANONIFIER=$SCRIPTS/diff-remove-abspath btest-diff out
# Invalid on globals
global a: int &optional;
# TODO: Invalid on parameters
function f(a: int &optional)
{
# Invalid in locals
local b: int &optional;
}