It is a beginner implementation of some of what you can read in Language Implementation Patterns by Terence Parr.
The goal is to implement a LL(0) parser for Brainfuck. It just returns 1 if the code isn't valid and 0 if it is.
Note that it could become a recursive-descent parser if it was to parse more complicated grammars. That would just be an like an extent.
I implemented it in C. No compilation flag needed. Here is my code:
#include <stdio.h>
#include <stdlib.h>
int my_strlen(char *m) {
int i = 0;
while (m[i++] != '\0');
return i;
}
void my_strcpy(char *to, char *from) {
while ((*(to++) = *(from++)) != '\0');
}
void consume(char **p, char *t) {
if (**p == '\0') return;
if (**p == *t) (*p)++;
}
int abs(int i) {
if (i < 0) return (i * (-1));
else return i;
}
int expression(char **p) {
static int loops;
switch (**p) {
case '+':
case '-':
case '.':
case ',':
case '<':
case '>':
consume(p, *p);
break;
case '[':
consume(p, "[");
loops++;
break;
case ']':
consume(p, "]");
loops--;
if (loops < 0) {
exit(1);
}
break;
default:
exit(1);
}
return loops;
}
void whole(char **p) {
int loops;
while (**p != '\0') {
loops = expression(p);
}
if (loops > 0) {
exit(1);
}
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Feed me argument.\nFor example: ++[[-]].");
exit(1);
}
char *f = malloc(sizeof(char) * my_strlen(argv[1]));
my_strcpy(f, argv[1]);
char *bf = argv[1];
whole(&bf);
return 0;
}
If you're using bash, use the following to output the return code of the program:
echo $?
Waiting for your codes ! Any language.