Skip to content

Instantly share code, notes, and snippets.

@pervognsen
Last active May 28, 2023 02:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pervognsen/372aa279e48d58012825a66564757c40 to your computer and use it in GitHub Desktop.
Save pervognsen/372aa279e48d58012825a66564757c40 to your computer and use it in GitHub Desktop.
// Direct style
int paren_prefix(Ctx *c) {
next(c); // LPAREN
int x = binary(c, -1);
expect(c, RPAREN);
return x;
}
int binary(Ctx *c, int min_prec) {
int x = c->tok.prefix(c);
while (c->tok.prec > min_prec)
x = c->tok.postfix(c, x);
return x;
}
// Continuation passing style
typedef int (*Cont)(Ctx *c, int x);
int paren_prefix(Ctx *c, Cont k) {
pushk(c, k);
next(c); // LPAREN
return binary(c, paren_prefix2, -1);
}
int paren_prefix2(Ctx *c, int x) {
expect(c, RPAREN);
Cont k = popk(c);
return k(c, x);
}
int binary(Ctx *c, Cont k, int min_prec) {
pushk(c, k);
pushi(c, min_prec);
return c->tok.prefix(c, binary2);
}
int binary2(Ctx *c, int x) {
int min_prec = popi(c);
if (c->tok.prec > min_prec) {
pushi(c, min_prec);
return c->tok.postfix(c, binary2, x);
}
Cont k = popk(c);
return k(c, x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment