From 714bd61d56efb57d536b293b01c6c828d402b274 Mon Sep 17 00:00:00 2001 From: Calvin Rose Date: Fri, 6 Mar 2020 10:01:04 -0600 Subject: [PATCH] Address #300 Check for empty capture stack in replace rule. --- src/core/peg.c | 14 +++++++++----- test/suite8.janet | 5 +++++ 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/core/peg.c b/src/core/peg.c index 6e839f9e..fc05c9b7 100644 --- a/src/core/peg.c +++ b/src/core/peg.c @@ -369,19 +369,23 @@ tail: s->mode = oldmode; if (!result) return NULL; - Janet cap; + Janet cap = janet_wrap_nil(); Janet constant = s->constants[rule[2]]; switch (janet_type(constant)) { default: cap = constant; break; case JANET_STRUCT: - cap = janet_struct_get(janet_unwrap_struct(constant), - s->captures->data[s->captures->count - 1]); + if (s->captures->count) { + cap = janet_struct_get(janet_unwrap_struct(constant), + s->captures->data[s->captures->count - 1]); + } break; case JANET_TABLE: - cap = janet_table_get(janet_unwrap_table(constant), - s->captures->data[s->captures->count - 1]); + if (s->captures->count) { + cap = janet_table_get(janet_unwrap_table(constant), + s->captures->data[s->captures->count - 1]); + } break; case JANET_CFUNCTION: cap = janet_unwrap_cfunction(constant)(s->captures->count - cs.cap, diff --git a/test/suite8.janet b/test/suite8.janet index f314a53e..242d80db 100644 --- a/test/suite8.janet +++ b/test/suite8.janet @@ -112,4 +112,9 @@ (assert (= false (and false false)) "and 1") (assert (= false (or false false)) "or 1") +# #300 Regression test + +# Just don't segfault +(assert (peg/match '{:main (replace "S" {"S" :spade})} "S7") "regression #300") + (end-suite)