aboutsummaryrefslogtreecommitdiff
path: root/Lua
diff options
context:
space:
mode:
authorBruce Hill <bruce@bruce-hill.com>2022-05-14 16:01:37 -0400
committerBruce Hill <bruce@bruce-hill.com>2022-05-14 16:01:37 -0400
commitca89d65513c57c6517d5190d33f0bbc690ba5d46 (patch)
tree6cfba39eeccba4c9f23aa2d07503533bf3c352e6 /Lua
parent563ecf332ee6e79f0cc7361e00a09963723fd402 (diff)
Better error handling
Diffstat (limited to 'Lua')
-rw-r--r--Lua/lbp.c16
-rw-r--r--Lua/test.lua7
2 files changed, 21 insertions, 2 deletions
diff --git a/Lua/lbp.c b/Lua/lbp.c
index 2b6d62f..5e94890 100644
--- a/Lua/lbp.c
+++ b/Lua/lbp.c
@@ -31,6 +31,16 @@ static pat_t *builtins;
static void push_match(lua_State *L, match_t *m, const char *start);
+lua_State *cur_state = NULL;
+
+static void match_error(pat_t *pat, const char *msg)
+{
+ (void)pat;
+ recycle_all_matches();
+ lua_pushstring(cur_state, msg);
+ lua_error(cur_state);
+}
+
static inline void raise_parse_error(lua_State *L, maybe_pat_t m)
{
size_t err_len = (size_t)(m.value.error.end - m.value.error.start);
@@ -153,7 +163,8 @@ static int Lmatch(lua_State *L)
match_t *m = NULL;
int ret = 0;
- if (next_match(&m, text+index-1, &text[textlen], pat, builtins, NULL, false)) {
+ cur_state = L;
+ if (next_match_safe(&m, text+index-1, &text[textlen], pat, builtins, NULL, false, match_error)) {
push_match(L, m, text);
stop_matching(&m);
ret = 1;
@@ -191,7 +202,8 @@ static int Lreplace(lua_State *L)
int replacements = 0;
const char *prev = text;
pat_t *rep_pat = maybe_replacement.value.pat;
- for (match_t *m = NULL; next_match(&m, text, &text[textlen], rep_pat, builtins, NULL, false); ) {
+ cur_state = L;
+ for (match_t *m = NULL; next_match_safe(&m, text, &text[textlen], rep_pat, builtins, NULL, false, match_error); ) {
fwrite(prev, sizeof(char), (size_t)(m->start - prev), out);
fprint_match(out, text, m, NULL);
prev = m->end;
diff --git a/Lua/test.lua b/Lua/test.lua
index 731b044..d812009 100644
--- a/Lua/test.lua
+++ b/Lua/test.lua
@@ -54,3 +54,10 @@ print(pat:replace("{@0}", "...baz..."))
for m in pat:matches("hello world") do
print(m)
end
+
+
+local ok, err = pcall(function()
+ bp.match("nonexistent", "xxx")
+end)
+assert(not ok)
+print("(Successfully caught pattern matching error)")