refactor(api): VALIDATE macros #22256

- VALIDATE() takes a format string
- deduplicate check_string_array
- VALIDATE_RANGE
- validate UI args
This commit is contained in:
Justin M. Keyes
2023-02-14 08:07:38 -05:00
committed by GitHub
parent 3a6a7add57
commit ff3d04b75b
19 changed files with 434 additions and 416 deletions

View File

@@ -821,8 +821,7 @@ int object_to_hl_id(Object obj, const char *what, Error *err)
} else if (obj.type == kObjectTypeInteger) {
return MAX((int)obj.data.integer, 0);
} else {
api_set_error(err, kErrorTypeValidation,
"%s is not a valid highlight", what);
api_set_error(err, kErrorTypeValidation, "Invalid highlight: %s", what);
return 0;
}
}

View File

@@ -0,0 +1,28 @@
// This is an open source non-commercial project. Dear PVS-Studio, please check
// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include "nvim/api/private/defs.h"
#include "nvim/api/private/helpers.h"
#include "nvim/api/private/validate.h"
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "api/private/validate.c.generated.h"
#endif
bool check_string_array(Array arr, char *name, bool disallow_nl, Error *err)
{
snprintf(IObuff, sizeof(IObuff), "'%s' item", name);
for (size_t i = 0; i < arr.size; i++) {
VALIDATE_T(IObuff, kObjectTypeString, arr.items[i].type, {
return false;
});
// Disallow newlines in the middle of the line.
if (disallow_nl) {
const String l = arr.items[i].data.string;
VALIDATE(!memchr(l.data, NL, l.size), "'%s' item contains newlines", name, {
return false;
});
}
}
return true;
}

View File

@@ -24,19 +24,11 @@
} \
} while (0)
#define VALIDATE_R(cond, name, code) \
do { \
if (!(cond)) { \
api_set_error(err, kErrorTypeValidation, "'" name "' is required"); \
code; \
} \
} while (0)
#define VALIDATE_EXP(cond, name, expected, actual, code) \
do { \
if (!(cond)) { \
api_set_error(err, kErrorTypeValidation, "Invalid " name ": expected %s, got %s", \
expected, actual); \
api_set_error(err, kErrorTypeValidation, "Invalid %s: expected %s, got %s", \
name, expected, actual); \
code; \
} \
} while (0)
@@ -50,20 +42,27 @@
} \
} while (0)
#define VALIDATE(cond, msg_, code) \
#define VALIDATE(cond, fmt_, fmt_arg1, code) \
do { \
if (!(cond)) { \
api_set_error(err, kErrorTypeValidation, "%s", msg_); \
api_set_error(err, kErrorTypeValidation, fmt_, fmt_arg1); \
code; \
} \
} while (0)
#define VALIDATE_FMT(cond, fmt_, msg_, code) \
#define VALIDATE_RANGE(cond, name, code) \
do { \
if (!(cond)) { \
api_set_error(err, kErrorTypeValidation, fmt_, msg_); \
api_set_error(err, kErrorTypeValidation, "Invalid '%s': out of range", name); \
code; \
} \
} while (0)
#define VALIDATE_R(cond, name, code) \
VALIDATE(cond, "Required: '%s'", name, code);
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "api/private/validate.h.generated.h"
#endif
#endif // NVIM_API_PRIVATE_VALIDATE_H