Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix behavior of fe_write() on circular lists #22

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions scripts/circular.fe
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
(= items (list 1 2 3 4))
(setcar (cdr items) (cons items (cons 5 items)))
(setcdr (cdr (cdr (cdr items))) items)
(print items)
28 changes: 23 additions & 5 deletions src/fe.c
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ static void writestr(fe_Context *ctx, fe_WriteFn fn, void *udata, const char *s)
while (*s) { fn(ctx, udata, *s++); }
}

void fe_write(fe_Context *ctx, fe_Object *obj, fe_WriteFn fn, void *udata, int qt) {
static void write_(fe_Context *ctx, fe_Object *obj, fe_WriteFn fn, void *udata, int qt) {
char buf[32];

switch (type(obj)) {
Expand All @@ -357,22 +357,28 @@ void fe_write(fe_Context *ctx, fe_Object *obj, fe_WriteFn fn, void *udata, int q
break;

case FE_TPAIR:
if (tag(obj) & GCMARKBIT) { writestr(ctx, fn, udata, "..."); break; }
fn(ctx, udata, '(');
for (;;) {
fe_write(ctx, car(obj), fn, udata, 1);
/* mark 'obj' and write car(obj) */
fe_Object *tmp = car(obj);
tag(obj) |= GCMARKBIT;
write_(ctx, tmp, fn, udata, 1);
/* write cdr(obj) if isn't circular list */
obj = cdr(obj);
if (type(obj) != FE_TPAIR) { break; }
fn(ctx, udata, ' ');
if (tag(obj) & GCMARKBIT) { writestr(ctx, fn, udata, "..."); break; }
}
if (!isnil(obj)) {
if (!isnil(obj) && !(tag(obj) & GCMARKBIT)) {
writestr(ctx, fn, udata, " . ");
fe_write(ctx, obj, fn, udata, 1);
write_(ctx, obj, fn, udata, 1);
}
fn(ctx, udata, ')');
break;

case FE_TSYMBOL:
fe_write(ctx, car(cdr(obj)), fn, udata, 0);
write_(ctx, car(cdr(obj)), fn, udata, 0);
break;

case FE_TSTRING:
Expand All @@ -395,6 +401,18 @@ void fe_write(fe_Context *ctx, fe_Object *obj, fe_WriteFn fn, void *udata, int q
}
}

static void unmarkpairs(fe_Object *obj) {
for (; !isnil(obj) && (tag(obj) & GCMARKBIT); obj = cdr(obj)) {
tag(obj) &= ~GCMARKBIT;
unmarkpairs(car(obj));
}
}

void fe_write(fe_Context *ctx, fe_Object *obj, fe_WriteFn fn, void *udata, int qt) {
write_(ctx, obj, fn, udata, qt);
unmarkpairs(obj);
}


static void writefp(fe_Context *ctx, void *udata, char chr) {
unused(ctx);
Expand Down