Merge remote-tracking branch 'origin/topic/timw/tools-clang-tidy'

* origin/topic/timw/tools-clang-tidy:
  gen-zam: Move source files up a directory
  bifcl: Fix clang-tidy warnings
  bifcl: Run clang-format on c++ code embedded in builtin-func.{l,y}
  binpac: Fix a large number of clang-tidy warnings
  binpac: Replace delete_list macro uses
  binpac: Run clang-format on c++ code embedded in pac_parse.{ll,yy}
This commit is contained in:
Tim Wojtulewicz 2025-08-28 15:19:59 -07:00
commit 273abf3d08
64 changed files with 809 additions and 823 deletions

14
CHANGES
View file

@ -1,3 +1,17 @@
8.1.0-dev.475 | 2025-08-28 15:19:59 -0700
* gen-zam: Move source files up a directory (Tim Wojtulewicz, Corelight)
* bifcl: Fix clang-tidy warnings (Tim Wojtulewicz, Corelight)
* bifcl: Run clang-format on c++ code embedded in builtin-func.{l,y} (Tim Wojtulewicz, Corelight)
* binpac: Fix a large number of clang-tidy warnings (Tim Wojtulewicz, Corelight)
* binpac: Replace delete_list macro uses (Tim Wojtulewicz, Corelight)
* binpac: Run clang-format on c++ code embedded in pac_parse.{ll,yy} (Tim Wojtulewicz, Corelight)
8.1.0-dev.468 | 2025-08-28 13:06:25 -0700 8.1.0-dev.468 | 2025-08-28 13:06:25 -0700
* Link Prometheus symbols via Broker instead of directly (Tim Wojtulewicz, Corelight) * Link Prometheus symbols via Broker instead of directly (Tim Wojtulewicz, Corelight)

View file

@ -1 +1 @@
8.1.0-dev.468 8.1.0-dev.475

View file

@ -12,8 +12,15 @@ add_flex_bison_dependency(BIFScanner BIFParser)
set(bifcl_SRCS ${BISON_BIFParser_INPUT} ${FLEX_BIFScanner_INPUT} ${BISON_BIFParser_OUTPUTS} set(bifcl_SRCS ${BISON_BIFParser_INPUT} ${FLEX_BIFScanner_INPUT} ${BISON_BIFParser_OUTPUTS}
${FLEX_BIFScanner_OUTPUTS} bif_arg.cc module_util.cc) ${FLEX_BIFScanner_OUTPUTS} bif_arg.cc module_util.cc)
set(bifcl_bison_generated_files
${CMAKE_CURRENT_BINARY_DIR}/bif_parse.cc ${CMAKE_CURRENT_BINARY_DIR}/bif_parse.h
${CMAKE_CURRENT_BINARY_DIR}/bif_lex.cc)
set_source_files_properties(${bifcl_bison_generated_files} PROPERTIES SKIP_LINTING ON)
add_executable(bifcl ${bifcl_SRCS}) add_executable(bifcl ${bifcl_SRCS})
target_include_directories(bifcl BEFORE PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_include_directories(bifcl BEFORE PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
zeek_target_add_linters(bifcl)
if (MSVC) if (MSVC)
target_compile_options(bifcl PUBLIC "/J") # Similar to -funsigned-char on other platforms target_compile_options(bifcl PUBLIC "/J") # Similar to -funsigned-char on other platforms

View file

@ -1,6 +1,6 @@
// See the file "COPYING" in the main distribution directory for copyright. // See the file "COPYING" in the main distribution directory for copyright.
#include "bif_arg.h" #include "include/bif_arg.h"
#include <cstring> #include <cstring>
@ -16,6 +16,7 @@ static struct {
const char* constructor; const char* constructor;
const char* ctor_smart; const char* ctor_smart;
} builtin_func_arg_type[] = { } builtin_func_arg_type[] = {
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define DEFINE_BIF_TYPE(id, bif_type, zeek_type, c_type, c_type_smart, accessor, accessor_smart, cast_smart, \ #define DEFINE_BIF_TYPE(id, bif_type, zeek_type, c_type, c_type_smart, accessor, accessor_smart, cast_smart, \
constructor, ctor_smart) \ constructor, ctor_smart) \
{#id, bif_type, zeek_type, c_type, c_type_smart, accessor, accessor_smart, cast_smart, constructor, ctor_smart}, {#id, bif_type, zeek_type, c_type, c_type_smart, accessor, accessor_smart, cast_smart, constructor, ctor_smart},

View file

@ -143,11 +143,10 @@ HEX [0-9a-fA-F]+
} }
%% %%
int yywrap() int yywrap() {
{ yy_delete_buffer(YY_CURRENT_BUFFER);
yy_delete_buffer(YY_CURRENT_BUFFER); return 1;
return 1; }
}
extern int yyparse(); extern int yyparse();
char* input_filename = nullptr; char* input_filename = nullptr;
@ -171,297 +170,272 @@ void close_if_open(FILE **fpp);
void close_all_output_files(void); void close_all_output_files(void);
FILE* open_output_file(const char* surfix) FILE* open_output_file(const char* surfix) {
{ char fn[1024];
char fn[1024]; FILE* fp;
FILE* fp;
snprintf(fn, sizeof(fn), "%s.%s", input_filename, surfix); snprintf(fn, sizeof(fn), "%s.%s", input_filename, surfix);
if ( (fp = fopen(fn, "w")) == NULL ) if ( fp = fopen(fn, "w"); fp == nullptr ) {
{ fprintf(stderr, "Error: cannot open file: %s\n", fn);
fprintf(stderr, "Error: cannot open file: %s\n", fn); err_exit();
err_exit(); }
}
return fp; return fp;
} }
void usage() void usage() {
{ fprintf(stderr, "usage: bifcl [-p <plugin> | -s] *.bif\n");
fprintf(stderr, "usage: bifcl [-p <plugin> | -s] *.bif\n"); exit(1);
exit(1); }
}
void init_alternative_mode() void init_alternative_mode() {
{ fp_zeek_init = open_output_file("zeek");
fp_zeek_init = open_output_file("zeek"); fp_func_h = open_output_file("h");
fp_func_h = open_output_file("h"); fp_func_def = open_output_file("cc");
fp_func_def = open_output_file("cc"); fp_func_init = open_output_file("init.cc");
fp_func_init = open_output_file("init.cc"); fp_func_register = plugin ? open_output_file("register.cc") : nullptr;
fp_func_register = plugin ? open_output_file("register.cc") : nullptr;
fp_netvar_h = fp_func_h; fp_netvar_h = fp_func_h;
fp_netvar_def = fp_func_def; fp_netvar_def = fp_func_def;
fp_netvar_init = fp_func_init; fp_netvar_init = fp_func_init;
int n = 1024 + strlen(input_filename); int n = 1024 + strlen(input_filename);
auto auto_gen_comment_buf = std::make_unique<char[]>(n); auto auto_gen_comment_buf = std::make_unique<char[]>(n);
auto auto_gen_comment = auto_gen_comment_buf.get(); auto auto_gen_comment = auto_gen_comment_buf.get();
snprintf(auto_gen_comment, n, snprintf(auto_gen_comment, n, "This file was automatically generated by bifcl from %s (%s mode).",
"This file was automatically generated by bifcl from %s (%s mode).", input_filename_with_path, plugin ? "plugin" : "alternative");
input_filename_with_path, plugin ? "plugin" : "alternative");
fprintf(fp_zeek_init, "# %s\n\n", auto_gen_comment); fprintf(fp_zeek_init, "# %s\n\n", auto_gen_comment);
fprintf(fp_func_def, "// %s\n\n", auto_gen_comment); fprintf(fp_func_def, "// %s\n\n", auto_gen_comment);
fprintf(fp_func_h, "// %s\n\n", auto_gen_comment); fprintf(fp_func_h, "// %s\n\n", auto_gen_comment);
fprintf(fp_func_h, "#pragma once\n\n"); fprintf(fp_func_h, "#pragma once\n\n");
fprintf(fp_func_init, "// %s\n\n", auto_gen_comment); fprintf(fp_func_init, "// %s\n\n", auto_gen_comment);
if ( fp_func_register ) if ( fp_func_register )
fprintf(fp_func_register, "// %s\n\n", auto_gen_comment); fprintf(fp_func_register, "// %s\n\n", auto_gen_comment);
static char guard[1024]; static char guard[1024];
if ( getcwd(guard, sizeof(guard)) == NULL ) if ( getcwd(guard, sizeof(guard)) == nullptr ) {
{ fprintf(stderr, "Error: cannot get current working directory\n");
fprintf(stderr, "Error: cannot get current working directory\n"); err_exit();
err_exit(); }
} strncat(guard, "/", sizeof(guard) - strlen(guard) - 1);
strncat(guard, "/", sizeof(guard) - strlen(guard) - 1); strncat(guard, input_filename, sizeof(guard) - strlen(guard) - 1);
strncat(guard, input_filename, sizeof(guard) - strlen(guard) - 1);
for ( char* p = guard; *p; p++ ) for ( char* p = guard; *p; p++ ) {
{ if ( ! isalnum(*p) )
if ( ! isalnum(*p) ) *p = '_';
*p = '_'; }
}
fprintf(fp_func_h, "#if defined(ZEEK_IN_NETVAR) || ! defined(%s)\n", guard); fprintf(fp_func_h, "#if defined(ZEEK_IN_NETVAR) || ! defined(%s)\n", guard);
fprintf(fp_func_h, "#ifndef ZEEK_IN_NETVAR\n"); fprintf(fp_func_h, "#ifndef ZEEK_IN_NETVAR\n");
fprintf(fp_func_h, "#ifndef %s\n", guard); fprintf(fp_func_h, "#ifndef %s\n", guard);
fprintf(fp_func_h, "#define %s\n", guard); fprintf(fp_func_h, "#define %s\n", guard);
fprintf(fp_func_h, "#include \"zeek/zeek-bif.h\"\n"); fprintf(fp_func_h, "#include \"zeek/zeek-bif.h\"\n");
fprintf(fp_func_h, "#endif\n"); fprintf(fp_func_h, "#endif\n");
fprintf(fp_func_h, "#endif\n"); fprintf(fp_func_h, "#endif\n");
fprintf(fp_func_h, "\n"); fprintf(fp_func_h, "\n");
fprintf(fp_func_def, "\n"); fprintf(fp_func_def, "\n");
fprintf(fp_func_def, "#include \"%s.h\"\n", input_filename); fprintf(fp_func_def, "#include \"%s.h\"\n", input_filename);
fprintf(fp_func_def, "#include \"zeek/Func.h\"\n"); fprintf(fp_func_def, "#include \"zeek/Func.h\"\n");
fprintf(fp_func_def, "\n"); fprintf(fp_func_def, "\n");
static char name[1024]; static char name[1024];
strncpy(name, input_filename, sizeof(name) - 1); strncpy(name, input_filename, sizeof(name) - 1);
name[sizeof(name) - 1] = '\0'; name[sizeof(name) - 1] = '\0';
char* dot = strchr(name, '.'); char* dot = strchr(name, '.');
if ( dot ) if ( dot )
*dot = '\0'; *dot = '\0';
if ( plugin ) if ( plugin ) {
{ static char plugin_canon[1024];
static char plugin_canon[1024]; strncpy(plugin_canon, plugin, sizeof(plugin_canon) - 1);
strncpy(plugin_canon, plugin, sizeof(plugin_canon) - 1); plugin_canon[sizeof(plugin_canon) - 1] = '\0';
plugin_canon[sizeof(plugin_canon) - 1] = '\0'; char* colon = strstr(plugin_canon, "::");
char* colon = strstr(plugin_canon, "::");
if ( colon ) { if ( colon ) {
*colon = '_'; *colon = '_';
memmove(colon + 1, colon + 2, plugin_canon + strlen(plugin_canon) - colon); memmove(colon + 1, colon + 2, plugin_canon + strlen(plugin_canon) - colon);
}
fprintf(fp_func_init, "\n");
fprintf(fp_func_init, "#include <list>\n");
fprintf(fp_func_init, "#include <string>\n");
fprintf(fp_func_init, "#include \"zeek/plugin/Plugin.h\"\n");
fprintf(fp_func_init, "#include \"zeek/Func.h\"\n");
fprintf(fp_func_init, "#include \"%s.h\"\n", input_filename);
fprintf(fp_func_init, "\n");
fprintf(fp_func_init, "namespace plugin::%s {\n", plugin_canon);
fprintf(fp_func_init, "\n");
fprintf(fp_func_init, "void __bif_%s_init(zeek::plugin::Plugin* plugin)\n", name);
fprintf(fp_func_init, "\t{\n");
fprintf(fp_func_register, "#include \"zeek/plugin/Manager.h\"\n");
fprintf(fp_func_register, "\n");
fprintf(fp_func_register, "namespace plugin::%s {\n", plugin_canon);
fprintf(fp_func_register, "void __bif_%s_init(zeek::plugin::Plugin* plugin);\n", name);
fprintf(fp_func_register, "zeek::plugin::detail::__RegisterBif __register_bifs_%s_%s(\"%s\", __bif_%s_init);\n", plugin_canon, name, plugin, name);
fprintf(fp_func_register, "}\n");
} }
}
void finish_alternative_mode() fprintf(fp_func_init, "\n");
{ fprintf(fp_func_init, "#include <list>\n");
fprintf(fp_func_h, "\n"); fprintf(fp_func_init, "#include <string>\n");
fprintf(fp_func_h, "#endif\n"); fprintf(fp_func_init, "#include \"zeek/plugin/Plugin.h\"\n");
fprintf(fp_func_init, "#include \"zeek/Func.h\"\n");
fprintf(fp_func_init, "#include \"%s.h\"\n", input_filename);
fprintf(fp_func_init, "\n");
fprintf(fp_func_init, "namespace plugin::%s {\n", plugin_canon);
fprintf(fp_func_init, "\n");
fprintf(fp_func_init, "void __bif_%s_init(zeek::plugin::Plugin* plugin)\n", name);
fprintf(fp_func_init, "\t{\n");
if ( plugin ) fprintf(fp_func_register, "#include \"zeek/plugin/Manager.h\"\n");
{ fprintf(fp_func_register, "\n");
fprintf(fp_func_init, "\n"); fprintf(fp_func_register, "namespace plugin::%s {\n", plugin_canon);
fprintf(fp_func_init, "\t}\n"); fprintf(fp_func_register, "void __bif_%s_init(zeek::plugin::Plugin* plugin);\n", name);
fprintf(fp_func_init, "}\n"); fprintf(fp_func_register, "zeek::plugin::detail::__RegisterBif __register_bifs_%s_%s(\"%s\", __bif_%s_init);\n",
fprintf(fp_func_init, "\n"); plugin_canon, name, plugin, name);
fprintf(fp_func_init, "\n"); fprintf(fp_func_register, "}\n");
} }
} }
void finish_alternative_mode() {
fprintf(fp_func_h, "\n");
fprintf(fp_func_h, "#endif\n");
if ( plugin ) {
fprintf(fp_func_init, "\n");
fprintf(fp_func_init, "\t}\n");
fprintf(fp_func_init, "}\n");
fprintf(fp_func_init, "\n");
fprintf(fp_func_init, "\n");
}
}
// GCC uses __SANITIZE_ADDRESS__, Clang uses __has_feature // GCC uses __SANITIZE_ADDRESS__, Clang uses __has_feature
#if defined(__SANITIZE_ADDRESS__) #if defined(__SANITIZE_ADDRESS__)
#define USING_ASAN #define USING_ASAN
#endif #endif
#if defined(__has_feature) #if defined(__has_feature)
#if __has_feature(address_sanitizer) #if __has_feature(address_sanitizer)
#define USING_ASAN #define USING_ASAN
#endif #endif
#endif #endif
// FreeBSD doesn't support LeakSanitizer // FreeBSD doesn't support LeakSanitizer
#if defined(USING_ASAN) && !defined(__FreeBSD__) #if defined(USING_ASAN) && ! defined(__FreeBSD__)
#include <sanitizer/lsan_interface.h> #include <sanitizer/lsan_interface.h>
#define BIFCL_LSAN_DISABLE() __lsan_disable() #define BIFCL_LSAN_DISABLE() __lsan_disable()
#else #else
#define BIFCL_LSAN_DISABLE() #define BIFCL_LSAN_DISABLE()
#endif #endif
int main(int argc, char* argv[]) int main(int argc, char* argv[]) {
{ // We generally do not care at all if bifcl is leaking and the default
// We generally do not care at all if bifcl is leaking and the default // behavior of LSAN to treat leaks as errors only trips up Zeek's build.
// behavior of LSAN to treat leaks as errors only trips up Zeek's build. BIFCL_LSAN_DISABLE();
BIFCL_LSAN_DISABLE();
int opt; int opt;
while ( (opt = getopt(argc, argv, "p:s")) != -1 ) while ( (opt = getopt(argc, argv, "p:s")) != -1 ) {
{ switch ( opt ) {
switch ( opt ) { case 'p':
case 'p': alternative_mode = true;
alternative_mode = true; plugin = (char*)optarg;
plugin = (char*) optarg; break;
break;
case 's': case 's': alternative_mode = true; break;
alternative_mode = true;
break;
default: default: usage();
usage(); }
} }
}
for ( int i = optind; i < argc; i++ ) for ( int i = optind; i < argc; i++ ) {
{ FILE* fp_input;
FILE* fp_input;
input_filename = input_filename_with_path = argv[i]; input_filename = input_filename_with_path = argv[i];
char* slash = strrchr(input_filename, '/'); char* slash = strrchr(input_filename, '/');
if ( (fp_input = fopen(input_filename, "r")) == NULL ) if ( fp_input = fopen(input_filename, "r"); fp_input == nullptr ) {
{ fprintf(stderr, "Error: cannot open file: %s\n", input_filename);
fprintf(stderr, "Error: cannot open file: %s\n", input_filename); /* no output files open. can simply exit */
/* no output files open. can simply exit */ exit(1);
exit(1); }
}
if ( slash ) if ( slash )
input_filename = slash + 1; input_filename = slash + 1;
if ( ! alternative_mode ) if ( ! alternative_mode ) {
{ fp_zeek_init = open_output_file("zeek");
fp_zeek_init = open_output_file("zeek"); fp_func_h = open_output_file("func_h");
fp_func_h = open_output_file("func_h"); fp_func_def = open_output_file("func_def");
fp_func_def = open_output_file("func_def"); fp_func_init = open_output_file("func_init");
fp_func_init = open_output_file("func_init"); fp_netvar_h = open_output_file("netvar_h");
fp_netvar_h = open_output_file("netvar_h"); fp_netvar_def = open_output_file("netvar_def");
fp_netvar_def = open_output_file("netvar_def"); fp_netvar_init = open_output_file("netvar_init");
fp_netvar_init = open_output_file("netvar_init");
int n = 1024 + strlen(input_filename); int n = 1024 + strlen(input_filename);
auto auto_gen_comment_buf = std::make_unique<char[]>(n); auto auto_gen_comment_buf = std::make_unique<char[]>(n);
auto auto_gen_comment = auto_gen_comment_buf.get(); auto auto_gen_comment = auto_gen_comment_buf.get();
snprintf(auto_gen_comment, n, snprintf(auto_gen_comment, n, "This file was automatically generated by bifcl from %s.", input_filename);
"This file was automatically generated by bifcl from %s.",
input_filename);
fprintf(fp_zeek_init, "# %s\n\n", auto_gen_comment); fprintf(fp_zeek_init, "# %s\n\n", auto_gen_comment);
fprintf(fp_func_def, "// %s\n\n", auto_gen_comment); fprintf(fp_func_def, "// %s\n\n", auto_gen_comment);
fprintf(fp_func_h, "// %s\n\n", auto_gen_comment); fprintf(fp_func_h, "// %s\n\n", auto_gen_comment);
fprintf(fp_func_h, "#pragma once\n\n"); fprintf(fp_func_h, "#pragma once\n\n");
fprintf(fp_func_init, "// %s\n\n", auto_gen_comment); fprintf(fp_func_init, "// %s\n\n", auto_gen_comment);
fprintf(fp_netvar_def, "// %s\n\n", auto_gen_comment); fprintf(fp_netvar_def, "// %s\n\n", auto_gen_comment);
fprintf(fp_netvar_h, "// %s\n\n", auto_gen_comment); fprintf(fp_netvar_h, "// %s\n\n", auto_gen_comment);
fprintf(fp_netvar_h, "#pragma once\n\n"); fprintf(fp_netvar_h, "#pragma once\n\n");
fprintf(fp_netvar_init, "// %s\n\n", auto_gen_comment); fprintf(fp_netvar_init, "// %s\n\n", auto_gen_comment);
} }
else else
init_alternative_mode(); init_alternative_mode();
fprintf(fp_netvar_init, "#ifdef __GNUC__\n"); fprintf(fp_netvar_init, "#ifdef __GNUC__\n");
fprintf(fp_netvar_init, "#pragma GCC diagnostic push\n"); fprintf(fp_netvar_init, "#pragma GCC diagnostic push\n");
fprintf(fp_netvar_init, "#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n\n"); fprintf(fp_netvar_init, "#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n\n");
fprintf(fp_netvar_init, "#endif\n"); fprintf(fp_netvar_init, "#endif\n");
yy_switch_to_buffer(yy_create_buffer(fp_input, YY_BUF_SIZE)); yy_switch_to_buffer(yy_create_buffer(fp_input, YY_BUF_SIZE));
yyparse(); yyparse();
fprintf(fp_netvar_init, "#ifdef __GNUC__\n"); fprintf(fp_netvar_init, "#ifdef __GNUC__\n");
fprintf(fp_netvar_init, "\n\n#pragma GCC diagnostic pop\n"); fprintf(fp_netvar_init, "\n\n#pragma GCC diagnostic pop\n");
fprintf(fp_netvar_init, "#endif\n"); fprintf(fp_netvar_init, "#endif\n");
if ( alternative_mode ) if ( alternative_mode )
finish_alternative_mode(); finish_alternative_mode();
fclose(fp_input); fclose(fp_input);
close_all_output_files(); close_all_output_files();
}
}
} void close_if_open(FILE** fpp) {
} if ( *fpp )
fclose(*fpp);
*fpp = nullptr;
}
void close_if_open(FILE **fpp) void close_all_output_files(void) {
{ close_if_open(&fp_zeek_init);
if (*fpp) close_if_open(&fp_func_h);
fclose(*fpp); close_if_open(&fp_func_def);
*fpp = nullptr; close_if_open(&fp_func_init);
} close_if_open(&fp_func_register);
void close_all_output_files(void) if ( ! alternative_mode ) {
{ close_if_open(&fp_netvar_h);
close_if_open(&fp_zeek_init); close_if_open(&fp_netvar_def);
close_if_open(&fp_func_h); close_if_open(&fp_netvar_init);
close_if_open(&fp_func_def); }
close_if_open(&fp_func_init); }
close_if_open(&fp_func_register);
if ( ! alternative_mode ) void remove_file(const char* surfix) {
{ char fn[1024];
close_if_open(&fp_netvar_h);
close_if_open(&fp_netvar_def);
close_if_open(&fp_netvar_init);
}
}
void remove_file(const char *surfix) snprintf(fn, sizeof(fn), "%s.%s", input_filename, surfix);
{ unlink(fn);
char fn[1024]; }
snprintf(fn, sizeof(fn), "%s.%s", input_filename, surfix); void err_exit(void) {
unlink(fn); close_all_output_files();
} /* clean up. remove all output files we've generated so far */
remove_file("zeek");
void err_exit(void) remove_file("func_h");
{ remove_file("func_def");
close_all_output_files(); remove_file("func_init");
/* clean up. remove all output files we've generated so far */ remove_file("func_register");
remove_file("zeek"); remove_file("netvar_h");
remove_file("func_h"); remove_file("netvar_def");
remove_file("func_def"); remove_file("netvar_init");
remove_file("func_init"); exit(1);
remove_file("func_register"); }
remove_file("netvar_h");
remove_file("netvar_def");
remove_file("netvar_init");
exit(1);
}

View file

@ -65,92 +65,88 @@ struct decl_struct {
string enqueue_c_fullname; string enqueue_c_fullname;
} decl; } decl;
void set_definition_type(int type, const char *arg_type_name) void set_definition_type(int type, const char* arg_type_name) {
{ definition_type = type;
definition_type = type; if ( type == TYPE_DEF && arg_type_name )
if ( type == TYPE_DEF && arg_type_name ) type_name = string(arg_type_name);
type_name = string(arg_type_name); else
else type_name = "";
type_name = ""; }
}
void set_decl_name(const char *name) void set_decl_name(const char* name) {
{ decl.bare_name = extract_var_name(name);
decl.bare_name = extract_var_name(name);
// make_full_var_name prepends the correct module, if any // make_full_var_name prepends the correct module, if any
// then we can extract the module name again. // then we can extract the module name again.
string varname = make_full_var_name(current_module.c_str(), name); string varname = make_full_var_name(current_module.c_str(), name);
decl.module_name = extract_module_name(varname.c_str()); decl.module_name = extract_module_name(varname.c_str());
decl.c_namespace_start = ""; decl.c_namespace_start = "";
decl.c_namespace_end = ""; decl.c_namespace_end = "";
decl.c_fullname = ""; decl.c_fullname = "";
decl.zeek_fullname = ""; decl.zeek_fullname = "";
decl.zeek_name = ""; decl.zeek_name = "";
decl.enqueue_c_fullname = ""; decl.enqueue_c_fullname = "";
decl.enqueue_c_barename = string("enqueue_") + decl.bare_name; decl.enqueue_c_barename = string("enqueue_") + decl.bare_name;
decl.enqueue_c_namespace_start = ""; decl.enqueue_c_namespace_start = "";
decl.enqueue_c_namespace_end = ""; decl.enqueue_c_namespace_end = "";
switch ( definition_type ) { switch ( definition_type ) {
case TYPE_DEF: case TYPE_DEF:
decl.c_namespace_start = "BifType::" + type_name + ""; decl.c_namespace_start = "BifType::" + type_name + "";
decl.c_fullname = "BifType::" + type_name + "::"; decl.c_fullname = "BifType::" + type_name + "::";
break; break;
case CONST_DEF: case CONST_DEF:
decl.c_namespace_start = "BifConst"; decl.c_namespace_start = "BifConst";
decl.c_fullname = "BifConst::"; decl.c_fullname = "BifConst::";
break; break;
case FUNC_DEF: case FUNC_DEF:
decl.c_namespace_start = "BifFunc"; decl.c_namespace_start = "BifFunc";
decl.c_fullname = "BifFunc::"; decl.c_fullname = "BifFunc::";
break; break;
case EVENT_DEF: case EVENT_DEF:
decl.c_namespace_start = ""; decl.c_namespace_start = "";
decl.c_namespace_end = ""; decl.c_namespace_end = "";
decl.c_fullname = "::"; // need this for namespace qualified events due do event_c_body decl.c_fullname = "::"; // need this for namespace qualified events due do event_c_body
decl.enqueue_c_namespace_start = "BifEvent"; decl.enqueue_c_namespace_start = "BifEvent";
decl.enqueue_c_fullname = "zeek::BifEvent::"; decl.enqueue_c_fullname = "zeek::BifEvent::";
break; break;
default: default: break;
break; }
}
if ( decl.module_name != GLOBAL_MODULE_NAME ) if ( decl.module_name != GLOBAL_MODULE_NAME ) {
{ if ( decl.c_namespace_start.empty() ) {
if ( decl.c_namespace_start.empty() ) { decl.c_namespace_start += "namespace " + decl.module_name + " { ";
decl.c_namespace_start += "namespace " + decl.module_name + " { "; decl.c_namespace_end += " }";
decl.c_namespace_end += " }"; }
} else {
else { decl.c_namespace_start += "::" + decl.module_name;
decl.c_namespace_start += "::" + decl.module_name; decl.c_namespace_end = "";
decl.c_namespace_end = ""; }
} decl.c_fullname += decl.module_name + "::";
decl.c_fullname += decl.module_name + "::"; decl.zeek_fullname += decl.module_name + "::";
decl.zeek_fullname += decl.module_name + "::";
if ( decl.enqueue_c_namespace_start.empty() ) { if ( decl.enqueue_c_namespace_start.empty() ) {
decl.enqueue_c_namespace_start += "namespace " + decl.module_name + " { "; decl.enqueue_c_namespace_start += "namespace " + decl.module_name + " { ";
decl.enqueue_c_namespace_end += " } "; decl.enqueue_c_namespace_end += " } ";
} }
else { else {
decl.enqueue_c_namespace_start += "::" + decl.module_name; decl.enqueue_c_namespace_start += "::" + decl.module_name;
decl.enqueue_c_namespace_end = ""; decl.enqueue_c_namespace_end = "";
} }
decl.enqueue_c_fullname += decl.module_name + "::"; decl.enqueue_c_fullname += decl.module_name + "::";
} }
decl.zeek_fullname += decl.bare_name; decl.zeek_fullname += decl.bare_name;
decl.c_fullname += decl.bare_name; decl.c_fullname += decl.bare_name;
decl.zeek_name += name; decl.zeek_name += name;
decl.enqueue_c_fullname += decl.enqueue_c_barename; decl.enqueue_c_fullname += decl.enqueue_c_barename;
} }
const char* arg_list_name = "BiF_ARGS"; const char* arg_list_name = "BiF_ARGS";
@ -168,22 +164,20 @@ static struct {
const char* constructor; const char* constructor;
const char* ctor_smatr; const char* ctor_smatr;
} builtin_types[] = { } builtin_types[] = {
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define DEFINE_BIF_TYPE(id, bif_type, zeek_type, c_type, c_type_smart, accessor, accessor_smart, cast_smart, constructor, ctor_smart) \ #define DEFINE_BIF_TYPE(id, bif_type, zeek_type, c_type, c_type_smart, accessor, accessor_smart, cast_smart, constructor, ctor_smart) \
{bif_type, zeek_type, c_type, c_type_smart, accessor, accessor_smart, cast_smart, constructor, ctor_smart}, {bif_type, zeek_type, c_type, c_type_smart, accessor, accessor_smart, cast_smart, constructor, ctor_smart},
#include "bif_type.def" #include "bif_type.def"
#undef DEFINE_BIF_TYPE #undef DEFINE_BIF_TYPE
}; };
int get_type_index(const char *type_name) int get_type_index(const char* type_name) {
{ for ( int i = 0; builtin_types[i].bif_type[0] != '\0'; ++i ) {
for ( int i = 0; builtin_types[i].bif_type[0] != '\0'; ++i ) if ( strcmp(builtin_types[i].bif_type, type_name) == 0 )
{ return i;
if ( strcmp(builtin_types[i].bif_type, type_name) == 0 ) }
return i; return TYPE_OTHER;
} }
return TYPE_OTHER;
}
int var_arg; // whether the number of arguments is variable int var_arg; // whether the number of arguments is variable
std::vector<BuiltinFuncArg*> args; std::vector<BuiltinFuncArg*> args;
@ -192,108 +186,94 @@ extern int yyerror(const char[]);
extern int yywarn(const char msg[]); extern int yywarn(const char msg[]);
extern int yylex(); extern int yylex();
char* concat(const char* str1, const char* str2) char* concat(const char* str1, const char* str2) {
{ int len1 = strlen(str1);
int len1 = strlen(str1); int len2 = strlen(str2);
int len2 = strlen(str2);
char* s = new char[len1 + len2 +1]; char* s = new char[len1 + len2 + 1];
memcpy(s, str1, len1); memcpy(s, str1, len1);
memcpy(s + len1, str2, len2); memcpy(s + len1, str2, len2);
s[len1+len2] = '\0'; s[len1 + len2] = '\0';
return s; return s;
} }
static void print_event_c_prototype_args(FILE* fp) static void print_event_c_prototype_args(FILE * fp) {
{ for ( auto i = 0u; i < args.size(); ++i ) {
for ( auto i = 0u; i < args.size(); ++i ) if ( i > 0 )
{ fprintf(fp, ", ");
if ( i > 0 )
fprintf(fp, ", ");
args[i]->PrintCArg(fp, i); args[i]->PrintCArg(fp, i);
} }
} }
static void print_event_c_prototype_header(FILE* fp) static void print_event_c_prototype_header(FILE * fp) {
{ fprintf(fp, "namespace zeek::%s { void %s(zeek::analyzer::Analyzer* analyzer%s",
fprintf(fp, "namespace zeek::%s { void %s(zeek::analyzer::Analyzer* analyzer%s", decl.enqueue_c_namespace_start.c_str(), decl.enqueue_c_barename.c_str(), args.size() ? ", " : "");
decl.enqueue_c_namespace_start.c_str(),
decl.enqueue_c_barename.c_str(),
args.size() ? ", " : "" );
print_event_c_prototype_args(fp); print_event_c_prototype_args(fp);
fprintf(fp, ")"); fprintf(fp, ")");
fprintf(fp, "; %s }\n", decl.enqueue_c_namespace_end.c_str()); fprintf(fp, "; %s }\n", decl.enqueue_c_namespace_end.c_str());
} }
static void print_event_c_prototype_impl(FILE* fp) static void print_event_c_prototype_impl(FILE * fp) {
{ fprintf(fp, "void %s(zeek::analyzer::Analyzer* analyzer%s", decl.enqueue_c_fullname.c_str(),
fprintf(fp, "void %s(zeek::analyzer::Analyzer* analyzer%s", args.size() ? ", " : "");
decl.enqueue_c_fullname.c_str(),
args.size() ? ", " : "" );
print_event_c_prototype_args(fp); print_event_c_prototype_args(fp);
fprintf(fp, ")"); fprintf(fp, ")");
fprintf(fp, "\n"); fprintf(fp, "\n");
} }
static void print_event_c_body(FILE* fp) static void print_event_c_body(FILE * fp) {
{ fprintf(fp, "\t{\n");
fprintf(fp, "\t{\n"); fprintf(fp, "\t// Note that it is intentional that here we do not\n");
fprintf(fp, "\t// Note that it is intentional that here we do not\n"); fprintf(fp, "\t// check if %s is NULL, which should happen *before*\n", decl.c_fullname.c_str());
fprintf(fp, "\t// check if %s is NULL, which should happen *before*\n", fprintf(fp, "\t// %s is called to avoid unnecessary Val\n", decl.enqueue_c_fullname.c_str());
decl.c_fullname.c_str()); fprintf(fp, "\t// allocation.\n");
fprintf(fp, "\t// %s is called to avoid unnecessary Val\n", fprintf(fp, "\n");
decl.enqueue_c_fullname.c_str());
fprintf(fp, "\t// allocation.\n");
fprintf(fp, "\n");
BuiltinFuncArg* connection_arg = nullptr; BuiltinFuncArg* connection_arg = nullptr;
fprintf(fp, "\tzeek::event_mgr.Enqueue(%s, zeek::Args{\n", decl.c_fullname.c_str()); fprintf(fp, "\tzeek::event_mgr.Enqueue(%s, zeek::Args{\n", decl.c_fullname.c_str());
for ( int i = 0; i < (int) args.size(); ++i ) for ( const auto& arg : args ) {
{ fprintf(fp, "\t ");
fprintf(fp, "\t "); arg->PrintValConstructor(fp);
args[i]->PrintValConstructor(fp); fprintf(fp, ",\n");
fprintf(fp, ",\n");
if ( args[i]->Type() == TYPE_CONNECTION ) if ( arg->Type() == TYPE_CONNECTION ) {
{ if ( connection_arg == nullptr )
if ( connection_arg == nullptr ) connection_arg = arg;
connection_arg = args[i]; else {
else // We are seeing two connection type arguments.
{ yywarn(
// We are seeing two connection type arguments. "Warning: with more than connection-type "
yywarn("Warning: with more than connection-type " "event arguments, bifcl only passes "
"event arguments, bifcl only passes " "the first one to EventMgr as cookie.");
"the first one to EventMgr as cookie."); }
} }
} }
}
fprintf(fp, "\t },\n\t zeek::util::detail::SOURCE_LOCAL, analyzer ? analyzer->GetID() : 0"); fprintf(fp, "\t },\n\t zeek::util::detail::SOURCE_LOCAL, analyzer ? analyzer->GetID() : 0");
if ( connection_arg ) if ( connection_arg )
// Pass the connection to the EventMgr as the "cookie" // Pass the connection to the EventMgr as the "cookie"
fprintf(fp, ", %s", connection_arg->Name()); fprintf(fp, ", %s", connection_arg->Name());
fprintf(fp, ");\n"); fprintf(fp, ");\n");
fprintf(fp, "\t}\n\n"); fprintf(fp, "\t}\n\n");
//fprintf(fp, "%s // end namespace\n", decl.enqueue_c_namespace_end.c_str()); // fprintf(fp, "%s // end namespace\n", decl.enqueue_c_namespace_end.c_str());
} }
void record_bif_item(const char* id, const char* type) void record_bif_item(const char* id, const char* type) {
{ if ( ! plugin )
if ( ! plugin ) return;
return;
fprintf(fp_func_init, "\tplugin->AddBifItem(\"%s\", zeek::plugin::BifItem::%s);\n", id, type); fprintf(fp_func_init, "\tplugin->AddBifItem(\"%s\", zeek::plugin::BifItem::%s);\n", id, type);
} }
%} %}
@ -474,7 +454,7 @@ enum_list: enum_list TOK_ID opt_ws ',' opt_ws
const_def: TOK_CONST opt_ws TOK_ID opt_ws ':' opt_ws TOK_ID opt_ws ';' const_def: TOK_CONST opt_ws TOK_ID opt_ws ':' opt_ws TOK_ID opt_ws ';'
{ {
set_definition_type(CONST_DEF, 0); set_definition_type(CONST_DEF, nullptr);
set_decl_name($3); set_decl_name($3);
int typeidx = get_type_index($7); int typeidx = get_type_index($7);
char accessor[1024]; char accessor[1024];
@ -525,11 +505,11 @@ opt_attr_list:
; ;
func_prefix: TOK_FUNCTION func_prefix: TOK_FUNCTION
{ set_definition_type(FUNC_DEF, 0); } { set_definition_type(FUNC_DEF, nullptr); }
; ;
event_prefix: TOK_EVENT event_prefix: TOK_EVENT
{ set_definition_type(EVENT_DEF, 0); } { set_definition_type(EVENT_DEF, nullptr); }
; ;
end_of_head: /* nothing */ end_of_head: /* nothing */
@ -792,44 +772,41 @@ extern char* input_filename;
extern int line_number; extern int line_number;
void err_exit(void); void err_exit(void);
void print_msg(const char msg[]) void print_msg(const char msg[]) {
{ int msg_len = strlen(msg) + strlen(yytext) + 64;
int msg_len = strlen(msg) + strlen(yytext) + 64; char* msgbuf = new char[msg_len];
char* msgbuf = new char[msg_len];
if ( yytext[0] == '\n' ) if ( yytext[0] == '\n' )
snprintf(msgbuf, msg_len, "%s, on previous line", msg); snprintf(msgbuf, msg_len, "%s, on previous line", msg);
else if ( yytext[0] == '\0' ) else if ( yytext[0] == '\0' )
snprintf(msgbuf, msg_len, "%s, at end of file", msg); snprintf(msgbuf, msg_len, "%s, at end of file", msg);
else else
snprintf(msgbuf, msg_len, "%s, at or near \"%s\"", msg, yytext); snprintf(msgbuf, msg_len, "%s, at or near \"%s\"", msg, yytext);
/* /*
extern int column; extern int column;
sprintf(msgbuf, "%*s\n%*s\n", column, "^", column, msg); sprintf(msgbuf, "%*s\n%*s\n", column, "^", column, msg);
*/ */
if ( input_filename ) if ( input_filename )
fprintf(stderr, "%s:%d: ", input_filename, line_number); fprintf(stderr, "%s:%d: ", input_filename, line_number);
else else
fprintf(stderr, "line %d: ", line_number); fprintf(stderr, "line %d: ", line_number);
fprintf(stderr, "%s\n", msgbuf); fprintf(stderr, "%s\n", msgbuf);
delete [] msgbuf; delete[] msgbuf;
} }
int yywarn(const char msg[]) int yywarn(const char msg[]) {
{ print_msg(msg);
print_msg(msg); return 0;
return 0; }
}
int yyerror(const char msg[]) int yyerror(const char msg[]) {
{ print_msg(msg);
print_msg(msg);
err_exit(); err_exit();
return 0; return 0;
} }

View file

@ -6,6 +6,7 @@
#include <cstdio> #include <cstdio>
enum builtin_func_arg_type : uint8_t { enum builtin_func_arg_type : uint8_t {
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define DEFINE_BIF_TYPE(id, bif_type, bro_type, c_type, c_type_smart, accessor, accessor_smart, cast_smart, \ #define DEFINE_BIF_TYPE(id, bif_type, bro_type, c_type, c_type_smart, accessor, accessor_smart, cast_smart, \
constructor, ctor_smart) \ constructor, ctor_smart) \
id, id,

View file

@ -21,6 +21,7 @@ if (BUILD_STATIC_BINPAC)
target_compile_options(binpac_static PRIVATE "/J") target_compile_options(binpac_static PRIVATE "/J")
endif () endif ()
set(BinPAC_LIBRARY binpac_static CACHE STRING "BinPAC library" FORCE) set(BinPAC_LIBRARY binpac_static CACHE STRING "BinPAC library" FORCE)
zeek_target_add_linters(binpac_static)
else () else ()
add_library(binpac_lib SHARED) add_library(binpac_lib SHARED)
target_sources(binpac_lib PRIVATE ${binpac_lib_SRCS}) target_sources(binpac_lib PRIVATE ${binpac_lib_SRCS})
@ -31,6 +32,7 @@ else ()
endif () endif ()
install(TARGETS binpac_lib DESTINATION ${CMAKE_INSTALL_LIBDIR}) install(TARGETS binpac_lib DESTINATION ${CMAKE_INSTALL_LIBDIR})
set(BinPAC_LIBRARY binpac_lib CACHE STRING "BinPAC library" FORCE) set(BinPAC_LIBRARY binpac_lib CACHE STRING "BinPAC library" FORCE)
zeek_target_add_linters(binpac_lib)
endif () endif ()
if (ZEEK_ROOT_DIR) if (ZEEK_ROOT_DIR)

View file

@ -1,8 +1,8 @@
// See the file "COPYING" in the main distribution directory for copyright. // See the file "COPYING" in the main distribution directory for copyright.
#include <stdio.h> #include <cstdio>
#include <stdlib.h> #include <cstdlib>
#include <string.h> // for memcpy #include <cstring> // for memcpy
#define binpac_regex_h #define binpac_regex_h
@ -82,7 +82,7 @@ void FlowBuffer::ResetLineState() {
case CR_OR_LF: state_ = CR_OR_LF_0; break; case CR_OR_LF: state_ = CR_OR_LF_0; break;
case STRICT_CRLF: state_ = STRICT_CRLF_0; break; case STRICT_CRLF: state_ = STRICT_CRLF_0; break;
case LINE_BREAKER: break; // Nothing to reset case LINE_BREAKER: break; // Nothing to reset
default: BINPAC_ASSERT(0); break; default: BINPAC_ASSERT(false); break;
} }
} }
@ -248,7 +248,7 @@ void FlowBuffer::MarkOrCopyLine() {
case CR_OR_LF: MarkOrCopyLine_CR_OR_LF(); break; case CR_OR_LF: MarkOrCopyLine_CR_OR_LF(); break;
case STRICT_CRLF: MarkOrCopyLine_STRICT_CRLF(); break; case STRICT_CRLF: MarkOrCopyLine_STRICT_CRLF(); break;
case LINE_BREAKER: MarkOrCopyLine_LINEBREAK(); break; case LINE_BREAKER: MarkOrCopyLine_LINEBREAK(); break;
default: BINPAC_ASSERT(0); break; default: BINPAC_ASSERT(false); break;
} }
} }

View file

@ -4,11 +4,11 @@
#include "binpac_bytestring.h" #include "binpac_bytestring.h"
#include <stdlib.h> #include <cstdlib>
namespace binpac { namespace binpac {
std::string std_string(bytestring const* s) { return std::string((const char*)s->begin(), (const char*)s->end()); } std::string std_string(bytestring const* s) { return {(const char*)s->begin(), (const char*)s->end()}; }
int bytestring_to_int(bytestring const* s) { return atoi((const char*)s->begin()); } int bytestring_to_int(bytestring const* s) { return atoi((const char*)s->begin()); }

View file

@ -11,6 +11,18 @@ else ()
set_property(SOURCE pac_scan.cc APPEND_STRING PROPERTY COMPILE_FLAGS "-Wno-sign-compare") set_property(SOURCE pac_scan.cc APPEND_STRING PROPERTY COMPILE_FLAGS "-Wno-sign-compare")
endif () endif ()
set(binpac_bison_generated_files
${CMAKE_CURRENT_BINARY_DIR}/pac_parse.cc ${CMAKE_CURRENT_BINARY_DIR}/pac_parse.h
${CMAKE_CURRENT_BINARY_DIR}/pac_scan.cc)
set_source_files_properties(${binpac_bison_generated_files} PROPERTIES SKIP_LINTING ON)
# pac_main.cc includes up pac_parse.h, and so clang-tidy reports a bunch of warnings from
# that header as part of it. adding NOLINTBEGIN/END around the include didn't resolve it.
# I fixed the findings in pac_main.cc, but am ignoring it from here on to avoid the extra
# noise.
set_source_files_properties(pac_main.cc PROPERTIES SKIP_LINTING ON)
set(binpac_SRCS set(binpac_SRCS
${BISON_PACParser_INPUT} ${BISON_PACParser_INPUT}
${FLEX_PACScanner_INPUT} ${FLEX_PACScanner_INPUT}
@ -55,7 +67,9 @@ set(binpac_SRCS
pac_exception.cc pac_exception.cc
pac_main.cc) pac_main.cc)
add_executable(binpac ${binpac_SRCS}) add_executable(binpac)
target_sources(binpac PRIVATE ${binpac_SRCS})
zeek_target_add_linters(binpac)
target_include_directories(binpac BEFORE PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) target_include_directories(binpac BEFORE PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_include_directories(binpac BEFORE PUBLIC ${CMAKE_CURRENT_BINARY_DIR}) target_include_directories(binpac BEFORE PUBLIC ${CMAKE_CURRENT_BINARY_DIR})

View file

@ -11,7 +11,7 @@
#include "pac_utils.h" #include "pac_utils.h"
AnalyzerAction::AnalyzerAction(ID* action_id, When when, ActionParam* param, EmbeddedCode* code) AnalyzerAction::AnalyzerAction(ID* action_id, When when, ActionParam* param, EmbeddedCode* code)
: AnalyzerElement(ACTION), action_id_(action_id), when_(when), param_(param), code_(code), analyzer_(nullptr) {} : AnalyzerElement(ACTION), action_id_(action_id), when_(when), param_(param), code_(code) {}
AnalyzerAction::~AnalyzerAction() { AnalyzerAction::~AnalyzerAction() {
delete action_id_; delete action_id_;

View file

@ -3,6 +3,8 @@
#ifndef pac_action_h #ifndef pac_action_h
#define pac_action_h #define pac_action_h
#include <cstdint>
// Classes representing analyzer actions. // Classes representing analyzer actions.
#include "pac_analyzer.h" #include "pac_analyzer.h"
@ -10,7 +12,7 @@
class AnalyzerAction : public AnalyzerElement { class AnalyzerAction : public AnalyzerElement {
public: public:
enum When { BEFORE, AFTER }; enum When : uint8_t { BEFORE, AFTER };
AnalyzerAction(ID* action_id, When when, ActionParam* param, EmbeddedCode* code); AnalyzerAction(ID* action_id, When when, ActionParam* param, EmbeddedCode* code);
@ -35,7 +37,7 @@ private:
When when_; When when_;
ActionParam* param_; ActionParam* param_;
EmbeddedCode* code_; EmbeddedCode* code_;
AnalyzerDecl* analyzer_; AnalyzerDecl* analyzer_ = nullptr;
}; };
class ActionParam { class ActionParam {
@ -56,7 +58,7 @@ private:
class ActionParamType { class ActionParamType {
public: public:
ActionParamType(const ID* type_id, const ID* field_id = 0) : type_id_(type_id), field_id_(field_id) {} ActionParamType(const ID* type_id, const ID* field_id = nullptr) : type_id_(type_id), field_id_(field_id) {}
const ID* type_id() const { return type_id_; } const ID* type_id() const { return type_id_; }
const ID* field_id() const { return field_id_; } const ID* field_id() const { return field_id_; }

View file

@ -34,14 +34,14 @@ AnalyzerDecl::AnalyzerDecl(ID* id, DeclType decl_type, ParamList* params) : Type
} }
AnalyzerDecl::~AnalyzerDecl() { AnalyzerDecl::~AnalyzerDecl() {
delete_list(StateVarList, statevars_); delete_list(statevars_);
delete_list(AnalyzerActionList, actions_); delete_list(actions_);
delete_list(AnalyzerHelperList, helpers_); delete_list(helpers_);
delete_list(FunctionList, functions_); delete_list(functions_);
delete_list(ParamList, params_); delete_list(params_);
delete_list(AnalyzerHelperList, constructor_helpers_); delete_list(constructor_helpers_);
delete_list(AnalyzerHelperList, destructor_helpers_); delete_list(destructor_helpers_);
delete_list(AnalyzerHelperList, eof_helpers_); delete_list(eof_helpers_);
} }
void AnalyzerDecl::AddElements(AnalyzerElementList* elemlist) { void AnalyzerDecl::AddElements(AnalyzerElementList* elemlist) {

View file

@ -3,6 +3,8 @@
#ifndef pac_analyzer_h #ifndef pac_analyzer_h
#define pac_analyzer_h #define pac_analyzer_h
#include <cstdint>
#include "pac_common.h" #include "pac_common.h"
#include "pac_field.h" #include "pac_field.h"
#include "pac_typedecl.h" #include "pac_typedecl.h"
@ -16,8 +18,8 @@ class AnalyzerDataUnit;
class AnalyzerFunction; class AnalyzerFunction;
class ConnDecl; class ConnDecl;
class FlowDecl; class FlowDecl;
typedef vector<AnalyzerHelper*> AnalyzerHelperList; using AnalyzerHelperList = vector<AnalyzerHelper*>;
typedef vector<Function*> FunctionList; using FunctionList = vector<Function*>;
class AnalyzerDecl : public TypeDecl { class AnalyzerDecl : public TypeDecl {
public: public:
@ -84,7 +86,7 @@ protected:
class AnalyzerElement : public Object { class AnalyzerElement : public Object {
public: public:
enum ElementType { STATE, ACTION, FUNCTION, HELPER, FLOW, DATAUNIT }; enum ElementType : uint8_t { STATE, ACTION, FUNCTION, HELPER, FLOW, DATAUNIT };
AnalyzerElement(ElementType type) : type_(type) {} AnalyzerElement(ElementType type) : type_(type) {}
virtual ~AnalyzerElement() {} virtual ~AnalyzerElement() {}
@ -109,7 +111,7 @@ private:
// A collection of embedded C++ code // A collection of embedded C++ code
class AnalyzerHelper : public AnalyzerElement { class AnalyzerHelper : public AnalyzerElement {
public: public:
enum Type { enum Type : uint8_t {
MEMBER_DECLS, MEMBER_DECLS,
INIT_CODE, INIT_CODE,
CLEANUP_CODE, CLEANUP_CODE,
@ -140,7 +142,7 @@ public:
class AnalyzerFlow : public AnalyzerElement { class AnalyzerFlow : public AnalyzerElement {
public: public:
enum Direction { UP, DOWN }; enum Direction : uint8_t { UP, DOWN };
AnalyzerFlow(Direction dir, ID* type_id, ExprList* params); AnalyzerFlow(Direction dir, ID* type_id, ExprList* params);
~AnalyzerFlow() override; ~AnalyzerFlow() override;

View file

@ -3,10 +3,12 @@
#ifndef pac_attr_h #ifndef pac_attr_h
#define pac_attr_h #define pac_attr_h
#include <cstdint>
#include "pac_common.h" #include "pac_common.h"
#include "pac_datadep.h" #include "pac_datadep.h"
enum AttrType { enum AttrType : uint8_t {
ATTR_BYTEORDER, ATTR_BYTEORDER,
ATTR_CHECK, ATTR_CHECK,
ATTR_CHUNKED, ATTR_CHUNKED,

View file

@ -19,6 +19,7 @@ bool BuiltInType::CompatibleBuiltInTypes(BuiltInType* type1, BuiltInType* type2)
} }
static const char* basic_pactype_name[] = { static const char* basic_pactype_name[] = {
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define TYPE_DEF(name, pactype, ctype, size) pactype, #define TYPE_DEF(name, pactype, ctype, size) pactype,
#include "pac_type.def" #include "pac_type.def"
#undef TYPE_DEF #undef TYPE_DEF
@ -40,6 +41,7 @@ int BuiltInType::LookUpByName(const char* name) {
} }
static const char* basic_ctype_name[] = { static const char* basic_ctype_name[] = {
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define TYPE_DEF(name, pactype, ctype, size) ctype, #define TYPE_DEF(name, pactype, ctype, size) ctype,
#include "pac_type.def" #include "pac_type.def"
#undef TYPE_DEF #undef TYPE_DEF
@ -52,6 +54,7 @@ string BuiltInType::DataTypeStr() const { return basic_ctype_name[bit_type_]; }
int BuiltInType::StaticSize(Env* /* env */) const { int BuiltInType::StaticSize(Env* /* env */) const {
static const size_t basic_type_size[] = { static const size_t basic_type_size[] = {
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define TYPE_DEF(name, pactype, ctype, size) size, #define TYPE_DEF(name, pactype, ctype, size) size,
#include "pac_type.def" #include "pac_type.def"
#undef TYPE_DEF #undef TYPE_DEF

View file

@ -3,11 +3,14 @@
#ifndef pac_btype_h #ifndef pac_btype_h
#define pac_btype_h #define pac_btype_h
#include <cstdint>
#include "pac_type.h" #include "pac_type.h"
class BuiltInType : public Type { class BuiltInType : public Type {
public: public:
enum BITType { enum BITType : uint8_t {
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define TYPE_DEF(name, pactype, ctype, size) name, #define TYPE_DEF(name, pactype, ctype, size) name,
#include "pac_type.def" #include "pac_type.def"
#undef TYPE_DEF #undef TYPE_DEF
@ -29,7 +32,7 @@ public:
bool IsPointerType() const override { return false; } bool IsPointerType() const override { return false; }
bool ByteOrderSensitive() const override { return StaticSize(0) >= 2; } bool ByteOrderSensitive() const override { return StaticSize(nullptr) >= 2; }
void GenInitCode(Output* out_cc, Env* env) override; void GenInitCode(Output* out_cc, Env* env) override;

View file

@ -2,7 +2,7 @@
#include "pac_case.h" #include "pac_case.h"
#include <stdint.h> #include <cstdint>
#include <limits> #include <limits>
#include "pac_btype.h" #include "pac_btype.h"
@ -219,7 +219,7 @@ CaseField::CaseField(ExprList* index, ID* id, Type* type)
index_var_ = nullptr; index_var_ = nullptr;
} }
CaseField::~CaseField() { delete_list(ExprList, index_); } CaseField::~CaseField() { delete_list(index_); }
void GenCaseStr(ExprList* index_list, Output* out_cc, Env* env, Type* switch_type) { void GenCaseStr(ExprList* index_list, Output* out_cc, Env* env, Type* switch_type) {
if ( index_list ) { if ( index_list ) {

View file

@ -49,7 +49,7 @@ protected:
ID* index_var_; ID* index_var_;
CaseFieldList* cases_; CaseFieldList* cases_;
typedef map<const ID*, CaseField*, ID_ptr_cmp> member_map_t; using member_map_t = map<const ID*, CaseField*, ID_ptr_cmp>;
member_map_t member_map_; member_map_t member_map_;
}; };

View file

@ -3,9 +3,9 @@
#ifndef pac_common_h #ifndef pac_common_h
#define pac_common_h #define pac_common_h
#include <ctype.h> #include <cctype>
#include <stdlib.h> #include <cstdlib>
#include <string.h> #include <cstring>
#include <vector> #include <vector>
#include "pac_utils.h" #include "pac_utils.h"
@ -87,47 +87,49 @@ class WithInputField;
// The ID of the current declaration. // The ID of the current declaration.
extern const ID* current_decl_id; extern const ID* current_decl_id;
typedef vector<ActionParam*> ActionParamList; using ActionParamList = vector<ActionParam*>;
typedef vector<AnalyzerAction*> AnalyzerActionList; using AnalyzerActionList = vector<AnalyzerAction*>;
typedef vector<AnalyzerElement*> AnalyzerElementList; using AnalyzerElementList = vector<AnalyzerElement*>;
typedef vector<Attr*> AttrList; using AttrList = vector<Attr*>;
typedef vector<CaseExpr*> CaseExprList; using CaseExprList = vector<CaseExpr*>;
typedef vector<CaseField*> CaseFieldList; using CaseFieldList = vector<CaseField*>;
typedef vector<ContextField*> ContextFieldList; using ContextFieldList = vector<ContextField*>;
typedef vector<Decl*> DeclList; using DeclList = vector<Decl*>;
typedef vector<Enum*> EnumList; using EnumList = vector<Enum*>;
typedef vector<Expr*> ExprList; using ExprList = vector<Expr*>;
typedef vector<Field*> FieldList; using FieldList = vector<Field*>;
typedef vector<LetField*> LetFieldList; using LetFieldList = vector<LetField*>;
typedef vector<Number*> NumList; using NumList = vector<Number*>;
typedef vector<Param*> ParamList; using ParamList = vector<Param*>;
typedef vector<RecordField*> RecordFieldList; using RecordFieldList = vector<RecordField*>;
typedef vector<StateVar*> StateVarList; using StateVarList = vector<StateVar*>;
// NOLINTBEGIN(cppcoreguidelines-macro-usage,modernize-loop-convert)
#define foreach(i, ct, pc) \ #define foreach(i, ct, pc) \
if ( pc ) \ if ( pc ) \
for ( ct::iterator i = (pc)->begin(); i != (pc)->end(); ++i ) for ( ct::iterator i = (pc)->begin(); (i) != (pc)->end(); ++(i) )
// NOLINTEND(cppcoreguidelines-macro-usage,modernize-loop-convert)
#define delete_list(ct, pc) \ template<typename T>
{ \ constexpr void delete_list(T* container) {
foreach (delete_list_i, ct, pc) \ for ( auto& i : *container )
delete *delete_list_i; \ delete i;
delete pc; \
pc = 0; \ delete container;
} }
// Constants // Constants
const char* const kComputeFrameLength = "compute_frame_length"; constexpr char kComputeFrameLength[] = "compute_frame_length";
const char* const kFlowBufferClass = "FlowBuffer"; constexpr char kFlowBufferClass[] = "FlowBuffer";
const char* const kFlowBufferVar = "flow_buffer"; constexpr char kFlowBufferVar[] = "flow_buffer";
const char* const kFlowEOF = "FlowEOF"; constexpr char kFlowEOF[] = "FlowEOF";
const char* const kFlowGap = "NewGap"; constexpr char kFlowGap[] = "NewGap";
const char* const kInitialBufferLengthFunc = "initial_buffer_length"; constexpr char kInitialBufferLengthFunc[] = "initial_buffer_length";
const char* const kNeedMoreData = "need_more_data"; constexpr char kNeedMoreData[] = "need_more_data";
const char* const kNewData = "NewData"; constexpr char kNewData[] = "NewData";
const char* const kParseFuncWithBuffer = "ParseBuffer"; constexpr char kParseFuncWithBuffer[] = "ParseBuffer";
const char* const kParseFuncWithoutBuffer = "Parse"; constexpr char kParseFuncWithoutBuffer[] = "Parse";
const char* const kRefCountClass = "binpac::RefCount"; constexpr char kRefCountClass[] = "binpac::RefCount";
const char* const kTypeWithLengthClass = "binpac::TypeWithLength"; constexpr char kTypeWithLengthClass[] = "binpac::TypeWithLength";
#endif // pac_common_h #endif // pac_common_h

View file

@ -26,7 +26,7 @@ ConnDecl::~ConnDecl() {
} }
void ConnDecl::AddBaseClass(vector<string>* base_classes) const { void ConnDecl::AddBaseClass(vector<string>* base_classes) const {
base_classes->push_back("binpac::ConnectionAnalyzer"); base_classes->emplace_back("binpac::ConnectionAnalyzer");
} }
void ConnDecl::ProcessFlowElement(AnalyzerFlow* flow_elem) { void ConnDecl::ProcessFlowElement(AnalyzerFlow* flow_elem) {

View file

@ -53,7 +53,7 @@ AnalyzerContextDecl::AnalyzerContextDecl(ID* id, ContextFieldList* context_field
AnalyzerContextDecl::~AnalyzerContextDecl() { AnalyzerContextDecl::~AnalyzerContextDecl() {
delete context_name_id_; delete context_name_id_;
delete param_type_; delete param_type_;
delete_list(ContextFieldList, context_fields_); delete_list(context_fields_);
} }
void AnalyzerContextDecl::GenForwardDeclaration(Output* out_h) { void AnalyzerContextDecl::GenForwardDeclaration(Output* out_h) {

View file

@ -77,7 +77,7 @@ int expand_escape(const char*& s) {
} // namespace } // namespace
ConstString::ConstString(const string& s) : str_(s) { ConstString::ConstString(string s) : str_(std::move(s)) {
// Copied from scan.l of Zeek // Copied from scan.l of Zeek
try { try {
const char* text = str_.c_str(); const char* text = str_.c_str();

View file

@ -7,7 +7,7 @@
class ConstString : public Object { class ConstString : public Object {
public: public:
ConstString(const string& s); ConstString(string s);
// The string in its escaped form, with surrounding '"'s // The string in its escaped form, with surrounding '"'s
const string& str() const { return str_; } const string& str() const { return str_; }

View file

@ -6,7 +6,7 @@
#include "pac_id.h" #include "pac_id.h"
#include "pac_type.h" #include "pac_type.h"
DataDepElement::DataDepElement(DDE_Type type) : dde_type_(type), in_traversal(false) {} DataDepElement::DataDepElement(DDE_Type type) : dde_type_(type) {}
bool DataDepElement::Traverse(DataDepVisitor* visitor) { bool DataDepElement::Traverse(DataDepVisitor* visitor) {
// Avoid infinite loop // Avoid infinite loop

View file

@ -3,17 +3,18 @@
#ifndef pac_datadep_h #ifndef pac_datadep_h
#define pac_datadep_h #define pac_datadep_h
#include <cstdint>
// To provide a way to traverse through the data dependency graph. // To provide a way to traverse through the data dependency graph.
// That is, to evaluate X, what must be evaluated. // That is, to evaluate X, what must be evaluated.
#include "pac_common.h" #include "pac_common.h"
#include "pac_dbg.h"
class DataDepVisitor; class DataDepVisitor;
class DataDepElement { class DataDepElement {
public: public:
enum DDE_Type { enum DDE_Type : uint8_t {
ATTR, ATTR,
CASEEXPR, CASEEXPR,
EXPR, EXPR,
@ -38,7 +39,7 @@ public:
protected: protected:
DDE_Type dde_type_; DDE_Type dde_type_;
bool in_traversal; bool in_traversal = false;
}; };
class DataDepVisitor { class DataDepVisitor {
@ -51,8 +52,6 @@ public:
class RequiresAnalyzerContext : public DataDepVisitor { class RequiresAnalyzerContext : public DataDepVisitor {
public: public:
RequiresAnalyzerContext() : requires_analyzer_context_(false) {}
// Returns whether to continue traversal // Returns whether to continue traversal
bool PreProcess(DataDepElement* element) override; bool PreProcess(DataDepElement* element) override;
bool PostProcess(DataDepElement* element) override; bool PostProcess(DataDepElement* element) override;
@ -64,7 +63,7 @@ public:
protected: protected:
void ProcessExpr(Expr* expr); void ProcessExpr(Expr* expr);
bool requires_analyzer_context_; bool requires_analyzer_context_ = false;
}; };
#endif // pac_datadep_h #endif // pac_datadep_h

View file

@ -17,6 +17,9 @@ public:
DataPtr(DataPtr const& x) { *this = x; } DataPtr(DataPtr const& x) { *this = x; }
DataPtr const& operator=(DataPtr const& x) { DataPtr const& operator=(DataPtr const& x) {
if ( this == &x )
return *this;
id_ = x.id(); id_ = x.id();
offset_ = x.offset(); offset_ = x.offset();
ptr_expr_ = x.ptr_expr(); ptr_expr_ = x.ptr_expr();

View file

@ -3,6 +3,8 @@
#ifndef pac_dataunit_h #ifndef pac_dataunit_h
#define pac_dataunit_h #define pac_dataunit_h
#include <cstdint>
#include "pac_analyzer.h" #include "pac_analyzer.h"
// The type and parameters of input data unit of a flow. For instance, the // The type and parameters of input data unit of a flow. For instance, the
@ -10,7 +12,7 @@
class AnalyzerDataUnit : public AnalyzerElement { class AnalyzerDataUnit : public AnalyzerElement {
public: public:
enum DataUnitType { DATAGRAM, FLOWUNIT }; enum DataUnitType : uint8_t { DATAGRAM, FLOWUNIT };
AnalyzerDataUnit(DataUnitType type, ID* id, ExprList* type_params, ExprList* context_params); AnalyzerDataUnit(DataUnitType type, ID* id, ExprList* type_params, ExprList* context_params);
~AnalyzerDataUnit() override; ~AnalyzerDataUnit() override;

View file

@ -8,7 +8,8 @@
extern bool FLAGS_pac_debug; extern bool FLAGS_pac_debug;
#define ASSERT(x) assert(x) constexpr void ASSERT(bool flag) { assert(flag); }
constexpr void ASSERT(int flag) { assert(flag); }
#define DEBUG_MSG(...) \ #define DEBUG_MSG(...) \
if ( FLAGS_pac_debug ) \ if ( FLAGS_pac_debug ) \
fprintf(stderr, __VA_ARGS__) fprintf(stderr, __VA_ARGS__)

View file

@ -19,20 +19,18 @@
DeclList* Decl::decl_list_ = nullptr; DeclList* Decl::decl_list_ = nullptr;
Decl::DeclMap Decl::decl_map_; Decl::DeclMap Decl::decl_map_;
Decl::Decl(ID* id, DeclType decl_type) : id_(id), decl_type_(decl_type), attrlist_(nullptr) { Decl::Decl(ID* id, DeclType decl_type) : id_(id), decl_type_(decl_type) {
decl_map_[id_] = this; decl_map_[id_] = this;
if ( ! decl_list_ ) if ( ! decl_list_ )
decl_list_ = new DeclList(); decl_list_ = new DeclList();
decl_list_->push_back(this); decl_list_->push_back(this);
DEBUG_MSG("Finished Decl %s\n", id_->Name()); DEBUG_MSG("Finished Decl %s\n", id_->Name());
analyzer_context_ = nullptr;
} }
Decl::~Decl() { Decl::~Decl() {
delete id_; delete id_;
delete_list(AttrList, attrlist_); delete_list(attrlist_);
} }
void Decl::AddAttrs(AttrList* attrs) { void Decl::AddAttrs(AttrList* attrs) {

View file

@ -3,6 +3,8 @@
#ifndef pac_decl_h #ifndef pac_decl_h
#define pac_decl_h #define pac_decl_h
#include <cstdint>
#include "pac_common.h" #include "pac_common.h"
#include "pac_id.h" #include "pac_id.h"
@ -10,7 +12,7 @@ class Decl : public Object {
public: public:
// Note: ANALYZER is not for AnalyzerDecl (which is an // Note: ANALYZER is not for AnalyzerDecl (which is an
// abstract class) , but for AnalyzerContextDecl. // abstract class) , but for AnalyzerContextDecl.
enum DeclType { ENUM, LET, TYPE, FUNC, CONN, FLOW, ANALYZER, HELPER, REGEX }; enum DeclType : uint8_t { ENUM, LET, TYPE, FUNC, CONN, FLOW, ANALYZER, HELPER, REGEX };
Decl(ID* id, DeclType decl_type); Decl(ID* id, DeclType decl_type);
virtual ~Decl(); virtual ~Decl();
@ -41,8 +43,8 @@ protected:
ID* id_; ID* id_;
DeclType decl_type_; DeclType decl_type_;
AttrList* attrlist_; AttrList* attrlist_ = nullptr;
AnalyzerContextDecl* analyzer_context_; AnalyzerContextDecl* analyzer_context_ = nullptr;
public: public:
static void ProcessDecls(Output* out_h, Output* out_cc); static void ProcessDecls(Output* out_h, Output* out_cc);
@ -50,13 +52,13 @@ public:
private: private:
static DeclList* decl_list_; static DeclList* decl_list_;
typedef map<const ID*, Decl*, ID_ptr_cmp> DeclMap; using DeclMap = map<const ID*, Decl*, ID_ptr_cmp>;
static DeclMap decl_map_; static DeclMap decl_map_;
}; };
class HelperDecl : public Decl { class HelperDecl : public Decl {
public: public:
enum HelperType { enum HelperType : uint8_t {
HEADER, HEADER,
CODE, CODE,
EXTERN, EXTERN,

View file

@ -6,7 +6,7 @@
#include "pac_output.h" #include "pac_output.h"
#include "pac_primitive.h" #include "pac_primitive.h"
EmbeddedCodeSegment::EmbeddedCodeSegment(const string& s) : s_(s), primitive_(nullptr) {} EmbeddedCodeSegment::EmbeddedCodeSegment(string s) : s_(std::move(s)), primitive_(nullptr) {}
EmbeddedCodeSegment::EmbeddedCodeSegment(PacPrimitive* primitive) : s_(""), primitive_(primitive) {} EmbeddedCodeSegment::EmbeddedCodeSegment(PacPrimitive* primitive) : s_(""), primitive_(primitive) {}
@ -20,7 +20,7 @@ string EmbeddedCodeSegment::ToCode(Env* env) {
EmbeddedCode::EmbeddedCode() { segments_ = new EmbeddedCodeSegmentList(); } EmbeddedCode::EmbeddedCode() { segments_ = new EmbeddedCodeSegmentList(); }
EmbeddedCode::~EmbeddedCode() { delete_list(EmbeddedCodeSegmentList, segments_); } EmbeddedCode::~EmbeddedCode() { delete_list(segments_); }
void EmbeddedCode::Append(int atom) { current_segment_ += static_cast<char>(atom); } void EmbeddedCode::Append(int atom) { current_segment_ += static_cast<char>(atom); }

View file

@ -7,7 +7,7 @@
class EmbeddedCodeSegment { class EmbeddedCodeSegment {
public: public:
explicit EmbeddedCodeSegment(const string& s); explicit EmbeddedCodeSegment(string s);
explicit EmbeddedCodeSegment(PacPrimitive* primitive); explicit EmbeddedCodeSegment(PacPrimitive* primitive);
~EmbeddedCodeSegment(); ~EmbeddedCodeSegment();
@ -18,7 +18,7 @@ private:
PacPrimitive* primitive_; PacPrimitive* primitive_;
}; };
typedef vector<EmbeddedCodeSegment*> EmbeddedCodeSegmentList; using EmbeddedCodeSegmentList = vector<EmbeddedCodeSegment*>;
class EmbeddedCode : public Object { class EmbeddedCode : public Object {
public: public:

View file

@ -34,7 +34,7 @@ EnumDecl::EnumDecl(ID* id, EnumList* enumlist) : Decl(id, ENUM), enumlist_(enuml
} }
EnumDecl::~EnumDecl() { EnumDecl::~EnumDecl() {
delete_list(EnumList, enumlist_); delete_list(enumlist_);
delete extern_typedecl_; delete extern_typedecl_;
} }

View file

@ -7,7 +7,7 @@
class Enum { class Enum {
public: public:
Enum(ID* id, Expr* expr = 0); Enum(ID* id, Expr* expr = nullptr);
~Enum(); ~Enum();
void GenHeader(Output* out_h, int* pval); void GenHeader(Output* out_h, int* pval);

View file

@ -45,6 +45,7 @@ string EvalExprList(ExprList* exprlist, Output* out, Env* env) {
} }
static const char* expr_fmt[] = { static const char* expr_fmt[] = {
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define EXPR_DEF(type, num_op, fmt) fmt, #define EXPR_DEF(type, num_op, fmt) fmt,
#include "pac_expr.def" #include "pac_expr.def"
#undef EXPR_DEF #undef EXPR_DEF
@ -155,8 +156,8 @@ Expr::~Expr() {
delete operand_[0]; delete operand_[0];
delete operand_[1]; delete operand_[1];
delete operand_[2]; delete operand_[2];
delete_list(ExprList, args_); delete_list(args_);
delete_list(CaseExprList, cases_); delete_list(cases_);
} }
void Expr::AddCaseExpr(CaseExpr* case_expr) { void Expr::AddCaseExpr(CaseExpr* case_expr) {
@ -311,11 +312,11 @@ void Expr::GenEval(Output* out_cc, Env* env) {
Type* ty; Type* ty;
try { try {
if ( (rf = GetRecordField(id, env)) != nullptr ) { if ( rf = GetRecordField(id, env); rf != nullptr ) {
str_ = strfmt("%s", rf->FieldSize(out_cc, env)); str_ = strfmt("%s", rf->FieldSize(out_cc, env));
} }
} catch ( ExceptionIDNotFound& e ) { } catch ( ExceptionIDNotFound& e ) {
if ( (ty = TypeDecl::LookUpType(id)) != nullptr ) { if ( ty = TypeDecl::LookUpType(id); ty != nullptr ) {
int ty_size = ty->StaticSize(global_env()); int ty_size = ty->StaticSize(global_env());
if ( ty_size >= 0 ) if ( ty_size >= 0 )
str_ = strfmt("%d", ty_size); str_ = strfmt("%d", ty_size);
@ -339,9 +340,9 @@ void Expr::GenEval(Output* out_cc, Env* env) {
default: default:
// Evaluate every operand by default // Evaluate every operand by default
for ( int i = 0; i < 3; ++i ) for ( auto& op : operand_ )
if ( operand_[i] ) if ( op )
operand_[i]->GenEval(out_cc, env); op->GenEval(out_cc, env);
GenStrFromFormat(env); GenStrFromFormat(env);
break; break;
} }
@ -373,9 +374,9 @@ void Expr::ForceIDEval(Output* out_cc, Env* env) {
default: default:
// Evaluate every operand by default // Evaluate every operand by default
for ( int i = 0; i < 3; ++i ) for ( auto& op : operand_ )
if ( operand_[i] ) if ( op )
operand_[i]->ForceIDEval(out_cc, env); op->ForceIDEval(out_cc, env);
break; break;
} }
} }
@ -670,14 +671,14 @@ int Expr::MinimalHeaderSize(Env* env) {
RecordField* rf; RecordField* rf;
Type* ty; Type* ty;
if ( (rf = GetRecordField(id, env)) != nullptr ) { if ( rf = GetRecordField(id, env); rf != nullptr ) {
if ( rf->StaticSize(env, -1) >= 0 ) if ( rf->StaticSize(env, -1) >= 0 )
mhs = 0; mhs = 0;
else else
mhs = mhs_recordfield(env, rf); mhs = mhs_recordfield(env, rf);
} }
else if ( (ty = TypeDecl::LookUpType(id)) != nullptr ) { else if ( ty = TypeDecl::LookUpType(id); ty != nullptr ) {
mhs = 0; mhs = 0;
} }
@ -703,25 +704,24 @@ int Expr::MinimalHeaderSize(Env* env) {
case EXPR_CALLARGS: { case EXPR_CALLARGS: {
mhs = 0; mhs = 0;
if ( args_ ) if ( args_ )
for ( unsigned int i = 0; i < args_->size(); ++i ) for ( const auto& arg : *args_ )
mhs = mhs_max(mhs, (*args_)[i]->MinimalHeaderSize(env)); mhs = mhs_max(mhs, arg->MinimalHeaderSize(env));
} break; } break;
case EXPR_CASE: { case EXPR_CASE: {
mhs = operand_[0]->MinimalHeaderSize(env); mhs = operand_[0]->MinimalHeaderSize(env);
for ( unsigned int i = 0; i < cases_->size(); ++i ) { for ( const auto& ce : *cases_ ) {
CaseExpr* ce = (*cases_)[i];
if ( ce->index() ) if ( ce->index() )
for ( unsigned int j = 0; j < ce->index()->size(); ++j ) for ( const auto& idx : *(ce->index()) )
mhs = mhs_max(mhs, (*ce->index())[j]->MinimalHeaderSize(env)); mhs = mhs_max(mhs, idx->MinimalHeaderSize(env));
mhs = mhs_max(mhs, ce->value()->MinimalHeaderSize(env)); mhs = mhs_max(mhs, ce->value()->MinimalHeaderSize(env));
} }
} break; } break;
default: default:
// Evaluate every operand by default // Evaluate every operand by default
mhs = 0; mhs = 0;
for ( int i = 0; i < 3; ++i ) for ( auto& op : operand_ )
if ( operand_[i] ) if ( op )
mhs = mhs_max(mhs, operand_[i]->MinimalHeaderSize(env)); mhs = mhs_max(mhs, op->MinimalHeaderSize(env));
break; break;
} }
@ -750,8 +750,8 @@ bool Expr::HasReference(const ID* id) const {
default: default:
// Evaluate every operand by default // Evaluate every operand by default
for ( int i = 0; i < 3; ++i ) { for ( auto& op : operand_ ) {
if ( operand_[i] && operand_[i]->HasReference(id) ) { if ( op && op->HasReference(id) ) {
return true; return true;
} }
} }
@ -788,8 +788,8 @@ bool Expr::DoTraverse(DataDepVisitor* visitor) {
default: default:
// Evaluate every operand by default // Evaluate every operand by default
for ( int i = 0; i < 3; ++i ) { for ( auto& op : operand_ ) {
if ( operand_[i] && ! operand_[i]->Traverse(visitor) ) { if ( op && ! op->Traverse(visitor) ) {
return false; return false;
} }
} }
@ -828,9 +828,9 @@ bool Expr::RequiresAnalyzerContext() const {
default: default:
// Evaluate every operand by default // Evaluate every operand by default
for ( int i = 0; i < 3; ++i ) for ( auto& op : operand_ )
if ( operand_[i] && operand_[i]->RequiresAnalyzerContext() ) { if ( op && op->RequiresAnalyzerContext() ) {
DEBUG_MSG("'%s' requires analyzer context\n", operand_[i]->orig()); DEBUG_MSG("'%s' requires analyzer context\n", op->orig());
return true; return true;
} }
return false; return false;
@ -841,7 +841,8 @@ CaseExpr::CaseExpr(ExprList* index, Expr* value)
: DataDepElement(DataDepElement::CASEEXPR), index_(index), value_(value) {} : DataDepElement(DataDepElement::CASEEXPR), index_(index), value_(value) {}
CaseExpr::~CaseExpr() { CaseExpr::~CaseExpr() {
delete_list(ExprList, index_); delete_list(index_);
index_ = nullptr;
delete value_; delete value_;
} }

View file

@ -13,6 +13,7 @@ class CaseExpr;
class Expr : public Object, public DataDepElement { class Expr : public Object, public DataDepElement {
public: public:
enum ExprType : uint8_t { enum ExprType : uint8_t {
// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
#define EXPR_DEF(type, x, y) type, #define EXPR_DEF(type, x, y) type,
#include "pac_expr.def" #include "pac_expr.def"
#undef EXPR_DEF #undef EXPR_DEF

View file

@ -3,6 +3,8 @@
#ifndef pac_exttype_h #ifndef pac_exttype_h
#define pac_exttype_h #define pac_exttype_h
#include <cstdint>
#include "pac_type.h" #include "pac_type.h"
// ExternType represent external C++ types that are not defined in // ExternType represent external C++ types that are not defined in
@ -12,7 +14,7 @@
class ExternType : public Type { class ExternType : public Type {
public: public:
enum EXTType { PLAIN, NUMBER, POINTER, BOOLEAN }; enum EXTType : uint8_t { PLAIN, NUMBER, POINTER, BOOLEAN };
ExternType(const ID* id, EXTType ext_type) : Type(EXTERN), id_(id), ext_type_(ext_type) {} ExternType(const ID* id, EXTType ext_type) : Type(EXTERN), id_(id), ext_type_(ext_type) {}
bool DefineValueVar() const override; bool DefineValueVar() const override;

View file

@ -18,7 +18,7 @@ Field::Field(FieldType tof, int flags, ID* id, Type* type)
Field::~Field() { Field::~Field() {
delete id_; delete id_;
delete type_; delete type_;
delete_list(AttrList, attrs_); delete_list(attrs_);
} }
void Field::AddAttr(AttrList* attrs) { void Field::AddAttr(AttrList* attrs) {

View file

@ -3,12 +3,14 @@
#ifndef pac_field_h #ifndef pac_field_h
#define pac_field_h #define pac_field_h
#include <cstdint>
#include "pac_common.h" #include "pac_common.h"
#include "pac_datadep.h" #include "pac_datadep.h"
// A "field" is a member of class. // A "field" is a member of class.
enum FieldType { enum FieldType : uint8_t {
CASE_FIELD, CASE_FIELD,
CONTEXT_FIELD, CONTEXT_FIELD,
FLOW_FIELD, FLOW_FIELD,

View file

@ -38,7 +38,7 @@ ParameterizedType* FlowDecl::flow_buffer_type() {
return flow_buffer_type_; return flow_buffer_type_;
} }
void FlowDecl::AddBaseClass(vector<string>* base_classes) const { base_classes->push_back("binpac::FlowAnalyzer"); } void FlowDecl::AddBaseClass(vector<string>* base_classes) const { base_classes->emplace_back("binpac::FlowAnalyzer"); }
void FlowDecl::ProcessFlowElement(AnalyzerFlow* flow_elem) { void FlowDecl::ProcessFlowElement(AnalyzerFlow* flow_elem) {
throw Exception(flow_elem, "flow should be defined in only a connection declaration"); throw Exception(flow_elem, "flow should be defined in only a connection declaration");

View file

@ -8,16 +8,12 @@
#include "pac_param.h" #include "pac_param.h"
#include "pac_type.h" #include "pac_type.h"
Function::Function(ID* id, Type* type, ParamList* params) Function::Function(ID* id, Type* type, ParamList* params) : id_(id), type_(type), params_(params) {}
: id_(id), type_(type), params_(params), expr_(nullptr), code_(nullptr) {
analyzer_decl_ = nullptr;
env_ = nullptr;
}
Function::~Function() { Function::~Function() {
delete id_; delete id_;
delete type_; delete type_;
delete_list(ParamList, params_); delete_list(params_);
delete env_; delete env_;
delete expr_; delete expr_;
delete code_; delete code_;

View file

@ -27,16 +27,16 @@ public:
void GenCode(Output* out_h, Output* out_cc); void GenCode(Output* out_h, Output* out_cc);
private: private:
Env* env_; Env* env_ = nullptr;
ID* id_; ID* id_;
Type* type_; Type* type_;
ParamList* params_; ParamList* params_;
AnalyzerDecl* analyzer_decl_; AnalyzerDecl* analyzer_decl_ = nullptr;
Expr* expr_; Expr* expr_ = nullptr;
EmbeddedCode* code_; EmbeddedCode* code_ = nullptr;
}; };
class FuncDecl : public Decl { class FuncDecl : public Decl {

View file

@ -168,9 +168,9 @@ Env::Env(Env* parent_env, Object* context_object) : parent(parent_env), context_
} }
Env::~Env() { Env::~Env() {
for ( id_map_t::iterator it = id_map.begin(); it != id_map.end(); ++it ) { for ( auto& id : id_map ) {
delete it->second; delete id.second;
it->second = 0; id.second = nullptr;
} }
} }
@ -365,8 +365,8 @@ Env* global_env() {
the_global_env->AddConstID(null_id, 0, extern_type_nullptr); the_global_env->AddConstID(null_id, 0, extern_type_nullptr);
#if 0 #if 0
the_global_env->AddID(null_byteseg_id, the_global_env->AddID(null_byteseg_id,
GLOBAL_VAR, GLOBAL_VAR,
extern_type_const_byteseg); extern_type_const_byteseg);
#endif #endif
} }

View file

@ -3,6 +3,7 @@
#ifndef pac_id_h #ifndef pac_id_h
#define pac_id_h #define pac_id_h
#include <cstdint>
#include <map> #include <map>
#include <string> #include <string>
using namespace std; using namespace std;
@ -24,7 +25,7 @@ using namespace std;
// Env -- a mapping from ID names to their L/R-value expressions and evaluation // Env -- a mapping from ID names to their L/R-value expressions and evaluation
// methods. // methods.
enum IDType { enum IDType : uint8_t {
CONST, CONST,
GLOBAL_VAR, GLOBAL_VAR,
TEMP_VAR, TEMP_VAR,
@ -44,7 +45,7 @@ class Evaluatable;
class ID : public Object { class ID : public Object {
public: public:
ID(string arg_name) : name(arg_name), anonymous_id_(false) { locname = nfmt("%s:%s", Location(), Name()); } ID(string arg_name) : name(std::move(arg_name)) { locname = nfmt("%s:%s", Location(), Name()); }
~ID() { delete[] locname; } ~ID() { delete[] locname; }
bool operator==(ID const& x) const { return name == x.Name(); } bool operator==(ID const& x) const { return name == x.Name(); }
@ -57,8 +58,8 @@ public:
protected: protected:
string name; string name;
bool anonymous_id_; bool anonymous_id_ = false;
char* locname; char* locname = nullptr;
friend class ID_ptr_cmp; friend class ID_ptr_cmp;
public: public:
@ -146,7 +147,7 @@ public:
void set_in_branch(bool x) { in_branch_ = x; } void set_in_branch(bool x) { in_branch_ = x; }
void AddID(const ID* id, IDType id_type, Type* type); void AddID(const ID* id, IDType id_type, Type* type);
void AddConstID(const ID* id, const int c, Type* type = 0); void AddConstID(const ID* id, const int c, Type* type = nullptr);
void AddMacro(const ID* id, Expr* expr); void AddMacro(const ID* id, Expr* expr);
// Generate a temp ID with a unique name // Generate a temp ID with a unique name
@ -192,7 +193,7 @@ protected:
private: private:
Env* parent; Env* parent;
Object* context_object_; Object* context_object_;
typedef map<const ID*, IDRecord*, ID_ptr_cmp> id_map_t; using id_map_t = map<const ID*, IDRecord*, ID_ptr_cmp>;
id_map_t id_map; id_map_t id_map;
bool allow_undefined_id_; bool allow_undefined_id_;
bool in_branch_; bool in_branch_;

View file

@ -31,5 +31,5 @@ DataPtr InputBuffer::GenDataBeginEnd(Output* out_cc, Env* env) {
env->SetEvaluated(begin_of_data); env->SetEvaluated(begin_of_data);
env->SetEvaluated(end_of_data); env->SetEvaluated(end_of_data);
return DataPtr(env, begin_of_data, 0); return {env, begin_of_data, 0};
} }

View file

@ -1,7 +1,7 @@
// See the file "COPYING" in the main distribution directory for copyright. // See the file "COPYING" in the main distribution directory for copyright.
#include <ctype.h>
#include <unistd.h> #include <unistd.h>
#include <cctype>
#include "pac_common.h" #include "pac_common.h"
#include "pac_decl.h" #include "pac_decl.h"
@ -9,7 +9,9 @@
#include "pac_exttype.h" #include "pac_exttype.h"
#include "pac_id.h" #include "pac_id.h"
#include "pac_output.h" #include "pac_output.h"
// NOLINTBEGIN
#include "pac_parse.h" #include "pac_parse.h"
// NOLINTEND
#include "pac_type.h" #include "pac_type.h"
#include "pac_utils.h" #include "pac_utils.h"
@ -27,7 +29,8 @@ Output* header_output = nullptr;
Output* source_output = nullptr; Output* source_output = nullptr;
void add_to_include_directories(string dirs) { void add_to_include_directories(string dirs) {
unsigned int dir_begin = 0, dir_end; unsigned int dir_begin = 0;
unsigned int dir_end = 0;
while ( dir_begin < dirs.length() ) { while ( dir_begin < dirs.length() ) {
for ( dir_end = dir_begin; dir_end < dirs.length(); ++dir_end ) for ( dir_end = dir_begin; dir_end < dirs.length(); ++dir_end )
if ( dirs[dir_end] == ':' ) if ( dirs[dir_end] == ':' )

View file

@ -2,10 +2,10 @@
#include "pac_output.h" #include "pac_output.h"
#include <errno.h> #include <cerrno>
#include <stdarg.h> #include <cstdarg>
#include <stdio.h> #include <cstdio>
#include <string.h> #include <cstring>
#include "pac_utils.h" #include "pac_utils.h"

View file

@ -1,7 +1,7 @@
%token TOK_TYPE TOK_RECORD TOK_CASE TOK_ENUM TOK_LET TOK_FUNCTION %token TOK_TYPE TOK_RECORD TOK_CASE TOK_ENUM TOK_LET TOK_FUNCTION
%token TOK_REFINE TOK_CASEFUNC TOK_CASETYPE TOK_TYPEATTR %token TOK_REFINE TOK_CASEFUNC TOK_CASETYPE TOK_TYPEATTR
%token TOK_HELPERHEADER TOK_HELPERCODE %token TOK_HELPERHEADER TOK_HELPERCODE
%token TOK_RIGHTARROW TOK_DEFAULT TOK_OF %token TOK_RIGHTARROW TOK_DEFAULT TOK_OF
%token TOK_PADDING TOK_TO TOK_ALIGN %token TOK_PADDING TOK_TO TOK_ALIGN
%token TOK_WITHINPUT %token TOK_WITHINPUT
%token TOK_INT8 TOK_INT16 TOK_INT32 TOK_INT64 %token TOK_INT8 TOK_INT16 TOK_INT32 TOK_INT64
@ -11,19 +11,19 @@
%token TOK_ATTR_ALSO %token TOK_ATTR_ALSO
%token TOK_ATTR_BYTEORDER TOK_ATTR_CHECK TOK_ATTR_CHUNKED TOK_ATTR_ENFORCE %token TOK_ATTR_BYTEORDER TOK_ATTR_CHECK TOK_ATTR_CHUNKED TOK_ATTR_ENFORCE
%token TOK_ATTR_EXPORTSOURCEDATA TOK_ATTR_IF %token TOK_ATTR_EXPORTSOURCEDATA TOK_ATTR_IF
%token TOK_ATTR_LENGTH TOK_ATTR_LET %token TOK_ATTR_LENGTH TOK_ATTR_LET
%token TOK_ATTR_LINEBREAKER TOK_ATTR_MULTILINE TOK_ATTR_ONELINE %token TOK_ATTR_LINEBREAKER TOK_ATTR_MULTILINE TOK_ATTR_ONELINE
%token TOK_ATTR_REFCOUNT TOK_ATTR_REQUIRES %token TOK_ATTR_REFCOUNT TOK_ATTR_REQUIRES
%token TOK_ATTR_RESTOFDATA TOK_ATTR_RESTOFFLOW %token TOK_ATTR_RESTOFDATA TOK_ATTR_RESTOFFLOW
%token TOK_ATTR_TRANSIENT TOK_ATTR_UNTIL %token TOK_ATTR_TRANSIENT TOK_ATTR_UNTIL
%token TOK_ANALYZER TOK_CONNECTION TOK_FLOW %token TOK_ANALYZER TOK_CONNECTION TOK_FLOW
%token TOK_STATE TOK_ACTION TOK_WHEN TOK_HELPER %token TOK_STATE TOK_ACTION TOK_WHEN TOK_HELPER
%token TOK_DATAUNIT TOK_FLOWDIR TOK_WITHCONTEXT %token TOK_DATAUNIT TOK_FLOWDIR TOK_WITHCONTEXT
%token TOK_LPB_EXTERN TOK_LPB_HEADER TOK_LPB_CODE %token TOK_LPB_EXTERN TOK_LPB_HEADER TOK_LPB_CODE
%token TOK_LPB_MEMBER TOK_LPB_INIT TOK_LPB_CLEANUP TOK_LPB_EOF %token TOK_LPB_MEMBER TOK_LPB_INIT TOK_LPB_CLEANUP TOK_LPB_EOF
%token TOK_LPB TOK_RPB %token TOK_LPB TOK_RPB
%token TOK_EMBEDDED_ATOM TOK_EMBEDDED_STRING %token TOK_EMBEDDED_ATOM TOK_EMBEDDED_STRING
%token TOK_PAC_VAL TOK_PAC_SET TOK_PAC_TYPE TOK_PAC_TYPEOF TOK_PAC_CONST_DEF %token TOK_PAC_VAL TOK_PAC_SET TOK_PAC_TYPE TOK_PAC_TYPEOF TOK_PAC_CONST_DEF
%token TOK_END_PAC %token TOK_END_PAC
%token TOK_EXTERN TOK_NULLPTR %token TOK_EXTERN TOK_NULLPTR
@ -35,7 +35,7 @@
%left TOK_AND %left TOK_AND
%nonassoc TOK_EQUAL TOK_NEQ TOK_LE TOK_GE '<' '>' %nonassoc TOK_EQUAL TOK_NEQ TOK_LE TOK_GE '<' '>'
%left '&' '|' '^' %left '&' '|' '^'
%left TOK_LSHIFT TOK_RSHIFT %left TOK_LSHIFT TOK_RSHIFT
%left '+' '-' %left '+' '-'
%left '*' '/' '%' %left '*' '/' '%'
%right '~' '!' %right '~' '!'
@ -64,14 +64,14 @@
%type <field> withinputfield letfield %type <field> withinputfield letfield
%type <fieldlist> letfieldlist %type <fieldlist> letfieldlist
%type <function> funcproto function %type <function> funcproto function
%type <id> TOK_ID tok_id optfieldid %type <id> TOK_ID tok_id optfieldid
%type <input> input %type <input> input
%type <nullp> TOK_NULLPTR %type <nullp> TOK_NULLPTR
%type <num> TOK_NUMBER %type <num> TOK_NUMBER
%type <pacprimitive> embedded_pac_primitive %type <pacprimitive> embedded_pac_primitive
%type <param> param %type <param> param
%type <paramlist> optparams paramlist %type <paramlist> optparams paramlist
%type <recordfield> recordfield recordfield0 padding %type <recordfield> recordfield recordfield0 padding
%type <recordfieldlist> recordfieldlist %type <recordfieldlist> recordfieldlist
%type <regex> regex %type <regex> regex
%type <statevar> statevar %type <statevar> statevar
@ -262,15 +262,15 @@ decl_with_attr : TOK_TYPE tok_id { current_decl_id = $2; } optparams '=' type
decl_without_attr: TOK_LPB_HEADER embedded_code TOK_RPB decl_without_attr: TOK_LPB_HEADER embedded_code TOK_RPB
{ {
$$ = new HelperDecl(HelperDecl::HEADER, 0, $2); $$ = new HelperDecl(HelperDecl::HEADER, nullptr, $2);
} }
| TOK_LPB_CODE embedded_code TOK_RPB | TOK_LPB_CODE embedded_code TOK_RPB
{ {
$$ = new HelperDecl(HelperDecl::CODE, 0, $2); $$ = new HelperDecl(HelperDecl::CODE, nullptr, $2);
} }
| TOK_LPB_EXTERN embedded_code TOK_RPB | TOK_LPB_EXTERN embedded_code TOK_RPB
{ {
$$ = new HelperDecl(HelperDecl::EXTERN, 0, $2); $$ = new HelperDecl(HelperDecl::EXTERN, nullptr, $2);
} }
| TOK_REFINE TOK_TYPEATTR tok_id TOK_PLUSEQ attrlist | TOK_REFINE TOK_TYPEATTR tok_id TOK_PLUSEQ attrlist
{ {
@ -359,11 +359,11 @@ optparams : '(' paramlist ')'
} }
| /* empty */ | /* empty */
{ {
$$ = 0; $$ = nullptr;
} }
; ;
paramlist : paramlist ',' param paramlist : paramlist ',' param
{ {
$1->push_back($3); $1->push_back($3);
$$ = $1; $$ = $1;
@ -387,7 +387,7 @@ param : tok_id ':' type2
optinit : /* nothing */ optinit : /* nothing */
{ {
$$ = 0; $$ = nullptr;
} }
| '=' expr | '=' expr
{ {
@ -397,7 +397,7 @@ optinit : /* nothing */
opttype : /* nothing */ opttype : /* nothing */
{ {
$$ = 0; $$ = nullptr;
} }
| ':' type2 | ':' type2
{ {
@ -465,7 +465,7 @@ recordfieldlist : recordfieldlist recordfield ';'
$1->push_back($2); $1->push_back($2);
$$ = $1; $$ = $1;
} }
| /* empty */ | /* empty */
{ {
$$ = new RecordFieldList(); $$ = new RecordFieldList();
} }
@ -526,7 +526,7 @@ casefieldlist : casefieldlist casefield ';'
$1->push_back($2); $1->push_back($2);
$$ = $1; $$ = $1;
} }
| /* empty */ | /* empty */
{ {
$$ = new CaseFieldList(); $$ = new CaseFieldList();
} }
@ -534,7 +534,7 @@ casefieldlist : casefieldlist casefield ';'
casefield : casefield0 optattrs casefield : casefield0 optattrs
{ {
$1->AddAttr($2); $1->AddAttr($2);
$$ = $1; $$ = $1;
} }
; ;
@ -545,13 +545,13 @@ casefield0 : exprlist TOK_RIGHTARROW tok_id ':' type2
} }
| TOK_DEFAULT TOK_RIGHTARROW tok_id ':' type2 | TOK_DEFAULT TOK_RIGHTARROW tok_id ':' type2
{ {
$$ = new CaseField(0, $3, $5); $$ = new CaseField(nullptr, $3, $5);
} }
; ;
optexprlist : /* nothing */ optexprlist : /* nothing */
{ {
$$ = 0; $$ = nullptr;
} }
| exprlist | exprlist
{ {
@ -605,8 +605,8 @@ expr : tok_id
} }
| expr '(' optexprlist ')' | expr '(' optexprlist ')'
{ {
$$ = new Expr(Expr::EXPR_CALL, $$ = new Expr(Expr::EXPR_CALL,
$1, $1,
new Expr($3)); new Expr($3));
} }
| '-' expr | '-' expr
@ -697,7 +697,7 @@ expr : tok_id
{ {
$$ = new Expr(Expr::EXPR_COND, $1, $3, $5); $$ = new Expr(Expr::EXPR_COND, $1, $3, $5);
} }
| TOK_CASE expr TOK_OF '{' caseexprlist '}' | TOK_CASE expr TOK_OF '{' caseexprlist '}'
{ {
$$ = new Expr($2, $5); $$ = new Expr($2, $5);
} }
@ -718,8 +718,8 @@ cstr : TOK_STRING
; ;
regex : TOK_BEGIN_RE TOK_REGEX TOK_END_RE regex : TOK_BEGIN_RE TOK_REGEX TOK_END_RE
{ {
$$ = new RegEx($2); $$ = new RegEx($2);
} }
; ;
@ -740,7 +740,7 @@ caseexpr : exprlist TOK_RIGHTARROW expr
} }
| TOK_DEFAULT TOK_RIGHTARROW expr | TOK_DEFAULT TOK_RIGHTARROW expr
{ {
$$ = new CaseExpr(0, $3); $$ = new CaseExpr(nullptr, $3);
} }
; ;
@ -823,8 +823,8 @@ sah : TOK_LPB_MEMBER embedded_code TOK_RPB
| TOK_DATAUNIT '=' tok_id optargs TOK_WITHCONTEXT '(' optexprlist ')' ';' | TOK_DATAUNIT '=' tok_id optargs TOK_WITHCONTEXT '(' optexprlist ')' ';'
{ {
$$ = new AnalyzerDataUnit( $$ = new AnalyzerDataUnit(
(AnalyzerDataUnit::DataUnitType) $1, (AnalyzerDataUnit::DataUnitType) $1,
$3, $3,
$4, $4,
$7); $7);
} }
@ -916,7 +916,7 @@ embedded_pac_primitive: TOK_PAC_VAL expr TOK_END_PAC
optargs : /* empty */ optargs : /* empty */
{ {
$$ = 0; $$ = nullptr;
} }
| '(' optexprlist ')' | '(' optexprlist ')'
{ {
@ -924,7 +924,7 @@ optargs : /* empty */
} }
; ;
letfieldlist : letfieldlist letfield ';' letfieldlist : letfieldlist letfield ';'
{ {
$1->push_back($2); $1->push_back($2);
$$ = $1; $$ = $1;
@ -961,9 +961,9 @@ input : expr
} }
; ;
optattrs : /* empty */ optattrs : /* empty */
{ {
$$ = 0; $$ = nullptr;
} }
| attrlist | attrlist
{ {
@ -993,7 +993,7 @@ attr : TOK_ATTR_BYTEORDER '=' expr
{ {
$$ = new Attr(ATTR_BYTEORDER, $3); $$ = new Attr(ATTR_BYTEORDER, $3);
} }
| TOK_ATTR_CHECK expr | TOK_ATTR_CHECK expr
{ {
$$ = new Attr(ATTR_CHECK, $2); $$ = new Attr(ATTR_CHECK, $2);
} }
@ -1009,7 +1009,7 @@ attr : TOK_ATTR_BYTEORDER '=' expr
{ {
$$ = new Attr(ATTR_EXPORTSOURCEDATA); $$ = new Attr(ATTR_EXPORTSOURCEDATA);
} }
| TOK_ATTR_IF expr | TOK_ATTR_IF expr
{ {
$$ = new Attr(ATTR_IF, $2); $$ = new Attr(ATTR_IF, $2);
} }
@ -1061,7 +1061,7 @@ attr : TOK_ATTR_BYTEORDER '=' expr
optlinebreaker : /* nothing */ optlinebreaker : /* nothing */
{ {
$$ = 0; $$ = nullptr;
} }
| '(' expr ')' | '(' expr ')'
{ {
@ -1071,35 +1071,34 @@ optlinebreaker : /* nothing */
%% %%
const ID* current_decl_id = 0; const ID* current_decl_id = nullptr;
int yyerror(const char msg[]) int yyerror(const char msg[]) {
{ auto n = strlen(msg) + yyleng + 64;
auto n = strlen(msg) + yyleng + 64; char* msgbuf = new char[n];
char* msgbuf = new char[n];
if ( ! yychar || ! yytext || yytext[0] == '\0' ) if ( ! yychar || ! yytext || yytext[0] == '\0' )
snprintf(msgbuf, n, "%s, at end of file", msg); snprintf(msgbuf, n, "%s, at end of file", msg);
else if ( yytext[0] == '\n' ) else if ( yytext[0] == '\n' )
snprintf(msgbuf, n, "%s, on previous line", msg); snprintf(msgbuf, n, "%s, on previous line", msg);
else else
snprintf(msgbuf, n, "%s, at or near \"%s\"", msg, yytext); snprintf(msgbuf, n, "%s, at or near \"%s\"", msg, yytext);
/* /*
extern int column; extern int column;
sprintf(msgbuf, "%*s\n%*s\n", column, "^", column, msg); sprintf(msgbuf, "%*s\n%*s\n", column, "^", column, msg);
*/ */
if ( ! input_filename.empty() ) if ( ! input_filename.empty() )
fprintf(stderr, "%s:%d: ", input_filename.c_str(), line_number); fprintf(stderr, "%s:%d: ", input_filename.c_str(), line_number);
else else
fprintf(stderr, "line %d: ", line_number); fprintf(stderr, "line %d: ", line_number);
fprintf(stderr, "%s", msgbuf); fprintf(stderr, "%s", msgbuf);
fprintf(stderr, " (yychar=%d)", yychar); fprintf(stderr, " (yychar=%d)", yychar);
fprintf(stderr, "\n"); fprintf(stderr, "\n");
delete[] msgbuf; delete[] msgbuf;
return 0; return 0;
} }

View file

@ -9,7 +9,7 @@
string PPVal::ToCode(Env* env) { string PPVal::ToCode(Env* env) {
ASSERT(expr_); ASSERT(expr_);
return string(expr_->EvalExpr(nullptr, env)); return {expr_->EvalExpr(nullptr, env)};
} }
string PPSet::ToCode(Env* env) { string PPSet::ToCode(Env* env) {

View file

@ -3,11 +3,13 @@
#ifndef pac_primitive_h #ifndef pac_primitive_h
#define pac_primitive_h #define pac_primitive_h
#include <cstdint>
#include "pac_common.h" #include "pac_common.h"
class PacPrimitive { class PacPrimitive {
public: public:
enum PrimitiveType { VAL, SET, TYPE, CONST_DEF }; enum PrimitiveType : uint8_t { VAL, SET, TYPE, CONST_DEF };
explicit PacPrimitive(PrimitiveType type) : type_(type) {} explicit PacPrimitive(PrimitiveType type) : type_(type) {}
virtual ~PacPrimitive() {} virtual ~PacPrimitive() {}

View file

@ -29,7 +29,7 @@ RecordType::RecordType(RecordFieldList* record_fields) : Type(RECORD) {
} }
RecordType::~RecordType() { RecordType::~RecordType() {
// Do not delete_list(RecordFieldList, record_fields_) // Do not delete_list(record_fields_)
// because the fields are also in fields_. // because the fields are also in fields_.
delete record_fields_; delete record_fields_;
delete parsing_dataptr_var_field_; delete parsing_dataptr_var_field_;

View file

@ -135,7 +135,7 @@ protected:
bool DoTraverse(DataDepVisitor* visitor) override; bool DoTraverse(DataDepVisitor* visitor) override;
}; };
enum PaddingType { PAD_BY_LENGTH, PAD_TO_OFFSET, PAD_TO_NEXT_WORD }; enum PaddingType : uint8_t { PAD_BY_LENGTH, PAD_TO_OFFSET, PAD_TO_NEXT_WORD };
class RecordPaddingField : public RecordField { class RecordPaddingField : public RecordField {
public: public:

View file

@ -45,38 +45,36 @@ int line_number = 1;
int begin_pac_primitive(int tok); int begin_pac_primitive(int tok);
int end_pac_primitive(); int end_pac_primitive();
int string_token(int tok) int string_token(int tok) {
{ yylval.str = copy_string(yytext);
yylval.str = copy_string(yytext); return tok;
return tok; }
}
int char_token(int tok) int char_token(int tok) {
{ yylval.val = yytext[0];
yylval.val = yytext[0]; return tok;
return tok; }
}
void include_file(const char *filename); void include_file(const char* filename);
std::string do_dirname(std::string_view s) std::string do_dirname(std::string_view s) {
{
#ifdef _MSC_VER #ifdef _MSC_VER
return std::filesystem::path(s).parent_path().string(); return std::filesystem::path(s).parent_path().string();
#else #else
std::unique_ptr<char[]> tmp{new char[s.size()+1]}; std::unique_ptr<char[]> tmp{new char[s.size() + 1]};
strncpy(tmp.get(), s.data(), s.size()); strncpy(tmp.get(), s.data(), s.size());
tmp[s.size()] = '\0'; tmp[s.size()] = '\0';
char* dn = dirname(tmp.get()); char* dn = dirname(tmp.get());
if ( !dn ) if ( ! dn )
return ""; return "";
std::string res{dn}; std::string res{dn};
return res; return res;
#endif #endif
} }
%} %}
/* EC -- embedded code state */ /* EC -- embedded code state */
@ -283,133 +281,109 @@ ESCSEQ (\\([^\n]|[0-7]{3}|x[[:xdigit:]]{2}))
%% %%
void begin_RE() void begin_RE() {
{ BEGIN(RE);
BEGIN(RE); }
}
void end_RE() void end_RE() { BEGIN(INITIAL); }
{
BEGIN(INITIAL);
}
// The DECL state is deprecated // The DECL state is deprecated
void begin_decl() void begin_decl() {
{ // BEGIN(DECL);
// BEGIN(DECL); }
}
void end_decl() void end_decl() {
{ // BEGIN(INITIAL);
// BEGIN(INITIAL); }
}
int begin_pac_primitive(int tok) int begin_pac_primitive(int tok) {
{ BEGIN(PP);
BEGIN(PP); return tok;
return tok; }
}
int end_pac_primitive() int end_pac_primitive() {
{ BEGIN(EC);
BEGIN(EC); return TOK_END_PAC;
return TOK_END_PAC; }
}
const int MAX_INCLUDE_DEPTH = 100; constexpr int MAX_INCLUDE_DEPTH = 100;
struct IncludeState { struct IncludeState {
YY_BUFFER_STATE yystate; YY_BUFFER_STATE yystate;
string input_filename; string input_filename;
int line_number; int line_number;
}; };
IncludeState include_stack[MAX_INCLUDE_DEPTH]; IncludeState include_stack[MAX_INCLUDE_DEPTH];
int include_stack_ptr = 0; int include_stack_ptr = 0;
void switch_to_file(FILE *fp) void switch_to_file(FILE* fp) { yy_switch_to_buffer(yy_create_buffer(fp, YY_BUF_SIZE)); }
{
yy_switch_to_buffer(yy_create_buffer(fp, YY_BUF_SIZE));
}
void switch_to_file(const char *filename) void switch_to_file(const char* filename) {
{ if ( include_stack_ptr >= MAX_INCLUDE_DEPTH ) {
if ( include_stack_ptr >= MAX_INCLUDE_DEPTH ) fprintf(stderr, "Includes nested too deeply");
{ exit(1);
fprintf( stderr, "Includes nested too deeply" ); }
exit( 1 );
}
IncludeState state = IncludeState state = {YY_CURRENT_BUFFER, input_filename, line_number};
{ YY_CURRENT_BUFFER, input_filename, line_number }; include_stack[include_stack_ptr++] = state;
include_stack[include_stack_ptr++] = state;
FILE *fp = fopen(filename, "r"); FILE* fp = fopen(filename, "r");
if ( ! fp ) if ( ! fp ) {
{ fprintf(stderr, "%s:%d: error: cannot include file \"%s\"\n", input_filename.c_str(), line_number, filename);
fprintf(stderr, "%s:%d: error: cannot include file \"%s\"\n", exit(1);
input_filename.c_str(), line_number,filename); }
exit( 1 );
}
yyin = fp; yyin = fp;
input_filename = string(filename); input_filename = string(filename);
line_number = 1; line_number = 1;
switch_to_file(yyin); switch_to_file(yyin);
if ( !FLAGS_quiet ) if ( ! FLAGS_quiet )
fprintf(stderr, "switching to file %s\n", input_filename.c_str()); fprintf(stderr, "switching to file %s\n", input_filename.c_str());
} }
void include_file(const char *filename) void include_file(const char* filename) {
{ ASSERT(filename);
ASSERT(filename);
string full_filename; string full_filename;
if ( filename[0] == '/' ) if ( filename[0] == '/' )
full_filename = filename; full_filename = filename;
else if ( filename[0] == '.' ) else if ( filename[0] == '.' ) {
{ string dir = do_dirname(input_filename);
string dir = do_dirname(input_filename);
if ( ! dir.empty() ) if ( ! dir.empty() )
full_filename = dir + "/" + filename; full_filename = dir + "/" + filename;
else else {
{ fprintf(stderr, "%s:%d error: cannot include file \"%s\": %s\n", input_filename.c_str(), line_number,
fprintf(stderr, "%s:%d error: cannot include file \"%s\": %s\n", filename, strerror(errno));
input_filename.c_str(), line_number, filename, exit(1);
strerror(errno)); }
exit( 1 ); }
} else {
} int i;
else for ( i = 0; i < (int)FLAGS_include_directories.size(); ++i ) {
{ full_filename = FLAGS_include_directories[i] + filename;
int i; DEBUG_MSG("Try include file: \"%s\"\n", full_filename.c_str());
for ( i = 0; i < (int) FLAGS_include_directories.size(); ++i ) if ( access(full_filename.c_str(), R_OK) == 0 )
{ break;
full_filename = FLAGS_include_directories[i] + filename; }
DEBUG_MSG("Try include file: \"%s\"\n", if ( i >= (int)FLAGS_include_directories.size() )
full_filename.c_str()); full_filename = filename;
if ( access(full_filename.c_str(), R_OK) == 0 ) }
break;
}
if ( i >= (int) FLAGS_include_directories.size() )
full_filename = filename;
}
switch_to_file(full_filename.c_str()); switch_to_file(full_filename.c_str());
} }
int yywrap() int yywrap() {
{ yy_delete_buffer(YY_CURRENT_BUFFER);
yy_delete_buffer(YY_CURRENT_BUFFER); --include_stack_ptr;
--include_stack_ptr; if ( include_stack_ptr < 0 )
if ( include_stack_ptr < 0 ) return 1;
return 1;
IncludeState state = include_stack[include_stack_ptr]; IncludeState state = include_stack[include_stack_ptr];
yy_switch_to_buffer(state.yystate); yy_switch_to_buffer(state.yystate);
input_filename = state.input_filename; input_filename = state.input_filename;
line_number = state.line_number; line_number = state.line_number;
return 0; return 0;
} }

View file

@ -273,11 +273,7 @@ void StringType::GenDynamicSizeRegEx(Output* out_cc, Env* env, const DataPtr& da
void StringType::GenDynamicSizeAnyStr(Output* out_cc, Env* env, const DataPtr& data) { void StringType::GenDynamicSizeAnyStr(Output* out_cc, Env* env, const DataPtr& data) {
ASSERT(type_ == ANYSTR); ASSERT(type_ == ANYSTR);
if ( attr_restofdata_ || attr_oneline_ ) { if ( attr_restofdata_ || attr_oneline_ || attr_restofflow_ ) {
out_cc->println("%s = (%s) - (%s);", env->LValue(string_length_var()), env->RValue(end_of_data),
data.ptr_expr());
}
else if ( attr_restofflow_ ) {
out_cc->println("%s = (%s) - (%s);", env->LValue(string_length_var()), env->RValue(end_of_data), out_cc->println("%s = (%s) - (%s);", env->LValue(string_length_var()), env->RValue(end_of_data),
data.ptr_expr()); data.ptr_expr());
} }

View file

@ -3,12 +3,14 @@
#ifndef pac_strtype_h #ifndef pac_strtype_h
#define pac_strtype_h #define pac_strtype_h
#include <cstdint>
#include "pac_type.h" #include "pac_type.h"
// TODO: question: shall we merge it with ArrayType? // TODO: question: shall we merge it with ArrayType?
class StringType : public Type { class StringType : public Type {
public: public:
enum StringTypeEnum { CSTR, REGEX, ANYSTR }; enum StringTypeEnum : uint8_t { CSTR, REGEX, ANYSTR };
explicit StringType(StringTypeEnum anystr); explicit StringType(StringTypeEnum anystr);
explicit StringType(ConstString* str); explicit StringType(ConstString* str);

View file

@ -75,14 +75,14 @@ Type::~Type() {
delete buffering_state_var_field_; delete buffering_state_var_field_;
delete has_value_field_; delete has_value_field_;
delete[] size_expr_; delete[] size_expr_;
delete_list(FieldList, fields_); delete_list(fields_);
delete attrs_; delete attrs_;
delete attr_byteorder_expr_; delete attr_byteorder_expr_;
delete attr_if_expr_; delete attr_if_expr_;
delete attr_length_expr_; delete attr_length_expr_;
delete_list(ExprList, attr_checks_); delete_list(attr_checks_);
delete_list(ExprList, attr_enforces_); delete_list(attr_enforces_);
delete_list(ExprList, attr_requires_); delete_list(attr_requires_);
} }
Type* Type::Clone() const { Type* Type::Clone() const {
@ -696,7 +696,7 @@ string Type::DataSize(Output* out_cc, Env* env, const DataPtr& data) {
} }
else { else {
if ( ! size_var() || ! env->Evaluated(size_var()) ) { if ( ! size_var() || ! env->Evaluated(size_var()) ) {
ASSERT(out_cc != 0); ASSERT(out_cc != nullptr);
GenDynamicSize(out_cc, env, data); GenDynamicSize(out_cc, env, data);
ASSERT(size_var()); ASSERT(size_var());
} }

View file

@ -303,7 +303,7 @@ public:
static Type* LookUpByID(ID* id); static Type* LookUpByID(ID* id);
protected: protected:
typedef map<string, Type*> type_map_t; using type_map_t = map<string, Type*>;
static type_map_t type_map_; static type_map_t type_map_;
}; };

View file

@ -27,7 +27,7 @@ TypeDecl::~TypeDecl() {
delete env_; delete env_;
delete type_; delete type_;
delete_list(ParamList, params_); delete_list(params_);
} }
void TypeDecl::ProcessAttr(Attr* a) { type_->ProcessAttr(a); } void TypeDecl::ProcessAttr(Attr* a) { type_->ProcessAttr(a); }
@ -101,7 +101,7 @@ void TypeDecl::GenCode(Output* out_h, Output* out_cc) {
AddBaseClass(&base_classes); AddBaseClass(&base_classes);
if ( type_->attr_refcount() ) if ( type_->attr_refcount() )
base_classes.push_back(kRefCountClass); base_classes.emplace_back(kRefCountClass);
// The first line of class definition // The first line of class definition
out_h->println(""); out_h->println("");
@ -232,7 +232,8 @@ string TypeDecl::ParseFuncPrototype(Env* env) {
} }
void TypeDecl::GenParsingEnd(Output* out_cc, Env* env, const DataPtr& data) { void TypeDecl::GenParsingEnd(Output* out_cc, Env* env, const DataPtr& data) {
string ret_val_0, ret_val_1; string ret_val_0;
string ret_val_1;
if ( type_->incremental_input() ) { if ( type_->incremental_input() ) {
ret_val_0 = type_->parsing_complete(env).c_str(); ret_val_0 = type_->parsing_complete(env).c_str();
@ -259,9 +260,6 @@ void TypeDecl::GenParsingEnd(Output* out_cc, Env* env, const DataPtr& data) {
out_cc->println("BINPAC_ASSERT(!(%s));", type_->parsing_complete(env).c_str()); out_cc->println("BINPAC_ASSERT(!(%s));", type_->parsing_complete(env).c_str());
out_cc->println("return %s;", ret_val_1.c_str()); out_cc->println("return %s;", ret_val_1.c_str());
} }
else if ( type_->incremental_input() ) {
out_cc->println("return %s;", ret_val_0.c_str());
}
else { else {
out_cc->println("return %s;", ret_val_0.c_str()); out_cc->println("return %s;", ret_val_0.c_str());
} }

View file

@ -2,9 +2,9 @@
#include "pac_utils.h" #include "pac_utils.h"
#include <stdarg.h> #include <cstdarg>
#include <stdio.h> #include <cstdio>
#include <string.h> #include <cstring>
char* copy_string(const char* s) { char* copy_string(const char* s) {
char* c = new char[strlen(s) + 1]; char* c = new char[strlen(s) + 1];
@ -27,7 +27,7 @@ string strfmt(const char* format, ...) {
va_start(ap, format); va_start(ap, format);
const char* r = do_fmt(format, ap); const char* r = do_fmt(format, ap);
va_end(ap); va_end(ap);
return string(r); return {r};
} }
char* nfmt(const char* format, ...) { char* nfmt(const char* format, ...) {

View file

@ -1,2 +1,2 @@
add_executable(gen-zam) add_executable(gen-zam)
target_sources(gen-zam PRIVATE src/Gen-ZAM.cc) target_sources(gen-zam PRIVATE Gen-ZAM.cc)