all repos — hex @ 9aaa768d8cc05714f8a0cab71bee46742aaab31d

A tiny, minimalist, slightly-esoteric concatenative programming lannguage.

src/main.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
#ifndef HEX_H
#include "hex.h"
#endif

// Read a file into a buffer
char *hex_read_file(hex_context_t *ctx, const char *filename)
{
    FILE *file = fopen(filename, "r");
    if (file == NULL)
    {
        hex_error(ctx, "Failed to open file: %s", filename);
        return NULL;
    }

    // Allocate an initial buffer
    int bufferSize = 1024; // Start with a 1 KB buffer
    char *content = (char *)malloc(bufferSize);
    if (content == NULL)
    {
        hex_error(ctx, "Memory allocation failed");
        fclose(file);
        return NULL;
    }

    int bytesReadTotal = 0;
    int bytesRead = 0;

    // Handle hashbang if present
    char hashbangLine[1024];
    if (fgets(hashbangLine, sizeof(hashbangLine), file) != NULL)
    {
        if (strncmp(hashbangLine, "#!", 2) != 0)
        {
            // Not a hashbang line, reset file pointer to the beginning
            fseek(file, 0, SEEK_SET);
            ctx->hashbang = 0;
        }
        else
        {
            ctx->hashbang = 1;
        }
    }

    while ((bytesRead = fread(content + bytesReadTotal, 1, bufferSize - bytesReadTotal, file)) > 0)
    {
        bytesReadTotal += bytesRead;

        // Resize the buffer if necessary
        if (bytesReadTotal == bufferSize)
        {
            bufferSize *= 2; // Double the buffer size
            char *temp = (char *)realloc(content, bufferSize);
            if (temp == NULL)
            {
                hex_error(ctx, "Memory reallocation failed");
                free(content);
                fclose(file);
                return NULL;
            }
            content = temp;
        }
    }

    if (ferror(file))
    {
        hex_error(ctx, "Error reading the file");
        free(content);
        fclose(file);
        return NULL;
    }

    // Null-terminate the content
    char *finalContent = (char *)realloc(content, bytesReadTotal + 1);
    if (finalContent == NULL)
    {
        hex_error(ctx, "Final memory allocation failed");
        free(content);
        fclose(file);
        return NULL;
    }
    content = finalContent;
    content[bytesReadTotal] = '\0';

    fclose(file);
    return content;
}

#if defined(__EMSCRIPTEN__) && defined(BROWSER)
static void prompt()
{
    // no prompt needed on browser
}
#elif defined(__EMSCRIPTEN__) && !defined(BROWSER)
static void prompt()
{
    printf(">\n");
}
#else
static void prompt()
{
    printf("> ");
    fflush(stdout);
}
#endif

#if defined(__EMSCRIPTEN__)
static void do_repl(void *v_ctx)
{
    hex_context_t *ctx = (hex_context_t *)v_ctx;
    prompt();
    char line[1024];
    char *p = line;
    p = em_fgets(line, 1024);
    if (!p)
    {
        printf("Error reading output");
        return;
    }
    // Normalize line endings (remove trailing \r\n or \n)
    line[strcspn(line, "\r\n")] = '\0';

    // Tokenize and process the input
    hex_interpret(ctx, line, "<repl>", 1, 1);
    // Print the top item of the stack
    if (ctx->stack.top >= 0)
    {
        hex_print_item(stdout, ctx->stack.entries[ctx->stack.top]);
        // hex_print_item(stdout, HEX_STACK[HEX_TOP]);
        printf("\n");
    }
    return;
}

#else

static int do_repl(void *v_ctx)
{
    hex_context_t *ctx = (hex_context_t *)v_ctx;
    char line[1024];
    prompt();
    if (fgets(line, sizeof(line), stdin) == NULL)
    {
        printf("\n"); // Handle EOF (Ctrl+D)
        return 1;
    }
    // Normalize line endings (remove trailing \r\n or \n)
    line[strcspn(line, "\r\n")] = '\0';

    // Tokenize and process the input
    hex_interpret(ctx, line, "<repl>", 1, 1);
    // Print the top item of the stack
    if (ctx->stack.top >= 0)
    {
        hex_print_item(stdout, ctx->stack.entries[ctx->stack.top]);
        // hex_print_item(stdout, HEX_STACK[HEX_TOP]);
        printf("\n");
    }
    return 0;
}

#endif

// REPL implementation
void hex_repl(hex_context_t *ctx)
{
#if defined(__EMSCRIPTEN__)
    printf("   _*_ _\n");
    printf("  / \\hex\\*\n");
    printf(" *\\_/_/_/  v%s - WASM Build\n", HEX_VERSION);
    printf("      *\n");
    int fps = 0;
    int simulate_infinite_loop = 1;
    emscripten_set_main_loop_arg(do_repl, ctx, fps, simulate_infinite_loop);
#else

    printf("   _*_ _\n");
    printf("  / \\hex\\*\n");
    printf(" *\\_/_/_/  v%s - Press Ctrl+C to exit.\n", HEX_VERSION);
    printf("      *\n");

    while (1)
    {
        if (do_repl(ctx) != 0)
        {
            exit(1);
        }
    }
#endif
}

void hex_handle_sigint(int sig)
{
    (void)sig; // Suppress unused warning
    printf("\n");
    exit(0);
}

// Process piped input from stdin
void hex_process_stdin(hex_context_t *ctx)
{

    char buffer[8192]; // Adjust buffer size as needed
    int bytesRead = fread(buffer, 1, sizeof(buffer) - 1, stdin);
    if (bytesRead == 0)
    {
        hex_error(ctx, "Error: No input provided via stdin.");
        return;
    }

    buffer[bytesRead] = '\0'; // Null-terminate the input
    hex_interpret(ctx, buffer, "<stdin>", 1, 1);
}

void hex_print_help()
{
    printf("   _*_ _\n"
           "  / \\hex\\*\n"
           " *\\_/_/_/  v%s - (c) 2024 Fabio Cevasco\n"
           "      *      \n",
           HEX_VERSION);
    printf("\n"
           "USAGE\n"
           "  hex [options] [file]\n"
           "\n"
           "ARGUMENTS\n"
           "  file            A .hex file to interpret\n"
           "\n"
           "OPTIONS\n"
           "  -d, --debug     Enable debug mode.\n"
           "  -h, --help      Display this help message.\n"
           "  -m, --manual    Display the manual.\n"
           "  -v, --version   Display hex version.\n\n");
}

void hex_print_docs(hex_doc_dictionary_t *docs)
{
    printf("\n"
           "   _*_ _\n"
           "  / \\hex\\*\n"
           " *\\_/_/_/  v%s - (c) 2024 Fabio Cevasco\n"
           "      *   \n",
           HEX_VERSION);
    printf("\n"
           "BASICS\n"
           "  hex is a minimalist, slightly-esoteric, concatenative programming language that supports\n"
           "  only integers, strings, symbols, and quotations (lists).\n"
           "\n"
           "  It uses a stack-based execution model and provides 64 native symbols for stack\n"
           "  manipulation, arithmetic operations, control flow, reading and writing\n"
           "  (standard input/output/error and files), executing external processes, and more.\n"
           "\n"
           "  Symbols and literals are separated by whitespace and can be grouped in quotations using\n"
           "  parentheses.\n"
           "\n"
           "  Symbols are evaluated only when they are pushed on the stack, therefore, symbols inside\n"
           "  quotations are not evaluated until the contents of the quotation are pushed on the stack.\n"
           "  You can define your own symbols using the symbol ':' and execute a quotation with '.'.\n"
           "\n"
           "  Oh, and of course all integers are in hexadecimal format! ;)\n"
           "\n"
           "SYMBOLS\n"
           "  +---------+----------------------------+-------------------------------------------------+\n"
           "  | Symbol  | Input -> Output            | Description                                     |\n"
           "  +---------+----------------------------+-------------------------------------------------+\n");
    for (int i = 0; i < docs->size; i++)
    {
        printf("  | ");
        hex_rpad(docs->entries[i].name, 7);
        printf(" | ");
        hex_lpad(docs->entries[i].input, 15);
        printf(" -> ");
        hex_rpad(docs->entries[i].output, 7);
        printf(" | ");
        hex_rpad(docs->entries[i].description, 47);
        printf(" |\n");
    }
    printf("  +---------+----------------------------+-------------------------------------------------+\n");
}

////////////////////////////////////////
// Main Program                       //
////////////////////////////////////////

int main(int argc, char *argv[])
{
    // Register SIGINT (Ctrl+C) signal handler
    signal(SIGINT, hex_handle_sigint);

    // Initialize the context
    hex_context_t ctx = hex_init();
    ctx.argc = argc;
    ctx.argv = argv;

    hex_register_symbols(&ctx);
    hex_create_docs(&ctx.docs);

    char *file;

    if (argc > 1)
    {
        for (int i = 1; i < argc; i++)
        {
            char *arg = strdup(argv[i]);
            if ((strcmp(arg, "-v") == 0 || strcmp(arg, "--version") == 0))
            {
                printf("%s\n", HEX_VERSION);
                return 0;
            }
            else if ((strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0))
            {
                hex_print_help();
                return 0;
            }
            else if ((strcmp(arg, "-m") == 0 || strcmp(arg, "--manual") == 0))
            {
                hex_print_docs(&ctx.docs);
                return 0;
            }
            else if ((strcmp(arg, "-d") == 0 || strcmp(arg, "--debug") == 0))
            {
                ctx.settings.debugging_enabled = 1;
                printf("*** Debug mode enabled ***\n");
            }
            else
            {
                file = arg;
            }
        }
        if (file)
        {
            char *fileContent = hex_read_file(&ctx, file);
            hex_interpret(&ctx, fileContent, file, 1 + ctx.hashbang, 1);
            return 0;
        }
    }
#if !(__EMSCRIPTEN__)
    if (!isatty(fileno(stdin)))
    {
        ctx.settings.stack_trace_enabled = 0;
        // Process piped input from stdin
        hex_process_stdin(&ctx);
    }
#endif
    else
    {
        ctx.settings.stack_trace_enabled = 0;
        // Start REPL
        hex_repl(&ctx);
    }

    return 0;
}