Add &default_insert attribute for tables

This is based on the discussion in zeek/zeek#2668. Using &default with tables
can be confusing as the default value is not inserted. The following example
prints an empty table at the end even new Service records was instantiated.

    type Service: record {
        occurrences: count &default=0;
        last_seen: time &default=network_time();
    };

    global services: table[string] of Service &default=Service();

    event zeek_init()
        {
        services["http"]$occurrences += 1;
        services["http"]$last_seen = network_time();

        print services;
        }

Changing above &default to &default_insert will insert the newly created
default value upon a missed lookup and act less surprising.

Other examples that caused confusion previously revolved around table of sets
 or table of vectors and `add` or `+=` not working as expected.

    tbl_of_vector["http"] += 1
    add tbl_of_set["http"][1];
This commit is contained in:
Arne Welzel 2023-07-07 17:05:00 +02:00
parent 81ce83590d
commit 431767d04b
22 changed files with 230 additions and 13 deletions

View file

@ -5,7 +5,7 @@
// Switching parser table type fixes ambiguity problems.
%define lr.type ielr
%expect 211
%expect 217
%token TOK_ADD TOK_ADD_TO TOK_ADDR TOK_ANY TOK_ASSERT
%token TOK_ATENDIF TOK_ATELSE TOK_ATIF TOK_ATIFDEF TOK_ATIFNDEF
@ -23,7 +23,7 @@
%token TOK_WHILE TOK_AS TOK_IS
%token TOK_GLOBAL_ID
%token TOK_ATTR_ADD_FUNC TOK_ATTR_DEFAULT TOK_ATTR_OPTIONAL TOK_ATTR_REDEF
%token TOK_ATTR_ADD_FUNC TOK_ATTR_DEFAULT TOK_ATTR_DEFAULT_INSERT TOK_ATTR_OPTIONAL TOK_ATTR_REDEF
%token TOK_ATTR_DEL_FUNC TOK_ATTR_EXPIRE_FUNC
%token TOK_ATTR_EXPIRE_CREATE TOK_ATTR_EXPIRE_READ TOK_ATTR_EXPIRE_WRITE
%token TOK_ATTR_RAW_OUTPUT TOK_ATTR_ON_CHANGE TOK_ATTR_BROKER_STORE
@ -1720,6 +1720,8 @@ attr_list:
attr:
TOK_ATTR_DEFAULT '=' expr
{ $$ = new Attr(ATTR_DEFAULT, {AdoptRef{}, $3}); }
| TOK_ATTR_DEFAULT_INSERT '=' expr
{ $$ = new Attr(ATTR_DEFAULT_INSERT, {AdoptRef{}, $3}); }
| TOK_ATTR_OPTIONAL
{ $$ = new Attr(ATTR_OPTIONAL); }
| TOK_ATTR_REDEF