ZackTactical34
United States
 
 
Software Engineer who speaks a little Japanese
Basic Interpreter
// interpreter.c

#include "interpreter.h"

// Lexer code
void advance(interpreter *ptr) {
ptr->pos++;
if(ptr->pos >= strlen(ptr->text)) { //accounts for '\n'
ptr->current_ch = 0;
} else {
ptr->current_ch = ptr->text[ptr->pos];
}
}

void skipwhitespace(interpreter *ptr) {
while(ptr->current_ch == ' ' || ptr->current_ch == '\t') {
advance(ptr);
}
}

void error() {
exit(1);
}

int integer(interpreter *ptr) {
int result = 0;
while(ptr->current_ch >= '0' && ptr->current_ch <= '9') {
result = result * 10 + ptr->current_ch - '0';
advance(ptr);
}
return result;
}

void get_next_token(interpreter *ptr) {
token *tkn = (token *) malloc(sizeof(token));
tkn->type = -1;
tkn->value = NULL;
while(ptr->current_ch != 0) {

if(ptr->current_ch == ' ' || ptr->current_ch == '\t') {
skipwhitespace(ptr);
continue;
}

if(ptr->current_ch >= '0' && ptr->current_ch <= '9') {
tkn->type = 0;
int *my_x = (int *) malloc(sizeof(int));
*my_x = integer(ptr);
tkn->value = my_x;
break;
}

if(ptr->current_ch == '+') {
advance(ptr);
tkn->type = 1;
tkn->value = "+";
break;
}

if(ptr->current_ch == '-') {
advance(ptr);
tkn->type = 2;
tkn->value = "-";
break;
}
}
ptr->current_token = tkn;
}


// Parser / Interpreter code
void eat(interpreter *ptr, int type) {
if(ptr->current_token->type == type) {
free(ptr->current_token);
get_next_token(ptr);
} else {
error();
}
}

int term(interpreter *ptr) {
int *value = ptr->current_token->value;
eat(ptr, 0);
return *value;
}

int expr(interpreter *ptr) {
//initializes the first token
get_next_token(ptr);

int result = term(ptr);
while(ptr->current_token->type == 1 || ptr->current_token->type == 2) {
if(ptr->current_token->type == 1) {
eat(ptr, 1);
result += term(ptr);
} else {
eat(ptr, 2);
result -= term(ptr);
}
}

return result;
}


// Main
int main() {
interpreter *ptr = malloc(sizeof(interpreter));
char input[100];
while(true) {
printf("> ");
scanf("%s", input); //need to figure out how to include whitespace lol
ptr->pos = 0;
ptr->text = input;
ptr->current_ch = ptr->text[ptr->pos];
printf("%d\n", expr(ptr));
}
return 0;
}



// interpreter.h

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

typedef struct {
int type;
void *value;
} token;

typedef struct {
int pos;
char *text;
char current_ch;
token *current_token;
} interpreter;
Screenshot Showcase
Love CSS!
1 1