all repos — xyw @ 2600b9906e83561915446420ad28b34214c13889

A minimal virtual machine and assembler for terminals.

xyw.c

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
#include <stdio.h>
#include <string.h>
#include "xyw.h"

int xyw_debug = 0;

// Instruction mnemonics definition
const char xyw_instructions[][4] = {
    "BRK", "PSH", "POP", "CLR",
    "LDB", "LDW", "STB", "STW",
    "INC", "DEC", "SHL", "SHR",
    "ADD", "SUB", "MUL", "DIV",
    "EQU", "NEQ", "GTH", "LTH",
    "AND", "IOR", "XOR", "NOT",
    "SWP", "DUP", "OVR", "ROT",
    "JMP", "JCN", "JSR", "RTS"};


int main(int argc, char *argv[])
{
    (void)argc;
    for (int i = 1; i < argc; i++)
    {
        if (strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "--debug") == 0)
        {
            xyw_debug = 1;
        }
        else
        {
            const char *input_file = argv[i];
            char output_file[256];
            snprintf(output_file, sizeof(output_file), "%.*s.xim", (int)(strlen(input_file) - 4), input_file);
            const char *ext = strrchr(input_file, '.');
            if (ext && strcmp(ext, ".xyw") == 0)
            {
                if (xyw_assemble(input_file, output_file) != 0)
                {
                    fprintf(stderr, "Assembly failed for file: %s\n", input_file);
                    return -1;
                }
                else
                {
                    if (xyw_debug)
                    {
                        printf("Assembled %s to %s\n", input_file, output_file);
                    }
                }
            }
            else if (ext && strcmp(ext, ".xim") == 0)
            {
                if (xyw_run(input_file) != 0)
                {
                    fprintf(stderr, "Execution failed for file: %s\n", input_file);
                    return -1;
                }
            }
            else
            {
                fprintf(stderr, "Unsupported file type: %s\n", input_file);
                return -1;
            }
        }
    }
}