all repos — xyw @ 37343040403ae70fc12b1256e256eb26afb7ca07

A minimal virtual machine and assembler for terminals.

xywasm.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
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
#include <stdio.h>
#include "xyw.h"

#define TOKEN_MAX_LENGTH 32
#define DIRECTIVE_CONTENT_MAX_LENGTH 256
#define COMMENT_CONTENT_MAX_LENGTH 256
#define STRING_MAX_LENGTH 256

#define MODE_X 0x20
#define MODE_Y 0x40
#define MODE_W 0x80

#define error(msg) fprintf(stderr, "Error - %s [%s]\n", msg, ctx->file)
#define token_error(msg) fprintf(stderr, "Error - %s: %s [%s - Ln %d, Col %d]\n", token, msg, ctx->file, ctx->line, ctx->column)
#define symbol_error(symbol, msg) fprintf(stderr, "Error - %s: %s [%s - Ln %d, Col %d]\n", symbol, msg, ctx->file, ctx->line, ctx->column)

#define PSH 0x01

typedef struct
{
    int line;
    int column;
    char *file;
    FILE *fp;
} xyw_context;

typedef enum
{
    TOKEN_TYPE_UNKNOWN,
    TOKEN_TYPE_COMMENT,
    TOKEN_TYPE_DIRECTIVE,
    TOKEN_TYPE_NUMBER,
    TOKEN_TYPE_INSTRUCTION,
    TOKEN_TYPE_STRING,
    TOKEN_TYPE_SYMBOL
} xyw_token_type;

// Instruction mnemonics
static char instructions[][4] = {
    "BRK", "PSH", "POP", "NOT",
    "LDR", "STR", "LDD", "STD",
    "ILD", "LDI", "DLD", "LDD",
    "ADD", "SUB", "MUL", "DIV",
    "EQU", "NEQ", "GTH", "LTH",
    "AND", "IOR", "XOR", "SFT",
    "SWP", "DUP", "OVR", "ROT",
    "JMP", "JCN", "JSR", "RTS"};

// The token being processed
static char token[TOKEN_MAX_LENGTH];
static unsigned int token_length = 0;
static xyw_token_type token_type = TOKEN_TYPE_UNKNOWN;

// Directive identifier
static char directive[TOKEN_MAX_LENGTH];
static unsigned int directive_length = 0;

// Directive data
static char directive_data[DIRECTIVE_CONTENT_MAX_LENGTH];
static unsigned int directive_data_length = 0;

// Bytecode to be written
xyw_byte data[0xffff - 0x0100];

// Current write pointer
xyw_short ptr = 0x0100;

//// Utilities

static int strcmpn(const char *s1, const char *s2, unsigned int n)
{
    for (unsigned int i = 0; i < n; i++)
    {
        if (s1[i] != s2[i])
        {
            return s1[i] - s2[i];
        }
    }
    return 0;
}

void byte_to_binary(xyw_byte byte, char *str)
{
    int i;
    for (i = 7; i >= 0; i--)
    {
        str[7 - i] = ((byte >> i) & 1) ? '1' : '0';
    }
    str[8] = '\0';
}

static int validate_symbol(xyw_context *ctx, char *str, unsigned int length)
{
    // symbols must start with a letter or underscore,
    // and they can contain letters, numbers, underscores, dashes, or dots.
    if (!((str[0] >= 'A' && str[0] <= 'Z') || (str[0] >= 'a' && str[0] <= 'z') || str[0] == '_'))
    {
        symbol_error(str, "symbol must start with a letter or underscore");
        return -1;
    }
    for (unsigned int i = 1; i < length; i++)
    {
        char c = str[i];
        if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.'))
        {
            symbol_error(str, "symbol can only contain letters, numbers, underscores, dashes, or dots");
            return -1;
        }
    }
    return 0;
}

static void reset_directive()
{
    directive_length = 0;
    directive[0] = '\0';
    directive_data_length = 0;
    directive_data[0] = '\0';
}

// Write raw bytecode data
static inline void write(xyw_short val)
{
    if (val > 0xff)
    {
        data[ptr++] = val & 0xFF;
        data[ptr++] = (val >> 8) & 0xFF;
        return;
    }
    data[ptr++] = (xyw_byte)val;
}

// Encode a push instruction
static inline void push(xyw_short val)
{
    (val > 0xff) ? write(PSH | MODE_W) : write(PSH);
    write(val);
}

//// Processing functions

static int process_comment(xyw_context *ctx)
{
    char c;
    char comment_data[COMMENT_CONTENT_MAX_LENGTH];
    unsigned int comment_length = 0;
    reset_directive();
    // Process single-line comment
    while (fread(&c, 1, 1, ctx->fp) == 1)
    {
        if (c == '\n')
        {
            ctx->line++;
            ctx->column = 0;
            break;
        }
        ctx->column++;
        if (comment_length < COMMENT_CONTENT_MAX_LENGTH - 1)
        {
            comment_data[comment_length++] = c;
            comment_data[comment_length] = '\0';
        }
        else
        {
            token_error("Comment too long");
            return -1;
        }
    }
    // TODO: Remove
    printf("Comment:\t%s%s\n", token, comment_data);
    token_type = TOKEN_TYPE_COMMENT;
    return 0;
}

static int process_hex_number(xyw_context *ctx)
{
    // Token is a hex number starting with $
    xyw_short value = 0;
    for (unsigned int i = 1; i < token_length; i++)
    {
        char c = token[i];
        value <<= 4;
        if (c >= '0' && c <= '9')
        {
            value |= (c - '0');
        }
        else if (c >= 'A' && c <= 'F')
        {
            value |= (c - 'A' + 10);
        }
        else if (c >= 'a' && c <= 'f')
        {
            value |= (c - 'a' + 10);
        }
        else
        {
            token_error("Invalid hex digit");
            return -1;
        }
    }
    // TODO: Remove
    printf("Hex number:\t%s\t(%04X) [directive: %s]\n", token, value, directive_length > 0 ? directive : "N/A");
    token_type = TOKEN_TYPE_NUMBER;
    return 0;
}

static int process_binary_number(xyw_context *ctx)
{
    // Token is a binary number starting with %
    xyw_short value = 0;
    for (unsigned int i = 1; i < token_length; i++)
    {
        char c = token[i];
        value <<= 1;
        if (c == '0')
        {
            // do nothing
        }
        else if (c == '1')
        {
            value |= 1;
        }
        else
        {
            token_error("Invalid binary digit");
            return -1;
        }
    }
    // TODO: Remove
    printf("Binary number:\t%s\t(%04X) [directive: %s]\n", token, value, directive_length > 0 ? directive : "N/A");
    token_type = TOKEN_TYPE_NUMBER;
    return 0;
}

static int process_decimal_number(xyw_context *ctx)
{
    // Token is a decimal number (may or may not start with -)
    xyw_short value = 0;
    unsigned int start_index = 0;
    int is_negative = 0;
    if (token[0] == '-')
    {
        is_negative = 1;
        start_index = 1;
    }
    for (unsigned int i = start_index; i < token_length; i++)
    {
        char c = token[i];
        if (c >= '0' && c <= '9')
        {
            value = value * 10 + (c - '0');
        }
        else
        {
            token_error("Invalid decimal digit");
            return -1;
        }
    }
    if (is_negative)
    {
        value = -value;
    }
    // TODO: Remove
    printf("Decimal number:\t%s\t(%04X) [directive: %s]\n", token, value, directive_length > 0 ? directive : "N/A");
    token_type = TOKEN_TYPE_NUMBER;
    return 0;
}

static int process_instruction(xyw_context *ctx)
{
    (void)ctx;
    xyw_byte opcode = 0;
    // Match token against instruction mnemonics
    for (unsigned int i = 0; i < sizeof(instructions) / sizeof(instructions[0]); i++)
    {
        if (strcmpn(token, instructions[i], 3) == 0)
        {
            opcode = (xyw_byte)i;
            // There could be 0 to 3 modes (x y z) after the mnemonic in any order
            if (token_length > 3)
            {
                for (unsigned int j = 3; j < token_length; j++)
                {
                    char mode_char = token[j];
                    int mode_found = 0;
                    if (mode_char == 'x' || mode_char == 'X')
                    {
                        opcode |= MODE_X;
                        mode_found = 1;
                    }
                    else if (mode_char == 'y' || mode_char == 'Y')
                    {
                        opcode |= MODE_Y;
                        mode_found = 1;
                    }
                    else if (mode_char == 'w' || mode_char == 'W')
                    {
                        opcode |= MODE_W;
                        mode_found = 1;
                    }
                    if (!mode_found)
                    {
                        return -1;
                    }
                }
            }
            // TODO: Remove
            char bits[9];
            byte_to_binary(opcode, bits);
            printf("Instruction:\t%s\t(%02X - %s) [directive: %s]\n", token, opcode, bits, directive_length > 0 ? directive : "N/A");
            write(opcode);
            token_type = TOKEN_TYPE_INSTRUCTION;
            return 0;
        }
    }
    return -1;
}

static int process_string(xyw_context *ctx)
{
    (void)ctx;
    // Token is a string enclosed in double quotes
    // TODO: Remove
    printf("String:\t\t%s [directive: %s]\n", token, directive_length > 0 ? directive : "N/A");
    // TODO: Store string data
    token_type = TOKEN_TYPE_STRING;
    return 0;
}

static int process_symbol(xyw_context *ctx)
{
    if (validate_symbol(ctx, token, token_length) != 0)
    {
        return -1;
    }
    // TODO: Remove
    printf("Symbol:\t\t%s [directive: %s]\n", token, directive_length > 0 ? directive : "N/A");
    token_type = TOKEN_TYPE_SYMBOL;
    return 0;
}

// Returns: 1 token processed, 0 EOF, -1 error
static int next_token(xyw_context *ctx);

static int process_directive_label(xyw_context *ctx)
{
    int r = next_token(ctx);
    if (r != 1 || token_type != TOKEN_TYPE_SYMBOL)
    {
        token_error("Expected symbol after .label directive");
        return -1;
    }
    // TODO: store label info
    return 0;
}

static int process_directive(xyw_context *ctx)
{
    if (validate_symbol(ctx, token + 1, token_length - 1) != 0)
    {
        return -1;
    }
    directive_length = token_length;
    for (unsigned int i = 0; i < directive_length; i++)
    {
        directive[i] = token[i];
    }
    directive[directive_length] = '\0';
    // TODO: Remove
    printf("Directive:\t%s\n", token);
    token_type = TOKEN_TYPE_DIRECTIVE;
    // TODO: Process directive
    if (strcmpn(directive, ".label", 6) == 0)
    {
        return process_directive_label(ctx);
    }
    return 0;
}

// Process and validate tokens
static int process_token(xyw_context *ctx)
{
    if (token[0] == ';')
    {
        return process_comment(ctx);
    }
    else if (token[0] == '.')
    {
        return process_directive(ctx);
    }
    else if (token[0] == '$')
    {
        return process_hex_number(ctx);
    }
    else if (token[0] == '%')
    {
        return process_binary_number(ctx);
    }
    else if (token[0] == '\"')
    {
        return process_string(ctx);
    }
    else if ((token[0] >= '0' && token[0] <= '9') || token[0] == '-')
    {
        return process_decimal_number(ctx);
    }
    else if ((token[0] >= 'A' && token[0] <= 'Z') || (token[0] >= 'a' && token[0] <= 'z') || token[0] == '_')
    {
        if (process_instruction(ctx) == 0)
        {
            return 0;
        }
        return process_symbol(ctx);
    }
    token_error("Unrecognized token");
    return -1;
}

static int next_token(xyw_context *ctx)
{
    unsigned char c;
    token_length = 0;
    token[0] = '\0';
    int in_string = 0;

    while (fread(&c, 1, 1, ctx->fp) == 1)
    {
        if (!in_string && c == '\n')
        {
            if (token_length > 0)
            {
                if (process_token(ctx) != 0)
                    return -1;
                token_length = 0;
                token[0] = '\0';
                ctx->line++;
                ctx->column = 1;
                reset_directive();
                return 1;
            }
            ctx->line++;
            ctx->column = 1;
            reset_directive();
            continue;
        }
        if (!in_string && token_length == 0 && c == ';')
        {
            token[token_length++] = (char)c;
            token[token_length] = '\0';
            ctx->column++;
            if (process_token(ctx) != 0)
                return -1;
            token_length = 0;
            token[0] = '\0';
            return 1;
        }
        if (c == '"')
        {
            ctx->column++;
            if (!in_string)
            {
                in_string = 1;
                if (token_length < STRING_MAX_LENGTH - 1)
                {
                    token[token_length++] = (char)c;
                    token[token_length] = '\0';
                }
                else
                {
                    token_error("Token too long");
                    return -1;
                }
                continue;
            }
            else
            {
                if (token_length < STRING_MAX_LENGTH - 1)
                {
                    token[token_length++] = (char)c;
                    token[token_length] = '\0';
                }
                else
                {
                    token_error("Token too long");
                    return -1;
                }
                if (process_token(ctx) != 0)
                    return -1;
                token_length = 0;
                token[0] = '\0';
                in_string = 0;
                return 1;
            }
        }
        else if (in_string)
        {
            ctx->column++;
            if (token_length < STRING_MAX_LENGTH - 1)
            {
                token[token_length++] = (char)c;
                token[token_length] = '\0';
            }
            else
            {
                token_error("Token too long");
                return -1;
            }
            continue;
        }
        else if (c == ' ' || c == '\t')
        {
            if (token_length > 0)
            {
                if (process_token(ctx) != 0)
                    return -1;
                token_length = 0;
                token[0] = '\0';
                ctx->column++;
                return 1;
            }
            ctx->column++;
            continue;
        }
        else if (c > 0x20 && c != 0x7f)
        {
            ctx->column++;
            if (token_length < TOKEN_MAX_LENGTH - 1)
            {
                token[token_length++] = (char)c;
                token[token_length] = '\0';
                if (directive_length > 0)
                {
                    if (directive_data_length >= DIRECTIVE_CONTENT_MAX_LENGTH - 1)
                    {
                        token_error("Directive data too long");
                        return -1;
                    }
                    directive_data[directive_data_length++] = (char)c;
                    directive_data[directive_data_length] = '\0';
                }
            }
            else
            {
                token_error("Token too long");
                return -1;
            }
        }
        else
        {
            token_error("Invalid character encountered");
            return -1;
        }
    }
    if (token_length > 0)
    {
        if (process_token(ctx) != 0)
            return -1;
        token_length = 0;
        token[0] = '\0';
        return 1; // last token at EOF
    }
    return 0; // EOF no token
}

// Read a file and process its tokens
static int process_file(xyw_context *ctx)
{
    ctx->fp = fopen(ctx->file, "r");
    if (!ctx->fp)
    {
        error("Could not open file");
        return -1;
    }

    int r;
    while ((r = next_token(ctx)) == 1)
    {
        // tokens processed inline
    }
    fclose(ctx->fp);
    return r;
}

///// Public API

int xyw_assemble(const char *input, const char *output)
{
    xyw_context ctx;
    ctx.file = (char *)input;
    ctx.line = 1;
    ctx.column = 1;

    if (process_file(&ctx) != 0)
    {
        return -1;
    }

    (void)output; // TODO: write to output file
    return 0;
}