Allow delete statement for tables, sets and vectors

Relates to #3472. This allow "delete tbl" as an alternative for
clear_table(tbl). Also works for vectors.
This commit is contained in:
Arne Welzel 2024-02-21 17:36:20 +01:00
parent 6d86a48a6a
commit 2f1893bc58
7 changed files with 68 additions and 0 deletions

6
NEWS
View file

@ -12,6 +12,12 @@ Breaking Changes
New Functionality New Functionality
----------------- -----------------
- Support ``delete`` on tables, sets and vectors to clear their contents.
global v = vector(1, 2, 3);
delete v;
assert |v| == 0;
Changed Functionality Changed Functionality
--------------------- ---------------------

View file

@ -408,6 +408,24 @@ NameExpr::NameExpr(IDPtr arg_id, bool const_init) : Expr(EXPR_NAME), id(std::mov
#pragma GCC diagnostic pop #pragma GCC diagnostic pop
} }
bool NameExpr::CanDel() const {
if ( IsError() )
return true; // avoid cascading the error report
return GetType()->Tag() == TYPE_TABLE || GetType()->Tag() == TYPE_VECTOR;
}
void NameExpr::Delete(Frame* f) {
if ( auto v = Eval(f) ) {
if ( GetType()->Tag() == TYPE_TABLE )
v->AsTableVal()->RemoveAll();
else if ( GetType()->Tag() == TYPE_VECTOR )
v->AsVectorVal()->Resize(0);
else
RuntimeError("delete unsupported");
}
}
// This isn't in-lined to avoid needing to pull in ID.h. // This isn't in-lined to avoid needing to pull in ID.h.
const IDPtr& NameExpr::IdPtr() const { return id; } const IDPtr& NameExpr::IdPtr() const { return id; }

View file

@ -428,6 +428,9 @@ class NameExpr final : public Expr {
public: public:
explicit NameExpr(IDPtr id, bool const_init = false); explicit NameExpr(IDPtr id, bool const_init = false);
bool CanDel() const override;
void Delete(Frame* f) override;
ID* Id() const { return id.get(); } ID* Id() const { return id.get(); }
const IDPtr& IdPtr() const; const IDPtr& IdPtr() const;

View file

@ -0,0 +1 @@
### BTest baseline data generated by btest-diff. Do not edit. Use "btest -U/-u" to update. Requires BTest >= 0.63.

View file

@ -0,0 +1,15 @@
### BTest baseline data generated by btest-diff. Do not edit. Use "btest -U/-u" to update. Requires BTest >= 0.63.
t, {
[42] = 4711
}
s, {
42
}
v, [1, 2, 3]
t, {
}
s, {
}
v, []

View file

@ -0,0 +1 @@
### BTest baseline data generated by btest-diff. Do not edit. Use "btest -U/-u" to update. Requires BTest >= 0.63.

View file

@ -0,0 +1,24 @@
# @TEST-DOC: Deleteing a table, set or vector removes all of its elements.
# @TEST-EXEC: zeek -b %INPUT >output
# @TEST-EXEC: btest-diff output
# @TEST-EXEC: btest-diff .stderr
global t: table[count] of count &read_expire=1sec;
global s: set[count];
global v = vector(1,2,3);
t[42] = 4711;
add s[42];
print "t", t;
print "s", s;
print "v", v;
delete t;
delete s;
delete v;
print "t", t;
print "s", s;
print "v", v;