/* Heap based virtual machine described in section 3.4 of Three Implementation Models for Scheme, Dybvig */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> char token[128][32]; int lexer(char* input) { int ii = 0; // input index int ti = 0; // token index while(input[ii] != '\0') switch(input[ii]) { // Ignore whitespace and newlines case ' ': case '\n': ++ii; break; // Turn a left parenthesis into a token. case '(': token[ti][0] = '('; token[ti][1] = '\0'; ++ii; ++ti; break; // Turn a right parenthesis into a token. case ')': token[ti][0] = ')'; token[ti][1] = '\0'; ++ii; ++ti; break; // Turn an apostrophe into a token. case '\'': token[ti][0] = '\''; token[ti][1] = '\0'; ++ii; ++ti; break; // Anything else is a symbol default: for(int i = 0;; ++i) { if(input[ii] != ' ' && input[ii] != ')' && input[ii] != '(' && input[ii] != '\n' && input[ii] != '\0') { token[ti][i] = input[ii++]; } else { token[ti][i] = '\0'; break; } } ++ti; break; } return ti; } int curtok; char* nexttok() { return token[curtok++]; } char* peektok() { return token[curtok]; } typedef struct Pair { void* car; void* cdr; } Pair; typedef struct Text { char* car; struct Text* cdr; } Text; Pair text[1280]; Pair* textptr; int istext(void* x) { return x >= (void*)&text && x < (void*)&text[1280]; } Pair* cons(void* x, void* y) { assert(istext(textptr)); textptr->car = x; textptr->cdr = y; return textptr++; } void* read(char* ln); void* read_exp(); void* read_list(); void* read(char* ln) { // Initialize the lexer and list memory. curtok = 0; textptr = text; lexer(ln); return read_exp(); } void* read_exp() { char* tok = nexttok(); if (tok[0] == '(' && peektok()[0] == ')') { nexttok(); return NULL; } else if (tok[0] == '\'') return cons("quote", cons(read_exp(), NULL)); else if (tok[0] == '(') return read_list(); else return tok; } void* read_list() { char* tok = peektok(); if(tok[0] == ')') { nexttok(); return NULL; } else if(tok[0] == '.') { nexttok(); tok ...
First seen: 2025-10-06 15:06
Last seen: 2025-10-07 13:09