all repos — hex @ 31235ed67aea3e1fbc8864321876f824fbdd4454

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

hex.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
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
 1000
 1001
 1002
 1003
 1004
 1005
 1006
 1007
 1008
 1009
 1010
 1011
 1012
 1013
 1014
 1015
 1016
 1017
 1018
 1019
 1020
 1021
 1022
 1023
 1024
 1025
 1026
 1027
 1028
 1029
 1030
 1031
 1032
 1033
 1034
 1035
 1036
 1037
 1038
 1039
 1040
 1041
 1042
 1043
 1044
 1045
 1046
 1047
 1048
 1049
 1050
 1051
 1052
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#ifdef _WIN32
#include <windows.h>
#include <io.h>
int hex_isatty(int fd)
{
    HANDLE h = (HANDLE)_get_osfhandle(fd);
    return (GetFileType(h) == FILE_TYPE_CHAR);
}
#else
#include <unistd.h>
#endif

// Size of STDIN buffer (gets symbol)
#define HEX_STDIN_BUFFER_SIZE 256
// Global Registry for Variables
#define HEX_REGISTRY_SIZE 1024
// Stack Definition
#define HEX_STACK_SIZE 100

// Error function
void hex_error(const char *format, ...)
{
    va_list args;
    va_start(args, format);
    vfprintf(stderr, format, args);
    fprintf(stderr, "\n");
    va_end(args);
}

// Enum to represent the type of stack elements
typedef enum
{
    HEX_TYPE_INTEGER,
    HEX_TYPE_STRING,
    HEX_TYPE_QUOTATION,
    HEX_TYPE_FUNCTION
} HEX_ElementType;

// Unified Stack Element
typedef struct HEX_StackElement
{
    HEX_ElementType type;
    union
    {
        int intValue;
        char *strValue;
        int (*functionPointer)();
        struct HEX_StackElement **quotationValue;
    } data;
    char *symbolName;     // Symbol name (valid for HEX_TYPE_FUNCTION)
    size_t quotationSize; // Size of the quotation (valid for HEX_TYPE_QUOTATION)
} HEX_StackElement;

////////////////////////////////////////
// Registry Implementation            //
////////////////////////////////////////

// Registry Entry
typedef struct
{
    char *key;
    HEX_StackElement value;
} HEX_RegistryEntry;

HEX_RegistryEntry hex_registry[HEX_REGISTRY_SIZE];
int hex_dictCount = 0;

void hex_free_element(HEX_StackElement element);

int hex_valid_symbol(const char *symbol)
{
    // Check that key starts with a letter, or underscore
    // and subsequent characters (if any) are letters, numbers, or underscores
    if (strlen(symbol) == 0)
    {
        hex_error("Symbol name cannot be an empty string");
        return 1;
    }
    if (!isalpha(symbol[0]) && symbol[0] != '_')
    {
        hex_error("Invalid symbol name: %s", symbol);
        return 1;
    }
    for (int j = 1; j < strlen(symbol); j++)
    {
        if (!isalnum(symbol[j]) && symbol[j] != '_')
        {
            hex_error("Invalid symbol name: %s", symbol);
            return 1;
        }
    }
    return 0;
}

// Add a symbol to the registry
int hex_set_symbol(const char *key, HEX_StackElement value, int native)
{
    if (!native && hex_valid_symbol(key) != 0)
    {
        return 1;
    }
    for (int i = 0; i < hex_dictCount; i++)
    {
        if (strcmp(hex_registry[i].key, key) == 0)
        {
            if (hex_registry[i].value.type == HEX_TYPE_FUNCTION)
            {
                hex_error("Cannot overwrite native symbol %s", key);
                return 1;
            }
            free(hex_registry[i].key);
            hex_free_element(hex_registry[i].value);
            value.symbolName = strdup(key);
            hex_registry[i].key = strdup(key);
            hex_registry[i].value = value;
            return 0;
        }
    }

    if (hex_dictCount >= HEX_REGISTRY_SIZE)
    {
        hex_error("Registry overflow");
        return 1;
    }

    hex_registry[hex_dictCount].key = strdup(key);
    hex_registry[hex_dictCount].value = value;
    hex_dictCount++;
    return 0;
}

// Register a native symbol
void hex_register_symbol(const char *name, int (*func)())
{
    HEX_StackElement funcElement;
    funcElement.type = HEX_TYPE_FUNCTION;
    funcElement.data.functionPointer = func;
    funcElement.symbolName = strdup(name);

    if (hex_set_symbol(name, funcElement, 1) != 0)
    {
        hex_error("Error: Failed to register native symbol '%s'", name);
    }
}

// Get a symbol value from the registry
int hex_get_symbol(const char *key, HEX_StackElement *result)
{
    for (int i = 0; i < hex_dictCount; i++)
    {
        if (strcmp(hex_registry[i].key, key) == 0)
        {
            *result = hex_registry[i].value;
            return 1;
        }
    }
    return 0;
}

////////////////////////////////////////
// Stack Implementation               //
////////////////////////////////////////

HEX_StackElement hex_stack[HEX_STACK_SIZE];
int hex_top = -1;

// Push functions
int hex_push(HEX_StackElement element)
{
    if (hex_top >= HEX_STACK_SIZE - 1)
    {
        hex_error("Stack overflow");
        return 1;
    }
    hex_stack[++hex_top] = element;
    return 0;
}

int hex_push_int(int value)
{
    HEX_StackElement element = {.type = HEX_TYPE_INTEGER, .data.intValue = value};
    return hex_push(element);
}

int hex_push_string(const char *value)
{
    HEX_StackElement element = {.type = HEX_TYPE_STRING, .data.strValue = strdup(value)};
    return hex_push(element);
}

int hex_push_quotation(HEX_StackElement **quotation, size_t size)
{
    HEX_StackElement element = {.type = HEX_TYPE_QUOTATION, .data.quotationValue = quotation, .quotationSize = size};
    return hex_push(element);
}

int hex_push_symbol(const char *name)
{
    HEX_StackElement value;
    if (hex_get_symbol(name, &value))
    {
        if (value.type == HEX_TYPE_FUNCTION)
        {
            return value.data.functionPointer();
        }
        else
        {
            return hex_push(value);
        }
    }
    else
    {
        hex_error("Undefined symbol: %s", name);
        return 1;
    }
}

// Pop function
HEX_StackElement hex_pop()
{
    if (hex_top < 0)
    {
        hex_error("Insufficient elements on the stack");
    }
    return hex_stack[hex_top--];
}

// Free a stack element
void hex_free_element(HEX_StackElement element)
{
    if (element.type == HEX_TYPE_STRING)
    {
        free(element.data.strValue);
    }
    else if (element.type == HEX_TYPE_QUOTATION)
    {
        for (size_t i = 0; i < element.quotationSize; i++)
        {
            hex_free_element(*element.data.quotationValue[i]);
            free(element.data.quotationValue[i]);
        }
        free(element.data.quotationValue);
    }
}

////////////////////////////////////////
// Tokenizer Implementation           //
////////////////////////////////////////

// Token Types
typedef enum
{
    HEX_TOKEN_NUMBER,
    HEX_TOKEN_STRING,
    HEX_TOKEN_SYMBOL,
    HEX_TOKEN_QUOTATION_START,
    HEX_TOKEN_QUOTATION_END
} HEX_TokenType;

typedef struct
{
    HEX_TokenType type;
    char *value;
} HEX_Token;

// Process a token from the input
HEX_Token *hex_next_token(const char **input)
{
    const char *ptr = *input;

    // Skip whitespace and comments
    while (isspace(*ptr) || *ptr == ';')
    {
        if (*ptr == ';')
        {
            while (*ptr != '\0' && *ptr != '\n')
            {
                ptr++;
            }
        }
        ptr++;
    }

    if (*ptr == '\0')
    {
        return NULL; // End of input
    }

    HEX_Token *token = (HEX_Token *)malloc(sizeof(HEX_Token));
    token->value = NULL;

    if (*ptr == '"')
    {
        // String token
        ptr++;
        const char *start = ptr;
        size_t len = 0;

        while (*ptr != '\0')
        {
            if (*ptr == '\\' && *(ptr + 1) == '"')
            {
                ptr += 2;
                len++;
            }
            else if (*ptr == '"')
            {
                break;
            }
            else
            {
                ptr++;
                len++;
            }
        }

        if (*ptr != '"')
        {
            hex_error("Unterminated string");
        }

        token->value = (char *)malloc(len + 1);
        char *dst = token->value;

        ptr = start;
        while (*ptr != '\0' && *ptr != '"')
        {
            if (*ptr == '\\' && *(ptr + 1) == '"')
            {
                *dst++ = '"';
                ptr += 2;
            }
            else
            {
                *dst++ = *ptr++;
            }
        }
        *dst = '\0';
        ptr++;
        token->type = HEX_TOKEN_STRING;
    }
    else if (strncmp(ptr, "0x", 2) == 0 || strncmp(ptr, "0X", 2) == 0)
    {
        // Hexadecimal integer token
        const char *start = ptr;
        ptr += 2; // Skip the "0x" prefix
        while (isxdigit(*ptr))
        {
            ptr++;
        }
        size_t len = ptr - start;
        token->value = (char *)malloc(len + 1);
        strncpy(token->value, start, len);
        token->value[len] = '\0';
        token->type = HEX_TOKEN_NUMBER;
    }
    else if (*ptr == '(')
    {
        token->type = HEX_TOKEN_QUOTATION_START;
        ptr++;
    }
    else if (*ptr == ')')
    {
        token->type = HEX_TOKEN_QUOTATION_END;
        ptr++;
    }
    else
    {
        const char *start = ptr;
        while (*ptr != '\0' && !isspace(*ptr) && *ptr != ';')
        {
            ptr++;
        }
        size_t len = ptr - start;
        token->value = (char *)malloc(len + 1);
        strncpy(token->value, start, len);
        token->value[len] = '\0';
        token->type = HEX_TOKEN_SYMBOL;
    }

    *input = ptr;
    return token;
}

// Free a token
void hex_free_token(HEX_Token *token)
{
    if (token)
    {
        free(token->value);
        free(token);
    }
}

// Recursive quotation parsing
HEX_StackElement **hex_parse_quotation(const char **input, size_t *size)
{
    HEX_StackElement **quotation = NULL;
    size_t capacity = 2;
    *size = 0;

    quotation = (HEX_StackElement **)malloc(capacity * sizeof(HEX_StackElement *));
    if (!quotation)
    {
        hex_error("Memory allocation failed");
    }

    HEX_Token *token;
    while ((token = hex_next_token(input)) != NULL)
    {
        if (token->type == HEX_TOKEN_QUOTATION_END)
        {
            hex_free_token(token);
            break;
        }

        if (*size >= capacity)
        {
            capacity *= 2;
            quotation = (HEX_StackElement **)realloc(quotation, capacity * sizeof(HEX_StackElement *));
            if (!quotation)
            {
                hex_error("Memory allocation failed");
            }
        }

        HEX_StackElement *element = (HEX_StackElement *)malloc(sizeof(HEX_StackElement));
        if (token->type == HEX_TOKEN_NUMBER)
        {
            element->type = HEX_TYPE_INTEGER;
            element->data.intValue = (int)strtol(token->value, NULL, 16);
        }
        else if (token->type == HEX_TOKEN_STRING)
        {
            element->type = HEX_TYPE_STRING;
            element->data.strValue = strdup(token->value);
        }
        else if (token->type == HEX_TOKEN_QUOTATION_START)
        {
            element->type = HEX_TYPE_QUOTATION;
            element->data.quotationValue = hex_parse_quotation(input, &element->quotationSize);
        }
        else
        {
            hex_error("Unexpected token in quotation");
        }

        quotation[*size] = element;
        (*size)++;
        hex_free_token(token);
    }

    return quotation;
}

////////////////////////////////////////
// Helper Functions                   //
////////////////////////////////////////

char *hex_itoa(int num)
{
    static char str[20];
    int i = 0;
    int base = 16;

    // Handle 0 explicitly, otherwise empty string is printed
    if (num == 0)
    {
        str[i++] = '0';
        str[i] = '\0';
        return str;
    }

    // Process each digit
    while (num != 0)
    {
        int rem = num % base;
        str[i++] = (rem > 9) ? (rem - 10) + 'a' : rem + '0';
        num = num / base;
    }

    str[i] = '\0'; // Null-terminate string

    // Reverse the string
    int start = 0;
    int end = i - 1;
    while (start < end)
    {
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }

    return str;
}

void hex_print_element(FILE *stream, HEX_StackElement element)
{
    switch (element.type)
    {
    case HEX_TYPE_INTEGER:
        fprintf(stream, "0x%x", element.data.intValue);
        break;
    case HEX_TYPE_STRING:
        fprintf(stream, "\"%s\"", element.data.strValue);
        break;
    case HEX_TYPE_FUNCTION:
        fprintf(stream, element.symbolName);
        break;
    case HEX_TYPE_QUOTATION:
    {
        fprintf(stream, "(");
        for (size_t i = 0; i < element.quotationSize; i++)
        {
            if (i > 0)
                fprintf(stream, " "); // Add space between elements
            hex_print_element(stream, *element.data.quotationValue[i]);
        }
        fprintf(stream, ")");
        break;
    }
    default:
    }
}

int hex_is_symbol(HEX_Token *token, char *value)
{
    return strcmp(token->value, value) == 0;
}

////////////////////////////////////////
// Native Symbol Implementations      //
////////////////////////////////////////

int hex_symbol_store()
{
    HEX_StackElement name = hex_pop();
    HEX_StackElement value = hex_pop();
    if (name.type != HEX_TYPE_STRING)
    {
        hex_error("Variable name must be a string");
        return 1;
    }
    if (hex_set_symbol(name.data.strValue, value, 0))
    {
        hex_error("Failed to store variable");
        return 1;
    }
    hex_free_element(name);
    return 0;
}

// IO Symbols

int hex_symbol_puts()
{
    HEX_StackElement element = hex_pop();
    hex_print_element(stdout, element);
    printf("\n");
    hex_free_element(element);
    return 0;
}

int hex_symbol_warn()
{
    HEX_StackElement element = hex_pop();
    hex_print_element(stderr, element);
    printf("\n");
    hex_free_element(element);
    return 0;
}

int hex_symbol_print()
{
    HEX_StackElement element = hex_pop();
    hex_print_element(stdout, element);
    hex_free_element(element);
    return 0;
}

int hex_symbol_gets()
{
    char input[HEX_STDIN_BUFFER_SIZE]; // Buffer to store the input (adjust size if needed)

    if (fgets(input, sizeof(input), stdin) != NULL)
    {
        // Strip the newline character at the end of the string
        input[strcspn(input, "\n")] = '\0';

        // Push the input string onto the stack
        return hex_push_string(input);
    }
    else
    {
        hex_error("Failed to read input");
        return 1;
    }
}

// Mathematical symbols
int hex_symbol_add()
{
    HEX_StackElement b = hex_pop();
    HEX_StackElement a = hex_pop();
    int result = 0;
    if (a.type == HEX_TYPE_INTEGER && b.type == HEX_TYPE_INTEGER)
    {
        result = hex_push_int(a.data.intValue + b.data.intValue);
    }
    else
    {
        hex_error("'+' symbol requires two integers");
        result = 1;
    }
    hex_free_element(a);
    hex_free_element(b);
    return result;
}

int hex_symbol_subtract()
{
    HEX_StackElement b = hex_pop();
    HEX_StackElement a = hex_pop();
    int result = 0;
    if (a.type == HEX_TYPE_INTEGER && b.type == HEX_TYPE_INTEGER)
    {
        result = hex_push_int(a.data.intValue - b.data.intValue);
    }
    else
    {
        hex_error("'-' symbol requires two integers");
        result = 1;
    }
    hex_free_element(a);
    hex_free_element(b);
    return result;
}

int hex_symbol_multiply()
{
    HEX_StackElement b = hex_pop();
    HEX_StackElement a = hex_pop();
    int result = 0;
    if (a.type == HEX_TYPE_INTEGER && b.type == HEX_TYPE_INTEGER)
    {
        result = hex_push_int(a.data.intValue * b.data.intValue);
    }
    else
    {
        hex_error("'*' symbol requires two integers");
    }
    hex_free_element(a);
    hex_free_element(b);
    return result;
}

int hex_symbol_divide()
{
    HEX_StackElement b = hex_pop();
    HEX_StackElement a = hex_pop();
    int result = 0;
    if (a.type == HEX_TYPE_INTEGER && b.type == HEX_TYPE_INTEGER)
    {
        if (b.data.intValue == 0)
        {
            hex_error("Division by zero");
        }
        result = hex_push_int(a.data.intValue / b.data.intValue);
    }
    else
    {
        hex_error("'/' symbol requires two integers");
        result = 1;
    }
    hex_free_element(a);
    hex_free_element(b);
    return result;
}

// Bit symbols

int hex_symbol_bitand()
{
    HEX_StackElement right = hex_pop(); // Pop the second operand
    HEX_StackElement left = hex_pop();  // Pop the first operand
    int result = 0;
    if (left.type == HEX_TYPE_INTEGER && right.type == HEX_TYPE_INTEGER)
    {
        int value = left.data.intValue & right.data.intValue; // Bitwise AND
        result = hex_push_int(value);                         // Push the result back onto the stack
    }
    else
    {
        hex_error("Bitwise AND requires two integers");
        result = 1;
    }
    hex_free_element(left);
    hex_free_element(right);
    return result;
}

int hex_symbol_bitor()
{
    HEX_StackElement right = hex_pop();
    HEX_StackElement left = hex_pop();
    int result = 0;
    if (left.type == HEX_TYPE_INTEGER && right.type == HEX_TYPE_INTEGER)
    {
        int value = left.data.intValue | right.data.intValue; // Bitwise OR
        result = hex_push_int(value);
    }
    else
    {
        hex_error("Bitwise OR requires two integers");
        result = 1;
    }
    hex_free_element(left);
    hex_free_element(right);
    return result;
}

int hex_symbol_bitxor()
{
    HEX_StackElement right = hex_pop();
    HEX_StackElement left = hex_pop();
    int result = 0;
    if (left.type == HEX_TYPE_INTEGER && right.type == HEX_TYPE_INTEGER)
    {
        int value = left.data.intValue ^ right.data.intValue; // Bitwise XOR
        result = hex_push_int(value);
    }
    else
    {
        hex_error("Bitwise XOR requires two integers");
        result = 1;
    }
    hex_free_element(left);
    hex_free_element(right);
    return result;
}

int hex_symbol_shiftleft()
{
    HEX_StackElement right = hex_pop(); // The number of positions to shift
    HEX_StackElement left = hex_pop();  // The value to shift
    int result = 0;
    if (left.type == HEX_TYPE_INTEGER && right.type == HEX_TYPE_INTEGER)
    {
        int value = left.data.intValue << right.data.intValue; // Left shift
        result = hex_push_int(value);
    }
    else
    {
        hex_error("Left shift requires two integers");
        result = 1;
    }
    hex_free_element(left);
    hex_free_element(right);
    return result;
}

int hex_symbol_shiftright()
{
    HEX_StackElement right = hex_pop(); // The number of positions to shift
    HEX_StackElement left = hex_pop();  // The value to shift
    int result = 0;
    if (left.type == HEX_TYPE_INTEGER && right.type == HEX_TYPE_INTEGER)
    {
        int value = left.data.intValue >> right.data.intValue; // Right shift
        result = hex_push_int(value);
    }
    else
    {
        hex_error("Right shift requires two integers");
        result = 1;
    }
    hex_free_element(left);
    hex_free_element(right);
    return result;
}

int hex_symbol_bitnot()
{
    HEX_StackElement element = hex_pop(); // Only one operand for bitwise NOT
    int result = 0;
    if (element.type == HEX_TYPE_INTEGER)
    {
        int value = ~element.data.intValue; // Bitwise NOT (complement)
        result = hex_push_int(value);
    }
    else
    {
        hex_error("Bitwise NOT requires one integer");
        result = 1;
    }
    hex_free_element(element);
    return result;
}

// Conversion symbols

int hex_symbol_int()
{
    HEX_StackElement a = hex_pop();
    int result = 0;
    if (a.type == HEX_TYPE_QUOTATION)
    {
        hex_error("Cannot convert a quotation to an integer");
        result = 1;
    }
    else if (a.type == HEX_TYPE_INTEGER)
    {
        result = hex_push_int(a.data.intValue);
    }
    else if (a.type == HEX_TYPE_STRING)
    {
        result = hex_push_int(strtol(a.data.strValue, NULL, 16));
    }
    hex_free_element(a);
    return result;
}

int hex_symbol_str()
{
    HEX_StackElement a = hex_pop();
    int result = 0;
    if (a.type == HEX_TYPE_QUOTATION)
    {
        hex_error("Cannot convert a quotation to a string");
        result = 1;
    }
    else if (a.type == HEX_TYPE_INTEGER)
    {
        result = hex_push_string(hex_itoa(a.data.intValue));
    }
    else if (a.type == HEX_TYPE_STRING)
    {
        result = hex_push_string(a.data.strValue);
    }
    hex_free_element(a);
    return result;
}

////////////////////////////////////////
// Native Symbol Registration         //
////////////////////////////////////////

void hex_register_symbols()
{
    hex_register_symbol("store", hex_symbol_store);
    hex_register_symbol("puts", hex_symbol_puts);
    hex_register_symbol("warn", hex_symbol_warn);
    hex_register_symbol("print", hex_symbol_print);
    hex_register_symbol("gets", hex_symbol_gets);
    hex_register_symbol("+", hex_symbol_add);
    hex_register_symbol("-", hex_symbol_subtract);
    hex_register_symbol("*", hex_symbol_multiply);
    hex_register_symbol("/", hex_symbol_divide);
    hex_register_symbol("&", hex_symbol_bitand);
    hex_register_symbol("|", hex_symbol_bitor);
    hex_register_symbol("^", hex_symbol_bitxor);
    hex_register_symbol("~", hex_symbol_bitnot);
    hex_register_symbol("<<", hex_symbol_shiftleft);
    hex_register_symbol(">>", hex_symbol_shiftright);
    hex_register_symbol("int", hex_symbol_int);
    hex_register_symbol("str", hex_symbol_str);
}

////////////////////////////////////////
// Hex Interpreter Implementation     //
////////////////////////////////////////

int hex_interpret(const char *code)
{
    const char *input = code;
    HEX_Token *token;

    while ((token = hex_next_token(&input)) != NULL)
    {
        if (token->type == HEX_TOKEN_NUMBER)
        {
            if (hex_push_int((int)strtol(token->value, NULL, 16)) != 0)
            {
                hex_free_token(token);
                return 1;
            }
        }
        else if (token->type == HEX_TOKEN_STRING)
        {
            HEX_StackElement symbolValue;
            if (hex_get_symbol(token->value, &symbolValue))
            {
                if (hex_push(symbolValue) != 0)
                {
                    hex_free_token(token);
                    return 1;
                }
            }
            else
            {
                if (hex_push_string(token->value) != 0)
                {
                    hex_free_token(token);
                    return 1;
                }
            }
        }
        else if (token->type == HEX_TOKEN_SYMBOL)
        {
            if (hex_push_symbol(token->value) != 0)
            {
                hex_free_token(token);
                return 1;
            }
        }
        else if (token->type == HEX_TOKEN_QUOTATION_START)
        {
            size_t quotationSize;
            HEX_StackElement **quotation = hex_parse_quotation(&input, &quotationSize);
            if (hex_push_quotation(quotation, quotationSize) != 0)
            {
                hex_free_token(token);
                return 1;
            }
        }
        hex_free_token(token);
    }
}

// Read a file into a buffer
char *hex_read_file(const char *filename)
{
    FILE *file = fopen(filename, "r");
    if (!file)
    {
        hex_error("Could not open file: %s", filename);
        exit(1);
    }

    fseek(file, 0, SEEK_END);
    long length = ftell(file);
    fseek(file, 0, SEEK_SET);

    char *buffer = (char *)malloc(length + 1);
    if (!buffer)
    {
        hex_error("Memory allocation failed");
    }

    fread(buffer, 1, length, file);
    buffer[length] = '\0';
    fclose(file);
    return buffer;
}

volatile sig_atomic_t hex_keep_running = 1;

// REPL implementation
void hex_repl()
{
    char line[1024];
    printf("hex Interactive REPL. Type 'exit' to quit or press Ctrl+C.\n");

    while (hex_keep_running)
    {
        printf("> "); // Prompt
        if (fgets(line, sizeof(line), stdin) == NULL)
        {
            printf("\n"); // Handle EOF (Ctrl+D)
            break;
        }

        // Normalize line endings (remove trailing \r\n or \n)
        line[strcspn(line, "\r\n")] = '\0';

        // Exit command
        if (strcmp(line, "exit") == 0)
        {
            break;
        }

        // Tokenize and process the input
        hex_interpret(line);
    }
}

void hex_handle_sigint(int sig)
{
    (void)sig; // Suppress unused warning
    hex_keep_running = 0;
    printf("\nExiting hex REPL. Goodbye!\n");
}

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

    buffer[bytesRead] = '\0'; // Null-terminate the input
    hex_interpret(buffer);
}

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

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

    hex_register_symbols();

    if (argc == 2)
    {
        // Process a file
        const char *filename = argv[1];
        char *fileContent = hex_read_file(filename);
        if (!fileContent)
        {
            return 1;
        }

        hex_interpret(fileContent);
        free(fileContent); // Free the allocated memory
    }
    else if (!hex_isatty(fileno(stdin)))
    {
        // Process piped input from stdin
        hex_process_stdin();
    }
    else
    {
        // Start REPL
        hex_repl();
    }

    return 0;
}