Files
equi/equi.c
T
2022-08-08 11:07:24 +03:00

473 lines
12 KiB
C

/*
* Equi platform reference implementation
*
* Created in 2022 by Luxferre, released into public domain
*
* See equi.md file for the specification and manual
*
* @license Unlicense <https://unlicense.org>
* @author Luxferre
*/
/* Standard includes with size optimizations for TCC */
#ifdef __TINYC__
#include <tcclib.h>
#define stderr 2
#else
#include <stdlib.h>
#include <stdio.h>
#endif
/*
* Non-standard includes
* To save space, we emulate necessary conio functions on non-6502 systems, not vice versa
*/
#ifdef __CC65__
#include <conio.h>
#else
#define cgetc() (getchar())
#define cputc(c) (putchar(c))
#endif
/* Definitions section */
#define EQUI_VER "0.0.1"
#define cerr(s) (fputs(s, stderr))
#define ushort unsigned short /* basic 16-bit integer */
#define uchar unsigned char /* basic 8-bit integer */
#define WS sizeof(ushort) /* Equi word size in bytes */
#define CLT_ENTRY_LEN 6u /* Amount of significant compiled word characters */
#define CLT_ENTRY_SIZE (CLT_ENTRY_LEN + WS) /* Full size in bytes taken by one CLT entry */
#define BS 8u /* Backspace character code */
#define CR 13u /* Character return code */
/* Configuration section (constants overridable at compile-time) */
/* Main and return stack size in bytes */
#ifndef STACK_SIZE
#define STACK_SIZE 256u
#endif
/* Literal stack size in bytes */
#ifndef LIT_STACK_SIZE
#define LIT_STACK_SIZE 32u
#endif
/* Command buffer size in bytes */
#ifndef GPD_AREA_SIZE
#define GPD_AREA_SIZE 6400u
#endif
/* Command buffer size in bytes */
#ifndef CMD_BUF_SIZE
#define CMD_BUF_SIZE 15600u
#endif
/* Maximum amount of CLT entries */
#ifndef CLT_ENTRIES_MAX
#define CLT_ENTRIES_MAX 512u
#endif
/* Some necessary constants and offsets derived from the above values */
#define STACK_SIZE_WORDS (STACK_SIZE / WS) /* Main and return stack size in words */
/*
* Structures that describe Equi machine RAM using the above configuration
*/
struct CLTEntry {
uchar name[CLT_ENTRY_LEN]; /* compiled word name */
ushort loc; /* compiled word location */
};
struct EquiRAM {
ushort main_stack[STACK_SIZE_WORDS];
ushort return_stack[STACK_SIZE_WORDS];
uchar literal_stack[LIT_STACK_SIZE];
ushort pc; /* program counter */
ushort msp; /* main stack pointer */
ushort rsp; /* return stack pointer */
uchar lsp; /* literal stack pointer */
ushort cbp; /* compilation buffer pointer */
ushort cltp; /* compilation lookup table pointer */
unsigned int II:1; /* instruction ignore mode */
unsigned int CM:1; /* compilation mode */
unsigned int IM:1; /* interpretation mode */
ushort gpd_start;
ushort cmd_start;
ushort cmd_size;
ushort ibp; /* input buffer pointer */
struct CLTEntry clt[CLT_ENTRIES_MAX]; /* compilation lookup table */
uchar gpd[GPD_AREA_SIZE];
uchar cmdbuf[CMD_BUF_SIZE];
};
/* Before running the main code, instantiate the machine RAM */
static struct EquiRAM ram;
/* Also create an alternative view of the same RAM area for direct offset-based access */
static uchar* flatram = (uchar *)&ram;
/* Error reporting codes */
enum EquiErrors {
SUCCESS=0,
STACK_OVERFLOW,
STACK_UNDERFLOW,
DIV_BY_ZERO,
CLT_OVERFLOW,
CMD_OVERFLOW,
INVALID_INSTRUCTION,
PORT_IO_ERROR
};
/* Error reporting method */
void trapout(errcode) {
if(errcode > 0) {
fprintf(stderr, "Error %d at 0x%x (instruction %c): ", errcode, ram.pc, ram.cmdbuf[ram.pc]);
switch(errcode) {
case STACK_OVERFLOW:
cerr("Stack overflow");
break;
case STACK_UNDERFLOW:
cerr("Stack underflow");
break;
case DIV_BY_ZERO:
cerr("Division by zero");
break;
case CLT_OVERFLOW:
cerr("Compilation lookup table full");
break;
case CMD_OVERFLOW:
cerr("Command buffer full");
break;
case INVALID_INSTRUCTION:
cerr("Invalid instruction");
break;
case PORT_IO_ERROR:
cerr("Port I/O error");
break;
}
exit(errcode);
}
}
/* Equi instructions enum */
enum EquiInstructions {
INS_IISTART='(',
INS_IIEND=')',
INS_CMSTART=':',
INS_CMEND=';',
INS_LITINT='#',
INS_LITSTR='"',
INS_LITCALL='\'',
INS_RET='R',
INS_M2R=']', /* main -> return */
INS_R2M='[', /* return -> main */
INS_LOAD='L',
INS_STORE='S',
INS_STOREBYTE='W',
INS_DROP='!',
INS_DUP='$',
INS_SWAP='%',
INS_ROT='@',
INS_OVER='\\',
INS_JUMP='J',
INS_IF='I',
INS_EXPOINT='X', /* locate execution point */
INS_GT='>',
INS_LT='<',
INS_EQ='=',
INS_ADD='+',
INS_SUB='-',
INS_MUL='*',
INS_DIV='/',
INS_NEG='N',
INS_NOT='~',
INS_AND='&',
INS_OR='|',
INS_XOR='^',
INS_COUT='.',
INS_NBKIN=',', /* non-blocking key input */
INS_BKIN='?', /* blocking key input */
INS_PORTIO='P',
INS_PERSIST_WRITE='}',
INS_PERSIST_READ='{',
INS_QUIT='Q'
};
/* push a value onto the main stack */
void pushMain(ushort val) {
ram.main_stack[ram.msp++] = val;
if(ram.msp >= STACK_SIZE_WORDS)
trapout(STACK_OVERFLOW);
}
/* push a value onto the return stack */
void pushRet(ushort val) {
ram.return_stack[ram.rsp++] = val;
if(ram.rsp >= STACK_SIZE_WORDS)
trapout(STACK_OVERFLOW);
}
/* pop a value from the main stack */
ushort popMain() {
if(ram.msp == 0)
trapout(STACK_UNDERFLOW);
else
return ram.main_stack[--ram.msp];
}
/* pop a value from the return stack */
ushort popRet() {
if(ram.rsp == 0)
trapout(STACK_UNDERFLOW);
else
return ram.return_stack[--ram.rsp];
}
/* push a character to the literal stack, auto-discarding overflown items */
void pushLit(uchar c) {
ram.literal_stack[ram.lsp++] = c;
if(ram.lsp >= LIT_STACK_SIZE)
ram.lsp = 0;
}
/* pop a character from the literal stack */
uchar popLit() {
if(ram.lsp == 0)
trapout(STACK_UNDERFLOW);
else
return ram.literal_stack[--ram.lsp];
}
/* clear the literal stack */
void clearLit() {
ram.lsp = 0; /* clear the literal stack */
}
/* shape 2-byte vlaue on the main stack from the 4 values of the literal stack */
void pushLitVal(strict) {
uchar p1, p2, p3, p4;
if(ram.lsp < 4) { /* if we don't strictly expect 4 bytes, do nothing */
if(strict) trapout(STACK_UNDERFLOW);
else {
ram.lsp = 0; /* clear the literal stack */
return;
}
}
else {
p4 = popLit();
p3 = popLit();
p2 = popLit();
p1 = popLit();
pushMain((p1<<12) | (p2<<8) | (p3<<4) | p4);
ram.lsp = 0; /* clear the literal stack */
}
}
/* Main interpreter loop */
void equi_main_loop() {
uchar instr, i;
/* reset all stacks before running and reinit CLT */
ram.msp = ram.rsp = ram.lsp = ram.cltp = 0;
/* reset pc */
ram.pc = 65535;
while(1) { /* iterate over the instructions in the command buffer */
instr = ram.cmdbuf[++ram.pc];
/* first, check for II mode */
if(ram.II) {
if(instr == INS_IIEND)
ram.II = 0; /* unset instruction ignore mode flag */
continue;
}
/* then, check for compilation mode */
if(ram.CM) {
if(instr == INS_CMEND) { /* trigger word compilation logic as per the spec */
ram.cmdbuf[ram.pc] = INS_RET; /* in-place patch this instruction to R */
/* compiled words are saved vice versa to save code size */
for(i=0;i<CLT_ENTRY_LEN;++i)
ram.clt[ram.cltp].name[i] = popLit();
ram.lsp = 0; /* clear the literal stack */
ram.clt[ram.cltp].loc = ram.cbp; /* stored the compiled code location from the most recent CBP value */
++ram.cltp; /* increase the word */
if(ram.cltp == CLT_ENTRIES_MAX) {
trapout(CLT_OVERFLOW);
break;
}
ram.CM = 0; /* unset compilation mode flag */
}
continue;
}
/* other than that, continue with interpretation mode */
/* first, detect lowercase, underscore, digit and A to F */
if((instr >= '0' && instr <= '9') || (instr >= 'A' && instr <= 'F') || instr == '_' || (instr >= 'a' && instr <= 'z')) {
pushLit(instr);
continue;
}
/* then trigger literal auto-push if applicable */
if(ram.lsp > 0 && instr != INS_LITSTR && instr != INS_LITCALL && instr != INS_LITINT && instr != INS_CMSTART)
pushLitVal(0);
switch(instr) { /* then perform all main interpretation logic */
case INS_IISTART: /* instruction ignore start */
ram.II = 1; /* raise II flag */
break;
case INS_CMSTART: /* compilation start */
ram.cbp = ram.pc + 1; /* save CBP */
ram.CM = 1; /* raise CM flag */
break;
case INS_QUIT: /* gracefully quit the interpretation mode */
goto brx;
case INS_LITINT: /* literal stack -> main stack as short */
pushLitVal(1);
break;
case INS_LITSTR:
break;
case INS_LITCALL:
break;
case INS_RET:
ram.pc = popRet();
break;
case INS_M2R:
break;
case INS_R2M:
break;
case INS_LOAD:
break;
case INS_STORE:
break;
case INS_STOREBYTE:
break;
case INS_DROP:
break;
case INS_DUP:
break;
case INS_SWAP:
break;
case INS_ROT:
break;
case INS_OVER:
break;
case INS_JUMP:
break;
case INS_IF:
break;
case INS_EXPOINT: /* Locate execution point */
pushMain(ram.pc + 1);
break;
case INS_GT:
break;
case INS_LT:
break;
case INS_EQ:
break;
case INS_ADD:
break;
case INS_SUB:
break;
case INS_MUL:
break;
case INS_DIV:
break;
case INS_NEG:
break;
case INS_NOT:
break;
case INS_AND:
break;
case INS_OR:
break;
case INS_XOR:
break;
case INS_COUT:
break;
case INS_NBKIN:
case INS_BKIN:
break;
case INS_PORTIO:
break;
case INS_PERSIST_READ:
break;
case INS_PERSIST_WRITE:
break;
default: /* all characters not processed before are invalid instructions */
trapout(INVALID_INSTRUCTION);
goto brx;
}
continue;
brx: break;
}
/* unset interpretation mode flag and exit */
ram.IM = 0;
}
/* Equi VM entry point */
int main(int argc, char* argv[]) {
/* _attempt_ to disable buffering for char input/output */
#if !defined __CC65__ && !defined __TINYC__
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
#endif
uchar instr;
/* initialize the RAM in the most standard way */
ram.gpd_start = (uchar *)&ram.gpd - (uchar *)&ram.main_stack;
ram.cmd_start = (uchar *)&ram.cmdbuf - (uchar *)&ram.main_stack;
ram.cmd_size = CMD_BUF_SIZE;
ram.II = ram.CM = ram.IM = 0; /* reset all flags */
/* Start both execution and input buffering from the start of command buffer (-1 because we use prefix increment) */
ram.pc = ram.ibp = ram.cmd_start-1;
printf("Welcome to Equi v" EQUI_VER " by Luxferre, 2022\n\nCLT: 0x%X (%d bytes)\nGPD: 0x%X (%d bytes)\nCommand buffer: 0x%X (%d bytes)\nEqui ready\n\n",
(uchar *)&ram.clt - (uchar *)&ram.main_stack,
(uchar *)&ram.gpd - (uchar *)&ram.clt,
ram.gpd_start,
ram.cmd_start - ram.gpd_start,
ram.cmd_start, ram.cmd_size);
cputc('>');
cputc(' ');
while(1) { /* Now, we're in the command mode loop */
instr = ram.cmdbuf[++ram.ibp] = cgetc(); /* Fetch the next instruction from the keyboard */
if(instr == BS && ram.ibp > ram.cmd_start) { /* process the backspace */
#ifdef __CC65__
cputc(instr); /* echo it */
#endif
--ram.ibp;
} else if(instr == INS_IISTART) { /* process II just to avoid quitting in command mode */
#ifdef __CC65__
cputc(instr); /* echo it */
#endif
ram.II = 1;
} else if(instr == INS_IIEND) { /* process II just to avoid quitting in command mode */
#ifdef __CC65__
cputc(instr); /* echo it */
#endif
ram.II = 0;
} else if(instr == CR) { /* process carriage return */
cputc(CR); /* echo it */
#ifdef __CC65__
cputc(10); /* echo it */
#endif
ram.IM = 1; /* set the mandatory interpretation mode flag */
equi_main_loop(); /* and run the interpreter loop */
cputc(CR); /* echo it */
#ifdef __CC65__
cputc(10); /* echo it */
#endif
cputc('>');
cputc(' ');
}
#ifdef __CC65__
else cputc(instr); /* echo it */
#endif
} /* command mode loop end */
return 0;
}