qbe-wasm [ Home ] [ Demos ] [ Source ]

Came across a Small C brainfuck interpreter on reddit while looking for more code samples to compile as test cases. This one looked good as it shows off some decent control flow, static memory allocation and calls back to the host. I did have to make one small type change (unsigned char**v) to get it to compile using cproc.

qbe-wasm does not have wasi support, so this demo rolls its own putchar and getchar.

bf.c

      
#include <stdio.h>
#define B break
unsigned char*p,t[1<<16],i,*d;
void c(){do{switch(*p)
{case'+':(*d)++;B;
case'-':(*d)--;B;
case'<':(d)--;B;
case'>':(d)++;B;
case'.':putchar(*d);B;
case',':(*d)=getchar();B;
case'[':if(!*d){int n=1;while(n)if(*++p=='[')n++;else if(*p==']')n--;}B;
case']':if(*d){int n=1;while(n)if(*--p==']')n++;else if(*p=='[')n--;}B;
default:;}}while(*++p);}
int main(int a,unsigned char**v){if(a<2)return 1;p=v[1];d=t;c();}

cproc -emit-qbe -o bf.qbe -c bf.c

qbe-wasm -o bf.wasm bf.qbe

qbe-wasm -t wat -o bf.wat bf.qbe
      

      ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.