From 3972edb455faaff347bb10e41d5b3250bebf5dc7 Mon Sep 17 00:00:00 2001 From: Cameron Reikes Date: Sun, 3 Sep 2023 14:44:42 -0700 Subject: [PATCH] Remove MD_ prefix from almost everything --- codegen.c | 134 +- main.c | 896 ++++++----- makeprompt.h | 170 +- ser.h | 32 +- thirdparty/md.c | 2980 +++++++++++++++++------------------ thirdparty/md.h | 1284 +++++++-------- thirdparty/md_stb_sprintf.h | 6 +- todo.txt | 1 - 8 files changed, 2747 insertions(+), 2756 deletions(-) diff --git a/codegen.c b/codegen.c index 85f93b4..5da17d4 100644 --- a/codegen.c +++ b/codegen.c @@ -17,22 +17,22 @@ #pragma warning(disable : 4244) // loss of data warning #pragma warning(disable : 4101) // unreferenced local variable #define STBSP_ADD_TO_FUNCTIONS no_ubsan -#define MD_FUNCTION no_ubsan +#define FUNCTION no_ubsan #include "md.h" #include "md.c" #pragma warning(pop) -void dump(MD_Node* from) { - printf("/ %.*s\n", MD_S8VArg(from->string)); +void dump(Node* from) { + printf("/ %.*s\n", S8VArg(from->string)); int d = 0; - for (MD_EachNode(child, from->first_child)) + for (EachNode(child, from->first_child)) { - printf("|-- Child %d Tag [%.*s] string[%.*s] first child string[%.*s]\n", d, MD_S8VArg(child->first_tag->string), MD_S8VArg(child->string), MD_S8VArg(child->first_child->string)); + printf("|-- Child %d Tag [%.*s] string[%.*s] first child string[%.*s]\n", d, S8VArg(child->first_tag->string), S8VArg(child->string), S8VArg(child->first_child->string)); d += 1; } } -bool has_decimal(MD_String8 s) +bool has_decimal(String8 s) { for (int i = 0; i < s.size; i++) { @@ -41,24 +41,24 @@ bool has_decimal(MD_String8 s) return false; } -MD_Arena *cg_arena = NULL; +Arena *cg_arena = NULL; -#define S8(s) MD_S8Lit(s) -#define S8V(s) MD_S8VArg(s) +#define S8(s) S8Lit(s) +#define S8V(s) S8VArg(s) -MD_String8 ChildValue(MD_Node *n, MD_String8 name) { - MD_Node *child_with_value = MD_ChildFromString(n, name, 0); +String8 ChildValue(Node *n, String8 name) { + Node *child_with_value = MD_ChildFromString(n, name, 0); assert(child_with_value); - assert(!MD_NodeIsNil(child_with_value->first_child)); // MD_S8Lit("Must have child")); + assert(!NodeIsNil(child_with_value->first_child)); // S8Lit("Must have child")); return child_with_value->first_child->string; } -MD_String8 asset_file_path(MD_String8 filename) { - return MD_S8Fmt(cg_arena, "%.*s/%.*s", MD_S8VArg(S8("assets")), MD_S8VArg(filename)); +String8 asset_file_path(String8 filename) { + return S8Fmt(cg_arena, "%.*s/%.*s", S8VArg(S8("assets")), S8VArg(filename)); } -char *nullterm(MD_String8 s) { - char *to_return = MD_ArenaPush(cg_arena, s.size + 1); +char *nullterm(String8 s) { + char *to_return = ArenaPush(cg_arena, s.size + 1); memcpy(to_return, s.str, s.size); to_return[s.size] = '\0'; return to_return; @@ -72,18 +72,18 @@ char* fillnull(char *s, char c) { } s++; } - assert(false); // MD_S8Lit("Couldn't find char")); + assert(false); // S8Lit("Couldn't find char")); return NULL; } -#define StrSame(s1, s2) MD_S8Match((s1), (s2), 0) -#define EachString(it, first) MD_String8Node *it = (first); it != 0; it = it->next +#define StrSame(s1, s2) S8Match((s1), (s2), 0) +#define EachString(it, first) String8Node *it = (first); it != 0; it = it->next -typedef BUFF(MD_Node*, 256) Nodes; -MD_Node* find_by_name(Nodes *n, MD_String8 name) +typedef BUFF(Node*, 256) Nodes; +Node* find_by_name(Nodes *n, String8 name) { - MD_Node *node_with = 0; - BUFF_ITER(MD_Node *, n) + Node *node_with = 0; + BUFF_ITER(Node *, n) { if (StrSame((*it)->string, name)) { @@ -107,35 +107,35 @@ char* goto_end_of(char *tomove, size_t max_move, char *pattern) { return NULL; } -#define list_printf(list_ptr, ...) MD_S8ListPush(cg_arena, list_ptr, MD_S8Fmt(cg_arena, __VA_ARGS__)) -void dump_full(MD_Node* from) +#define list_printf(list_ptr, ...) S8ListPush(cg_arena, list_ptr, S8Fmt(cg_arena, __VA_ARGS__)) +void dump_full(Node* from) { - for (MD_EachNode(node, from)) + for (EachNode(node, from)) { - printf("@%.*s %.*s\n", MD_S8VArg(node->first_tag->string), MD_S8VArg(node->string)); + printf("@%.*s %.*s\n", S8VArg(node->first_tag->string), S8VArg(node->string)); } - /* MD_String8List output_list = {0}; - MD_DebugDumpFromNode(cg_arena, &output_list, from, 4, S8(" "), 0); - MD_StringJoin join = (MD_StringJoin){0}; - MD_String8 debugged = MD_S8ListJoin(cg_arena, output_list , &join); - printf("%.*s\n", MD_S8VArg(debugged));*/ + /* String8List output_list = {0}; + DebugDumpFromNode(cg_arena, &output_list, from, 4, S8(" "), 0); + StringJoin join = (StringJoin){0}; + String8 debugged = S8ListJoin(cg_arena, output_list , &join); + printf("%.*s\n", S8VArg(debugged));*/ } #include "character_info.h" int main(int argc, char **argv) { - cg_arena = MD_ArenaAlloc(); + cg_arena = ArenaAlloc(); assert(cg_arena); - MD_String8 test = MD_S8Lit("*testing*other"); - MD_String8 to_split = MD_S8Lit("*"); - MD_String8List split_up = MD_S8Split(cg_arena, test, 1, &to_split); + String8 test = S8Lit("*testing*other"); + String8 to_split = S8Lit("*"); + String8List split_up = S8Split(cg_arena, test, 1, &to_split); printf("Split up: "); - for(MD_String8Node * cur = split_up.first; cur; cur = cur->next) + for(String8Node * cur = split_up.first; cur; cur = cur->next) { - printf("'%.*s', ", MD_S8VArg(cur->string)); + printf("'%.*s', ", S8VArg(cur->string)); } printf("\n"); @@ -154,50 +154,50 @@ int main(int argc, char **argv) // do assets - MD_String8 writeto = MD_S8Fmt(cg_arena, "gen/assets.gen.c"); - Log("Writing to %.*s\n", MD_S8VArg(writeto)); + String8 writeto = S8Fmt(cg_arena, "gen/assets.gen.c"); + Log("Writing to %.*s\n", S8VArg(writeto)); FILE *output = fopen(nullterm(writeto), "w"); - MD_ParseResult parse = MD_ParseWholeFile(cg_arena, MD_S8Lit("assets.mdesk")); - - MD_String8List declarations_list = { 0 }; - MD_String8List load_list = { 0 }; - MD_String8List level_decl_list = { 0 }; - MD_String8List tileset_decls = { 0 }; - for (MD_EachNode(node, parse.node->first_child)) { - if (MD_S8Match(node->first_tag->string, MD_S8Lit("sound"), 0)) { - MD_String8 variable_name = MD_S8Fmt(cg_arena, "sound_%.*s", MD_S8VArg(node->string)); - Log("New sound variable %.*s\n", MD_S8VArg(variable_name)); - MD_String8 filepath = ChildValue(node, MD_S8Lit("filepath")); + ParseResult parse = ParseWholeFile(cg_arena, S8Lit("assets.mdesk")); + + String8List declarations_list = { 0 }; + String8List load_list = { 0 }; + String8List level_decl_list = { 0 }; + String8List tileset_decls = { 0 }; + for (EachNode(node, parse.node->first_child)) { + if (S8Match(node->first_tag->string, S8Lit("sound"), 0)) { + String8 variable_name = S8Fmt(cg_arena, "sound_%.*s", S8VArg(node->string)); + Log("New sound variable %.*s\n", S8VArg(variable_name)); + String8 filepath = ChildValue(node, S8Lit("filepath")); filepath = asset_file_path(filepath); - assert(filepath.str != 0); // MD_S8Fmt(cg_arena, "No filepath specified for sound '%.*s'", MD_S8VArg(node->string))); + assert(filepath.str != 0); // S8Fmt(cg_arena, "No filepath specified for sound '%.*s'", S8VArg(node->string))); FILE *asset_file = fopen(nullterm(filepath), "r"); - assert(asset_file); // MD_S8Fmt(cg_arena, "Could not open filepath %.*s for asset '%.*s'", MD_S8VArg(filepath), MD_S8VArg(node->string))); + assert(asset_file); // S8Fmt(cg_arena, "Could not open filepath %.*s for asset '%.*s'", S8VArg(filepath), S8VArg(node->string))); fclose(asset_file); - MD_S8ListPush(cg_arena, &declarations_list, MD_S8Fmt(cg_arena, "AudioSample %.*s = {0};\n", MD_S8VArg(variable_name))); - MD_S8ListPush(cg_arena, &load_list, MD_S8Fmt(cg_arena, "%.*s = load_wav_audio(\"%.*s\");\n", MD_S8VArg(variable_name), MD_S8VArg(filepath))); + S8ListPush(cg_arena, &declarations_list, S8Fmt(cg_arena, "AudioSample %.*s = {0};\n", S8VArg(variable_name))); + S8ListPush(cg_arena, &load_list, S8Fmt(cg_arena, "%.*s = load_wav_audio(\"%.*s\");\n", S8VArg(variable_name), S8VArg(filepath))); } - if (MD_S8Match(node->first_tag->string, MD_S8Lit("image"), 0)) { - MD_String8 variable_name = MD_S8Fmt(cg_arena, "image_%.*s", MD_S8VArg(node->string)); - //Log("New image variable %.*s\n", MD_S8VArg(variable_name)); - MD_String8 filepath = ChildValue(node, MD_S8Lit("filepath")); + if (S8Match(node->first_tag->string, S8Lit("image"), 0)) { + String8 variable_name = S8Fmt(cg_arena, "image_%.*s", S8VArg(node->string)); + //Log("New image variable %.*s\n", S8VArg(variable_name)); + String8 filepath = ChildValue(node, S8Lit("filepath")); filepath = asset_file_path(filepath); - assert(filepath.str != 0); // , MD_S8Fmt(cg_arena, "No filepath specified for image '%.*s'", MD_S8VArg(node->string))); + assert(filepath.str != 0); // , S8Fmt(cg_arena, "No filepath specified for image '%.*s'", S8VArg(node->string))); FILE *asset_file = fopen(nullterm(filepath), "rb"); - assert(asset_file); // , MD_S8Fmt(cg_arena, "Could not open filepath %.*s for asset '%.*s'", MD_S8VArg(filepath), MD_S8VArg(node->string))); + assert(asset_file); // , S8Fmt(cg_arena, "Could not open filepath %.*s for asset '%.*s'", S8VArg(filepath), S8VArg(node->string))); fclose(asset_file); - MD_S8ListPush(cg_arena, &declarations_list, MD_S8Fmt(cg_arena, "sg_image %.*s = {0};\n", MD_S8VArg(variable_name))); - MD_S8ListPush(cg_arena, &load_list, MD_S8Fmt(cg_arena, "%.*s = load_image(MD_S8Lit(\"%.*s\"));\n", MD_S8VArg(variable_name), MD_S8VArg(filepath))); + S8ListPush(cg_arena, &declarations_list, S8Fmt(cg_arena, "sg_image %.*s = {0};\n", S8VArg(variable_name))); + S8ListPush(cg_arena, &load_list, S8Fmt(cg_arena, "%.*s = load_image(S8Lit(\"%.*s\"));\n", S8VArg(variable_name), S8VArg(filepath))); } } - MD_StringJoin join = { 0 }; - MD_String8 declarations = MD_S8ListJoin(cg_arena, declarations_list, &join); - MD_String8 loads = MD_S8ListJoin(cg_arena, load_list, &join); - fprintf(output, "%.*s\nvoid load_assets() {\n%.*s\n}\n", MD_S8VArg(declarations), MD_S8VArg(loads)); + StringJoin join = { 0 }; + String8 declarations = S8ListJoin(cg_arena, declarations_list, &join); + String8 loads = S8ListJoin(cg_arena, load_list, &join); + fprintf(output, "%.*s\nvoid load_assets() {\n%.*s\n}\n", S8VArg(declarations), S8VArg(loads)); fclose(output); diff --git a/main.c b/main.c index 52950cb..9bda9df 100644 --- a/main.c +++ b/main.c @@ -91,7 +91,7 @@ __declspec(dllexport) uint32_t AmdPowerXpressRequestHighPerformance = 0x00000001 #ifdef WEB #define __gnu_linux__ #define i386 -#define MD_DEFAULT_ARENA 0 +#define DEFAULT_ARENA 0 typedef struct WebArena { @@ -168,14 +168,14 @@ void web_arena_set_auto_align(WebArena *arena, size_t align) arena->align = align; } -#define MD_IMPL_Arena WebArena -#define MD_IMPL_ArenaAlloc web_arena_alloc -#define MD_IMPL_ArenaRelease web_arena_release -#define MD_IMPL_ArenaGetPos web_arena_get_pos -#define MD_IMPL_ArenaPush web_arena_push -#define MD_IMPL_ArenaPopTo web_arena_pop_to -#define MD_IMPL_ArenaSetAutoAlign web_arena_set_auto_align -#define MD_IMPL_ArenaMinPos 64 // no idea what this is honestly +#define IMPL_Arena WebArena +#define IMPL_ArenaAlloc web_arena_alloc +#define IMPL_ArenaRelease web_arena_release +#define IMPL_ArenaGetPos web_arena_get_pos +#define IMPL_ArenaPush web_arena_push +#define IMPL_ArenaPopTo web_arena_pop_to +#define IMPL_ArenaSetAutoAlign web_arena_set_auto_align +#define IMPL_ArenaMinPos 64 // no idea what this is honestly #endif // web #pragma warning(disable : 4996) // fopen is safe. I don't care about fopen_s @@ -189,10 +189,10 @@ void web_arena_set_auto_align(WebArena *arena, size_t align) #pragma warning(disable : 4457) // hiding function variable happens #pragma warning(disable : 4668) // __GNU_C__ macro undefined, fixing #define STBSP_ADD_TO_FUNCTIONS no_ubsan -#define MD_FUNCTION no_ubsan +#define FUNCTION no_ubsan #include "md.h" -#undef MD_Assert -#define MD_Assert assert +#undef Assert +#define Assert assert #include "md.c" #pragma warning(pop) @@ -208,10 +208,10 @@ void web_arena_set_auto_align(WebArena *arena, size_t align) #endif #include "profiling.h" -MD_String8 nullterm(MD_Arena *copy_onto, MD_String8 to_nullterm) +String8 nullterm(Arena *copy_onto, String8 to_nullterm) { - MD_String8 to_return = {0}; - to_return.str = MD_PushArray(copy_onto, MD_u8, to_nullterm.size + 1); + String8 to_return = {0}; + to_return.str = PushArray(copy_onto, u8, to_nullterm.size + 1); to_return.size = to_nullterm.size + 1; to_return.str[to_return.size - 1] = '\0'; memcpy(to_return.str, to_nullterm.str, to_nullterm.size); @@ -321,14 +321,6 @@ typedef struct Quad #include "makeprompt.h" typedef BUFF(Entity*, 16) Overlapping; -// no alignment etc because lazy -typedef struct Arena -{ - char *data; - size_t data_size; - size_t cur; -} Arena; - typedef struct AudioSample { float *pcm_data; // allocated by loader, must be freed @@ -417,7 +409,7 @@ bool is_receiving_text_input() } #ifdef DESKTOP -MD_u8 text_input_buffer[MAX_SENTENCE_LENGTH] = {0}; +u8 text_input_buffer[MAX_SENTENCE_LENGTH] = {0}; int text_input_buffer_length = 0; #else #ifdef WEB @@ -453,15 +445,15 @@ Vec2 FloorV2(Vec2 v) return V2(floorf(v.x), floorf(v.y)); } -MD_Arena *frame_arena = 0; -MD_Arena *persistent_arena = 0; // watch out, arenas have limited size. +Arena *frame_arena = 0; +Arena *persistent_arena = 0; // watch out, arenas have limited size. #ifdef WINDOWS // uses frame arena -LPCWSTR windows_string(MD_String8 s) +LPCWSTR windows_string(String8 s) { int num_characters = MultiByteToWideChar(CP_UTF8, 0, (LPCCH)s.str, (int)s.size, 0, 0); - wchar_t *to_return = MD_PushArray(frame_arena, wchar_t, num_characters + 1); // also allocate for null terminating character + wchar_t *to_return = PushArray(frame_arena, wchar_t, num_characters + 1); // also allocate for null terminating character assert(MultiByteToWideChar(CP_UTF8, 0, (LPCCH)s.str, (int)s.size, to_return, num_characters) == num_characters); to_return[num_characters] = '\0'; return to_return; @@ -485,8 +477,8 @@ typedef struct ChatRequest int status; TextChunk generated; uintptr_t thread_handle; - MD_Arena *arena; - MD_String8 post_req_body; // allocated on thread_arena + Arena *arena; + String8 post_req_body; // allocated on thread_arena } ChatRequest; ChatRequest *requests_first = 0; @@ -506,7 +498,7 @@ void generation_thread(void* my_request_voidptr) HINTERNET hSession = WinHttpOpen(L"PlayGPT winhttp backend", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); WinAssertWithErrorCode(hSession); - LPCWSTR windows_server_name = windows_string(MD_S8Lit(SERVER_DOMAIN)); + LPCWSTR windows_server_name = windows_string(S8Lit(SERVER_DOMAIN)); HINTERNET hConnect = WinHttpConnect(hSession, windows_server_name, SERVER_PORT, 0); WinAssertWithErrorCode(hConnect); int security_flags = 0; @@ -540,7 +532,7 @@ void generation_thread(void* my_request_voidptr) WinAssertWithErrorCode(status_code != 500); DWORD dwSize = 0; - MD_String8List received_data_list = {0}; + String8List received_data_list = {0}; do { dwSize = 0; @@ -552,17 +544,17 @@ void generation_thread(void* my_request_voidptr) } else { - MD_u8* out_buffer = MD_PushArray(my_request->arena, MD_u8, dwSize + 1); + u8* out_buffer = PushArray(my_request->arena, u8, dwSize + 1); DWORD dwDownloaded = 0; WinAssertWithErrorCode(WinHttpReadData(hRequest, (LPVOID)out_buffer, dwSize, &dwDownloaded)); out_buffer[dwDownloaded - 1] = '\0'; Log("Got this from http, size %lu: %s\n", dwDownloaded, out_buffer); - MD_S8ListPush(my_request->arena, &received_data_list, MD_S8(out_buffer, dwDownloaded)); + S8ListPush(my_request->arena, &received_data_list, S8(out_buffer, dwDownloaded)); } } while (dwSize > 0); - MD_String8 received_data = MD_S8ListJoin(my_request->arena, received_data_list, &(MD_StringJoin){0}); + String8 received_data = S8ListJoin(my_request->arena, received_data_list, &(StringJoin){0}); - MD_String8 ai_response = MD_S8Substring(received_data, 1, received_data.size); + String8 ai_response = S8Substring(received_data, 1, received_data.size); if(ai_response.size > ARRLEN(my_request->generated.text)) { Log("%lld too big for %lld\n", ai_response.size, ARRLEN(my_request->generated.text)); @@ -574,10 +566,10 @@ void generation_thread(void* my_request_voidptr) } } -int make_generation_request(MD_String8 post_req_body) +int make_generation_request(String8 post_req_body) { // checking for taken characters, pipe should only occur at the beginning - for(MD_u64 i = 1; i < post_req_body.size; i++) + for(u64 i = 1; i < post_req_body.size; i++) { assert(post_req_body.str[i] != '|'); } @@ -587,25 +579,25 @@ int make_generation_request(MD_String8 post_req_body) { to_return = requests_free_list; requests_free_list = requests_free_list->next; - //MD_StackPop(requests_free_list); + //StackPop(requests_free_list); *to_return = (ChatRequest){0}; } else { - to_return = MD_PushArrayZero(persistent_arena, ChatRequest, 1); + to_return = PushArrayZero(persistent_arena, ChatRequest, 1); } - to_return->arena = MD_ArenaAlloc(); + to_return->arena = ArenaAlloc(); to_return->id = next_request_id; next_request_id += 1; - to_return->post_req_body.str = MD_PushArrayZero(to_return->arena, MD_u8, post_req_body.size); + to_return->post_req_body.str = PushArrayZero(to_return->arena, u8, post_req_body.size); to_return->post_req_body.size = post_req_body.size; memcpy(to_return->post_req_body.str, post_req_body.str, post_req_body.size); to_return->thread_handle = _beginthread(generation_thread, 0, to_return); assert(to_return->thread_handle); - MD_DblPushBack(requests_first, requests_last, to_return); + DblPushBack(requests_first, requests_last, to_return); return to_return->id; } @@ -629,9 +621,9 @@ ChatRequest *get_by_id(int id) void done_with_request(int id) { ChatRequest *req = get_by_id(id); - MD_ArenaRelease(req->arena); - MD_DblRemove(requests_first, requests_last, req); - MD_StackPush(requests_free_list, req); + ArenaRelease(req->arena); + DblRemove(requests_first, requests_last, req); + StackPush(requests_free_list, req); } #else @@ -644,28 +636,28 @@ RememberedError *remembered_error_free_list = 0; // s.size must be less than MAX_SENTENCE_LENGTH, or assert fails -RememberedError *allocate_remembered_error(MD_Arena *arena) +RememberedError *allocate_remembered_error(Arena *arena) { RememberedError *to_return = 0; if(remembered_error_free_list) { to_return = remembered_error_free_list; - MD_StackPop(remembered_error_free_list); + StackPop(remembered_error_free_list); } else { - to_return = MD_PushArray(arena, RememberedError, 1); + to_return = PushArray(arena, RememberedError, 1); } *to_return = (RememberedError){0}; return to_return; } void remove_remembered_error_from(RememberedError **first, RememberedError **last, RememberedError *chunk) { - MD_DblRemove(*first, *last, chunk); - MD_StackPush(remembered_error_free_list, chunk); + DblRemove(*first, *last, chunk); + StackPush(remembered_error_free_list, chunk); } -void append_to_errors(Entity *from, Memory incorrect_memory, MD_String8 s) +void append_to_errors(Entity *from, Memory incorrect_memory, String8 s) { RememberedError *err = allocate_remembered_error(persistent_arena); chunk_from_s8(&err->reason_why_its_bad, s); @@ -679,17 +671,17 @@ void append_to_errors(Entity *from, Memory incorrect_memory, MD_String8 s) if(count < REMEMBERED_ERRORS) break; remove_remembered_error_from(&from->errorlist_first, &from->errorlist_last, from->errorlist_first); } - MD_DblPushBack(from->errorlist_first, from->errorlist_last, err); + DblPushBack(from->errorlist_first, from->errorlist_last, err); from->perceptions_dirty = true; } -MD_String8 tprint(char *format, ...) +String8 tprint(char *format, ...) { - MD_String8 to_return = {0}; + String8 to_return = {0}; va_list argptr; va_start(argptr, format); - to_return = MD_S8FmtV(frame_arena, format, argptr); + to_return = S8FmtV(frame_arena, format, argptr); va_end(argptr); return to_return; @@ -777,26 +769,26 @@ AABB entity_aabb(Entity *e) typedef struct LoadedImage { struct LoadedImage *next; - MD_String8 name; + String8 name; sg_image image; } LoadedImage; LoadedImage *loaded_images = 0; -sg_image load_image(MD_String8 path) +sg_image load_image(String8 path) { - MD_ArenaTemp scratch = MD_GetScratch(0, 0); + ArenaTemp scratch = GetScratch(0, 0); for(LoadedImage *cur = loaded_images; cur; cur = cur->next) { - if(MD_S8Match(cur->name, path, 0)) + if(S8Match(cur->name, path, 0)) { return cur->image; } } - LoadedImage *loaded = MD_PushArray(persistent_arena, LoadedImage, 1); - loaded->name = MD_S8Copy(persistent_arena, path); - MD_StackPush(loaded_images, loaded); + LoadedImage *loaded = PushArray(persistent_arena, LoadedImage, 1); + loaded->name = S8Copy(persistent_arena, path); + StackPush(loaded_images, loaded); sg_image to_return = { 0 }; @@ -811,8 +803,8 @@ sg_image load_image(MD_String8 path) if(num_channels == 3) { stbi_uc *old_pixels = pixels; - pixels = MD_ArenaPush(scratch.arena, png_width * png_height * 4 * sizeof(stbi_uc)); - for(MD_u64 pixel_i = 0; pixel_i < png_width * png_height; pixel_i++) + pixels = ArenaPush(scratch.arena, png_width * png_height * 4 * sizeof(stbi_uc)); + for(u64 pixel_i = 0; pixel_i < png_width * png_height; pixel_i++) { pixels[pixel_i*4 + 0] = old_pixels[pixel_i*3 + 0]; pixels[pixel_i*4 + 1] = old_pixels[pixel_i*3 + 1]; @@ -826,7 +818,7 @@ sg_image load_image(MD_String8 path) assert(pixels); assert(desired_channels == num_channels); - //Log("Path %.*s | Loading image with dimensions %d %d\n", MD_S8VArg(path), png_width, png_height); + //Log("Path %.*s | Loading image with dimensions %d %d\n", S8VArg(path), png_width, png_height); to_return = sg_make_image(&(sg_image_desc) { .width = png_width, @@ -841,7 +833,7 @@ sg_image load_image(MD_String8 path) }); loaded->image = to_return; - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); return to_return; } @@ -857,7 +849,7 @@ SER_MAKE_FOR_TYPE(Vec2); SER_MAKE_FOR_TYPE(Vec3); SER_MAKE_FOR_TYPE(EntityRef); SER_MAKE_FOR_TYPE(NPCPlayerStanding); -SER_MAKE_FOR_TYPE(MD_u16); +SER_MAKE_FOR_TYPE(u16); void ser_Quat(SerState *ser, Quat *q) { @@ -886,7 +878,7 @@ typedef struct { Vec3 position; Vec2 uv; - MD_u16 joint_indices[4]; + u16 joint_indices[4]; float joint_weights[4]; } ArmatureVertex; @@ -897,11 +889,11 @@ typedef struct Mesh struct Mesh *next; Vertex *vertices; - MD_u64 num_vertices; + u64 num_vertices; sg_buffer loaded_buffer; sg_image image; - MD_String8 name; + String8 name; } Mesh; typedef struct PoseBone @@ -915,19 +907,19 @@ typedef struct Bone struct Bone *parent; Mat4 matrix_local; Mat4 inverse_model_space_pos; - MD_String8 name; + String8 name; float length; } Bone; typedef struct AnimationTrack { PoseBone *poses; - MD_u64 poses_length; + u64 poses_length; } AnimationTrack; typedef struct Animation { - MD_String8 name; + String8 name; // assumed to be the same as the number of bones in the armature the animation is in AnimationTrack *tracks; } Animation; @@ -944,7 +936,7 @@ typedef struct PlacedMesh struct PlacedMesh *next; Transform t; Mesh *draw_with; - MD_String8 name; + String8 name; } PlacedMesh; typedef struct PlacedEntity @@ -958,9 +950,9 @@ typedef struct PlacedEntity // arena must last as long as the Mesh lasts. Internal data points to `arena`, such as // the name of the mesh's buffer in sokol. The returned mesh doesn't point to the binary // file anymore. -Mesh load_mesh(MD_Arena *arena, MD_String8 binary_file, MD_String8 mesh_name) +Mesh load_mesh(Arena *arena, String8 binary_file, String8 mesh_name) { - MD_ArenaTemp scratch = MD_GetScratch(&arena, 1); + ArenaTemp scratch = GetScratch(&arena, 1); SerState ser = { .data = binary_file.str, .max = binary_file.size, @@ -974,27 +966,27 @@ Mesh load_mesh(MD_Arena *arena, MD_String8 binary_file, MD_String8 mesh_name) ser_bool(&ser, &is_armature); assert(!is_armature); - MD_String8 image_filename; - ser_MD_String8(&ser, &image_filename, scratch.arena); - to_return.image = load_image(MD_S8Fmt(scratch.arena, "assets/exported_3d/%.*s", MD_S8VArg(image_filename))); + String8 image_filename; + ser_String8(&ser, &image_filename, scratch.arena); + to_return.image = load_image(S8Fmt(scratch.arena, "assets/exported_3d/%.*s", S8VArg(image_filename))); - ser_MD_u64(&ser, &to_return.num_vertices); - //Log("Mesh %.*s has %llu vertices and image filename '%.*s'\n", MD_S8VArg(mesh_name), to_return.num_vertices, MD_S8VArg(image_filename)); + ser_u64(&ser, &to_return.num_vertices); + //Log("Mesh %.*s has %llu vertices and image filename '%.*s'\n", S8VArg(mesh_name), to_return.num_vertices, S8VArg(image_filename)); - to_return.vertices = MD_ArenaPush(arena, sizeof(*to_return.vertices) * to_return.num_vertices); - for(MD_u64 i = 0; i < to_return.num_vertices; i++) + to_return.vertices = ArenaPush(arena, sizeof(*to_return.vertices) * to_return.num_vertices); + for(u64 i = 0; i < to_return.num_vertices; i++) { ser_Vertex(&ser, &to_return.vertices[i]); } assert(!ser.cur_error.failed); - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); to_return.loaded_buffer = sg_make_buffer(&(sg_buffer_desc) { .usage = SG_USAGE_IMMUTABLE, .data = (sg_range){.ptr = to_return.vertices, .size = to_return.num_vertices * sizeof(Vertex)}, - .label = (const char*)nullterm(arena, MD_S8Fmt(arena, "%.*s-vertices", MD_S8VArg(mesh_name))).str, + .label = (const char*)nullterm(arena, S8Fmt(arena, "%.*s-vertices", S8VArg(mesh_name))).str, }); to_return.name = mesh_name; @@ -1048,20 +1040,20 @@ Transform default_transform() typedef struct { - MD_String8 name; + String8 name; Bone *bones; - MD_u64 bones_length; + u64 bones_length; Animation *animations; - MD_u64 animations_length; + u64 animations_length; // when set, blends to that animation next time this armature is processed for that - MD_String8 go_to_animation; + String8 go_to_animation; bool next_animation_isnt_looping; Transform *current_poses; // allocated on loading of the armature - MD_String8 currently_playing_animation; // CANNOT be null. + String8 currently_playing_animation; // CANNOT be null. bool currently_playing_isnt_looping; float animation_blend_t; // [0,1] how much between current_animation and target_animation. Once >= 1, current = target and target = null. double cur_animation_time; // used for non looping animations to play once @@ -1069,7 +1061,7 @@ typedef struct Transform *anim_blended_poses; // recalculated once per frame depending on above parameters, which at the same code location are calculated. Is `bones_length` long ArmatureVertex *vertices; - MD_u64 vertices_length; + u64 vertices_length; sg_buffer loaded_buffer; sg_image bones_texture; @@ -1079,10 +1071,10 @@ typedef struct } Armature; // armature_name is used for debugging purposes, it has to effect on things -Armature load_armature(MD_Arena *arena, MD_String8 binary_file, MD_String8 armature_name) +Armature load_armature(Arena *arena, String8 binary_file, String8 armature_name) { assert(binary_file.str); - MD_ArenaTemp scratch = MD_GetScratch(&arena, 1); + ArenaTemp scratch = GetScratch(&arena, 1); SerState ser = { .data = binary_file.str, .max = binary_file.size, @@ -1096,26 +1088,26 @@ Armature load_armature(MD_Arena *arena, MD_String8 binary_file, MD_String8 armat ser_bool(&ser, &is_armature); assert(is_armature); - ser_MD_String8(&ser, &to_return.name, arena); + ser_String8(&ser, &to_return.name, arena); - MD_String8 image_filename; - ser_MD_String8(&ser, &image_filename, scratch.arena); + String8 image_filename; + ser_String8(&ser, &image_filename, scratch.arena); arena->align = 16; // SSE requires quaternions are 16 byte aligned - to_return.image = load_image(MD_S8Fmt(scratch.arena, "assets/exported_3d/%.*s", MD_S8VArg(image_filename))); + to_return.image = load_image(S8Fmt(scratch.arena, "assets/exported_3d/%.*s", S8VArg(image_filename))); - ser_MD_u64(&ser, &to_return.bones_length); - //Log("Armature %.*s has %llu bones\n", MD_S8VArg(armature_name), to_return.bones_length); - to_return.bones = MD_PushArray(arena, Bone, to_return.bones_length); + ser_u64(&ser, &to_return.bones_length); + //Log("Armature %.*s has %llu bones\n", S8VArg(armature_name), to_return.bones_length); + to_return.bones = PushArray(arena, Bone, to_return.bones_length); - for(MD_u64 i = 0; i < to_return.bones_length; i++) + for(u64 i = 0; i < to_return.bones_length; i++) { Bone *next_bone = &to_return.bones[i]; BlenderMat model_space_pose; BlenderMat inverse_model_space_pose; - MD_i32 parent_index; + i32 parent_index; - ser_MD_String8(&ser, &next_bone->name, arena); + ser_String8(&ser, &next_bone->name, arena); ser_int(&ser, &parent_index); ser_BlenderMat(&ser, &model_space_pose); ser_BlenderMat(&ser, &inverse_model_space_pose); @@ -1128,7 +1120,7 @@ Armature load_armature(MD_Arena *arena, MD_String8 binary_file, MD_String8 armat { if(parent_index < 0 || parent_index >= to_return.bones_length) { - ser.cur_error = (SerError){.failed = true, .why = MD_S8Fmt(arena, "Parent index deserialized %d is out of range of the pose bones, which has a size of %llu", parent_index, to_return.bones_length)}; + ser.cur_error = (SerError){.failed = true, .why = S8Fmt(arena, "Parent index deserialized %d is out of range of the pose bones, which has a size of %llu", parent_index, to_return.bones_length)}; } else { @@ -1137,41 +1129,41 @@ Armature load_armature(MD_Arena *arena, MD_String8 binary_file, MD_String8 armat } } - to_return.current_poses = MD_PushArray(arena, Transform, to_return.bones_length); - to_return.anim_blended_poses = MD_PushArray(arena, Transform, to_return.bones_length); + to_return.current_poses = PushArray(arena, Transform, to_return.bones_length); + to_return.anim_blended_poses = PushArray(arena, Transform, to_return.bones_length); for(int i = 0; i < to_return.bones_length; i++) { to_return.anim_blended_poses[i] = (Transform){.scale = V3(1,1,1), .rotation = Make_Q(1,0,0,1)}; } - ser_MD_u64(&ser, &to_return.animations_length); - //Log("Armature %.*s has %llu animations\n", MD_S8VArg(armature_name), to_return.animations_length); - to_return.animations = MD_PushArray(arena, Animation, to_return.animations_length); + ser_u64(&ser, &to_return.animations_length); + //Log("Armature %.*s has %llu animations\n", S8VArg(armature_name), to_return.animations_length); + to_return.animations = PushArray(arena, Animation, to_return.animations_length); - for(MD_u64 i = 0; i < to_return.animations_length; i++) + for(u64 i = 0; i < to_return.animations_length; i++) { Animation *new_anim = &to_return.animations[i]; *new_anim = (Animation){0}; - ser_MD_String8(&ser, &new_anim->name, arena); + ser_String8(&ser, &new_anim->name, arena); - new_anim->tracks = MD_PushArray(arena, AnimationTrack, to_return.bones_length); + new_anim->tracks = PushArray(arena, AnimationTrack, to_return.bones_length); - MD_u64 frames_in_anim; - ser_MD_u64(&ser, &frames_in_anim); - //Log("There are %llu animation frames in animation '%.*s'\n", frames_in_anim, MD_S8VArg(new_anim->name)); + u64 frames_in_anim; + ser_u64(&ser, &frames_in_anim); + //Log("There are %llu animation frames in animation '%.*s'\n", frames_in_anim, S8VArg(new_anim->name)); - for(MD_u64 i = 0; i < to_return.bones_length; i++) + for(u64 i = 0; i < to_return.bones_length; i++) { - new_anim->tracks[i].poses = MD_PushArray(arena, PoseBone, frames_in_anim); + new_anim->tracks[i].poses = PushArray(arena, PoseBone, frames_in_anim); new_anim->tracks[i].poses_length = frames_in_anim; } - for(MD_u64 anim_i = 0; anim_i < frames_in_anim; anim_i++) + for(u64 anim_i = 0; anim_i < frames_in_anim; anim_i++) { float time_through; ser_float(&ser, &time_through); - for(MD_u64 pose_bone_i = 0; pose_bone_i < to_return.bones_length; pose_bone_i++) + for(u64 pose_bone_i = 0; pose_bone_i < to_return.bones_length; pose_bone_i++) { PoseBone *next_pose_bone = &new_anim->tracks[pose_bone_i].poses[anim_i]; @@ -1184,16 +1176,16 @@ Armature load_armature(MD_Arena *arena, MD_String8 binary_file, MD_String8 armat } } - ser_MD_u64(&ser, &to_return.vertices_length); - to_return.vertices = MD_PushArray(arena, ArmatureVertex, to_return.vertices_length); - for(MD_u64 i = 0; i < to_return.vertices_length; i++) + ser_u64(&ser, &to_return.vertices_length); + to_return.vertices = PushArray(arena, ArmatureVertex, to_return.vertices_length); + for(u64 i = 0; i < to_return.vertices_length; i++) { ser_Vec3(&ser, &to_return.vertices[i].position); ser_Vec2(&ser, &to_return.vertices[i].uv); - MD_u16 joint_indices[4]; + u16 joint_indices[4]; float joint_weights[4]; for(int ii = 0; ii < 4; ii++) - ser_MD_u16(&ser, &joint_indices[ii]); + ser_u16(&ser, &joint_indices[ii]); for(int ii = 0; ii < 4; ii++) ser_float(&ser, &joint_weights[ii]); @@ -1202,22 +1194,22 @@ Armature load_armature(MD_Arena *arena, MD_String8 binary_file, MD_String8 armat for(int ii = 0; ii < 4; ii++) to_return.vertices[i].joint_weights[ii] = joint_weights[ii]; } - //Log("Armature %.*s has %llu vertices\n", MD_S8VArg(armature_name), to_return.vertices_length); + //Log("Armature %.*s has %llu vertices\n", S8VArg(armature_name), to_return.vertices_length); assert(!ser.cur_error.failed); - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); to_return.loaded_buffer = sg_make_buffer(&(sg_buffer_desc) { .usage = SG_USAGE_IMMUTABLE, .data = (sg_range){.ptr = to_return.vertices, .size = to_return.vertices_length * sizeof(ArmatureVertex)}, - .label = (const char*)nullterm(arena, MD_S8Fmt(arena, "%.*s-vertices", MD_S8VArg(armature_name))).str, + .label = (const char*)nullterm(arena, S8Fmt(arena, "%.*s-vertices", S8VArg(armature_name))).str, }); to_return.bones_texture_width = 16; to_return.bones_texture_height = (int)to_return.bones_length; - //Log("Armature %.*s has bones texture size (%d, %d)\n", MD_S8VArg(armature_name), to_return.bones_texture_width, to_return.bones_texture_height); + //Log("Armature %.*s has bones texture size (%d, %d)\n", S8VArg(armature_name), to_return.bones_texture_width, to_return.bones_texture_height); to_return.bones_texture = sg_make_image(&(sg_image_desc) { .width = to_return.bones_texture_width, .height = to_return.bones_texture_height, @@ -1259,7 +1251,7 @@ typedef struct Room { struct Room *next; - MD_String8 name; + String8 name; PlacedMesh *placed_mesh_list; CollisionCylinder *collision_list; PlacedEntity *placed_entity_list; @@ -1276,7 +1268,7 @@ Room *get_cur_room(GameState *gs, ThreeDeeLevel *level) Room *in_room = 0; for(Room *cur = level->room_list; cur; cur = cur->next) { - if(MD_S8Match(cur->name, gs->player->current_room_name, 0)) + if(S8Match(cur->name, gs->player->current_room_name, 0)) { in_room = cur; break; @@ -1314,9 +1306,9 @@ Transform blender_to_game_transform(BlenderTransform blender_transform) return to_return; } -ThreeDeeLevel load_level(MD_Arena *arena, MD_String8 binary_file) +ThreeDeeLevel load_level(Arena *arena, String8 binary_file) { - MD_ArenaTemp scratch = MD_GetScratch(&arena, 1); + ArenaTemp scratch = GetScratch(&arena, 1); SerState ser = { .data = binary_file.str, .max = binary_file.size, @@ -1326,40 +1318,40 @@ ThreeDeeLevel load_level(MD_Arena *arena, MD_String8 binary_file) }; ThreeDeeLevel out = {0}; - MD_u64 num_rooms = 0; - ser_MD_u64(&ser, &num_rooms); + u64 num_rooms = 0; + ser_u64(&ser, &num_rooms); - for(MD_u64 i = 0; i < num_rooms; i++) + for(u64 i = 0; i < num_rooms; i++) { - Room *new_room = MD_PushArray(arena, Room, 1); - ser_MD_String8(&ser, &new_room->name, arena); + Room *new_room = PushArray(arena, Room, 1); + ser_String8(&ser, &new_room->name, arena); // placed meshes { - MD_u64 num_placed = 0; - ser_MD_u64(&ser, &num_placed); + u64 num_placed = 0; + ser_u64(&ser, &num_placed); arena->align = 16; // SSE requires quaternions are 16 byte aligned - for (MD_u64 i = 0; i < num_placed; i++) + for (u64 i = 0; i < num_placed; i++) { - PlacedMesh *new_placed = MD_PushArray(arena, PlacedMesh, 1); + PlacedMesh *new_placed = PushArray(arena, PlacedMesh, 1); // PlacedMesh *new_placed = calloc(sizeof(PlacedMesh), 1); - ser_MD_String8(&ser, &new_placed->name, arena); + ser_String8(&ser, &new_placed->name, arena); BlenderTransform blender_transform = {0}; ser_BlenderTransform(&ser, &blender_transform); new_placed->t = blender_to_game_transform(blender_transform); - MD_StackPush(new_room->placed_mesh_list, new_placed); + StackPush(new_room->placed_mesh_list, new_placed); - // Log("Placed mesh '%.*s' pos %f %f %f rotation %f %f %f %f scale %f %f %f\n", MD_S8VArg(placed_mesh_name), v3varg(new_placed->t.offset), qvarg(new_placed->t.rotation), v3varg(new_placed->t.scale)); + // Log("Placed mesh '%.*s' pos %f %f %f rotation %f %f %f %f scale %f %f %f\n", S8VArg(placed_mesh_name), v3varg(new_placed->t.offset), qvarg(new_placed->t.rotation), v3varg(new_placed->t.scale)); // load the mesh if we haven't already bool mesh_found = false; for (Mesh *cur = out.mesh_list; cur; cur = cur->next) { - if (MD_S8Match(cur->name, new_placed->name, 0)) + if (S8Match(cur->name, new_placed->name, 0)) { mesh_found = true; new_placed->draw_with = cur; @@ -1370,53 +1362,53 @@ ThreeDeeLevel load_level(MD_Arena *arena, MD_String8 binary_file) if (!mesh_found) { - MD_String8 to_load_filepath = MD_S8Fmt(scratch.arena, "assets/exported_3d/%.*s.bin", MD_S8VArg(new_placed->name)); - // Log("Loading mesh '%.*s'...\n", MD_S8VArg(to_load_filepath)); - MD_String8 binary_mesh_file = MD_LoadEntireFile(scratch.arena, to_load_filepath); + String8 to_load_filepath = S8Fmt(scratch.arena, "assets/exported_3d/%.*s.bin", S8VArg(new_placed->name)); + // Log("Loading mesh '%.*s'...\n", S8VArg(to_load_filepath)); + String8 binary_mesh_file = LoadEntireFile(scratch.arena, to_load_filepath); if (!binary_mesh_file.str) { - ser.cur_error = (SerError){.failed = true, .why = MD_S8Fmt(ser.error_arena, "Couldn't load file '%.*s'", to_load_filepath)}; + ser.cur_error = (SerError){.failed = true, .why = S8Fmt(ser.error_arena, "Couldn't load file '%.*s'", to_load_filepath)}; } else { - Mesh *new_mesh = MD_PushArray(arena, Mesh, 1); + Mesh *new_mesh = PushArray(arena, Mesh, 1); *new_mesh = load_mesh(arena, binary_mesh_file, new_placed->name); - MD_StackPush(out.mesh_list, new_mesh); + StackPush(out.mesh_list, new_mesh); new_placed->draw_with = new_mesh; } } } } - MD_u64 num_collision_cubes; - ser_MD_u64(&ser, &num_collision_cubes); - for (MD_u64 i = 0; i < num_collision_cubes; i++) + u64 num_collision_cubes; + ser_u64(&ser, &num_collision_cubes); + for (u64 i = 0; i < num_collision_cubes; i++) { - CollisionCylinder *new_cylinder = MD_PushArray(arena, CollisionCylinder, 1); + CollisionCylinder *new_cylinder = PushArray(arena, CollisionCylinder, 1); Vec2 twodee_pos; Vec2 size; ser_Vec2(&ser, &twodee_pos); ser_Vec2(&ser, &size); new_cylinder->bounds.center = twodee_pos; new_cylinder->bounds.radius = (size.x + size.y) * 0.5f; // @TODO(Phillip): @Temporary - MD_StackPush(new_room->collision_list, new_cylinder); + StackPush(new_room->collision_list, new_cylinder); } // placed entities { - MD_u64 num_placed = 0; - ser_MD_u64(&ser, &num_placed); + u64 num_placed = 0; + ser_u64(&ser, &num_placed); arena->align = 16; // SSE requires quaternions are 16 byte aligned - for (MD_u64 i = 0; i < num_placed; i++) + for (u64 i = 0; i < num_placed; i++) { - PlacedEntity *new_placed = MD_PushArray(arena, PlacedEntity, 1); - MD_String8 placed_entity_name = {0}; - ser_MD_String8(&ser, &placed_entity_name, scratch.arena); + PlacedEntity *new_placed = PushArray(arena, PlacedEntity, 1); + String8 placed_entity_name = {0}; + ser_String8(&ser, &placed_entity_name, scratch.arena); bool found = false; ARR_ITER_I(CharacterGen, characters, kind) { - if (MD_S8Match(MD_S8CString(it->enum_name), placed_entity_name, 0)) + if (S8Match(S8CString(it->enum_name), placed_entity_name, 0)) { found = true; new_placed->npc_kind = kind; @@ -1427,22 +1419,22 @@ ThreeDeeLevel load_level(MD_Arena *arena, MD_String8 binary_file) if (found) { new_placed->t = blender_to_game_transform(blender_transform); - MD_StackPush(new_room->placed_entity_list, new_placed); + StackPush(new_room->placed_entity_list, new_placed); } else { - ser.cur_error = (SerError){.failed = true, .why = MD_S8Fmt(arena, "Couldn't find placed npc kind '%.*s'...\n", MD_S8VArg(placed_entity_name))}; + ser.cur_error = (SerError){.failed = true, .why = S8Fmt(arena, "Couldn't find placed npc kind '%.*s'...\n", S8VArg(placed_entity_name))}; } - // Log("Loaded placed entity '%.*s' at %f %f %f\n", MD_S8VArg(placed_entity_name), v3varg(new_placed->t.offset)); + // Log("Loaded placed entity '%.*s' at %f %f %f\n", S8VArg(placed_entity_name), v3varg(new_placed->t.offset)); } } - MD_StackPush(out.room_list, new_room); + StackPush(out.room_list, new_room); } assert(!ser.cur_error.failed); - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); return out; } @@ -1528,9 +1520,9 @@ Mat4 flycam_matrix() return to_return; } -# define MD_S8LitConst(s) {(MD_u8 *)(s), sizeof(s)-1} +# define S8LitConst(s) {(u8 *)(s), sizeof(s)-1} -MD_String8 showing_secret_str = MD_S8LitConst(""); +String8 showing_secret_str = S8LitConst(""); float showing_secret_alpha = 0.0f; PathCache cached_paths[32] = { 0 }; @@ -1636,11 +1628,11 @@ void push_memory(GameState *gs, Entity *e, Memory new_memory) if(memories_free_list) { memory_allocated = memories_free_list; - MD_StackPop(memories_free_list); + StackPop(memories_free_list); } else { - memory_allocated = MD_PushArray(persistent_arena, Memory, 1); + memory_allocated = PushArray(persistent_arena, Memory, 1); } *memory_allocated = new_memory; @@ -1663,14 +1655,14 @@ void push_memory(GameState *gs, Entity *e, Memory new_memory) } to_remove = to_remove->next; } - MD_DblRemove(e->memories_first, e->memories_last, to_remove); - MD_StackPush(memories_free_list, to_remove); + DblRemove(e->memories_first, e->memories_last, to_remove); + StackPush(memories_free_list, to_remove); count -= 1; } if(gs->stopped_time) - MD_StackPush(e->memories_added_while_time_stopped, memory_allocated); + StackPush(e->memories_added_while_time_stopped, memory_allocated); else - MD_DblPushBack(e->memories_first, e->memories_last, memory_allocated); + DblPushBack(e->memories_first, e->memories_last, memory_allocated); if(!new_memory.context.i_said_this) { @@ -1732,13 +1724,13 @@ void remember_action(GameState *gs, Entity *to_modify, Action a, MemoryContext c // returns reason why allocated on arena if invalid // to might be null here, from can't be null -MD_String8 is_action_valid(MD_Arena *arena, Entity *from, Action a) +String8 is_action_valid(Arena *arena, Entity *from, Action a) { assert(a.speech.text_length <= MAX_SENTENCE_LENGTH && a.speech.text_length >= 0); assert(a.kind >= 0 && a.kind < ARRLEN(actions)); assert(from); - MD_String8 error_message = (MD_String8){0}; + String8 error_message = (String8){0}; CanTalkTo talk = get_can_talk_to(from); if(error_message.size == 0 && a.talking_to_kind) @@ -1760,7 +1752,7 @@ MD_String8 is_action_valid(MD_Arena *arena, Entity *from, Action a) if(error_message.size == 0 && a.kind == ACT_leave && gete(from->joined) == 0) { - error_message = MD_S8Lit("You can't leave somebody unless you joined them."); + error_message = S8Lit("You can't leave somebody unless you joined them."); } if(error_message.size == 0 && a.kind == ACT_join && gete(from->joined) != 0) { @@ -1768,11 +1760,11 @@ MD_String8 is_action_valid(MD_Arena *arena, Entity *from, Action a) } if(error_message.size == 0 && a.kind == ACT_fire_shotgun && gete(from->aiming_shotgun_at) == 0) { - error_message = MD_S8Lit("You can't fire your shotgun without aiming it first"); + error_message = S8Lit("You can't fire your shotgun without aiming it first"); } if(error_message.size == 0 && a.kind == ACT_put_shotgun_away && gete(from->aiming_shotgun_at) == 0) { - error_message = MD_S8Lit("You can't put your shotgun away without aiming it first"); + error_message = S8Lit("You can't put your shotgun away without aiming it first"); } bool target_is_character = a.kind == ACT_join || a.kind == ACT_aim_shotgun; @@ -1795,16 +1787,16 @@ MD_String8 is_action_valid(MD_Arena *arena, Entity *from, Action a) AvailableActions available = {0}; fill_available_actions(&gs, from, &available); bool found = false; - MD_String8List action_strings_list = {0}; + String8List action_strings_list = {0}; BUFF_ITER(ActionKind, &available) { - MD_S8ListPush(arena, &action_strings_list, MD_S8CString(actions[*it].name)); + S8ListPush(arena, &action_strings_list, S8CString(actions[*it].name)); if(*it == a.kind) found = true; } if(!found) { - MD_String8 action_strings = MD_S8ListJoin(arena, action_strings_list, &(MD_StringJoin){.mid = MD_S8Lit(", ")}); - error_message = FmtWithLint(arena, "You cannot perform action %s right now, you can only perform these actions: [%.*s]", actions[a.kind].name, MD_S8VArg(action_strings)); + String8 action_strings = S8ListJoin(arena, action_strings_list, &(StringJoin){.mid = S8Lit(", ")}); + error_message = FmtWithLint(arena, "You cannot perform action %s right now, you can only perform these actions: [%.*s]", actions[a.kind].name, S8VArg(action_strings)); } } @@ -1818,12 +1810,12 @@ MD_String8 is_action_valid(MD_Arena *arena, Entity *from, Action a) void cause_action_side_effects(Entity *from, Action a) { assert(from); - MD_ArenaTemp scratch = MD_GetScratch(0, 0); + ArenaTemp scratch = GetScratch(0, 0); - MD_String8 failure_reason = is_action_valid(scratch.arena, from, a); + String8 failure_reason = is_action_valid(scratch.arena, from, a); if(failure_reason.size > 0) { - Log("Failed to process action, invalid action: `%.*s`\n", MD_S8VArg(failure_reason)); + Log("Failed to process action, invalid action: `%.*s`\n", S8VArg(failure_reason)); assert(false); } @@ -1866,7 +1858,7 @@ void cause_action_side_effects(Entity *from, Action a) gs.objective = a.argument.objective; } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); } typedef struct PropagatingAction @@ -1909,9 +1901,9 @@ void push_propagating(PropagatingAction to_push) if(!found) { - PropagatingAction *cur = MD_PushArray(persistent_arena, PropagatingAction, 1); + PropagatingAction *cur = PushArray(persistent_arena, PropagatingAction, 1); *cur = to_push; - MD_StackPush(propagating, cur); + StackPush(propagating, cur); } } @@ -1927,7 +1919,7 @@ float propagating_radius(PropagatingAction *p) // Returns if the action was valid or not bool perform_action(GameState *gs, Entity *from, Action a) { - MD_ArenaTemp scratch = MD_GetScratch(0, 0); + ArenaTemp scratch = GetScratch(0, 0); MemoryContext context = {0}; context.author_npc_kind = from->npc_kind; @@ -1937,7 +1929,7 @@ bool perform_action(GameState *gs, Entity *from, Action a) context.talking_to_kind = a.talking_to_kind; - MD_String8 is_valid = is_action_valid(scratch.arena, from, a); + String8 is_valid = is_action_valid(scratch.arena, from, a); bool proceed_propagating = true; if(is_valid.size > 0) { @@ -1953,7 +1945,7 @@ bool perform_action(GameState *gs, Entity *from, Action a) { targeted = get_targeted(from, a.talking_to_kind); if(from->errorlist_first) - MD_StackPush(remembered_error_free_list, from->errorlist_first); + StackPush(remembered_error_free_list, from->errorlist_first); from->errorlist_first = 0; from->errorlist_last = 0; @@ -1998,14 +1990,14 @@ bool perform_action(GameState *gs, Entity *from, Action a) } // the angel knows all - if(!MD_S8Match(gs->player->current_room_name, MD_S8Lit("StartingRoom"), 0) && !angel_heard_action) + if(!S8Match(gs->player->current_room_name, S8Lit("StartingRoom"), 0) && !angel_heard_action) { MemoryContext angel_context = context; angel_context.i_said_this = false; remember_action(gs, gs->angel, a, angel_context); } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); return proceed_propagating; } @@ -2035,11 +2027,11 @@ Entity *new_entity(GameState *gs) typedef struct ToVisit { struct ToVisit *next; struct ToVisit *prev; - MD_Node *ptr; + Node *ptr; int depth; } ToVisit ; -bool in_arr(ToVisit *arr, MD_Node *n) +bool in_arr(ToVisit *arr, Node *n) { for(ToVisit *cur = arr; cur; cur = cur->next) { @@ -2048,66 +2040,66 @@ bool in_arr(ToVisit *arr, MD_Node *n) return false; } -void dump_nodes(MD_Node *node) +void dump_nodes(Node *node) { - MD_ArenaTemp scratch = MD_GetScratch(0, 0); + ArenaTemp scratch = GetScratch(0, 0); ToVisit *horizon_first = 0; ToVisit *horizon_last = 0; ToVisit *visited = 0; - ToVisit *first = MD_PushArrayZero(scratch.arena, ToVisit, 1); + ToVisit *first = PushArrayZero(scratch.arena, ToVisit, 1); first->ptr = node; - MD_DblPushBack(horizon_first, horizon_last, first); + DblPushBack(horizon_first, horizon_last, first); while(horizon_first) { ToVisit *cur_tovisit = horizon_first; - MD_DblRemove(horizon_first, horizon_last, cur_tovisit); - MD_StackPush(visited, cur_tovisit); + DblRemove(horizon_first, horizon_last, cur_tovisit); + StackPush(visited, cur_tovisit); char *tagstr = " "; - if(cur_tovisit->ptr->kind == MD_NodeKind_Tag) tagstr = "TAG"; + if(cur_tovisit->ptr->kind == NodeKind_Tag) tagstr = "TAG"; printf("%s", tagstr); for(int i = 0; i < cur_tovisit->depth; i++) printf(" |"); - printf(" `%.*s`\n", MD_S8VArg(cur_tovisit->ptr->string)); + printf(" `%.*s`\n", S8VArg(cur_tovisit->ptr->string)); - for(MD_Node *cur = cur_tovisit->ptr->first_child; !MD_NodeIsNil(cur); cur = cur->next) + for(Node *cur = cur_tovisit->ptr->first_child; !NodeIsNil(cur); cur = cur->next) { if(!in_arr(visited, cur)) { - ToVisit *new = MD_PushArrayZero(scratch.arena, ToVisit, 1); + ToVisit *new = PushArrayZero(scratch.arena, ToVisit, 1); new->depth = cur_tovisit->depth + 1; new->ptr = cur; - MD_DblPushFront(horizon_first, horizon_last, new); + DblPushFront(horizon_first, horizon_last, new); } } - for(MD_Node *cur = cur_tovisit->ptr->first_tag; !MD_NodeIsNil(cur); cur = cur->next) + for(Node *cur = cur_tovisit->ptr->first_tag; !NodeIsNil(cur); cur = cur->next) { if(!in_arr(visited, cur)) { - ToVisit *new = MD_PushArrayZero(scratch.arena, ToVisit, 1); + ToVisit *new = PushArrayZero(scratch.arena, ToVisit, 1); new->depth = cur_tovisit->depth + 1; new->ptr = cur; - MD_DblPushFront(horizon_first, horizon_last, new); + DblPushFront(horizon_first, horizon_last, new); } } } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); } // allocates the error on the arena -MD_Node *expect_childnode(MD_Arena *arena, MD_Node *parent, MD_String8 string, MD_String8List *errors) +Node *expect_childnode(Arena *arena, Node *parent, String8 string, String8List *errors) { - MD_Node *to_return = MD_NilNode(); + Node *to_return = NilNode(); if(errors->node_count == 0) { - MD_Node *child_node = MD_ChildFromString(parent, string, 0); - if(MD_NodeIsNil(child_node)) + Node *child_node = MD_ChildFromString(parent, string, 0); + if(NodeIsNil(child_node)) { - PushWithLint(arena, errors, "Couldn't find expected field %.*s", MD_S8VArg(string)); + PushWithLint(arena, errors, "Couldn't find expected field %.*s", S8VArg(string)); } else { @@ -2117,13 +2109,13 @@ MD_Node *expect_childnode(MD_Arena *arena, MD_Node *parent, MD_String8 string, M return to_return; } -int parse_enumstr_impl(MD_Arena *arena, MD_String8 enum_str, char **enumstr_array, int enumstr_array_length, MD_String8List *errors, char *enum_kind_name, char *prefix) +int parse_enumstr_impl(Arena *arena, String8 enum_str, char **enumstr_array, int enumstr_array_length, String8List *errors, char *enum_kind_name, char *prefix) { - MD_ArenaTemp scratch = MD_GetScratch(&arena, 1); + ArenaTemp scratch = GetScratch(&arena, 1); int to_return = -1; if(errors->node_count == 0) { - MD_String8 enum_name_looking_for = enum_str; + String8 enum_name_looking_for = enum_str; if(enum_name_looking_for.size == 0) { PushWithLint(arena, errors, "`%s` string must be of size greater than 0", enum_kind_name); @@ -2132,7 +2124,7 @@ int parse_enumstr_impl(MD_Arena *arena, MD_String8 enum_str, char **enumstr_arra { for(int i = 0; i < enumstr_array_length; i++) { - if(MD_S8Match(FmtWithLint(scratch.arena, "%s%s", prefix, enumstr_array[i]), enum_name_looking_for, 0)) + if(S8Match(FmtWithLint(scratch.arena, "%s%s", prefix, enumstr_array[i]), enum_name_looking_for, 0)) { to_return = i; break; @@ -2143,10 +2135,10 @@ int parse_enumstr_impl(MD_Arena *arena, MD_String8 enum_str, char **enumstr_arra if(to_return == -1) { - PushWithLint(arena, errors, "The %s `%.*s` could not be recognized in the game", enum_kind_name, MD_S8VArg(enum_str)); + PushWithLint(arena, errors, "The %s `%.*s` could not be recognized in the game", enum_kind_name, S8VArg(enum_str)); } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); return to_return; } @@ -2165,15 +2157,15 @@ Vec2 point_plane(Vec3 p) ThreeDeeLevel level_threedee = {0}; -void transition_to_room(GameState *gs, ThreeDeeLevel *level, MD_String8 new_room_name) +void transition_to_room(GameState *gs, ThreeDeeLevel *level, String8 new_room_name) { - Log("Transitioning to %.*s...\n", MD_S8VArg(new_room_name)); + Log("Transitioning to %.*s...\n", S8VArg(new_room_name)); assert(gs); (void)level; gs->player->current_room_name = new_room_name; - if(MD_S8Match(new_room_name, MD_S8Lit("StartingRoom"), 0)) + if(S8Match(new_room_name, S8Lit("StartingRoom"), 0)) { gs->angel->perceptions_dirty = true; } @@ -2220,24 +2212,24 @@ void initialize_gamestate_from_threedee_level(GameState *gs, ThreeDeeLevel *leve it->target_rotation = it->rotation; } - transition_to_room(gs, &level_threedee, MD_S8Lit("Forest")); // hack to disable cold opening angel sequence right now + transition_to_room(gs, &level_threedee, S8Lit("Forest")); // hack to disable cold opening angel sequence right now // @Place(parse and enact the drama document parse drama) if(1) { - MD_String8List drama_errors = {0}; + String8List drama_errors = {0}; - MD_ArenaTemp scratch = MD_GetScratch(0, 0); - MD_String8 filename = MD_S8Lit("assets/drama.mdesk"); - MD_String8 drama_document = MD_LoadEntireFile(scratch.arena, filename); + ArenaTemp scratch = GetScratch(0, 0); + String8 filename = S8Lit("assets/drama.mdesk"); + String8 drama_document = LoadEntireFile(scratch.arena, filename); assert(drama_document.size != 0); - MD_ParseResult parse = MD_ParseWholeString(scratch.arena, filename, drama_document); + ParseResult parse = ParseWholeString(scratch.arena, filename, drama_document); if(parse.errors.first) { - for(MD_Message *cur = parse.errors.first; cur; cur = cur->next) + for(Message *cur = parse.errors.first; cur; cur = cur->next) { - MD_String8 to_print = MD_FormatMessage(scratch.arena, MD_CodeLocFromNode(cur->node), cur->kind, cur->string); - PushWithLint(scratch.arena, &drama_errors, "Failed to parse: `%.*s`\n", MD_S8VArg(to_print)); + String8 to_print = MD_FormatMessage(scratch.arena, CodeLocFromNode(cur->node), cur->kind, cur->string); + PushWithLint(scratch.arena, &drama_errors, "Failed to parse: `%.*s`\n", S8VArg(to_print)); } } @@ -2246,13 +2238,13 @@ void initialize_gamestate_from_threedee_level(GameState *gs, ThreeDeeLevel *leve { // used - MD_Node *can_hear = MD_NilNode(); - for(MD_Node *cur = parse.node->first_child->first_child; !MD_NodeIsNil(cur) && drama_errors.node_count == 0; cur = cur->next) + Node *can_hear = NilNode(); + for(Node *cur = parse.node->first_child->first_child; !NodeIsNil(cur) && drama_errors.node_count == 0; cur = cur->next) { - MD_Node *cur_can_hear = MD_ChildFromString(cur, MD_S8Lit("can_hear"), 0); - if(!MD_NodeIsNil(cur_can_hear)) + Node *cur_can_hear = MD_ChildFromString(cur, S8Lit("can_hear"), 0); + if(!NodeIsNil(cur_can_hear)) { - if(MD_NodeIsNil(cur_can_hear->first_child)) + if(NodeIsNil(cur_can_hear->first_child)) { PushWithLint(scratch.arena, &drama_errors, "`can_hear` must be followed by a valid array of NPC kinds who can hear the following conversation"); } @@ -2263,7 +2255,7 @@ void initialize_gamestate_from_threedee_level(GameState *gs, ThreeDeeLevel *leve } else { - if(MD_NodeIsNil(can_hear)) + if(NodeIsNil(can_hear)) { PushWithLint(scratch.arena, &drama_errors, "Expected a statement with `can_hear` before any speech that says who can hear the current speech"); } @@ -2273,18 +2265,18 @@ void initialize_gamestate_from_threedee_level(GameState *gs, ThreeDeeLevel *leve current_context.drama_memory = true; if(drama_errors.node_count == 0) { - MD_String8 enum_str = expect_childnode(scratch.arena, cur, MD_S8Lit("enum"), &drama_errors)->first_child->string; - MD_String8 dialog = expect_childnode(scratch.arena, cur, MD_S8Lit("dialog"), &drama_errors)->first_child->string; - MD_String8 action_str = MD_ChildFromString(cur, MD_S8Lit("action"), 0)->first_child->string; - MD_String8 action_argument_str = MD_ChildFromString(cur, MD_S8Lit("action_argument"), 0)->first_child->string; - MD_String8 to_str = MD_ChildFromString(cur, MD_S8Lit("to"), 0)->first_child->string; + String8 enum_str = expect_childnode(scratch.arena, cur, S8Lit("enum"), &drama_errors)->first_child->string; + String8 dialog = expect_childnode(scratch.arena, cur, S8Lit("dialog"), &drama_errors)->first_child->string; + String8 action_str = MD_ChildFromString(cur, S8Lit("action"), 0)->first_child->string; + String8 action_argument_str = MD_ChildFromString(cur, S8Lit("action_argument"), 0)->first_child->string; + String8 to_str = MD_ChildFromString(cur, S8Lit("to"), 0)->first_child->string; if(to_str.size > 0) { NpcKind talking_to = parse_enumstr(scratch.arena, to_str, &drama_errors, NpcKind_enum_names, "NpcKind", ""); if (talking_to == NPC_nobody) { - PushWithLint(scratch.arena, &drama_errors, "The string provided for the 'to' field, intended to be who the NPC is directing their speech and action at, is invalid and is '%.*s'", MD_S8VArg(to_str)); + PushWithLint(scratch.arena, &drama_errors, "The string provided for the 'to' field, intended to be who the NPC is directing their speech and action at, is invalid and is '%.*s'", S8VArg(to_str)); } else { @@ -2300,11 +2292,11 @@ void initialize_gamestate_from_threedee_level(GameState *gs, ThreeDeeLevel *leve } if(action_argument_str.size > 0) { - MD_String8 error = {0}; + String8 error = {0}; parse_action_argument(scratch.arena, &error, current_action.kind, action_argument_str, ¤t_action.argument); if(error.size > 0) { - PushWithLint(scratch.arena, &drama_errors, "Error parsing argument: '%.*s'", MD_S8VArg(error)); + PushWithLint(scratch.arena, &drama_errors, "Error parsing argument: '%.*s'", S8VArg(error)); } } @@ -2322,7 +2314,7 @@ void initialize_gamestate_from_threedee_level(GameState *gs, ThreeDeeLevel *leve if(drama_errors.node_count == 0) { - for(MD_Node *cur_kind_node = can_hear; !MD_NodeIsNil(cur_kind_node); cur_kind_node = cur_kind_node->next) + for(Node *cur_kind_node = can_hear; !NodeIsNil(cur_kind_node); cur_kind_node = cur_kind_node->next) { NpcKind want = parse_enumstr(scratch.arena, cur_kind_node->string, &drama_errors, NpcKind_enum_names, "NpcKind", ""); if(drama_errors.node_count == 0) @@ -2399,9 +2391,9 @@ void initialize_gamestate_from_threedee_level(GameState *gs, ThreeDeeLevel *leve if(drama_errors.node_count > 0) { - for(MD_String8Node *cur = drama_errors.first; cur; cur = cur->next) + for(String8Node *cur = drama_errors.first; cur; cur = cur->next) { - fprintf(stderr, "Error: %.*s\n", MD_S8VArg(cur->string)); + fprintf(stderr, "Error: %.*s\n", S8VArg(cur->string)); } assert(false); } @@ -2436,7 +2428,7 @@ enum #define SER_BUFF(ser, BuffElemType, buff_ptr) {ser_int(ser, &((buff_ptr)->cur_index));\ if((buff_ptr)->cur_index > ARRLEN((buff_ptr)->data))\ {\ - ser->cur_error = (SerError){.failed = true, .why = MD_S8Fmt(ser->error_arena, "Current index %d is more than the buffer %s's maximum, %d", (buff_ptr)->cur_index, #buff_ptr, ARRLEN((buff_ptr)->data))};\ + ser->cur_error = (SerError){.failed = true, .why = S8Fmt(ser->error_arena, "Current index %d is more than the buffer %s's maximum, %d", (buff_ptr)->cur_index, #buff_ptr, ARRLEN((buff_ptr)->data))};\ }\ BUFF_ITER(BuffElemType, buff_ptr)\ {\ @@ -2449,9 +2441,9 @@ void ser_TextChunk(SerState *ser, TextChunk *t) ser_int(ser, &t->text_length); if(t->text_length >= ARRLEN(t->text)) { - ser->cur_error = (SerError){.failed = true, .why = MD_S8Fmt(ser->error_arena, "In text chunk, length %d is too big to fit into %d", t->text_length, ARRLEN(t->text))}; + ser->cur_error = (SerError){.failed = true, .why = S8Fmt(ser->error_arena, "In text chunk, length %d is too big to fit into %d", t->text_length, ARRLEN(t->text))}; } - ser_bytes(ser, (MD_u8*)t->text, t->text_length); + ser_bytes(ser, (u8*)t->text, t->text_length); } void ser_entity(SerState *ser, Entity *e) @@ -2493,9 +2485,9 @@ void ser_entity(SerState *ser, Entity *e) ser_bool(ser, &more_errors); while(more_errors) { - TextChunkList *new_chunk = MD_PushArray(ser->arena, TextChunkList, 1); + TextChunkList *new_chunk = PushArray(ser->arena, TextChunkList, 1); ser_TextChunk(ser, &new_chunk->text); - MD_DblPushBack(e->errorlist_first, e->errorlist_last, new_chunk); + DblPushBack(e->errorlist_first, e->errorlist_last, new_chunk); ser_bool(ser, &more_errors); } } @@ -2520,9 +2512,9 @@ void ser_entity(SerState *ser, Entity *e) ser_bool(ser, &more_memories); while(more_memories) { - Memory *new_chunk = MD_PushArray(ser->arena, Memory, 1); + Memory *new_chunk = PushArray(ser->arena, Memory, 1); ser_Memory(ser, new_chunk); - MD_DblPushBack(e->memories_first, e->memories_last, new_chunk); + DblPushBack(e->memories_first, e->memories_last, new_chunk); ser_bool(ser, &more_memories); } } @@ -2549,7 +2541,7 @@ void ser_GameState(SerState *ser, GameState *gs) ser_int(ser, &ser->version); if(ser->version >= VMax) { - ser->cur_error = (SerError){.failed = true, .why = MD_S8Fmt(ser->error_arena, "Version %d is beyond the current version, %d", ser->version, VMax - 1)}; + ser->cur_error = (SerError){.failed = true, .why = S8Fmt(ser->error_arena, "Version %d is beyond the current version, %d", ser->version, VMax - 1)}; } ser_uint64_t(ser, &gs->tick); @@ -2587,20 +2579,20 @@ void ser_GameState(SerState *ser, GameState *gs) if(gs->player == 0) { - ser->cur_error = (SerError){.failed = true, .why = MD_S8Lit("No player entity found in deserialized entities")}; + ser->cur_error = (SerError){.failed = true, .why = S8Lit("No player entity found in deserialized entities")}; } if(gs->world_entity == 0) { - ser->cur_error = (SerError){.failed = true, .why = MD_S8Lit("No world entity found in deserialized entities")}; + ser->cur_error = (SerError){.failed = true, .why = S8Lit("No world entity found in deserialized entities")}; } } } // error_out is allocated onto arena if it fails -MD_String8 save_to_string(MD_Arena *output_bytes_arena, MD_Arena *error_arena, MD_String8 *error_out, GameState *gs) +String8 save_to_string(Arena *output_bytes_arena, Arena *error_arena, String8 *error_out, GameState *gs) { - MD_u8 *serialized_data = 0; - MD_u64 serialized_length = 0; + u8 *serialized_data = 0; + u64 serialized_length = 0; { SerState ser = { .version = VMax - 1, @@ -2619,16 +2611,16 @@ MD_String8 save_to_string(MD_Arena *output_bytes_arena, MD_Arena *error_arena, M ser.max = ser.cur; ser.cur = 0; ser.version = VMax - 1; - MD_ArenaTemp temp = MD_ArenaBeginTemp(output_bytes_arena); - serialized_data = MD_ArenaPush(temp.arena, ser.max); + ArenaTemp temp = ArenaBeginTemp(output_bytes_arena); + serialized_data = ArenaPush(temp.arena, ser.max); ser.data = serialized_data; ser_GameState(&ser, gs); if(ser.cur_error.failed) { Log("Very weird that serialization fails a second time...\n"); - *error_out = MD_S8Fmt(error_arena, "VERY BAD Serialization failed after it already had no error: %.*s", ser.cur_error.why); - MD_ArenaEndTemp(temp); + *error_out = S8Fmt(error_arena, "VERY BAD Serialization failed after it already had no error: %.*s", ser.cur_error.why); + ArenaEndTemp(temp); serialized_data = 0; } else @@ -2637,16 +2629,16 @@ MD_String8 save_to_string(MD_Arena *output_bytes_arena, MD_Arena *error_arena, M } } } - return MD_S8(serialized_data, serialized_length); + return S8(serialized_data, serialized_length); } // error strings are allocated on error_arena, probably scratch for that. If serialization fails, // nothing is allocated onto arena, the allocations are rewound // If there was an error, the gamestate returned might be partially constructed and bad. Don't use it -GameState load_from_string(MD_Arena *arena, MD_Arena *error_arena, MD_String8 data, MD_String8 *error_out) +GameState load_from_string(Arena *arena, Arena *error_arena, String8 data, String8 *error_out) { - MD_ArenaTemp temp = MD_ArenaBeginTemp(arena); + ArenaTemp temp = ArenaBeginTemp(arena); SerState ser = { .serializing = false, @@ -2659,7 +2651,7 @@ GameState load_from_string(MD_Arena *arena, MD_Arena *error_arena, MD_String8 da ser_GameState(&ser, &to_return); if(ser.cur_error.failed) { - MD_ArenaEndTemp(temp); // no allocations if it fails + ArenaEndTemp(temp); // no allocations if it fails *error_out = ser.cur_error.why; } return to_return; @@ -2669,14 +2661,14 @@ GameState load_from_string(MD_Arena *arena, MD_Arena *error_arena, MD_String8 da EMSCRIPTEN_KEEPALIVE void dump_save_data() { - MD_ArenaTemp scratch = MD_GetScratch(0, 0); + ArenaTemp scratch = GetScratch(0, 0); - MD_String8 error = {0}; - MD_String8 saved = save_to_string(scratch.arena, scratch.arena, &error, &gs); + String8 error = {0}; + String8 saved = save_to_string(scratch.arena, scratch.arena, &error, &gs); if(error.size > 0) { - Log("Failed to save game: %.*s\n", MD_S8VArg(error)); + Log("Failed to save game: %.*s\n", S8VArg(error)); } else { @@ -2685,35 +2677,35 @@ void dump_save_data() }, (char*)(saved.str), saved.size); } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); } EMSCRIPTEN_KEEPALIVE void read_from_save_data(char *data, size_t length) { - MD_ArenaTemp scratch = MD_GetScratch(0, 0); - MD_String8 data_str = MD_S8((MD_u8*)data, length); + ArenaTemp scratch = GetScratch(0, 0); + String8 data_str = S8((u8*)data, length); - MD_String8 error = {0}; + String8 error = {0}; GameState new_gs = load_from_string(persistent_arena, scratch.arena, data_str, &error); if(error.size > 0) { - Log("Failed to load from size %lu: %.*s\n", length, MD_S8VArg(error)); + Log("Failed to load from size %lu: %.*s\n", length, S8VArg(error)); } else { gs = new_gs; } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); } #endif // a callback, when 'text backend' has finished making text. End dialog void end_text_input(char *what_player_said_cstr) { - MD_ArenaTemp scratch = MD_GetScratch(0, 0); + ArenaTemp scratch = GetScratch(0, 0); // avoid double ending text input if (!receiving_text_input) { @@ -2730,11 +2722,11 @@ void end_text_input(char *what_player_said_cstr) } else { - MD_String8 what_player_said = MD_S8CString(what_player_said_cstr); - what_player_said = MD_S8ListJoin(scratch.arena, MD_S8Split(scratch.arena, what_player_said, 1, &MD_S8Lit("\n")), &(MD_StringJoin){0}); + String8 what_player_said = S8CString(what_player_said_cstr); + what_player_said = S8ListJoin(scratch.arena, S8Split(scratch.arena, what_player_said, 1, &S8Lit("\n")), &(StringJoin){0}); Action to_perform = {0}; - what_player_said = MD_S8Substring(what_player_said, 0, ARRLEN(to_perform.speech.text)); + what_player_said = S8Substring(what_player_said, 0, ARRLEN(to_perform.speech.text)); chunk_from_s8(&to_perform.speech, what_player_said); @@ -2756,7 +2748,7 @@ void end_text_input(char *what_player_said_cstr) perform_action(&gs, gs.player, to_perform); } } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); } /* AnimatedSprite moose_idle = @@ -2951,13 +2943,13 @@ int num_vertices = 0; // if it's an invalid anim name, it just returns the idle animation -Animation *get_anim_by_name(Armature *armature, MD_String8 anim_name) +Animation *get_anim_by_name(Armature *armature, String8 anim_name) { - MD_String8List anims = {0}; - for(MD_u64 i = 0; i < armature->animations_length; i++) + String8List anims = {0}; + for(u64 i = 0; i < armature->animations_length; i++) { - MD_S8ListPush(frame_arena, &anims, armature->animations[i].name); - if(MD_S8Match(armature->animations[i].name, anim_name, 0)) + S8ListPush(frame_arena, &anims, armature->animations[i].name); + if(S8Match(armature->animations[i].name, anim_name, 0)) { return &armature->animations[i]; } @@ -2965,13 +2957,13 @@ Animation *get_anim_by_name(Armature *armature, MD_String8 anim_name) if(anim_name.size > 0) { - MD_String8 anims_str = MD_S8ListJoin(frame_arena, anims, &(MD_StringJoin){.mid = MD_S8Lit(", ")}); - Log("No animation found '%.*s', the animations: [%.*s]\n", MD_S8VArg(anim_name), MD_S8VArg(anims_str)); + String8 anims_str = S8ListJoin(frame_arena, anims, &(StringJoin){.mid = S8Lit(", ")}); + Log("No animation found '%.*s', the animations: [%.*s]\n", S8VArg(anim_name), S8VArg(anims_str)); } - for(MD_u64 i = 0; i < armature->animations_length; i++) + for(u64 i = 0; i < armature->animations_length; i++) { - if(MD_S8Match(armature->animations[i].name, MD_S8Lit("Idle"), 0)) + if(S8Match(armature->animations[i].name, S8Lit("Idle"), 0)) { return &armature->animations[i]; } @@ -2995,7 +2987,7 @@ Transform get_animated_bone_transform(AnimationTrack *track, float time, bool do { time = fmodf(time, total_anim_time); } - for(MD_u64 i = 0; i < track->poses_length - 1; i++) + for(u64 i = 0; i < track->poses_length - 1; i++) { if(track->poses[i].time <= time && time <= track->poses[i + 1].time) { @@ -3014,7 +3006,7 @@ Transform get_animated_bone_transform(AnimationTrack *track, float time, bool do typedef struct { - MD_u8 rgba[4]; + u8 rgba[4]; } PixelData; PixelData encode_normalized_float32(float to_encode) @@ -3042,7 +3034,7 @@ PixelData encode_normalized_float32(float to_encode) for(int i = 0; i < 4; i++) { assert(0.0f <= to_return_vector.Elements[i] && to_return_vector.Elements[i] <= 1.0f); - to_return.rgba[i] = (MD_u8)(to_return_vector.Elements[i] * 255.0f); + to_return.rgba[i] = (u8)(to_return_vector.Elements[i] * 255.0f); } return to_return; @@ -3165,16 +3157,16 @@ Vec2 img_size(sg_image img) void do_metadesk_tests() { Log("Testing metadesk library...\n"); - MD_Arena *arena = MD_ArenaAlloc(); - MD_String8 s = MD_S8Lit("This is a testing|string"); + Arena *arena = ArenaAlloc(); + String8 s = S8Lit("This is a testing|string"); - MD_String8List split_up = MD_S8Split(arena, s, 1, &MD_S8Lit("|")); + String8List split_up = S8Split(arena, s, 1, &S8Lit("|")); assert(split_up.node_count == 2); - assert(MD_S8Match(split_up.first->string, MD_S8Lit("This is a testing"), 0)); - assert(MD_S8Match(split_up.last->string, MD_S8Lit("string"), 0)); + assert(S8Match(split_up.first->string, S8Lit("This is a testing"), 0)); + assert(S8Match(split_up.last->string, S8Lit("string"), 0)); - MD_ArenaRelease(arena); + ArenaRelease(arena); Log("Testing passed!\n"); } @@ -3182,8 +3174,8 @@ void do_parsing_tests() { Log("(UNIMPLEMENTED) Testing chatgpt parsing...\n"); - MD_ArenaTemp scratch = MD_GetScratch(0, 0); - MD_ReleaseScratch(scratch); + ArenaTemp scratch = GetScratch(0, 0); + ReleaseScratch(scratch); } // these tests rely on the base level having been loaded @@ -3191,15 +3183,15 @@ void do_serialization_tests() { Log("Testing serialization...\n"); - MD_ArenaTemp scratch = MD_GetScratch(0, 0); + ArenaTemp scratch = GetScratch(0, 0); GameState gs = {0}; initialize_gamestate_from_threedee_level(&gs, &level_threedee); gs.player->pos = V2(50.0f, 0.0); - MD_String8 error = {0}; - MD_String8 saved = save_to_string(scratch.arena, scratch.arena, &error, &gs); + String8 error = {0}; + String8 saved = save_to_string(scratch.arena, scratch.arena, &error, &gs); assert(error.size == 0); assert(saved.size > 0); @@ -3212,7 +3204,7 @@ void do_serialization_tests() Log("Default save data size is %lld bytes\n", saved.size); - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); } void do_float_encoding_tests() @@ -3236,7 +3228,7 @@ typedef struct { float font_size; float font_line_advance; float font_scale; - MD_String8 font_buffer; + String8 font_buffer; stbtt_bakedchar cdata[96]; // ascii characters? stbtt_fontinfo font; @@ -3247,20 +3239,20 @@ typedef struct { LoadedFont default_font; LoadedFont font_for_text_input; // is bigger -LoadedFont load_font(MD_Arena *arena, MD_String8 font_filepath, float font_size) +LoadedFont load_font(Arena *arena, String8 font_filepath, float font_size) { LoadedFont to_return = {0}; - to_return.font_buffer = MD_LoadEntireFile(arena, font_filepath); + to_return.font_buffer = LoadEntireFile(arena, font_filepath); to_return.font_size = font_size; - unsigned char *font_bitmap = MD_ArenaPush(arena, 512*512); + unsigned char *font_bitmap = ArenaPush(arena, 512*512); const int font_bitmap_width = 512; stbtt_BakeFontBitmap(to_return.font_buffer.str, 0, to_return.font_size, font_bitmap, font_bitmap_width, font_bitmap_width, 32, 96, to_return.cdata); - unsigned char *font_bitmap_rgba = MD_ArenaPush(frame_arena, 4 * font_bitmap_width * font_bitmap_width); + unsigned char *font_bitmap_rgba = ArenaPush(frame_arena, 4 * font_bitmap_width * font_bitmap_width); // also flip the image, because I think opengl or something I'm too tired for(int row = 0; row < 512; row++) @@ -3327,10 +3319,10 @@ void stbi_flip_into_correct_direction(bool do_it) if(do_it) stbi_set_flip_vertically_on_load(true); } -MD_String8 make_devtools_help(MD_Arena *arena) +String8 make_devtools_help(Arena *arena) { - MD_ArenaTemp scratch = MD_GetScratch(&arena, 1); - MD_String8List list = {0}; + ArenaTemp scratch = GetScratch(&arena, 1); + String8List list = {0}; #define P(...) PushWithLint(scratch.arena, &list, __VA_ARGS__) @@ -3350,8 +3342,8 @@ MD_String8 make_devtools_help(MD_Arena *arena) P("P - immediately kills %s\n", characters[NPC_Raphael].name); #undef P - MD_String8 to_return = MD_S8ListJoin(arena, list, &(MD_StringJoin){0}); - MD_ReleaseScratch(scratch); + String8 to_return = S8ListJoin(arena, list, &(StringJoin){0}); + ReleaseScratch(scratch); return to_return; } @@ -3365,16 +3357,16 @@ void init(void) }, SERVER_DOMAIN ); #endif - frame_arena = MD_ArenaAlloc(); + frame_arena = ArenaAlloc(); #ifdef WEB next_arena_big = true; #endif - persistent_arena = MD_ArenaAlloc(); + persistent_arena = ArenaAlloc(); #ifdef DEVTOOLS Log("Devtools is on!\n"); - MD_String8 devtools_help = make_devtools_help(frame_arena); - printf("%.*s\n", MD_S8VArg(devtools_help)); + String8 devtools_help = make_devtools_help(frame_arena); + printf("%.*s\n", S8VArg(devtools_help)); #else Log("Devtools is off!\n"); #endif @@ -3401,35 +3393,35 @@ void init(void) Log("Loading 3D assets...\n"); - MD_String8 binary_file; + String8 binary_file; - binary_file = MD_LoadEntireFile(frame_arena, MD_S8Lit("assets/exported_3d/rooms.bin")); + binary_file = LoadEntireFile(frame_arena, S8Lit("assets/exported_3d/rooms.bin")); level_threedee = load_level(persistent_arena, binary_file); - binary_file = MD_LoadEntireFile(frame_arena, MD_S8Lit("assets/exported_3d/Shotgun.bin")); - mesh_shotgun = load_mesh(persistent_arena, binary_file, MD_S8Lit("Shotgun.bin")); + binary_file = LoadEntireFile(frame_arena, S8Lit("assets/exported_3d/Shotgun.bin")); + mesh_shotgun = load_mesh(persistent_arena, binary_file, S8Lit("Shotgun.bin")); - binary_file = MD_LoadEntireFile(frame_arena, MD_S8Lit("assets/exported_3d/AngelTotem.bin")); - mesh_angel_totem = load_mesh(persistent_arena, binary_file, MD_S8Lit("AngelTotem.bin")); + binary_file = LoadEntireFile(frame_arena, S8Lit("assets/exported_3d/AngelTotem.bin")); + mesh_angel_totem = load_mesh(persistent_arena, binary_file, S8Lit("AngelTotem.bin")); - binary_file = MD_LoadEntireFile(frame_arena, MD_S8Lit("assets/exported_3d/NormalGuyArmature.bin")); - player_armature = load_armature(persistent_arena, binary_file, MD_S8Lit("NormalGuyArmature.bin")); + binary_file = LoadEntireFile(frame_arena, S8Lit("assets/exported_3d/NormalGuyArmature.bin")); + player_armature = load_armature(persistent_arena, binary_file, S8Lit("NormalGuyArmature.bin")); - man_in_black_armature = load_armature(persistent_arena, binary_file, MD_S8Lit("Man In Black")); + man_in_black_armature = load_armature(persistent_arena, binary_file, S8Lit("Man In Black")); man_in_black_armature.image = image_man_in_black; - angel_armature = load_armature(persistent_arena, binary_file, MD_S8Lit("Angel")); + angel_armature = load_armature(persistent_arena, binary_file, S8Lit("Angel")); angel_armature.image = image_angel; - binary_file = MD_LoadEntireFile(frame_arena, MD_S8Lit("assets/exported_3d/FarmerArmature.bin")); - farmer_armature = load_armature(persistent_arena, binary_file, MD_S8Lit("FarmerArmature.bin")); + binary_file = LoadEntireFile(frame_arena, S8Lit("assets/exported_3d/FarmerArmature.bin")); + farmer_armature = load_armature(persistent_arena, binary_file, S8Lit("FarmerArmature.bin")); - shifted_farmer_armature = load_armature(persistent_arena, binary_file, MD_S8Lit("Farmer.bin")); + shifted_farmer_armature = load_armature(persistent_arena, binary_file, S8Lit("Farmer.bin")); shifted_farmer_armature.image = image_shifted_farmer; Log("Done. Used %f of the frame arena, %llu kB\n", (double) frame_arena->pos / (double)frame_arena->cap, (frame_arena->pos/1024)); - MD_ArenaClear(frame_arena); + ArenaClear(frame_arena); reset_level(); @@ -3446,8 +3438,8 @@ void init(void) }); #endif - default_font = load_font(persistent_arena, MD_S8Lit("assets/PalanquinDark-Regular.ttf"), 35.0f); - font_for_text_input = load_font(persistent_arena, MD_S8Lit("assets/PalanquinDark-Regular.ttf"), 64.0f); + default_font = load_font(persistent_arena, S8Lit("assets/PalanquinDark-Regular.ttf"), 35.0f); + font_for_text_input = load_font(persistent_arena, S8Lit("assets/PalanquinDark-Regular.ttf"), 64.0f); state.bind.vertex_buffers[0] = sg_make_buffer(&(sg_buffer_desc) @@ -4447,7 +4439,7 @@ void draw_thing(DrawnThing params) typedef struct TextParams { bool dry_run; - MD_String8 text; + String8 text; Vec2 pos; Color color; float scale; @@ -4689,7 +4681,7 @@ Vec2 move_and_slide(MoveSlideParams p) { ENTITIES_ITER(gs.entities) { - if (it != p.from && !(it->is_npc && it->dead) && !it->is_world && MD_S8Match(it->current_room_name, p.from->current_room_name, 0)) + if (it != p.from && !(it->is_npc && it->dead) && !it->is_world && S8Match(it->current_room_name, p.from->current_room_name, 0)) { BUFF_APPEND(&to_check, ((CollisionObj){.circle.center = it->pos, .circle.radius = entity_radius(it), it})); } @@ -4815,17 +4807,17 @@ float character_width(LoadedFont for_font, int ascii_letter, float text_scale) // they're always joined by spaces anyways, so even if you add more delims // spaces will be added between them inshallah. -MD_String8List split_by_word(MD_Arena *arena, MD_String8 string) +String8List split_by_word(Arena *arena, String8 string) { - MD_String8 word_delimeters[] = { MD_S8Lit(" ") }; - return MD_S8Split(arena, string, ARRLEN(word_delimeters), word_delimeters); + String8 word_delimeters[] = { S8Lit(" ") }; + return S8Split(arena, string, ARRLEN(word_delimeters), word_delimeters); } typedef struct PlacedWord { struct PlacedWord *next; struct PlacedWord *prev; - MD_String8 text; + String8 text; Vec2 lower_left_corner; Vec2 size; int line_index; @@ -4844,10 +4836,10 @@ typedef enum JUST_CENTER, } TextJustification; -PlacedWordList place_wrapped_words(MD_Arena *arena, MD_String8List words, float text_scale, float maximum_width, LoadedFont for_font, TextJustification just) +PlacedWordList place_wrapped_words(Arena *arena, String8List words, float text_scale, float maximum_width, LoadedFont for_font, TextJustification just) { PlacedWordList to_return = {0}; - MD_ArenaTemp scratch = MD_GetScratch(&arena, 1); + ArenaTemp scratch = GetScratch(&arena, 1); int current_line_index = 0; { @@ -4855,7 +4847,7 @@ PlacedWordList place_wrapped_words(MD_Arena *arena, MD_String8List words, float Vec2 cur = at_position; float space_size = character_width(for_font, (int)' ', text_scale); float current_vertical_offset = 0.0f; // goes negative - for (MD_String8Node *next_word = words.first; next_word; next_word = next_word->next) + for (String8Node *next_word = words.first; next_word; next_word = next_word->next) { if (next_word->string.size == 0) { @@ -4873,13 +4865,13 @@ PlacedWordList place_wrapped_words(MD_Arena *arena, MD_String8List words, float next_x_position = cur.x + aabb_size(word_bounds).x; } - PlacedWord *new_placed = MD_PushArray(arena, PlacedWord, 1); + PlacedWord *new_placed = PushArray(arena, PlacedWord, 1); new_placed->text = next_word->string; new_placed->lower_left_corner = cur; new_placed->size = aabb_size(word_bounds); new_placed->line_index = current_line_index; - MD_DblPushBack(to_return.first, to_return.last, new_placed); + DblPushBack(to_return.first, to_return.last, new_placed); cur.x = next_x_position; } @@ -4892,7 +4884,7 @@ PlacedWordList place_wrapped_words(MD_Arena *arena, MD_String8List words, float break; case JUST_CENTER: { - //PlacedWord **by_line_index = MD_PushArray(scratch.arena, PlacedWord*, current_line_index); + //PlacedWord **by_line_index = PushArray(scratch.arena, PlacedWord*, current_line_index); for(int i = to_return.first->line_index; i <= to_return.last->line_index; i++) { PlacedWord *first_on_line = 0; @@ -4930,7 +4922,7 @@ PlacedWordList place_wrapped_words(MD_Arena *arena, MD_String8List words, float break; } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); return to_return; } @@ -4942,11 +4934,11 @@ void translate_words_by(PlacedWordList words, Vec2 translation) } } -MD_String8 last_said_sentence(Entity *npc) +String8 last_said_sentence(Entity *npc) { assert(npc->is_npc); - MD_String8 to_return = (MD_String8){0}; + String8 to_return = (String8){0}; for(Memory *cur = npc->memories_last; cur; cur = cur->prev) { @@ -4969,7 +4961,7 @@ typedef enum typedef struct { - MD_u8 speech[MAX_SENTENCE_LENGTH]; + u8 speech[MAX_SENTENCE_LENGTH]; int speech_length; DialogElementKind kind; NpcKind who_said_it; @@ -5060,7 +5052,7 @@ typedef struct { AABB button_aabb; float text_scale; - MD_String8 text; + String8 text; int key; float dt; bool force_down; @@ -5512,12 +5504,12 @@ void flush_all_drawn_things(Vec3 light_dir, Vec3 cam_pos, Vec3 cam_facing, Vec3 { if(it->armature) { - MD_ArenaTemp scratch = MD_GetScratch(0, 0); + ArenaTemp scratch = GetScratch(0, 0); Armature *armature = it->armature; int bones_tex_size = 4 * armature->bones_texture_width * armature->bones_texture_height; - MD_u8 *bones_tex = MD_ArenaPush(scratch.arena, bones_tex_size); + u8 *bones_tex = ArenaPush(scratch.arena, bones_tex_size); - for(MD_u64 i = 0; i < armature->bones_length; i++) + for(u64 i = 0; i < armature->bones_length; i++) { Bone *cur = &armature->bones[i]; @@ -5577,7 +5569,7 @@ void flush_all_drawn_things(Vec3 light_dir, Vec3 cam_pos, Vec3 cam_facing, Vec3 .subimage[0][0] = (sg_range){bones_tex, bones_tex_size}, }); - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); } } } @@ -5735,16 +5727,16 @@ TextPlacementSettings speech_bubble = { }; // Unsaid words are still there, so you gotta handle the animation homie -MD_String8List words_on_current_page(Entity *it, TextPlacementSettings *settings) +String8List words_on_current_page(Entity *it, TextPlacementSettings *settings) { - MD_String8 last = last_said_sentence(it); + String8 last = last_said_sentence(it); PlacedWordList placed = place_wrapped_words(frame_arena, split_by_word(frame_arena, last), settings->text_scale, settings->width_in_pixels, *settings->font, JUST_LEFT); - MD_String8List on_current_page = {0}; + String8List on_current_page = {0}; for(PlacedWord *cur = placed.first; cur; cur = cur->next) { if(cur->line_index / settings->lines_per_page == it->cur_page_index) - MD_S8ListPush(frame_arena, &on_current_page, cur->text); + S8ListPush(frame_arena, &on_current_page, cur->text); } return on_current_page; @@ -5752,16 +5744,16 @@ MD_String8List words_on_current_page(Entity *it, TextPlacementSettings *settings //return place_wrapped_words(frame_arena, on_current_page, text_scale, aabb_size(placing_text_in).x, default_font); } -MD_String8List words_on_current_page_without_unsaid(Entity *it, TextPlacementSettings *settings) +String8List words_on_current_page_without_unsaid(Entity *it, TextPlacementSettings *settings) { - MD_String8List all_words = words_on_current_page(it, settings); + String8List all_words = words_on_current_page(it, settings); int index = 0; - MD_String8List to_return = {0}; - for(MD_String8Node *cur = all_words.first; cur; cur = cur->next) + String8List to_return = {0}; + for(String8Node *cur = all_words.first; cur; cur = cur->next) { if(index > it->words_said_on_page) break; - MD_S8ListPush(frame_arena, &to_return, cur->string); + S8ListPush(frame_arena, &to_return, cur->string); index += 1; } return to_return; @@ -5891,28 +5883,28 @@ void frame(void) float seed = (float)((int64_t)cur % 1024); DrawnThing call = (DrawnThing){.mesh = cur->draw_with, .t = cur->t}; - if(MD_S8Match(cur->name, MD_S8Lit("Ground"), 0)) + if(S8Match(cur->name, S8Lit("Ground"), 0)) call.no_dust = true; call.no_dust = true; float helicopter_offset = (float)sin(elapsed_time*0.5f)*0.5f; - if(MD_S8Match(cur->name, MD_S8Lit("HelicopterBlade"), 0)) + if(S8Match(cur->name, S8Lit("HelicopterBlade"), 0)) { call.t.offset.y += helicopter_offset; call.t.rotation = QFromAxisAngle_RH(V3(0,1,0), (float)elapsed_time * 15.0f); } - if(MD_S8Match(cur->name, MD_S8Lit("BlurryBlade"), 0)) + if(S8Match(cur->name, S8Lit("BlurryBlade"), 0)) { call.t.rotation = QFromAxisAngle_RH(V3(0,1,0), (float)elapsed_time * 15.0f); call.t.offset.y += helicopter_offset; call.alpha_blend = true; call.dont_cast_shadows = true; } - if(MD_S8Match(cur->name, MD_S8Lit("HelicopterBody"), 0)) + if(S8Match(cur->name, S8Lit("HelicopterBody"), 0)) { call.t.offset.y += helicopter_offset; } - if(MD_S8FindSubstring(cur->name, MD_S8Lit("Bush"), 0, 0) == 0) + if(S8FindSubstring(cur->name, S8Lit("Bush"), 0, 0) == 0) { call.wobble_factor = 1.0f; call.seed = seed; @@ -5922,7 +5914,7 @@ void frame(void) ENTITIES_ITER(gs.entities) { - if(it->is_npc && MD_S8Match(it->current_room_name, gs.player->current_room_name, 0)) + if(it->is_npc && S8Match(it->current_room_name, gs.player->current_room_name, 0)) { assert(it->is_npc); Transform draw_with = entity_transform(it); @@ -5963,16 +5955,16 @@ void frame(void) } if (it->killed) { - to_use->go_to_animation = MD_S8Lit("Die Backwards"); + to_use->go_to_animation = S8Lit("Die Backwards"); to_use->next_animation_isnt_looping = true; } else if (LenV2(it->vel) > 0.5f) { - to_use->go_to_animation = MD_S8Lit("Running"); + to_use->go_to_animation = S8Lit("Running"); } else { - to_use->go_to_animation = MD_S8Lit("Idle"); + to_use->go_to_animation = S8Lit("Idle"); } draw_thing((DrawnThing){.armature = to_use, .t = draw_with, .outline = gete(gs.player->interacting_with) == it}); @@ -6008,7 +6000,7 @@ void frame(void) if(cur->go_to_animation.size > 0) { - if(MD_S8Match(cur->go_to_animation, cur->currently_playing_animation, 0)) + if(S8Match(cur->go_to_animation, cur->currently_playing_animation, 0)) { } else @@ -6016,7 +6008,7 @@ void frame(void) memcpy(cur->current_poses, cur->anim_blended_poses, cur->bones_length * sizeof(*cur->current_poses)); cur->currently_playing_animation = cur->go_to_animation; cur->animation_blend_t = 0.0f; - cur->go_to_animation = (MD_String8){0}; + cur->go_to_animation = (String8){0}; if(cur->next_animation_isnt_looping) { cur->cur_animation_time = 0.0; @@ -6037,7 +6029,7 @@ void frame(void) Animation *to_anim = get_anim_by_name(cur, cur->currently_playing_animation); assert(to_anim); - for(MD_u64 i = 0; i < cur->bones_length; i++) + for(u64 i = 0; i < cur->bones_length; i++) { Transform *output_transform = &cur->anim_blended_poses[i]; Transform from_transform = cur->current_poses[i]; @@ -6049,7 +6041,7 @@ void frame(void) else { Animation *cur_anim = get_anim_by_name(cur, cur->currently_playing_animation); - for(MD_u64 i = 0; i < cur->bones_length; i++) + for(u64 i = 0; i < cur->bones_length; i++) { cur->anim_blended_poses[i] = get_animated_bone_transform(&cur_anim->tracks[i], along_current_animation, cur->currently_playing_isnt_looping); } @@ -6073,7 +6065,7 @@ void frame(void) Entity *angel_entity = 0; ENTITIES_ITER(gs.entities) { - if (it->is_npc && it->npc_kind == NPC_Angel && MD_S8Match(it->current_room_name, gs.player->current_room_name, 0)) + if (it->is_npc && it->npc_kind == NPC_Angel && S8Match(it->current_room_name, gs.player->current_room_name, 0)) { assert(!angel_entity); angel_entity = it; @@ -6095,7 +6087,7 @@ void frame(void) if(should_be_visible) { assert(angel_entity); - MD_String8 new_to_say = {0}; + String8 new_to_say = {0}; if(angel_entity->undismissed_action) { new_to_say = last_said_sentence(angel_entity); @@ -6106,17 +6098,17 @@ void frame(void) { if(to_say_chunk == 0) { - to_say_chunk = MD_PushArray(persistent_arena, TextChunk, 1); + to_say_chunk = PushArray(persistent_arena, TextChunk, 1); } chunk_from_s8(to_say_chunk, new_to_say); } } - MD_String8List to_say = {0}; + String8List to_say = {0}; if(to_say_chunk != 0) to_say = split_by_word(frame_arena, TextChunkString8(*to_say_chunk)); - MD_String8 cur_word = {0}; - MD_String8Node *cur_word_node = 0; + String8 cur_word = {0}; + String8Node *cur_word_node = 0; double chars_said = cur_characters; - for(MD_String8Node *cur = to_say.first; cur; cur = cur->next) + for(String8Node *cur = to_say.first; cur; cur = cur->next) { if((int)chars_said < cur->string.size) { @@ -6142,9 +6134,9 @@ void frame(void) } assert(cur_word_node); - MD_String8Node *prev_next = cur_word_node->next; + String8Node *prev_next = cur_word_node->next; cur_word_node->next = 0; - //MD_String8 without_unsaid = MD_S8ListJoin(frame_arena, to_say, &(MD_StringJoin){.mid = MD_S8Lit(" ")}); + //String8 without_unsaid = S8ListJoin(frame_arena, to_say, &(StringJoin){.mid = S8Lit(" ")}); PlacedWordList placed = place_wrapped_words(frame_arena, to_say, 1.0f, screen_size().x*0.8f, font_for_text_input, JUST_CENTER); translate_words_by(placed, V2(screen_size().x*0.1f, screen_size().y*0.75f)); @@ -6159,18 +6151,18 @@ void frame(void) if(gs.assigned_objective) { float mission_font_scale = 1.0f; - MD_String8 mission_text = FmtWithLint(frame_arena, "Your mission: %.*s", MD_S8VArg(TextChunkString8(gs.objective.description))); + String8 mission_text = FmtWithLint(frame_arena, "Your mission: %.*s", S8VArg(TextChunkString8(gs.objective.description))); float button_height = 100.0f; float vert = button_height*0.5f; draw_centered_text((TextParams){false, mission_text, V2(screen_size().x * 0.5f, screen_size().y * 0.25f + vert), blendalpha(WHITE, visible), mission_font_scale, .use_font = &font_for_text_input, .layer = LAYER_ANGEL_SCREEN}); - if(imbutton(aabb_centered(V2(screen_size().x/2.0f, screen_size().y*0.25f - vert), MulV2F(V2(170.0f, button_height), visible)), visible, MD_S8Lit("Accept"), .layer = LAYER_ANGEL_SCREEN, .font = &font_for_text_input)) + if(imbutton(aabb_centered(V2(screen_size().x/2.0f, screen_size().y*0.25f - vert), MulV2F(V2(170.0f, button_height), visible)), visible, S8Lit("Accept"), .layer = LAYER_ANGEL_SCREEN, .font = &font_for_text_input)) { - transition_to_room(&gs, &level_threedee, MD_S8Lit("Forest")); + transition_to_room(&gs, &level_threedee, S8Lit("Forest")); } } else { - draw_centered_text((TextParams){false, MD_S8Lit("(Press E to speak)"), V2(screen_size().x * 0.5f, screen_size().y * 0.25f), blendalpha(WHITE, visible * 0.5f), 0.8f, .use_font = &font_for_text_input, .layer = LAYER_ANGEL_SCREEN}); + draw_centered_text((TextParams){false, S8Lit("(Press E to speak)"), V2(screen_size().x * 0.5f, screen_size().y * 0.25f), blendalpha(WHITE, visible * 0.5f), 0.8f, .use_font = &font_for_text_input, .layer = LAYER_ANGEL_SCREEN}); } if(should_be_visible && pressed.interact && !gs.assigned_objective) @@ -6192,7 +6184,7 @@ void frame(void) float text_scale = 1.0f; if(text_input_buffer_length > 0) { - AABB bounds = draw_centered_text((TextParams){false, MD_S8(text_input_buffer, text_input_buffer_length), MulV2F(screen_size(), 0.5f), blendalpha(WHITE, text_input_fade), text_scale, .use_font = &font_for_text_input, .layer = LAYER_UI_TEXTINPUT}); + AABB bounds = draw_centered_text((TextParams){false, S8(text_input_buffer, text_input_buffer_length), MulV2F(screen_size(), 0.5f), blendalpha(WHITE, text_input_fade), text_scale, .use_font = &font_for_text_input, .layer = LAYER_UI_TEXTINPUT}); edge_of_text = bounds.lower_right; } Vec2 cursor_center = V2(edge_of_text.x,screen_size().y/2.0f); @@ -6216,7 +6208,7 @@ void frame(void) { ENTITIES_ITER(gs.entities) { - if (it->is_npc && it->npc_kind != NPC_Player && MD_S8Match(it->current_room_name, gs.player->current_room_name, 0)) + if (it->is_npc && it->npc_kind != NPC_Player && S8Match(it->current_room_name, gs.player->current_room_name, 0)) { if(it->undismissed_action) { @@ -6246,7 +6238,7 @@ void frame(void) blendalpha(WHITE, dialog_alpha), .layer = LAYER_UI_FG, }); - MD_String8List words_to_say = words_on_current_page(it, &speech_bubble); + String8List words_to_say = words_on_current_page(it, &speech_bubble); if (unread) { draw_quad((DrawParams){ @@ -6292,7 +6284,7 @@ void frame(void) AABB placing_text_in = aabb_centered(AddV2(bubble_center, V2(0, 10.0f)), V2(speech_bubble.text_width_in_pixels, size.y * 0.15f)); dbgrect(placing_text_in); - MD_String8List to_draw = words_on_current_page_without_unsaid(it, &speech_bubble); + String8List to_draw = words_on_current_page_without_unsaid(it, &speech_bubble); if(to_draw.node_count != 0) { PlacedWordList placed = place_wrapped_words(frame_arena, to_draw, text_scale, aabb_size(placing_text_in).x, default_font, JUST_LEFT); @@ -6361,7 +6353,7 @@ void frame(void) bool should_propagate = true && it->is_npc && LenV2(SubV2(it->pos, cur->from)) < effective_radius - && MD_S8Match(TextChunkString8(cur->in_room_name), it->current_room_name, 0) + && S8Match(TextChunkString8(cur->in_room_name), it->current_room_name, 0) && it->npc_kind != NPC_Angel // angels already hear everything, this would duplicate the hearing of the action ; if(should_propagate) @@ -6445,14 +6437,14 @@ ISANERROR("Don't know how to do this stuff on this platform.") memcpy(sentence_cstr, get_by_id(it->gen_request_id)->generated.text, get_by_id(it->gen_request_id)->generated.text_length); #endif - MD_String8 sentence_str = MD_S8CString(sentence_cstr); + String8 sentence_str = S8CString(sentence_cstr); // parse out from the sentence NPC action and dialog Action out = {0}; - MD_ArenaTemp scratch = MD_GetScratch(0, 0); - Log("Parsing `%.*s`...\n", MD_S8VArg(sentence_str)); - MD_String8 parse_response = parse_chatgpt_response(scratch.arena, it, sentence_str, &out); + ArenaTemp scratch = GetScratch(0, 0); + Log("Parsing `%.*s`...\n", S8VArg(sentence_str)); + String8 parse_response = parse_chatgpt_response(scratch.arena, it, sentence_str, &out); // check that it wraps in below two lines TextPlacementSettings *to_wrap_to = &speech_bubble; @@ -6468,7 +6460,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") if(words_over_limit > 0) { - MD_String8 new_err = FmtWithLint(frame_arena, "Your speech is %d words over the maximum limit, you must be more succinct and remove at least that many words", words_over_limit); + String8 new_err = FmtWithLint(frame_arena, "Your speech is %d words over the maximum limit, you must be more succinct and remove at least that many words", words_over_limit); append_to_errors(it, make_memory(out, (MemoryContext){.i_said_this = true, .author_npc_kind = it->npc_kind, .talking_to_kind = out.talking_to_kind}), new_err); } else @@ -6482,7 +6474,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") } else { - Log("There was a parse error: `%.*s`\n", MD_S8VArg(parse_response)); + Log("There was a parse error: `%.*s`\n", S8VArg(parse_response)); append_to_errors(it, (Memory){0}, parse_response); } } @@ -6490,7 +6482,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); #ifdef WEB EM_ASM( { @@ -6508,7 +6500,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") /* Action to_perform = {0}; - MD_String8 speech_mdstring = MD_S8Lit("I'm not sure..."); + String8 speech_mdstring = S8Lit("I'm not sure..."); memcpy(to_perform.speech, speech_mdstring.str, speech_mdstring.size); to_perform.speech_length = (int)speech_mdstring.size; perform_action(&gs, it, to_perform); @@ -6534,10 +6526,10 @@ ISANERROR("Don't know how to do this stuff on this platform.") // character speech animation text input if (it->npc_kind != NPC_Angel) { - MD_ArenaTemp scratch = MD_GetScratch(0, 0); + ArenaTemp scratch = GetScratch(0, 0); - MD_String8List to_say = words_on_current_page(it, &speech_bubble); - MD_String8List to_say_without_unsaid = words_on_current_page_without_unsaid(it, &speech_bubble); + String8List to_say = words_on_current_page(it, &speech_bubble); + String8List to_say_without_unsaid = words_on_current_page_without_unsaid(it, &speech_bubble); if(to_say.node_count > 0 && it->words_said_on_page < to_say.node_count) { if(cur_unread_entity == it) @@ -6562,7 +6554,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") } } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); } @@ -6908,7 +6900,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") { Memory *prev = cur; cur = cur->next; - MD_StackPush(memories_free_list, prev); + StackPush(memories_free_list, prev); } it->memories_first = 0; it->memories_last = 0; @@ -6926,7 +6918,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") || it->npc_kind == NPC_Player || (it->npc_kind == NPC_Angel && gs.no_angel_screen) || !npc_does_dialog(it) // not sure what's up with this actually, potentially remove - || !MD_S8Match(it->current_room_name, gs.player->current_room_name, 0) + || !S8Match(it->current_room_name, gs.player->current_room_name, 0) || it->npc_kind == NPC_AngelTotem ; if (it->perceptions_dirty && doesnt_prompt_on_dirty_perceptions) @@ -6938,30 +6930,30 @@ ISANERROR("Don't know how to do this stuff on this platform.") if (!gs.stopped_time) { it->perceptions_dirty = false; // needs to be in beginning because they might be redirtied by the new perception - MD_String8 prompt_str = {0}; + String8 prompt_str = {0}; #ifdef DO_CHATGPT_PARSING prompt_str = generate_chatgpt_prompt(frame_arena, &gs, it, get_can_talk_to(it)); #else generate_prompt(it, &prompt); #endif - Log("Sending request with prompt `%.*s`\n", MD_S8VArg(prompt_str)); + Log("Sending request with prompt `%.*s`\n", S8VArg(prompt_str)); #ifdef WEB // fire off generation request, save id - MD_ArenaTemp scratch = MD_GetScratch(0, 0); - MD_String8 terminated_completion_url = nullterm(scratch.arena, FmtWithLint(scratch.arena, "%s://%s:%d/completion", IS_SERVER_SECURE ? "https" : "http", SERVER_DOMAIN, SERVER_PORT)); + ArenaTemp scratch = GetScratch(0, 0); + String8 terminated_completion_url = nullterm(scratch.arena, FmtWithLint(scratch.arena, "%s://%s:%d/completion", IS_SERVER_SECURE ? "https" : "http", SERVER_DOMAIN, SERVER_PORT)); int req_id = EM_ASM_INT({ return make_generation_request(UTF8ToString($0, $1), UTF8ToString($2, $3)); }, prompt_str.str, (int)prompt_str.size, terminated_completion_url.str, (int)terminated_completion_url.size); it->gen_request_id = req_id; - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); #endif #ifdef DESKTOP - MD_ArenaTemp scratch = MD_GetScratch(0, 0); + ArenaTemp scratch = GetScratch(0, 0); - MD_String8 ai_response = {0}; + String8 ai_response = {0}; bool mocking_the_ai_response = false; #ifdef DEVTOOLS #ifdef MOCK_AI_RESPONSE @@ -7003,7 +6995,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") } else { - ai_response = MD_S8Lit("{\"target\": \"nobody\", \"action\": \"none\", \"speech\": \"\"}"); + ai_response = S8Lit("{\"target\": \"nobody\", \"action\": \"none\", \"speech\": \"\"}"); } // something to mock @@ -7011,7 +7003,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") { Log("Mocking...\n"); Action a = {0}; - MD_String8 error_message = MD_S8Lit("Something really bad happened bro. File " STRINGIZE(__FILE__) " Line " STRINGIZE(__LINE__)); + String8 error_message = S8Lit("Something really bad happened bro. File " STRINGIZE(__FILE__) " Line " STRINGIZE(__LINE__)); if (succeeded) { error_message = parse_chatgpt_response(scratch.arena, it, ai_response, &a); @@ -7020,19 +7012,19 @@ ISANERROR("Don't know how to do this stuff on this platform.") assert(succeeded); assert(error_message.size == 0); - MD_String8 valid_str = is_action_valid(frame_arena, it, a); + String8 valid_str = is_action_valid(frame_arena, it, a); assert(valid_str.size == 0); perform_action(&gs, it, a); } } else { - MD_String8 post_request_body = FmtWithLint(scratch.arena, "|%.*s", MD_S8VArg(prompt_str)); + String8 post_request_body = FmtWithLint(scratch.arena, "|%.*s", S8VArg(prompt_str)); it->gen_request_id = make_generation_request(post_request_body); } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); #undef SAY #endif // desktop endif } @@ -7088,7 +7080,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") { if(closest_interact_with->npc_kind == NPC_AngelTotem) { - transition_to_room(&gs, &level_threedee, MD_S8Lit("StartingRoom")); + transition_to_room(&gs, &level_threedee, S8Lit("StartingRoom")); } // begin dialog with closest npc gs.player->talking_to = frome(closest_interact_with); @@ -7252,7 +7244,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") { Vec2 text_center = V2(screen_size().x / 2.0f, screen_size().y*0.8f); draw_quad((DrawParams){centered_quad(text_center, V2(screen_size().x*0.8f, screen_size().y*0.1f)), IMG(image_white_square), blendalpha(BLACK, 0.5f), .layer = LAYER_ULTRA_IMPORTANT_NOTIFICATIONS}); - draw_centered_text((TextParams){false, MD_S8Lit("The AI server is having technical difficulties..."), text_center, WHITE, 1.0f, .layer = LAYER_ULTRA_IMPORTANT_NOTIFICATIONS }); + draw_centered_text((TextParams){false, S8Lit("The AI server is having technical difficulties..."), text_center, WHITE, 1.0f, .layer = LAYER_ULTRA_IMPORTANT_NOTIFICATIONS }); } @@ -7270,9 +7262,9 @@ ISANERROR("Don't know how to do this stuff on this platform.") float shake_speed = 9.0f; Vec2 win_offset = V2(sinf((float)unwarped_elapsed_time * shake_speed * 1.5f + 0.1f), sinf((float)unwarped_elapsed_time * shake_speed + 0.3f)); win_offset = MulV2F(win_offset, 10.0f); - draw_centered_text((TextParams){false, MD_S8Lit("YOU WON"), AddV2(MulV2F(screen_size(), 0.5f), win_offset), WHITE, 9.0f*visible}); + draw_centered_text((TextParams){false, S8Lit("YOU WON"), AddV2(MulV2F(screen_size(), 0.5f), win_offset), WHITE, 9.0f*visible}); - if(imbutton(aabb_centered(V2(screen_size().x/2.0f, screen_size().y*0.25f), MulV2F(V2(170.0f, 60.0f), visible)), 1.5f*visible, MD_S8Lit("Restart"))) + if(imbutton(aabb_centered(V2(screen_size().x/2.0f, screen_size().y*0.25f), MulV2F(V2(170.0f, 60.0f), visible)), 1.5f*visible, S8Lit("Restart"))) { reset_level(); } @@ -7298,12 +7290,12 @@ ISANERROR("Don't know how to do this stuff on this platform.") float shake_speed = 9.0f; Vec2 win_offset = V2(sinf((float)unwarped_elapsed_time * shake_speed * 1.5f + 0.1f), sinf((float)unwarped_elapsed_time * shake_speed + 0.3f)); win_offset = MulV2F(win_offset, 10.0f); - draw_centered_text((TextParams){false, MD_S8Lit("YOU WERE KILLED"), AddV2(MulV2F(screen_size(), 0.5f), win_offset), WHITE, 3.0f*visible}); // YOU DIED + draw_centered_text((TextParams){false, S8Lit("YOU WERE KILLED"), AddV2(MulV2F(screen_size(), 0.5f), win_offset), WHITE, 3.0f*visible}); // YOU DIED - if(imbutton(aabb_centered(V2(screen_size().x/2.0f, screen_size().y*0.25f), MulV2F(V2(170.0f, 60.0f), visible)), 1.5f*visible, MD_S8Lit("Continue"))) + if(imbutton(aabb_centered(V2(screen_size().x/2.0f, screen_size().y*0.25f), MulV2F(V2(170.0f, 60.0f), visible)), 1.5f*visible, S8Lit("Continue"))) { gs.player->killed = false; - transition_to_room(&gs, &level_threedee, MD_S8Lit("StartingRoom")); + transition_to_room(&gs, &level_threedee, S8Lit("StartingRoom")); reset_level(); } } @@ -7372,14 +7364,14 @@ ISANERROR("Don't know how to do this stuff on this platform.") Vec2 start_at = V2(0,300); Vec2 cur_pos = start_at; - AABB bounds = draw_text((TextParams){false, MD_S8Fmt(frame_arena, "--Memories for %s--", characters[to_view->npc_kind].name), cur_pos, WHITE, 1.0}); + AABB bounds = draw_text((TextParams){false, S8Fmt(frame_arena, "--Memories for %s--", characters[to_view->npc_kind].name), cur_pos, WHITE, 1.0}); cur_pos.y -= aabb_size(bounds).y; for(Memory *cur = to_view->memories_first; cur; cur = cur->next) if(cur->speech.text_length > 0) { - MD_String8 to_text = cur->context.talking_to_kind != NPC_nobody ? MD_S8Fmt(frame_arena, " to %s ", characters[cur->context.talking_to_kind].name) : MD_S8Lit(""); - MD_String8 text = MD_S8Fmt(frame_arena, "%s%s%.*s: %.*s", to_view->npc_kind == cur->context.author_npc_kind ? "(Me) " : "", characters[cur->context.author_npc_kind].name, MD_S8VArg(to_text), cur->speech.text_length, cur->speech); + String8 to_text = cur->context.talking_to_kind != NPC_nobody ? S8Fmt(frame_arena, " to %s ", characters[cur->context.talking_to_kind].name) : S8Lit(""); + String8 text = S8Fmt(frame_arena, "%s%s%.*s: %.*s", to_view->npc_kind == cur->context.author_npc_kind ? "(Me) " : "", characters[cur->context.author_npc_kind].name, S8VArg(to_text), cur->speech.text_length, cur->speech); AABB bounds = draw_text((TextParams){false, text, cur_pos, WHITE, 1.0}); cur_pos.y -= aabb_size(bounds).y; } @@ -7391,16 +7383,16 @@ ISANERROR("Don't know how to do this stuff on this platform.") int mem_idx = 0; for(Memory *cur = to_view->memories_first; cur; cur = cur->next) { - MD_String8 to_text = cur->context.talking_to_kind != NPC_nobody ? MD_S8Fmt(frame_arena, " to %s ", characters[cur->context.talking_to_kind].name) : MD_S8Lit(""); - MD_String8 speech = TextChunkString8(cur->speech); - if(speech.size == 0) speech = MD_S8Lit(""); - MD_String8 text = MD_S8Fmt(frame_arena, "%s%s%.*s: %.*s", to_view->npc_kind == cur->context.author_npc_kind ? "(Me) " : "", characters[cur->context.author_npc_kind].name, MD_S8VArg(to_text), MD_S8VArg(speech)); - printf("Memory %d: %.*s\n", mem_idx, MD_S8VArg(text)); + String8 to_text = cur->context.talking_to_kind != NPC_nobody ? S8Fmt(frame_arena, " to %s ", characters[cur->context.talking_to_kind].name) : S8Lit(""); + String8 speech = TextChunkString8(cur->speech); + if(speech.size == 0) speech = S8Lit(""); + String8 text = S8Fmt(frame_arena, "%s%s%.*s: %.*s", to_view->npc_kind == cur->context.author_npc_kind ? "(Me) " : "", characters[cur->context.author_npc_kind].name, S8VArg(to_text), S8VArg(speech)); + printf("Memory %d: %.*s\n", mem_idx, S8VArg(text)); mem_idx++; } Log("\nPrompt-----------------------------\n"); - MD_String8 prompt = generate_chatgpt_prompt(frame_arena, &gs, to_view, get_can_talk_to(to_view)); - printf("%.*s\n", MD_S8VArg(prompt)); + String8 prompt = generate_chatgpt_prompt(frame_arena, &gs, to_view, get_can_talk_to(to_view)); + printf("%.*s\n", S8VArg(prompt)); } } } @@ -7409,7 +7401,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") Vec2 pos = V2(0.0, screen_size().Y); int num_entities = 0; ENTITIES_ITER(gs.entities) num_entities++; - MD_String8 stats = + String8 stats = tprint("Frametime: %.1f ms\n" "Processing: %.1f ms\n" "Gameplay processing: %.1f ms\n" @@ -7573,7 +7565,7 @@ ISANERROR("Don't know how to do this stuff on this platform.") last_frame_processing_time = stm_sec(stm_diff(stm_now(), time_start_frame)); - MD_ArenaClear(frame_arena); + ArenaClear(frame_arena); memset(keypressed, 0, sizeof(keypressed)); pressed = (PressedState) { 0 }; @@ -7589,11 +7581,11 @@ void cleanup(void) } #endif - MD_ArenaRelease(frame_arena); + ArenaRelease(frame_arena); // Don't free the persistent arena because threads still access their ChatRequest should_close fieldon shutdown, // and ChatRequest is allocated on the persistent arena. We just shamelessly leak this memory. Cowabunga! - //MD_ArenaRelease(persistent_arena); + //ArenaRelease(persistent_arena); sg_shutdown(); hmfree(imui_state); Log("Cleaning up\n"); diff --git a/makeprompt.h b/makeprompt.h index bde5c60..ccfc1f2 100644 --- a/makeprompt.h +++ b/makeprompt.h @@ -16,8 +16,8 @@ // Never expected such a stupid stuff from such a great director. If there is 0 stari can give that or -200 to this movie. Its worst to see and unnecessary loss of money -#define PushWithLint(arena, list, ...) { MD_S8ListPushFmt(arena, list, __VA_ARGS__); if(false) printf( __VA_ARGS__); } -#define FmtWithLint(arena, ...) (0 ? printf(__VA_ARGS__) : (void)0, MD_S8Fmt(arena, __VA_ARGS__)) +#define PushWithLint(arena, list, ...) { S8ListPushFmt(arena, list, __VA_ARGS__); if(false) printf( __VA_ARGS__); } +#define FmtWithLint(arena, ...) (0 ? printf(__VA_ARGS__) : (void)0, S8Fmt(arena, __VA_ARGS__)) typedef BUFF(char, 1024 * 10) Escaped; @@ -26,9 +26,9 @@ bool character_valid(char c) return c <= 126 && c >= 32; } -MD_String8 escape_for_json(MD_Arena *arena, MD_String8 from) +String8 escape_for_json(Arena *arena, String8 from) { - MD_u64 output_size = 0; + u64 output_size = 0; #define SHOULD_ESCAPE(c) (c == '"' || c == '\n' || c == '\\') for (int i = 0; i < from.size; i++) { @@ -48,13 +48,13 @@ MD_String8 escape_for_json(MD_Arena *arena, MD_String8 from) } } - MD_String8 output = { - .str = MD_PushArray(arena, MD_u8, output_size), + String8 output = { + .str = PushArray(arena, u8, output_size), .size = output_size, }; - MD_u64 output_cursor = 0; + u64 output_cursor = 0; - for(MD_u64 i = 0; i < from.size; i++) + for(u64 i = 0; i < from.size; i++) { #define APPEND(elem) APPEND_TO_NAME(output.str, output_cursor, output.size, elem); assert(output_cursor < output.size); @@ -195,10 +195,10 @@ typedef struct // text chunk must be a literal, not a pointer // and this returns a s8 that points at the text chunk memory -#define TextChunkString8(t) MD_S8((MD_u8*)(t).text, (t).text_length) -#define TextChunkVArg(t) MD_S8VArg(TextChunkString8(t)) +#define TextChunkString8(t) S8((u8*)(t).text, (t).text_length) +#define TextChunkVArg(t) S8VArg(TextChunkString8(t)) -void chunk_from_s8(TextChunk *into, MD_String8 from) +void chunk_from_s8(TextChunk *into, String8 from) { assert(from.size < ARRLEN(into->text)); memset(into->text, 0, ARRLEN(into->text)); @@ -207,7 +207,7 @@ void chunk_from_s8(TextChunk *into, MD_String8 from) } // returns ai understandable, human readable name, on the arena, so not the enum name -MD_String8 action_argument_string(MD_Arena *arena, ActionArgument arg) +String8 action_argument_string(Arena *arena, ActionArgument arg) { switch(arg.kind) { @@ -215,9 +215,9 @@ MD_String8 action_argument_string(MD_Arena *arena, ActionArgument arg) return FmtWithLint(arena, "%s", characters[arg.targeting].name); break; case ARG_OBJECTIVE: - return FmtWithLint(arena, "%.*s", MD_S8VArg(TextChunkString8(arg.objective.description))); + return FmtWithLint(arena, "%.*s", S8VArg(TextChunkString8(arg.objective.description))); } - return (MD_String8){0}; + return (String8){0}; } @@ -248,7 +248,7 @@ typedef struct Entity Vec2 vel; // only used sometimes, like in old man and bullet float damage; // at 1.0, dead! zero initialized bool dead; - MD_String8 current_room_name; + String8 current_room_name; // npcs EntityRef joined; @@ -384,9 +384,9 @@ bool npc_does_dialog(Entity *it) } // for no trailing comma just trim the last character -MD_String8 make_json_node(MD_Arena *arena, MessageType type, MD_String8 content) +String8 make_json_node(Arena *arena, MessageType type, String8 content) { - MD_ArenaTemp scratch = MD_GetScratch(&arena, 1); + ArenaTemp scratch = GetScratch(&arena, 1); const char *type_str = 0; if (type == MSG_SYSTEM) @@ -397,75 +397,75 @@ MD_String8 make_json_node(MD_Arena *arena, MessageType type, MD_String8 content) type_str = "assistant"; assert(type_str); - MD_String8 escaped = escape_for_json(scratch.arena, content); - MD_String8 to_return = FmtWithLint(arena, "{\"type\": \"%s\", \"content\": \"%.*s\"},", type_str, MD_S8VArg(escaped)); - MD_ReleaseScratch(scratch); + String8 escaped = escape_for_json(scratch.arena, content); + String8 to_return = FmtWithLint(arena, "{\"type\": \"%s\", \"content\": \"%.*s\"},", type_str, S8VArg(escaped)); + ReleaseScratch(scratch); return to_return; } -MD_String8 npc_to_human_readable(Entity *me, NpcKind kind) +String8 npc_to_human_readable(Entity *me, NpcKind kind) { if(me->npc_kind == kind) { - return MD_S8Lit("You"); + return S8Lit("You"); } else { - return MD_S8CString(characters[kind].name); + return S8CString(characters[kind].name); } } -MD_String8List dump_memory_as_json(MD_Arena *arena, Memory *it) +String8List dump_memory_as_json(Arena *arena, Memory *it) { - MD_ArenaTemp scratch = MD_GetScratch(&arena, 1); - MD_String8List current_list = {0}; + ArenaTemp scratch = GetScratch(&arena, 1); + String8List current_list = {0}; #define AddFmt(...) PushWithLint(arena, ¤t_list, __VA_ARGS__) AddFmt("{"); AddFmt("\"speech\":\"%.*s\",", TextChunkVArg(it->speech)); AddFmt("\"action\":\"%s\",", actions[it->action_taken].name); - MD_String8 arg_str = action_argument_string(scratch.arena, it->action_argument); - AddFmt("\"action_argument\":\"%.*s\",", MD_S8VArg(arg_str)); + String8 arg_str = action_argument_string(scratch.arena, it->action_argument); + AddFmt("\"action_argument\":\"%.*s\",", S8VArg(arg_str)); AddFmt("\"target\":\"%s\"}", characters[it->context.talking_to_kind].name); #undef AddFmt - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); return current_list; } // outputs json which is parsed by the server -MD_String8 generate_chatgpt_prompt(MD_Arena *arena, GameState *gs, Entity *e, CanTalkTo can_talk_to) +String8 generate_chatgpt_prompt(Arena *arena, GameState *gs, Entity *e, CanTalkTo can_talk_to) { assert(e->is_npc); assert(e->npc_kind < ARRLEN(characters)); - MD_ArenaTemp scratch = MD_GetScratch(&arena, 1); + ArenaTemp scratch = GetScratch(&arena, 1); - MD_String8List list = {0}; + String8List list = {0}; PushWithLint(scratch.arena, &list, "["); #define AddFmt(...) PushWithLint(scratch.arena, ¤t_list, __VA_ARGS__) - #define AddNewNode(node_type) { MD_S8ListPush(scratch.arena, &list, make_json_node(scratch.arena, node_type, MD_S8ListJoin(scratch.arena, current_list, &(MD_StringJoin){0}))); current_list = (MD_String8List){0}; } + #define AddNewNode(node_type) { S8ListPush(scratch.arena, &list, make_json_node(scratch.arena, node_type, S8ListJoin(scratch.arena, current_list, &(StringJoin){0}))); current_list = (String8List){0}; } // make first system node { - MD_String8List current_list = {0}; + String8List current_list = {0}; AddFmt("%s\n\n", global_prompt); AddFmt("%s\n\n", characters[e->npc_kind].prompt); AddFmt("The characters who are near you, that you can target:\n"); BUFF_ITER(Entity*, &can_talk_to) { assert((*it)->is_npc); - MD_String8 info = MD_S8Lit(""); + String8 info = S8Lit(""); if((*it)->killed) { - info = MD_S8Lit(" - they're currently dead, they were murdered"); + info = S8Lit(" - they're currently dead, they were murdered"); } - AddFmt("%s%.*s\n", characters[(*it)->npc_kind].name, MD_S8VArg(info)); + AddFmt("%s%.*s\n", characters[(*it)->npc_kind].name, S8VArg(info)); } AddFmt("\n"); @@ -485,7 +485,7 @@ MD_String8 generate_chatgpt_prompt(MD_Arena *arena, GameState *gs, Entity *e, Ca AddNewNode(MSG_SYSTEM); } - MD_String8List current_list = {0}; + String8List current_list = {0}; bool in_drama_memories = true; assert(e->memories_first->context.drama_memory); for(Memory *it = e->memories_first; it; it = it->next) @@ -506,7 +506,7 @@ MD_String8 generate_chatgpt_prompt(MD_Arena *arena, GameState *gs, Entity *e, Ca { switch(it->action_taken) { - #define HUMAN(kind) MD_S8VArg(npc_to_human_readable(e, kind)) + #define HUMAN(kind) S8VArg(npc_to_human_readable(e, kind)) case ACT_none: break; case ACT_join: @@ -540,22 +540,22 @@ MD_String8 generate_chatgpt_prompt(MD_Arena *arena, GameState *gs, Entity *e, Ca } if(it->speech.text_length > 0) { - MD_String8 target_string = MD_S8Lit("the world"); + String8 target_string = S8Lit("the world"); if(it->context.talking_to_kind != NPC_nobody) { if(it->context.talking_to_kind == e->npc_kind) - target_string = MD_S8Lit("you"); + target_string = S8Lit("you"); else - target_string = MD_S8CString(characters[it->context.talking_to_kind].name); + target_string = S8CString(characters[it->context.talking_to_kind].name); } - MD_String8 speaking_to_you_helper = MD_S8Lit("(Speaking directly you) "); + String8 speaking_to_you_helper = S8Lit("(Speaking directly you) "); if(it->context.talking_to_kind != e->npc_kind) { - speaking_to_you_helper = MD_S8Lit("(Overheard conversation, they aren't speaking directly to you) "); + speaking_to_you_helper = S8Lit("(Overheard conversation, they aren't speaking directly to you) "); } - AddFmt("%.*s%s said \"%.*s\" to %.*s (you are %s)\n", MD_S8VArg(speaking_to_you_helper), characters[it->context.author_npc_kind].name, TextChunkVArg(it->speech), MD_S8VArg(target_string), characters[e->npc_kind].name); + AddFmt("%.*s%s said \"%.*s\" to %.*s (you are %s)\n", S8VArg(speaking_to_you_helper), characters[it->context.author_npc_kind].name, TextChunkVArg(it->speech), S8VArg(target_string), characters[e->npc_kind].name); } if(no_longer_wants_to_converse) @@ -582,8 +582,8 @@ MD_String8 generate_chatgpt_prompt(MD_Arena *arena, GameState *gs, Entity *e, Ca { if(cur->offending_self_output.speech.text_length > 0 || cur->offending_self_output.action_taken != ACT_none) { - MD_String8 offending_json_output = MD_S8ListJoin(scratch.arena, dump_memory_as_json(scratch.arena, &cur->offending_self_output), &(MD_StringJoin){0}); - AddFmt("When you output, `%.*s`, ", MD_S8VArg(offending_json_output)); + String8 offending_json_output = S8ListJoin(scratch.arena, dump_memory_as_json(scratch.arena, &cur->offending_self_output), &(StringJoin){0}); + AddFmt("When you output, `%.*s`, ", S8VArg(offending_json_output)); } AddFmt("%.*s\n", TextChunkVArg(cur->reason_why_its_bad)); } @@ -594,34 +594,34 @@ MD_String8 generate_chatgpt_prompt(MD_Arena *arena, GameState *gs, Entity *e, Ca if(it->context.i_said_this) { - MD_String8List current_list = {0}; // shadow the list of human understandable sentences to quickly flush + String8List current_list = {0}; // shadow the list of human understandable sentences to quickly flush current_list = dump_memory_as_json(scratch.arena, it); AddNewNode(MSG_ASSISTANT); } } - MD_String8 with_trailing_comma = MD_S8ListJoin(scratch.arena, list, &(MD_StringJoin){MD_S8Lit(""),MD_S8Lit(""),MD_S8Lit(""),}); - MD_String8 no_trailing_comma = MD_S8Chop(with_trailing_comma, 1); + String8 with_trailing_comma = S8ListJoin(scratch.arena, list, &(StringJoin){S8Lit(""),S8Lit(""),S8Lit(""),}); + String8 no_trailing_comma = S8Chop(with_trailing_comma, 1); - MD_String8 to_return = MD_S8Fmt(arena, "%.*s]", MD_S8VArg(no_trailing_comma)); + String8 to_return = S8Fmt(arena, "%.*s]", S8VArg(no_trailing_comma)); - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); #undef AddFmt return to_return; } -MD_String8 get_field(MD_Node *parent, MD_String8 name) +String8 get_field(Node *parent, String8 name) { return MD_ChildFromString(parent, name, 0)->first_child->string; } -void parse_action_argument(MD_Arena *error_arena, MD_String8 *cur_error_message, ActionKind action, MD_String8 action_argument_str, ActionArgument *out) +void parse_action_argument(Arena *error_arena, String8 *cur_error_message, ActionKind action, String8 action_argument_str, ActionArgument *out) { assert(cur_error_message); if(cur_error_message->size > 0) return; - MD_ArenaTemp scratch = MD_GetScratch(&error_arena, 1); - MD_String8 action_str = MD_S8CString(actions[action].name); + ArenaTemp scratch = GetScratch(&error_arena, 1); + String8 action_str = S8CString(actions[action].name); // @TODO refactor into, action argument kinds and they parse into different action argument types bool arg_is_character = action == ACT_join || action == ACT_aim_shotgun || action == ACT_end_conversation; bool arg_is_gameplay_objective = action == ACT_assign_gameplay_objective; @@ -632,7 +632,7 @@ void parse_action_argument(MD_Arena *error_arena, MD_String8 *cur_error_message, bool found_npc = false; for (int i = 0; i < ARRLEN(characters); i++) { - if (MD_S8Match(MD_S8CString(characters[i].name), action_argument_str, 0)) + if (S8Match(S8CString(characters[i].name), action_argument_str, 0)) { found_npc = true; (*out).targeting = i; @@ -640,7 +640,7 @@ void parse_action_argument(MD_Arena *error_arena, MD_String8 *cur_error_message, } if (!found_npc) { - *cur_error_message = FmtWithLint(error_arena, "Argument for action `%.*s` you gave is `%.*s`, which doesn't exist in the game so is invalid", MD_S8VArg(action_str), MD_S8VArg(action_argument_str)); + *cur_error_message = FmtWithLint(error_arena, "Argument for action `%.*s` you gave is `%.*s`, which doesn't exist in the game so is invalid", S8VArg(action_str), S8VArg(action_argument_str)); } } else if (arg_is_gameplay_objective) @@ -648,8 +648,8 @@ void parse_action_argument(MD_Arena *error_arena, MD_String8 *cur_error_message, out->kind = ARG_OBJECTIVE; if(action_argument_str.size >= MAX_SENTENCE_LENGTH) { - MD_String8 trimmed = MD_S8Substring(action_argument_str, action_argument_str.size - MAX_SENTENCE_LENGTH/2, action_argument_str.size); - *cur_error_message = FmtWithLint(error_arena, "What you said for your action argument, '%.*s...' is WAY too big for the game to handle, it can be a maximum of %d characters, but you output %d!.", MD_S8VArg(trimmed), MAX_SENTENCE_LENGTH, (int)action_argument_str.size); + String8 trimmed = S8Substring(action_argument_str, action_argument_str.size - MAX_SENTENCE_LENGTH/2, action_argument_str.size); + *cur_error_message = FmtWithLint(error_arena, "What you said for your action argument, '%.*s...' is WAY too big for the game to handle, it can be a maximum of %d characters, but you output %d!.", S8VArg(trimmed), MAX_SENTENCE_LENGTH, (int)action_argument_str.size); } if(cur_error_message->size == 0) { @@ -660,47 +660,47 @@ void parse_action_argument(MD_Arena *error_arena, MD_String8 *cur_error_message, { assert(false); // don't know how to parse the argument string for this kind of action... } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); } // if returned string has size greater than 0, it's the error message. Allocated // on arena passed into it or in constant memory -MD_String8 parse_chatgpt_response(MD_Arena *arena, Entity *e, MD_String8 action_in_json, Action *out) +String8 parse_chatgpt_response(Arena *arena, Entity *e, String8 action_in_json, Action *out) { - MD_ArenaTemp scratch = MD_GetScratch(&arena, 1); + ArenaTemp scratch = GetScratch(&arena, 1); - MD_String8 error_message = {0}; + String8 error_message = {0}; *out = (Action) { 0 }; - MD_ParseResult result = MD_ParseWholeString(scratch.arena, MD_S8Lit("chat_message"), action_in_json); + ParseResult result = ParseWholeString(scratch.arena, S8Lit("chat_message"), action_in_json); if(result.errors.node_count > 0) { - MD_Message *cur = result.errors.first; - MD_CodeLoc loc = MD_CodeLocFromNode(cur->node); - error_message = FmtWithLint(arena, "Parse Error on column %d: %.*s", loc.column, MD_S8VArg(cur->string)); + Message *cur = result.errors.first; + CodeLoc loc = CodeLocFromNode(cur->node); + error_message = FmtWithLint(arena, "Parse Error on column %d: %.*s", loc.column, S8VArg(cur->string)); } - MD_Node *message_obj = result.node->first_child; + Node *message_obj = result.node->first_child; - MD_String8 speech_str = {0}; - MD_String8 action_str = {0}; - MD_String8 action_argument_str = {0}; - MD_String8 target_str = {0}; + String8 speech_str = {0}; + String8 action_str = {0}; + String8 action_argument_str = {0}; + String8 target_str = {0}; if(error_message.size == 0) { - speech_str = get_field(message_obj, MD_S8Lit("speech")); - action_str = get_field(message_obj, MD_S8Lit("action")); - action_argument_str = get_field(message_obj, MD_S8Lit("action_argument")); - target_str = get_field(message_obj, MD_S8Lit("target")); + speech_str = get_field(message_obj, S8Lit("speech")); + action_str = get_field(message_obj, S8Lit("action")); + action_argument_str = get_field(message_obj, S8Lit("action_argument")); + target_str = get_field(message_obj, S8Lit("target")); } if(error_message.size == 0 && action_str.size == 0) { - error_message = MD_S8Lit("The field `action` must be of nonzero length, if you don't want to do anything it should be `none`"); + error_message = S8Lit("The field `action` must be of nonzero length, if you don't want to do anything it should be `none`"); } if(error_message.size == 0 && action_str.size == 0) { - error_message = MD_S8Lit("The field `target` must be of nonzero length, if you don't want to target anybody it should be `nobody`"); + error_message = S8Lit("The field `target` must be of nonzero length, if you don't want to target anybody it should be `nobody`"); } if(error_message.size == 0 && speech_str.size >= MAX_SENTENCE_LENGTH) { error_message = FmtWithLint(arena, "Speech string provided is too big, maximum bytes is %d", MAX_SENTENCE_LENGTH); @@ -709,7 +709,7 @@ MD_String8 parse_chatgpt_response(MD_Arena *arena, Entity *e, MD_String8 action_ if(error_message.size == 0) { - if(MD_S8Match(target_str, MD_S8Lit("nobody"), 0)) + if(S8Match(target_str, S8Lit("nobody"), 0)) { out->talking_to_kind = NPC_nobody; } @@ -718,7 +718,7 @@ MD_String8 parse_chatgpt_response(MD_Arena *arena, Entity *e, MD_String8 action_ bool found = false; for(int i = 0; i < ARRLEN(characters); i++) { - if(MD_S8Match(target_str, MD_S8CString(characters[i].name), 0)) + if(S8Match(target_str, S8CString(characters[i].name), 0)) { found = true; out->talking_to_kind = i; @@ -726,7 +726,7 @@ MD_String8 parse_chatgpt_response(MD_Arena *arena, Entity *e, MD_String8 action_ } if(!found) { - error_message = FmtWithLint(arena, "Unrecognized character provided in field 'target': `%.*s`", MD_S8VArg(target_str)); + error_message = FmtWithLint(arena, "Unrecognized character provided in field 'target': `%.*s`", S8VArg(target_str)); } } } @@ -742,7 +742,7 @@ MD_String8 parse_chatgpt_response(MD_Arena *arena, Entity *e, MD_String8 action_ bool found_action = false; for(int i = 0; i < ARRLEN(actions); i++) { - if(MD_S8Match(MD_S8CString(actions[i].name), action_str, 0)) + if(S8Match(S8CString(actions[i].name), action_str, 0)) { assert(!found_action); found_action = true; @@ -751,7 +751,7 @@ MD_String8 parse_chatgpt_response(MD_Arena *arena, Entity *e, MD_String8 action_ } if(!found_action) { - error_message = FmtWithLint(arena, "Action `%.*s` is invalid, doesn't exist in the game", MD_S8VArg(action_str)); + error_message = FmtWithLint(arena, "Action `%.*s` is invalid, doesn't exist in the game", S8VArg(action_str)); } if(error_message.size == 0) @@ -763,6 +763,6 @@ MD_String8 parse_chatgpt_response(MD_Arena *arena, Entity *e, MD_String8 action_ } } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); return error_message; } \ No newline at end of file diff --git a/ser.h b/ser.h index d991084..bcea551 100644 --- a/ser.h +++ b/ser.h @@ -4,32 +4,32 @@ typedef struct { - MD_b8 failed; - MD_String8 why; + b8 failed; + String8 why; } SerError; typedef struct { - MD_u8 *data; // set to 0 to dry run and get maximum size. max doesn't matter in this case - MD_u64 cur; - MD_u64 max; + u8 *data; // set to 0 to dry run and get maximum size. max doesn't matter in this case + u64 cur; + u64 max; - MD_Arena *arena; // allocate everything new on this, so that if serialization fails allocations can be undone + Arena *arena; // allocate everything new on this, so that if serialization fails allocations can be undone // Serializing should never allocate. So this can be null when you serialize int version; SerError cur_error; - MD_Arena *error_arena; // all error messages are allocated here + Arena *error_arena; // all error messages are allocated here - MD_b8 serializing; + b8 serializing; } SerState; -void ser_bytes(SerState *ser, MD_u8 *bytes, MD_u64 bytes_size) +void ser_bytes(SerState *ser, u8 *bytes, u64 bytes_size) { if(!ser->data && !ser->serializing) { - ser->cur_error = (SerError){.failed = true, .why = MD_S8Lit("Deserializing but the data is null")}; + ser->cur_error = (SerError){.failed = true, .why = S8Lit("Deserializing but the data is null")}; } if(!ser->cur_error.failed) @@ -39,7 +39,7 @@ void ser_bytes(SerState *ser, MD_u8 *bytes, MD_u64 bytes_size) // maximum doesn't matter unless writing to data if(ser->cur + bytes_size > ser->max) { - ser->cur_error = (SerError){.failed = true, .why = MD_S8Lit("Too big bro")}; + ser->cur_error = (SerError){.failed = true, .why = S8Lit("Too big bro")}; } else { @@ -61,24 +61,24 @@ void ser_bytes(SerState *ser, MD_u8 *bytes, MD_u64 bytes_size) #define SER_MAKE_FOR_TYPE(type) void ser_##type(SerState *ser, type *into) \ { \ - ser_bytes(ser, (MD_u8*)into, sizeof(*into)); \ + ser_bytes(ser, (u8*)into, sizeof(*into)); \ } SER_MAKE_FOR_TYPE(int); -SER_MAKE_FOR_TYPE(MD_u64); +SER_MAKE_FOR_TYPE(u64); // Embeds the string into the serialized binary. When deserializing copies the // deserialized data onto a newly allocated buffer -void ser_MD_String8(SerState *ser, MD_String8 *s, MD_Arena *allocate_onto) +void ser_String8(SerState *ser, String8 *s, Arena *allocate_onto) { - ser_MD_u64(ser, &s->size); + ser_u64(ser, &s->size); if(ser->serializing) { ser_bytes(ser, s->str, s->size); } else { - s->str = MD_ArenaPush(allocate_onto, s->size); + s->str = ArenaPush(allocate_onto, s->size); ser_bytes(ser, s->str, s->size); } } diff --git a/thirdparty/md.c b/thirdparty/md.c index 0654411..2c0cb59 100644 --- a/thirdparty/md.c +++ b/thirdparty/md.c @@ -5,108 +5,108 @@ ** ** Overridable ** "basic types" ** REQUIRED -** #define/typedef MD_i8, MD_i16, MD_i32, MD_i64 -** #define/typedef MD_u8, MD_u16, MD_u32, MD_u64 -** #define/typedef MD_f32, MD_f64 +** #define/typedef i8, i16, i32, i64 +** #define/typedef u8, u16, u32, u64 +** #define/typedef f32, f64 ** ** "memset" ** REQUIRED -** #define MD_IMPL_Memset (void*, int, uint64) -> void* -** #define MD_IMPL_Memmove (void*, void*, uint64) -> void* +** #define IMPL_Memset (void*, int, uint64) -> void* +** #define IMPL_Memmove (void*, void*, uint64) -> void* ** ** "file iteration" ** OPTIONAL (required for the metadesk FileIter helpers to work) -** #define MD_IMPL_FileIterBegin (MD_FileIter*, MD_String8) -> Boolean -** #define MD_IMPL_FileIterNext (MD_Arena*, MD_FileIter*) -> MD_FileInfo -** #define MD_IMPL_FileIterEnd (MD_FileIter*) -> void +** #define IMPL_FileIterBegin (FileIter*, String8) -> Boolean +** #define IMPL_FileIterNext (Arena*, FileIter*) -> FileInfo +** #define IMPL_FileIterEnd (FileIter*) -> void ** -** "file load" ** OPTIONAL (required for MD_ParseWholeFile to work) -** #define MD_IMPL_LoadEntireFile (MD_Arena*, MD_String8 filename) -> MD_String8 +** "file load" ** OPTIONAL (required for ParseWholeFile to work) +** #define IMPL_LoadEntireFile (Arena*, String8 filename) -> String8 ** ** "low level memory" ** OPTIONAL (required when relying on the default arenas) -** #define MD_IMPL_Reserve (uint64) -> void* -** #define MD_IMPL_Commit (void*, uint64) -> MD_b32 -** #define MD_IMPL_Decommit (void*, uint64) -> void -** #define MD_IMPL_Release (void*, uint64) -> void +** #define IMPL_Reserve (uint64) -> void* +** #define IMPL_Commit (void*, uint64) -> b32 +** #define IMPL_Decommit (void*, uint64) -> void +** #define IMPL_Release (void*, uint64) -> void ** ** ** "arena" ** REQUIRED -** #define MD_IMPL_Arena (must set before including md.h) -** #define MD_IMPL_ArenaMinPos uint64 -** #define MD_IMPL_ArenaAlloc () -> MD_IMPL_Arena* -** #define MD_IMPL_ArenaRelease (MD_IMPL_Arena*) -> void -** #define MD_IMPL_ArenaGetPos (MD_IMPL_Arena*) -> uint64 -** #define MD_IMPL_ArenaPush (MD_IMPL_Arena*, uint64) -> void* -** #define MD_IMPL_ArenaPopTo (MD_IMPL_Arena*, uint64) -> void -** #define MD_IMPL_ArenaSetAutoAlign (MD_IMPL_Arena*, uint64) -> void +** #define IMPL_Arena (must set before including md.h) +** #define IMPL_ArenaMinPos uint64 +** #define IMPL_ArenaAlloc () -> IMPL_Arena* +** #define IMPL_ArenaRelease (IMPL_Arena*) -> void +** #define IMPL_ArenaGetPos (IMPL_Arena*) -> uint64 +** #define IMPL_ArenaPush (IMPL_Arena*, uint64) -> void* +** #define IMPL_ArenaPopTo (IMPL_Arena*, uint64) -> void +** #define IMPL_ArenaSetAutoAlign (IMPL_Arena*, uint64) -> void ** ** "scratch" ** REQUIRED -** #define MD_IMPL_GetScratch (MD_IMPL_Arena**, uint64) -> MD_IMPL_Arena* +** #define IMPL_GetScratch (IMPL_Arena**, uint64) -> IMPL_Arena* ** "scratch constants" ** OPTIONAL (required for default scratch) -** #define MD_IMPL_ScratchCount uint64 [default 2] +** #define IMPL_ScratchCount uint64 [default 2] ** ** "sprintf" ** REQUIRED -** #define MD_IMPL_Vsnprintf (char*, uint64, char const*, va_list) -> uint64 +** #define IMPL_Vsnprintf (char*, uint64, char const*, va_list) -> uint64 ** ** Static Parameters to the Default Arena Implementation -** #define MD_DEFAULT_ARENA_RES_SIZE uint64 [default 64 megabytes] -** #define MD_DEFAULT_ARENA_CMT_SIZE uint64 [default 64 kilabytes] +** #define DEFAULT_ARENA_RES_SIZE uint64 [default 64 megabytes] +** #define DEFAULT_ARENA_CMT_SIZE uint64 [default 64 kilabytes] ** ** Default Implementation Controls ** These controls default to '1' i.e. 'enabled' -** #define MD_DEFAULT_BASIC_TYPES -> construct "basic types" from stdint.h header -** #define MD_DEFAULT_MEMSET -> construct "memset" from CRT -** #define MD_DEFAULT_FILE_ITER -> construct "file iteration" from OS headers -** #define MD_DEFAULT_MEMORY -> construct "low level memory" from OS headers -** #define MD_DEFAULT_ARENA -> construct "arena" from "low level memory" -** #define MD_DEFAULT_SCRATCH -> construct "scratch" from "arena" -** #define MD_DEFAULT_SPRINTF -> construct "vsnprintf" from internal implementaion +** #define DEFAULT_BASIC_TYPES -> construct "basic types" from stdint.h header +** #define DEFAULT_MEMSET -> construct "memset" from CRT +** #define DEFAULT_FILE_ITER -> construct "file iteration" from OS headers +** #define DEFAULT_MEMORY -> construct "low level memory" from OS headers +** #define DEFAULT_ARENA -> construct "arena" from "low level memory" +** #define DEFAULT_SCRATCH -> construct "scratch" from "arena" +** #define DEFAULT_SPRINTF -> construct "vsnprintf" from internal implementaion ** */ -#if !defined(MD_C) -#define MD_C +#if !defined(C) +#define C //~///////////////////////////////////////////////////////////////////////////// /////////////////////////// CRT Implementation ///////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -#if MD_DEFAULT_MEMSET +#if DEFAULT_MEMSET #include #include -#if !defined(MD_IMPL_Memset) -# define MD_IMPL_Memset MD_CRT_Memset +#if !defined(IMPL_Memset) +# define IMPL_Memset CRT_Memset #endif -#if !defined(MD_IMPL_Memmove) -# define MD_IMPL_Memmove MD_CRT_Memmove +#if !defined(IMPL_Memmove) +# define IMPL_Memmove CRT_Memmove #endif -#define MD_CRT_Memset memset -#define MD_CRT_Memmove memmove +#define CRT_Memset memset +#define CRT_Memmove memmove #endif -#if MD_DEFAULT_FILE_LOAD +#if DEFAULT_FILE_LOAD #include -#if !defined(MD_IMPL_LoadEntireFile) -# define MD_IMPL_LoadEntireFile MD_CRT_LoadEntireFile +#if !defined(IMPL_LoadEntireFile) +# define IMPL_LoadEntireFile CRT_LoadEntireFile #endif -MD_FUNCTION MD_String8 -MD_CRT_LoadEntireFile(MD_Arena *arena, MD_String8 filename) +FUNCTION String8 +CRT_LoadEntireFile(Arena *arena, String8 filename) { - MD_ArenaTemp scratch = MD_GetScratch(&arena, 1); - MD_String8 file_contents = MD_ZERO_STRUCT; - MD_String8 filename_copy = MD_S8Copy(scratch.arena, filename); + ArenaTemp scratch = GetScratch(&arena, 1); + String8 file_contents = ZERO_STRUCT; + String8 filename_copy = S8Copy(scratch.arena, filename); FILE *file = fopen((char*)filename_copy.str, "rb"); if(file != 0) { fseek(file, 0, SEEK_END); - MD_u64 file_size = ftell(file); + u64 file_size = ftell(file); fseek(file, 0, SEEK_SET); - file_contents.str = MD_PushArray(arena, MD_u8, file_size+1); + file_contents.str = PushArray(arena, u8, file_size+1); if(file_contents.str) { file_contents.size = file_size; @@ -115,7 +115,7 @@ MD_CRT_LoadEntireFile(MD_Arena *arena, MD_String8 filename) } fclose(file); } - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); return file_contents; } @@ -127,67 +127,67 @@ MD_CRT_LoadEntireFile(MD_Arena *arena, MD_String8 filename) //////////////////////////////////////////////////////////////////////////////// //- win32 header -#if (MD_DEFAULT_FILE_ITER || MD_2DEFAULT_MEMORY) && MD_OS_WINDOWS +#if (DEFAULT_FILE_ITER || MD_2DEFAULT_MEMORY) && OS_WINDOWS # include # pragma comment(lib, "User32.lib") #endif //- win32 "file iteration" -#if MD_DEFAULT_FILE_ITER && MD_OS_WINDOWS +#if DEFAULT_FILE_ITER && OS_WINDOWS -#if !defined(MD_IMPL_FileIterBegin) -# define MD_IMPL_FileIterBegin MD_WIN32_FileIterBegin +#if !defined(IMPL_FileIterBegin) +# define IMPL_FileIterBegin WIN32_FileIterBegin #endif -#if !defined(MD_IMPL_FileIterNext) -# define MD_IMPL_FileIterNext MD_WIN32_FileIterNext +#if !defined(IMPL_FileIterNext) +# define IMPL_FileIterNext WIN32_FileIterNext #endif -#if !defined(MD_IMPL_FileIterEnd) -# define MD_IMPL_FileIterEnd MD_WIN32_FileIterEnd +#if !defined(IMPL_FileIterEnd) +# define IMPL_FileIterEnd WIN32_FileIterEnd #endif -typedef struct MD_WIN32_FileIter{ +typedef struct WIN32_FileIter{ HANDLE state; - MD_u64 first; + u64 first; WIN32_FIND_DATAW find_data; -} MD_WIN32_FileIter; +} WIN32_FileIter; -MD_StaticAssert(sizeof(MD_FileIter) >= sizeof(MD_WIN32_FileIter), file_iter_size_check); +StaticAssert(sizeof(FileIter) >= sizeof(WIN32_FileIter), file_iter_size_check); -static MD_b32 -MD_WIN32_FileIterBegin(MD_FileIter *it, MD_String8 path) +static b32 +WIN32_FileIterBegin(FileIter *it, String8 path) { //- init search - MD_ArenaTemp scratch = MD_GetScratch(0, 0); + ArenaTemp scratch = GetScratch(0, 0); - MD_u8 c = path.str[path.size - 1]; - MD_b32 need_star = (c == '/' || c == '\\'); - MD_String8 cpath = need_star ? MD_S8Fmt(scratch.arena, "%.*s*", MD_S8VArg(path)) : path; - MD_String16 cpath16 = MD_S16FromS8(scratch.arena, cpath); + u8 c = path.str[path.size - 1]; + b32 need_star = (c == '/' || c == '\\'); + String8 cpath = need_star ? S8Fmt(scratch.arena, "%.*s*", S8VArg(path)) : path; + String16 cpath16 = S16FromS8(scratch.arena, cpath); - WIN32_FIND_DATAW find_data = MD_ZERO_STRUCT; + WIN32_FIND_DATAW find_data = ZERO_STRUCT; HANDLE state = FindFirstFileW((WCHAR*)cpath16.str, &find_data); - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); //- fill results - MD_b32 result = !!state; + b32 result = !!state; if (result) { - MD_WIN32_FileIter *win32_it = (MD_WIN32_FileIter*)it; + WIN32_FileIter *win32_it = (WIN32_FileIter*)it; win32_it->state = state; win32_it->first = 1; - MD_MemoryCopy(&win32_it->find_data, &find_data, sizeof(find_data)); + MemoryCopy(&win32_it->find_data, &find_data, sizeof(find_data)); } return(result); } -static MD_FileInfo -MD_WIN32_FileIterNext(MD_Arena *arena, MD_FileIter *it) +static FileInfo +WIN32_FileIterNext(Arena *arena, FileIter *it) { //- get low-level file info for this step - MD_b32 good = 0; + b32 good = 0; - MD_WIN32_FileIter *win32_it = (MD_WIN32_FileIter*)it; + WIN32_FileIter *win32_it = (WIN32_FileIter*)it; WIN32_FIND_DATAW *find_data = &win32_it->find_data; if (win32_it->first) { @@ -199,72 +199,72 @@ MD_WIN32_FileIterNext(MD_Arena *arena, MD_FileIter *it) good = FindNextFileW(win32_it->state, find_data); } - //- convert to MD_FileInfo - MD_FileInfo result = {0}; + //- convert to FileInfo + FileInfo result = {0}; if (good) { if (find_data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { - result.flags |= MD_FileFlag_Directory; + result.flags |= FileFlag_Directory; } - MD_u16 *filename_base = (MD_u16*)find_data->cFileName; - MD_u16 *ptr = filename_base; + u16 *filename_base = (u16*)find_data->cFileName; + u16 *ptr = filename_base; for (;*ptr != 0; ptr += 1); - MD_String16 filename16 = {filename_base, (MD_u64)(ptr - filename_base)}; - result.filename = MD_S8FromS16(arena, filename16); - result.file_size = ((((MD_u64)find_data->nFileSizeHigh) << 32) | - ((MD_u64)find_data->nFileSizeLow)); + String16 filename16 = {filename_base, (u64)(ptr - filename_base)}; + result.filename = S8FromS16(arena, filename16); + result.file_size = ((((u64)find_data->nFileSizeHigh) << 32) | + ((u64)find_data->nFileSizeLow)); } return(result); } static void -MD_WIN32_FileIterEnd(MD_FileIter *it) +WIN32_FileIterEnd(FileIter *it) { - MD_WIN32_FileIter *win32_it = (MD_WIN32_FileIter*)it; + WIN32_FileIter *win32_it = (WIN32_FileIter*)it; CloseHandle(win32_it->state); } #endif //- win32 "low level memory" -#if MD_DEFAULT_MEMORY && MD_OS_WINDOWS +#if DEFAULT_MEMORY && OS_WINDOWS -#if !defined(MD_IMPL_Reserve) -# define MD_IMPL_Reserve MD_WIN32_Reserve +#if !defined(IMPL_Reserve) +# define IMPL_Reserve WIN32_Reserve #endif -#if !defined(MD_IMPL_Commit) -# define MD_IMPL_Commit MD_WIN32_Commit +#if !defined(IMPL_Commit) +# define IMPL_Commit WIN32_Commit #endif -#if !defined(MD_IMPL_Decommit) -# define MD_IMPL_Decommit MD_WIN32_Decommit +#if !defined(IMPL_Decommit) +# define IMPL_Decommit WIN32_Decommit #endif -#if !defined(MD_IMPL_Release) -# define MD_IMPL_Release MD_WIN32_Release +#if !defined(IMPL_Release) +# define IMPL_Release WIN32_Release #endif static void* -MD_WIN32_Reserve(MD_u64 size) +WIN32_Reserve(u64 size) { void *result = VirtualAlloc(0, size, MEM_RESERVE, PAGE_READWRITE); return(result); } -static MD_b32 -MD_WIN32_Commit(void *ptr, MD_u64 size) +static b32 +WIN32_Commit(void *ptr, u64 size) { - MD_b32 result = (VirtualAlloc(ptr, size, MEM_COMMIT, PAGE_READWRITE) != 0); + b32 result = (VirtualAlloc(ptr, size, MEM_COMMIT, PAGE_READWRITE) != 0); return(result); } static void -MD_WIN32_Decommit(void *ptr, MD_u64 size) +WIN32_Decommit(void *ptr, u64 size) { VirtualFree(ptr, size, MEM_DECOMMIT); } static void -MD_WIN32_Release(void *ptr, MD_u64 size) +WIN32_Release(void *ptr, u64 size) { VirtualFree(ptr, 0, MEM_RELEASE); } @@ -276,7 +276,7 @@ MD_WIN32_Release(void *ptr, MD_u64 size) //////////////////////////////////////////////////////////////////////////////// //- linux headers -#if (MD_DEFAULT_FILE_ITER || MD_DEFAULT_MEMORY) && MD_OS_LINUX +#if (DEFAULT_FILE_ITER || DEFAULT_MEMORY) && OS_LINUX # include # include # include @@ -293,27 +293,27 @@ MD_WIN32_Release(void *ptr, MD_u64 size) #endif //- linux "file iteration" -#if MD_DEFAULT_FILE_ITER && MD_OS_LINUX +#if DEFAULT_FILE_ITER && OS_LINUX -#if !defined(MD_IMPL_FileIterIncrement) -# define MD_IMPL_FileIterIncrement MD_LINUX_FileIterIncrement +#if !defined(IMPL_FileIterIncrement) +# define IMPL_FileIterIncrement LINUX_FileIterIncrement #endif -typedef struct MD_LINUX_FileIter MD_LINUX_FileIter; -struct MD_LINUX_FileIter +typedef struct LINUX_FileIter LINUX_FileIter; +struct LINUX_FileIter { int dir_fd; DIR *dir; }; -MD_StaticAssert(sizeof(MD_LINUX_FileIter) <= sizeof(MD_FileIter), file_iter_size_check); +StaticAssert(sizeof(LINUX_FileIter) <= sizeof(FileIter), file_iter_size_check); -static MD_b32 -MD_LINUX_FileIterIncrement(MD_Arena *arena, MD_FileIter *opaque_it, MD_String8 path, - MD_FileInfo *out_info) +static b32 +LINUX_FileIterIncrement(Arena *arena, FileIter *opaque_it, String8 path, + FileInfo *out_info) { - MD_b32 result = 0; + b32 result = 0; - MD_LINUX_FileIter *it = (MD_LINUX_FileIter *)opaque_it; + LINUX_FileIter *it = (LINUX_FileIter *)opaque_it; if(it->dir == 0) { it->dir = opendir((char*)path.str); @@ -325,7 +325,7 @@ MD_LINUX_FileIterIncrement(MD_Arena *arena, MD_FileIter *opaque_it, MD_String8 p struct dirent *dir_entry = readdir(it->dir); if(dir_entry) { - out_info->filename = MD_S8Fmt(arena, "%s", dir_entry->d_name); + out_info->filename = S8Fmt(arena, "%s", dir_entry->d_name); out_info->flags = 0; struct stat st; @@ -333,7 +333,7 @@ MD_LINUX_FileIterIncrement(MD_Arena *arena, MD_FileIter *opaque_it, MD_String8 p { if((st.st_mode & S_IFMT) == S_IFDIR) { - out_info->flags |= MD_FileFlag_Directory; + out_info->flags |= FileFlag_Directory; } out_info->file_size = st.st_size; } @@ -361,44 +361,44 @@ MD_LINUX_FileIterIncrement(MD_Arena *arena, MD_FileIter *opaque_it, MD_String8 p #endif //- linux "low level memory" -#if MD_DEFAULT_MEMORY && MD_OS_LINUX +#if DEFAULT_MEMORY && OS_LINUX -#if !defined(MD_IMPL_Reserve) -# define MD_IMPL_Reserve MD_LINUX_Reserve +#if !defined(IMPL_Reserve) +# define IMPL_Reserve LINUX_Reserve #endif -#if !defined(MD_IMPL_Commit) -# define MD_IMPL_Commit MD_LINUX_Commit +#if !defined(IMPL_Commit) +# define IMPL_Commit LINUX_Commit #endif -#if !defined(MD_IMPL_Decommit) -# define MD_IMPL_Decommit MD_LINUX_Decommit +#if !defined(IMPL_Decommit) +# define IMPL_Decommit LINUX_Decommit #endif -#if !defined(MD_IMPL_Release) -# define MD_IMPL_Release MD_LINUX_Release +#if !defined(IMPL_Release) +# define IMPL_Release LINUX_Release #endif static void* -MD_LINUX_Reserve(MD_u64 size) +LINUX_Reserve(u64 size) { void *result = mmap(0, size, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS, -1, (off_t)0); return(result); } -static MD_b32 -MD_LINUX_Commit(void *ptr, MD_u64 size) +static b32 +LINUX_Commit(void *ptr, u64 size) { - MD_b32 result = (mprotect(ptr, size, PROT_READ|PROT_WRITE) == 0); + b32 result = (mprotect(ptr, size, PROT_READ|PROT_WRITE) == 0); return(result); } static void -MD_LINUX_Decommit(void *ptr, MD_u64 size) +LINUX_Decommit(void *ptr, u64 size) { mprotect(ptr, size, PROT_NONE); madvise(ptr, size, MADV_DONTNEED); } static void -MD_LINUX_Release(void *ptr, MD_u64 size) +LINUX_Release(void *ptr, u64 size) { munmap(ptr, size); } @@ -409,55 +409,55 @@ MD_LINUX_Release(void *ptr, MD_u64 size) ///////////// MD Arena From Reserve/Commit/Decommit/Release //////////////////// //////////////////////////////////////////////////////////////////////////////// -#if MD_DEFAULT_ARENA +#if DEFAULT_ARENA -#if !defined(MD_DEFAULT_ARENA_RES_SIZE) -# define MD_DEFAULT_ARENA_RES_SIZE (64 << 20) +#if !defined(DEFAULT_ARENA_RES_SIZE) +# define DEFAULT_ARENA_RES_SIZE (64 << 20) #endif -#if !defined(MD_DEFAULT_ARENA_CMT_SIZE) -# define MD_DEFAULT_ARENA_CMT_SIZE (64 << 10) +#if !defined(DEFAULT_ARENA_CMT_SIZE) +# define DEFAULT_ARENA_CMT_SIZE (64 << 10) #endif -#define MD_DEFAULT_ARENA_VERY_BIG (MD_DEFAULT_ARENA_RES_SIZE - MD_IMPL_ArenaMinPos)/2 +#define DEFAULT_ARENA_VERY_BIG (DEFAULT_ARENA_RES_SIZE - IMPL_ArenaMinPos)/2 //- "low level memory" implementation check -#if !defined(MD_IMPL_Reserve) -# error Missing implementation for MD_IMPL_Reserve +#if !defined(IMPL_Reserve) +# error Missing implementation for IMPL_Reserve #endif -#if !defined(MD_IMPL_Commit) -# error Missing implementation for MD_IMPL_Commit +#if !defined(IMPL_Commit) +# error Missing implementation for IMPL_Commit #endif -#if !defined(MD_IMPL_Decommit) -# error Missing implementation for MD_IMPL_Decommit +#if !defined(IMPL_Decommit) +# error Missing implementation for IMPL_Decommit #endif -#if !defined(MD_IMPL_Release) -# error Missing implementation for MD_IMPL_Release +#if !defined(IMPL_Release) +# error Missing implementation for IMPL_Release #endif -#define MD_IMPL_ArenaMinPos 64 -MD_StaticAssert(sizeof(MD_ArenaDefault) <= MD_IMPL_ArenaMinPos, arena_def_size_check); +#define IMPL_ArenaMinPos 64 +StaticAssert(sizeof(ArenaDefault) <= IMPL_ArenaMinPos, arena_def_size_check); -#define MD_IMPL_ArenaAlloc MD_ArenaDefaultAlloc -#define MD_IMPL_ArenaRelease MD_ArenaDefaultRelease -#define MD_IMPL_ArenaGetPos MD_ArenaDefaultGetPos -#define MD_IMPL_ArenaPush MD_ArenaDefaultPush -#define MD_IMPL_ArenaPopTo MD_ArenaDefaultPopTo -#define MD_IMPL_ArenaSetAutoAlign MD_ArenaDefaultSetAutoAlign +#define IMPL_ArenaAlloc ArenaDefaultAlloc +#define IMPL_ArenaRelease ArenaDefaultRelease +#define IMPL_ArenaGetPos ArenaDefaultGetPos +#define IMPL_ArenaPush ArenaDefaultPush +#define IMPL_ArenaPopTo ArenaDefaultPopTo +#define IMPL_ArenaSetAutoAlign ArenaDefaultSetAutoAlign -static MD_ArenaDefault* -MD_ArenaDefaultAlloc__Size(MD_u64 cmt, MD_u64 res) +static ArenaDefault* +ArenaDefaultAlloc__Size(u64 cmt, u64 res) { - MD_Assert(MD_IMPL_ArenaMinPos < cmt && cmt <= res); - MD_u64 cmt_clamped = MD_ClampTop(cmt, res); - MD_ArenaDefault *result = 0; - void *mem = MD_IMPL_Reserve(res); - if (MD_IMPL_Commit(mem, cmt_clamped)) + Assert(IMPL_ArenaMinPos < cmt && cmt <= res); + u64 cmt_clamped = ClampTop(cmt, res); + ArenaDefault *result = 0; + void *mem = IMPL_Reserve(res); + if (IMPL_Commit(mem, cmt_clamped)) { - result = (MD_ArenaDefault*)mem; + result = (ArenaDefault*)mem; result->prev = 0; result->current = result; result->base_pos = 0; - result->pos = MD_IMPL_ArenaMinPos; + result->pos = IMPL_ArenaMinPos; result->cmt = cmt_clamped; result->cap = res; result->align = 8; @@ -465,44 +465,44 @@ MD_ArenaDefaultAlloc__Size(MD_u64 cmt, MD_u64 res) return(result); } -static MD_ArenaDefault* -MD_ArenaDefaultAlloc(void) +static ArenaDefault* +ArenaDefaultAlloc(void) { - MD_ArenaDefault *result = MD_ArenaDefaultAlloc__Size(MD_DEFAULT_ARENA_CMT_SIZE, - MD_DEFAULT_ARENA_RES_SIZE); + ArenaDefault *result = ArenaDefaultAlloc__Size(DEFAULT_ARENA_CMT_SIZE, + DEFAULT_ARENA_RES_SIZE); return(result); } static void -MD_ArenaDefaultRelease(MD_ArenaDefault *arena) +ArenaDefaultRelease(ArenaDefault *arena) { - for (MD_ArenaDefault *node = arena->current, *prev = 0; + for (ArenaDefault *node = arena->current, *prev = 0; node != 0; node = prev) { prev = node->prev; - MD_IMPL_Release(node, node->cap); + IMPL_Release(node, node->cap); } } -static MD_u64 -MD_ArenaDefaultGetPos(MD_ArenaDefault *arena) +static u64 +ArenaDefaultGetPos(ArenaDefault *arena) { - MD_ArenaDefault *current = arena->current; - MD_u64 result = current->base_pos + current->pos; + ArenaDefault *current = arena->current; + u64 result = current->base_pos + current->pos; return(result); } static void* -MD_ArenaDefaultPush(MD_ArenaDefault *arena, MD_u64 size) +ArenaDefaultPush(ArenaDefault *arena, u64 size) { // try to be fast! - MD_ArenaDefault *current = arena->current; - MD_u64 align = arena->align; - MD_u64 pos = current->pos; - MD_u64 pos_aligned = MD_AlignPow2(pos, align); - MD_u64 new_pos = pos_aligned + size; - void *result = (MD_u8*)current + pos_aligned; + ArenaDefault *current = arena->current; + u64 align = arena->align; + u64 pos = current->pos; + u64 pos_aligned = AlignPow2(pos, align); + u64 new_pos = pos_aligned + size; + void *result = (u8*)current + pos_aligned; current->pos = new_pos; // if it's not going to work do the slow path @@ -514,16 +514,16 @@ MD_ArenaDefaultPush(MD_ArenaDefault *arena, MD_u64 size) // new chunk if necessary if (new_pos > current->cap) { - MD_ArenaDefault *new_arena = 0; - if (size > MD_DEFAULT_ARENA_VERY_BIG) + ArenaDefault *new_arena = 0; + if (size > DEFAULT_ARENA_VERY_BIG) { - MD_u64 big_size_unrounded = size + MD_IMPL_ArenaMinPos; - MD_u64 big_size = MD_AlignPow2(big_size_unrounded, (4 << 10)); - new_arena = MD_ArenaDefaultAlloc__Size(big_size, big_size); + u64 big_size_unrounded = size + IMPL_ArenaMinPos; + u64 big_size = AlignPow2(big_size_unrounded, (4 << 10)); + new_arena = ArenaDefaultAlloc__Size(big_size, big_size); } else { - new_arena = MD_ArenaDefaultAlloc(); + new_arena = ArenaDefaultAlloc(); } // link in new chunk & recompute new_pos @@ -544,10 +544,10 @@ MD_ArenaDefaultPush(MD_ArenaDefault *arena, MD_u64 size) // extend commit if necessary if (new_pos > current->cmt) { - MD_u64 new_cmt_unclamped = MD_AlignPow2(new_pos, MD_DEFAULT_ARENA_CMT_SIZE); - MD_u64 new_cmt = MD_ClampTop(new_cmt_unclamped, current->cap); - MD_u64 cmt_size = new_cmt - current->cmt; - if (MD_IMPL_Commit((MD_u8*)current + current->cmt, cmt_size)) + u64 new_cmt_unclamped = AlignPow2(new_pos, DEFAULT_ARENA_CMT_SIZE); + u64 new_cmt = ClampTop(new_cmt_unclamped, current->cap); + u64 cmt_size = new_cmt - current->cmt; + if (IMPL_Commit((u8*)current + current->cmt, cmt_size)) { current->cmt = new_cmt; } @@ -556,7 +556,7 @@ MD_ArenaDefaultPush(MD_ArenaDefault *arena, MD_u64 size) // move ahead if the current chunk has enough commit if (new_pos <= current->cmt) { - result = (MD_u8*)current + current->pos; + result = (u8*)current + current->pos; current->pos = new_pos; } } @@ -566,43 +566,43 @@ MD_ArenaDefaultPush(MD_ArenaDefault *arena, MD_u64 size) } static void -MD_ArenaDefaultPopTo(MD_ArenaDefault *arena, MD_u64 pos) +ArenaDefaultPopTo(ArenaDefault *arena, u64 pos) { // pop chunks in the chain - MD_u64 pos_clamped = MD_ClampBot(MD_IMPL_ArenaMinPos, pos); + u64 pos_clamped = ClampBot(IMPL_ArenaMinPos, pos); { - MD_ArenaDefault *node = arena->current; - for (MD_ArenaDefault *prev = 0; + ArenaDefault *node = arena->current; + for (ArenaDefault *prev = 0; node != 0 && node->base_pos >= pos; node = prev) { prev = node->prev; - MD_IMPL_Release(node, node->cap); + IMPL_Release(node, node->cap); } arena->current = node; } // reset the pos of the current { - MD_ArenaDefault *current = arena->current; - MD_u64 local_pos_unclamped = pos - current->base_pos; - MD_u64 local_pos = MD_ClampBot(local_pos_unclamped, MD_IMPL_ArenaMinPos); + ArenaDefault *current = arena->current; + u64 local_pos_unclamped = pos - current->base_pos; + u64 local_pos = ClampBot(local_pos_unclamped, IMPL_ArenaMinPos); current->pos = local_pos; } } static void -MD_ArenaDefaultSetAutoAlign(MD_ArenaDefault *arena, MD_u64 align) +ArenaDefaultSetAutoAlign(ArenaDefault *arena, u64 align) { arena->align = align; } static void -MD_ArenaDefaultAbsorb(MD_ArenaDefault *arena, MD_ArenaDefault *sub_arena) +ArenaDefaultAbsorb(ArenaDefault *arena, ArenaDefault *sub_arena) { - MD_ArenaDefault *current = arena->current; - MD_u64 base_pos_shift = current->base_pos + current->cap; - for (MD_ArenaDefault *node = sub_arena->current; + ArenaDefault *current = arena->current; + u64 base_pos_shift = current->base_pos + current->cap; + for (ArenaDefault *node = sub_arena->current; node != 0; node = node->prev) { @@ -615,63 +615,63 @@ MD_ArenaDefaultAbsorb(MD_ArenaDefault *arena, MD_ArenaDefault *sub_arena) #endif //- "arena" implementation checks -#if !defined(MD_IMPL_ArenaAlloc) -# error Missing implementation for MD_IMPL_ArenaAlloc +#if !defined(IMPL_ArenaAlloc) +# error Missing implementation for IMPL_ArenaAlloc #endif -#if !defined(MD_IMPL_ArenaRelease) -# error Missing implementation for MD_IMPL_ArenaRelease +#if !defined(IMPL_ArenaRelease) +# error Missing implementation for IMPL_ArenaRelease #endif -#if !defined(MD_IMPL_ArenaGetPos) -# error Missing implementation for MD_IMPL_ArenaGetPos +#if !defined(IMPL_ArenaGetPos) +# error Missing implementation for IMPL_ArenaGetPos #endif -#if !defined(MD_IMPL_ArenaPush) -# error Missing implementation for MD_IMPL_ArenaPush +#if !defined(IMPL_ArenaPush) +# error Missing implementation for IMPL_ArenaPush #endif -#if !defined(MD_IMPL_ArenaPopTo) -# error Missing implementation for MD_IMPL_ArenaPopTo +#if !defined(IMPL_ArenaPopTo) +# error Missing implementation for IMPL_ArenaPopTo #endif -#if !defined(MD_IMPL_ArenaSetAutoAlign) -# error Missing implementation for MD_IMPL_ArenaSetAutoAlign +#if !defined(IMPL_ArenaSetAutoAlign) +# error Missing implementation for IMPL_ArenaSetAutoAlign #endif -#if !defined(MD_IMPL_ArenaMinPos) -# error Missing implementation for MD_IMPL_ArenaMinPos +#if !defined(IMPL_ArenaMinPos) +# error Missing implementation for IMPL_ArenaMinPos #endif //~///////////////////////////////////////////////////////////////////////////// ///////////////////////////// MD Scratch Pool ////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -#if MD_DEFAULT_SCRATCH +#if DEFAULT_SCRATCH -#if !defined(MD_IMPL_ScratchCount) -# define MD_IMPL_ScratchCount 2llu +#if !defined(IMPL_ScratchCount) +# define IMPL_ScratchCount 2llu #endif -#if !defined(MD_IMPL_GetScratch) -# define MD_IMPL_GetScratch MD_GetScratchDefault +#if !defined(IMPL_GetScratch) +# define IMPL_GetScratch GetScratchDefault #endif -MD_THREAD_LOCAL MD_Arena *md_thread_scratch_pool[MD_IMPL_ScratchCount] = {0, 0}; +THREAD_LOCAL Arena *md_thread_scratch_pool[IMPL_ScratchCount] = {0, 0}; -static MD_Arena* -MD_GetScratchDefault(MD_Arena **conflicts, MD_u64 count) +static Arena* +GetScratchDefault(Arena **conflicts, u64 count) { - MD_Arena **scratch_pool = md_thread_scratch_pool; + Arena **scratch_pool = md_thread_scratch_pool; if (scratch_pool[0] == 0) { - MD_Arena **arena_ptr = scratch_pool; - for (MD_u64 i = 0; i < MD_IMPL_ScratchCount; i += 1, arena_ptr += 1) + Arena **arena_ptr = scratch_pool; + for (u64 i = 0; i < IMPL_ScratchCount; i += 1, arena_ptr += 1) { - *arena_ptr = MD_ArenaAlloc(); + *arena_ptr = ArenaAlloc(); } } - MD_Arena *result = 0; - MD_Arena **arena_ptr = scratch_pool; - for (MD_u64 i = 0; i < MD_IMPL_ScratchCount; i += 1, arena_ptr += 1) + Arena *result = 0; + Arena **arena_ptr = scratch_pool; + for (u64 i = 0; i < IMPL_ScratchCount; i += 1, arena_ptr += 1) { - MD_Arena *arena = *arena_ptr; - MD_Arena **conflict_ptr = conflicts; - for (MD_u32 j = 0; j < count; j += 1, conflict_ptr += 1) + Arena *arena = *arena_ptr; + Arena **conflict_ptr = conflicts; + for (u32 j = 0; j < count; j += 1, conflict_ptr += 1) { if (arena == *conflict_ptr) { @@ -694,7 +694,7 @@ MD_GetScratchDefault(MD_Arena **conflicts, MD_u64 count) //////////////////////// MD Library Implementation ///////////////////////////// //////////////////////////////////////////////////////////////////////////////// -#if MD_DEFAULT_SPRINTF +#if DEFAULT_SPRINTF #define STB_SPRINTF_IMPLEMENTATION #define STB_SPRINTF_DECORATE(name) md_stbsp_##name #include "md_stb_sprintf.h" @@ -703,7 +703,7 @@ MD_GetScratchDefault(MD_Arena **conflicts, MD_u64 count) //~ Nil Node Definition -static MD_Node _md_nil_node = +static Node _md_nil_node = { &_md_nil_node, // next &_md_nil_node, // prev @@ -712,128 +712,128 @@ static MD_Node _md_nil_node = &_md_nil_node, // last_child &_md_nil_node, // first_tag &_md_nil_node, // last_tag - MD_NodeKind_Nil, // kind + NodeKind_Nil, // kind 0, // flags - MD_ZERO_STRUCT, // string - MD_ZERO_STRUCT, // raw_string + ZERO_STRUCT, // string + ZERO_STRUCT, // raw_string 0, // at &_md_nil_node, // ref_target - MD_ZERO_STRUCT, // prev_comment - MD_ZERO_STRUCT, // next_comment + ZERO_STRUCT, // prev_comment + ZERO_STRUCT, // next_comment }; //~ Arena Functions -MD_FUNCTION MD_Arena* -MD_ArenaAlloc(void) +FUNCTION Arena* +ArenaAlloc(void) { - return(MD_IMPL_ArenaAlloc()); + return(IMPL_ArenaAlloc()); } -MD_FUNCTION void -MD_ArenaRelease(MD_Arena *arena) +FUNCTION void +ArenaRelease(Arena *arena) { - MD_IMPL_ArenaRelease(arena); + IMPL_ArenaRelease(arena); } -MD_FUNCTION void* -MD_ArenaPush(MD_Arena *arena, MD_u64 size) +FUNCTION void* +ArenaPush(Arena *arena, u64 size) { - void *result = MD_IMPL_ArenaPush(arena, size); + void *result = IMPL_ArenaPush(arena, size); return(result); } -MD_FUNCTION void -MD_ArenaPutBack(MD_Arena *arena, MD_u64 size) +FUNCTION void +ArenaPutBack(Arena *arena, u64 size) { - MD_u64 pos = MD_IMPL_ArenaGetPos(arena); - MD_u64 new_pos = pos - size; - MD_u64 new_pos_clamped = MD_ClampBot(MD_IMPL_ArenaMinPos, new_pos); - MD_IMPL_ArenaPopTo(arena, new_pos_clamped); + u64 pos = IMPL_ArenaGetPos(arena); + u64 new_pos = pos - size; + u64 new_pos_clamped = ClampBot(IMPL_ArenaMinPos, new_pos); + IMPL_ArenaPopTo(arena, new_pos_clamped); } -MD_FUNCTION void -MD_ArenaSetAlign(MD_Arena *arena, MD_u64 boundary) +FUNCTION void +ArenaSetAlign(Arena *arena, u64 boundary) { - MD_IMPL_ArenaSetAutoAlign(arena, boundary); + IMPL_ArenaSetAutoAlign(arena, boundary); } -MD_FUNCTION void -MD_ArenaPushAlign(MD_Arena *arena, MD_u64 boundary) +FUNCTION void +ArenaPushAlign(Arena *arena, u64 boundary) { - MD_u64 pos = MD_IMPL_ArenaGetPos(arena); - MD_u64 align_m1 = boundary - 1; - MD_u64 new_pos_aligned = (pos + align_m1)&(~align_m1); + u64 pos = IMPL_ArenaGetPos(arena); + u64 align_m1 = boundary - 1; + u64 new_pos_aligned = (pos + align_m1)&(~align_m1); if (new_pos_aligned > pos) { - MD_u64 amt = new_pos_aligned - pos; - MD_MemoryZero(MD_IMPL_ArenaPush(arena, amt), amt); + u64 amt = new_pos_aligned - pos; + MemoryZero(IMPL_ArenaPush(arena, amt), amt); } } -MD_FUNCTION void -MD_ArenaClear(MD_Arena *arena) +FUNCTION void +ArenaClear(Arena *arena) { - MD_IMPL_ArenaPopTo(arena, MD_IMPL_ArenaMinPos); + IMPL_ArenaPopTo(arena, IMPL_ArenaMinPos); } -MD_FUNCTION MD_ArenaTemp -MD_ArenaBeginTemp(MD_Arena *arena) +FUNCTION ArenaTemp +ArenaBeginTemp(Arena *arena) { - MD_ArenaTemp result; + ArenaTemp result; result.arena = arena; - result.pos = MD_IMPL_ArenaGetPos(arena); + result.pos = IMPL_ArenaGetPos(arena); return(result); } -MD_FUNCTION void -MD_ArenaEndTemp(MD_ArenaTemp temp) +FUNCTION void +ArenaEndTemp(ArenaTemp temp) { - MD_IMPL_ArenaPopTo(temp.arena, temp.pos); + IMPL_ArenaPopTo(temp.arena, temp.pos); } //~ Arena Scratch Pool -MD_FUNCTION MD_ArenaTemp -MD_GetScratch(MD_Arena **conflicts, MD_u64 count) +FUNCTION ArenaTemp +GetScratch(Arena **conflicts, u64 count) { - MD_Arena *arena = MD_IMPL_GetScratch(conflicts, count); - MD_ArenaTemp result = MD_ZERO_STRUCT; + Arena *arena = IMPL_GetScratch(conflicts, count); + ArenaTemp result = ZERO_STRUCT; if (arena != 0) { - result = MD_ArenaBeginTemp(arena); + result = ArenaBeginTemp(arena); } return(result); } //~ Characters -MD_FUNCTION MD_b32 -MD_CharIsAlpha(MD_u8 c) +FUNCTION b32 +CharIsAlpha(u8 c) { - return MD_CharIsAlphaUpper(c) || MD_CharIsAlphaLower(c); + return CharIsAlphaUpper(c) || CharIsAlphaLower(c); } -MD_FUNCTION MD_b32 -MD_CharIsAlphaUpper(MD_u8 c) +FUNCTION b32 +CharIsAlphaUpper(u8 c) { return c >= 'A' && c <= 'Z'; } -MD_FUNCTION MD_b32 -MD_CharIsAlphaLower(MD_u8 c) +FUNCTION b32 +CharIsAlphaLower(u8 c) { return c >= 'a' && c <= 'z'; } -MD_FUNCTION MD_b32 -MD_CharIsDigit(MD_u8 c) +FUNCTION b32 +CharIsDigit(u8 c) { return (c >= '0' && c <= '9'); } -MD_FUNCTION MD_b32 -MD_CharIsUnreservedSymbol(MD_u8 c) +FUNCTION b32 +CharIsUnreservedSymbol(u8 c) { return (c == '~' || c == '!' || c == '$' || c == '%' || c == '^' || c == '&' || c == '*' || c == '-' || c == '=' || c == '+' || @@ -841,68 +841,68 @@ MD_CharIsUnreservedSymbol(MD_u8 c) c == '|'); } -MD_FUNCTION MD_b32 -MD_CharIsReservedSymbol(MD_u8 c) +FUNCTION b32 +CharIsReservedSymbol(u8 c) { return (c == '{' || c == '}' || c == '(' || c == ')' || c == '\\' || c == '[' || c == ']' || c == '#' || c == ',' || c == ';' || c == ':' || c == '@'); } -MD_FUNCTION MD_b32 -MD_CharIsSpace(MD_u8 c) +FUNCTION b32 +CharIsSpace(u8 c) { return c == ' ' || c == '\r' || c == '\t' || c == '\f' || c == '\v'; } -MD_FUNCTION MD_u8 -MD_CharToUpper(MD_u8 c) +FUNCTION u8 +CharToUpper(u8 c) { return (c >= 'a' && c <= 'z') ? ('A' + (c - 'a')) : c; } -MD_FUNCTION MD_u8 -MD_CharToLower(MD_u8 c) +FUNCTION u8 +CharToLower(u8 c) { return (c >= 'A' && c <= 'Z') ? ('a' + (c - 'A')) : c; } -MD_FUNCTION MD_u8 -MD_CharToForwardSlash(MD_u8 c) +FUNCTION u8 +CharToForwardSlash(u8 c) { return (c == '\\' ? '/' : c); } //~ Strings -MD_FUNCTION MD_u64 -MD_CalculateCStringLength(char *cstr) +FUNCTION u64 +CalculateCStringLength(char *cstr) { - MD_u64 i = 0; + u64 i = 0; for(; cstr[i]; i += 1); return i; } -MD_FUNCTION MD_String8 -MD_S8(MD_u8 *str, MD_u64 size) +FUNCTION String8 +S8(u8 *str, u64 size) { - MD_String8 string; + String8 string; string.str = str; string.size = size; return string; } -MD_FUNCTION MD_String8 -MD_S8Range(MD_u8 *first, MD_u8 *opl) +FUNCTION String8 +S8Range(u8 *first, u8 *opl) { - MD_String8 string; + String8 string; string.str = first; - string.size = (MD_u64)(opl - first); + string.size = (u64)(opl - first); return string; } -MD_FUNCTION MD_String8 -MD_S8Substring(MD_String8 str, MD_u64 min, MD_u64 max) +FUNCTION String8 +S8Substring(String8 str, u64 min, u64 max) { if(max > str.size) { @@ -914,7 +914,7 @@ MD_S8Substring(MD_String8 str, MD_u64 min, MD_u64 max) } if(min > max) { - MD_u64 swap = min; + u64 swap = min; min = max; max = swap; } @@ -923,47 +923,47 @@ MD_S8Substring(MD_String8 str, MD_u64 min, MD_u64 max) return str; } -MD_FUNCTION MD_String8 -MD_S8Skip(MD_String8 str, MD_u64 min) +FUNCTION String8 +S8Skip(String8 str, u64 min) { - return MD_S8Substring(str, min, str.size); + return S8Substring(str, min, str.size); } -MD_FUNCTION MD_String8 -MD_S8Chop(MD_String8 str, MD_u64 nmax) +FUNCTION String8 +S8Chop(String8 str, u64 nmax) { - return MD_S8Substring(str, 0, str.size - nmax); + return S8Substring(str, 0, str.size - nmax); } -MD_FUNCTION MD_String8 -MD_S8Prefix(MD_String8 str, MD_u64 size) +FUNCTION String8 +S8Prefix(String8 str, u64 size) { - return MD_S8Substring(str, 0, size); + return S8Substring(str, 0, size); } -MD_FUNCTION MD_String8 -MD_S8Suffix(MD_String8 str, MD_u64 size) +FUNCTION String8 +S8Suffix(String8 str, u64 size) { - return MD_S8Substring(str, str.size - size, str.size); + return S8Substring(str, str.size - size, str.size); } -MD_FUNCTION MD_b32 -MD_S8Match(MD_String8 a, MD_String8 b, MD_MatchFlags flags) +FUNCTION b32 +S8Match(String8 a, String8 b, MatchFlags flags) { int result = 0; - if(a.size == b.size || flags & MD_StringMatchFlag_RightSideSloppy) + if(a.size == b.size || flags & StringMatchFlag_RightSideSloppy) { result = 1; - for(MD_u64 i = 0; i < a.size; i += 1) + for(u64 i = 0; i < a.size; i += 1) { - MD_b32 match = (a.str[i] == b.str[i]); - if(flags & MD_StringMatchFlag_CaseInsensitive) + b32 match = (a.str[i] == b.str[i]); + if(flags & StringMatchFlag_CaseInsensitive) { - match |= (MD_CharToLower(a.str[i]) == MD_CharToLower(b.str[i])); + match |= (CharToLower(a.str[i]) == CharToLower(b.str[i])); } - if(flags & MD_StringMatchFlag_SlashInsensitive) + if(flags & StringMatchFlag_SlashInsensitive) { - match |= (MD_CharToForwardSlash(a.str[i]) == MD_CharToForwardSlash(b.str[i])); + match |= (CharToForwardSlash(a.str[i]) == CharToForwardSlash(b.str[i])); } if(match == 0) { @@ -975,21 +975,21 @@ MD_S8Match(MD_String8 a, MD_String8 b, MD_MatchFlags flags) return result; } -MD_FUNCTION MD_u64 -MD_S8FindSubstring(MD_String8 str, MD_String8 substring, MD_u64 start_pos, MD_MatchFlags flags) +FUNCTION u64 +S8FindSubstring(String8 str, String8 substring, u64 start_pos, MatchFlags flags) { - MD_b32 found = 0; - MD_u64 found_idx = str.size; - for(MD_u64 i = start_pos; i < str.size; i += 1) + b32 found = 0; + u64 found_idx = str.size; + for(u64 i = start_pos; i < str.size; i += 1) { if(i + substring.size <= str.size) { - MD_String8 substr_from_str = MD_S8Substring(str, i, i+substring.size); - if(MD_S8Match(substr_from_str, substring, flags)) + String8 substr_from_str = S8Substring(str, i, i+substring.size); + if(S8Match(substr_from_str, substring, flags)) { found_idx = i; found = 1; - if(!(flags & MD_MatchFlag_FindLast)) + if(!(flags & MatchFlag_FindLast)) { break; } @@ -999,64 +999,64 @@ MD_S8FindSubstring(MD_String8 str, MD_String8 substring, MD_u64 start_pos, MD_Ma return found_idx; } -MD_FUNCTION MD_String8 -MD_S8Copy(MD_Arena *arena, MD_String8 string) +FUNCTION String8 +S8Copy(Arena *arena, String8 string) { - MD_String8 res; + String8 res; res.size = string.size; - res.str = MD_PushArray(arena, MD_u8, string.size + 1); - MD_MemoryCopy(res.str, string.str, string.size); + res.str = PushArray(arena, u8, string.size + 1); + MemoryCopy(res.str, string.str, string.size); res.str[string.size] = 0; return(res); } -MD_FUNCTION MD_String8 -MD_S8FmtV(MD_Arena *arena, char *fmt, va_list args) +FUNCTION String8 +S8FmtV(Arena *arena, char *fmt, va_list args) { - MD_String8 result = MD_ZERO_STRUCT; + String8 result = ZERO_STRUCT; va_list args2; va_copy(args2, args); - MD_u64 needed_bytes = MD_IMPL_Vsnprintf(0, 0, fmt, args)+1; - result.str = MD_PushArray(arena, MD_u8, needed_bytes); + u64 needed_bytes = IMPL_Vsnprintf(0, 0, fmt, args)+1; + result.str = PushArray(arena, u8, needed_bytes); result.size = needed_bytes - 1; result.str[needed_bytes-1] = 0; - MD_IMPL_Vsnprintf((char*)result.str, needed_bytes, fmt, args2); + IMPL_Vsnprintf((char*)result.str, needed_bytes, fmt, args2); return result; } -MD_FUNCTION MD_String8 -MD_S8Fmt(MD_Arena *arena, char *fmt, ...) +FUNCTION String8 +S8Fmt(Arena *arena, char *fmt, ...) { va_list args; va_start(args, fmt); - MD_String8 result = MD_S8FmtV(arena, fmt, args); + String8 result = S8FmtV(arena, fmt, args); va_end(args); return result; } -MD_FUNCTION void -MD_S8ListPush(MD_Arena *arena, MD_String8List *list, MD_String8 string) +FUNCTION void +S8ListPush(Arena *arena, String8List *list, String8 string) { - MD_String8Node *node = MD_PushArrayZero(arena, MD_String8Node, 1); + String8Node *node = PushArrayZero(arena, String8Node, 1); node->string = string; - MD_QueuePush(list->first, list->last, node); + QueuePush(list->first, list->last, node); list->node_count += 1; list->total_size += string.size; } -MD_FUNCTION void -MD_S8ListPushFmt(MD_Arena *arena, MD_String8List *list, char *fmt, ...) +FUNCTION void +S8ListPushFmt(Arena *arena, String8List *list, char *fmt, ...) { va_list args; va_start(args, fmt); - MD_String8 string = MD_S8FmtV(arena, fmt, args); + String8 string = S8FmtV(arena, fmt, args); va_end(args); - MD_S8ListPush(arena, list, string); + S8ListPush(arena, list, string); } -MD_FUNCTION void -MD_S8ListConcat(MD_String8List *list, MD_String8List *to_push) +FUNCTION void +S8ListConcat(String8List *list, String8List *to_push) { if(to_push->first) { @@ -1073,25 +1073,25 @@ MD_S8ListConcat(MD_String8List *list, MD_String8List *to_push) list->last = to_push->last; } } - MD_MemoryZeroStruct(to_push); + MemoryZeroStruct(to_push); } -MD_FUNCTION MD_String8List -MD_S8Split(MD_Arena *arena, MD_String8 string, int split_count, MD_String8 *splits) +FUNCTION String8List +S8Split(Arena *arena, String8 string, int split_count, String8 *splits) { - MD_String8List list = MD_ZERO_STRUCT; + String8List list = ZERO_STRUCT; - MD_u64 split_start = 0; - for(MD_u64 i = 0; i < string.size; i += 1) + u64 split_start = 0; + for(u64 i = 0; i < string.size; i += 1) { - MD_b32 was_split = 0; + b32 was_split = 0; for(int split_idx = 0; split_idx < split_count; split_idx += 1) { - MD_b32 match = 0; + b32 match = 0; if(i + splits[split_idx].size <= string.size) { match = 1; - for(MD_u64 split_i = 0; split_i < splits[split_idx].size && i + split_i < string.size; split_i += 1) + for(u64 split_i = 0; split_i < splits[split_idx].size && i + split_i < string.size; split_i += 1) { if(splits[split_idx].str[split_i] != string.str[i + split_i]) { @@ -1102,8 +1102,8 @@ MD_S8Split(MD_Arena *arena, MD_String8 string, int split_count, MD_String8 *spli } if(match) { - MD_String8 split_string = MD_S8(string.str + split_start, i - split_start); - MD_S8ListPush(arena, &list, split_string); + String8 split_string = S8(string.str + split_start, i - split_start); + S8ListPush(arena, &list, split_string); split_start = i + splits[split_idx].size; i += splits[split_idx].size - 1; was_split = 1; @@ -1113,8 +1113,8 @@ MD_S8Split(MD_Arena *arena, MD_String8 string, int split_count, MD_String8 *spli if(was_split == 0 && i == string.size - 1) { - MD_String8 split_string = MD_S8(string.str + split_start, i+1 - split_start); - MD_S8ListPush(arena, &list, split_string); + String8 split_string = S8(string.str + split_start, i+1 - split_start); + S8ListPush(arena, &list, split_string); break; } } @@ -1122,61 +1122,61 @@ MD_S8Split(MD_Arena *arena, MD_String8 string, int split_count, MD_String8 *spli return list; } -MD_FUNCTION MD_String8 -MD_S8ListJoin(MD_Arena *arena, MD_String8List list, MD_StringJoin *join_ptr) +FUNCTION String8 +S8ListJoin(Arena *arena, String8List list, StringJoin *join_ptr) { // setup join parameters - MD_StringJoin join = MD_ZERO_STRUCT; + StringJoin join = ZERO_STRUCT; if (join_ptr != 0) { - MD_MemoryCopy(&join, join_ptr, sizeof(join)); + MemoryCopy(&join, join_ptr, sizeof(join)); } // calculate size & allocate - MD_u64 sep_count = 0; + u64 sep_count = 0; if (list.node_count > 1) { sep_count = list.node_count - 1; } - MD_String8 result = MD_ZERO_STRUCT; + String8 result = ZERO_STRUCT; result.size = (list.total_size + join.pre.size + sep_count*join.mid.size + join.post.size); - result.str = MD_PushArrayZero(arena, MD_u8, result.size); + result.str = PushArrayZero(arena, u8, result.size); // fill - MD_u8 *ptr = result.str; - MD_MemoryCopy(ptr, join.pre.str, join.pre.size); + u8 *ptr = result.str; + MemoryCopy(ptr, join.pre.str, join.pre.size); ptr += join.pre.size; - for(MD_String8Node *node = list.first; node; node = node->next) + for(String8Node *node = list.first; node; node = node->next) { - MD_MemoryCopy(ptr, node->string.str, node->string.size); + MemoryCopy(ptr, node->string.str, node->string.size); ptr += node->string.size; if (node != list.last) { - MD_MemoryCopy(ptr, join.mid.str, join.mid.size); + MemoryCopy(ptr, join.mid.str, join.mid.size); ptr += join.mid.size; } } - MD_MemoryCopy(ptr, join.pre.str, join.pre.size); + MemoryCopy(ptr, join.pre.str, join.pre.size); ptr += join.pre.size; return(result); } -MD_FUNCTION MD_String8 -MD_S8Stylize(MD_Arena *arena, MD_String8 string, MD_IdentifierStyle word_style, - MD_String8 separator) +FUNCTION String8 +S8Stylize(Arena *arena, String8 string, IdentifierStyle word_style, + String8 separator) { - MD_String8 result = MD_ZERO_STRUCT; + String8 result = ZERO_STRUCT; - MD_String8List words = MD_ZERO_STRUCT; + String8List words = ZERO_STRUCT; - MD_b32 break_on_uppercase = 0; + b32 break_on_uppercase = 0; { break_on_uppercase = 1; - for(MD_u64 i = 0; i < string.size; i += 1) + for(u64 i = 0; i < string.size; i += 1) { - if(!MD_CharIsAlpha(string.str[i]) && !MD_CharIsDigit(string.str[i])) + if(!CharIsAlpha(string.str[i]) && !CharIsDigit(string.str[i])) { break_on_uppercase = 0; break; @@ -1184,15 +1184,15 @@ MD_S8Stylize(MD_Arena *arena, MD_String8 string, MD_IdentifierStyle word_style, } } - MD_b32 making_word = 0; - MD_String8 word = MD_ZERO_STRUCT; + b32 making_word = 0; + String8 word = ZERO_STRUCT; - for(MD_u64 i = 0; i < string.size;) + for(u64 i = 0; i < string.size;) { if(making_word) { - if((break_on_uppercase && MD_CharIsAlphaUpper(string.str[i])) || - string.str[i] == '_' || MD_CharIsSpace(string.str[i]) || + if((break_on_uppercase && CharIsAlphaUpper(string.str[i])) || + string.str[i] == '_' || CharIsSpace(string.str[i]) || i == string.size - 1) { if(i == string.size - 1) @@ -1200,7 +1200,7 @@ MD_S8Stylize(MD_Arena *arena, MD_String8 string, MD_IdentifierStyle word_style, word.size += 1; } making_word = 0; - MD_S8ListPush(arena, &words, word); + S8ListPush(arena, &words, word); } else { @@ -1210,7 +1210,7 @@ MD_S8Stylize(MD_Arena *arena, MD_String8 string, MD_IdentifierStyle word_style, } else { - if(MD_CharIsAlpha(string.str[i])) + if(CharIsAlpha(string.str[i])) { making_word = 1; word.str = string.str + i; @@ -1225,54 +1225,54 @@ MD_S8Stylize(MD_Arena *arena, MD_String8 string, MD_IdentifierStyle word_style, { result.size += separator.size*(words.node_count-1); } - result.str = MD_PushArrayZero(arena, MD_u8, result.size); + result.str = PushArrayZero(arena, u8, result.size); { - MD_u64 write_pos = 0; - for(MD_String8Node *node = words.first; node; node = node->next) + u64 write_pos = 0; + for(String8Node *node = words.first; node; node = node->next) { // NOTE(rjf): Write word string to result. { - MD_MemoryCopy(result.str + write_pos, node->string.str, node->string.size); + MemoryCopy(result.str + write_pos, node->string.str, node->string.size); // NOTE(rjf): Transform string based on word style. switch(word_style) { - case MD_IdentifierStyle_UpperCamelCase: + case IdentifierStyle_UpperCamelCase: { - result.str[write_pos] = MD_CharToUpper(result.str[write_pos]); - for(MD_u64 i = write_pos+1; i < write_pos + node->string.size; i += 1) + result.str[write_pos] = CharToUpper(result.str[write_pos]); + for(u64 i = write_pos+1; i < write_pos + node->string.size; i += 1) { - result.str[i] = MD_CharToLower(result.str[i]); + result.str[i] = CharToLower(result.str[i]); } }break; - case MD_IdentifierStyle_LowerCamelCase: + case IdentifierStyle_LowerCamelCase: { - MD_b32 is_first = (node == words.first); + b32 is_first = (node == words.first); result.str[write_pos] = (is_first ? - MD_CharToLower(result.str[write_pos]) : - MD_CharToUpper(result.str[write_pos])); - for(MD_u64 i = write_pos+1; i < write_pos + node->string.size; i += 1) + CharToLower(result.str[write_pos]) : + CharToUpper(result.str[write_pos])); + for(u64 i = write_pos+1; i < write_pos + node->string.size; i += 1) { - result.str[i] = MD_CharToLower(result.str[i]); + result.str[i] = CharToLower(result.str[i]); } }break; - case MD_IdentifierStyle_UpperCase: + case IdentifierStyle_UpperCase: { - for(MD_u64 i = write_pos; i < write_pos + node->string.size; i += 1) + for(u64 i = write_pos; i < write_pos + node->string.size; i += 1) { - result.str[i] = MD_CharToUpper(result.str[i]); + result.str[i] = CharToUpper(result.str[i]); } }break; - case MD_IdentifierStyle_LowerCase: + case IdentifierStyle_LowerCase: { - for(MD_u64 i = write_pos; i < write_pos + node->string.size; i += 1) + for(u64 i = write_pos; i < write_pos + node->string.size; i += 1) { - result.str[i] = MD_CharToLower(result.str[i]); + result.str[i] = CharToLower(result.str[i]); } }break; @@ -1284,7 +1284,7 @@ MD_S8Stylize(MD_Arena *arena, MD_String8 string, MD_IdentifierStyle word_style, if(node->next) { - MD_MemoryCopy(result.str + write_pos, separator.str, separator.size); + MemoryCopy(result.str + write_pos, separator.str, separator.size); write_pos += separator.size; } } @@ -1295,27 +1295,27 @@ MD_S8Stylize(MD_Arena *arena, MD_String8 string, MD_IdentifierStyle word_style, //~ Unicode Conversions -MD_GLOBAL MD_u8 md_utf8_class[32] = { +GLOBAL u8 md_utf8_class[32] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,2,2,2,2,3,3,4,5, }; -MD_FUNCTION MD_DecodedCodepoint -MD_DecodeCodepointFromUtf8(MD_u8 *str, MD_u64 max) -{ -#define MD_bitmask1 0x01 -#define MD_bitmask2 0x03 -#define MD_bitmask3 0x07 -#define MD_bitmask4 0x0F -#define MD_bitmask5 0x1F -#define MD_bitmask6 0x3F -#define MD_bitmask7 0x7F -#define MD_bitmask8 0xFF -#define MD_bitmask9 0x01FF -#define MD_bitmask10 0x03FF +FUNCTION DecodedCodepoint +DecodeCodepointFromUtf8(u8 *str, u64 max) +{ +#define bitmask1 0x01 +#define bitmask2 0x03 +#define bitmask3 0x07 +#define bitmask4 0x0F +#define bitmask5 0x1F +#define bitmask6 0x3F +#define bitmask7 0x7F +#define bitmask8 0xFF +#define bitmask9 0x01FF +#define bitmask10 0x03FF - MD_DecodedCodepoint result = {~((MD_u32)0), 1}; - MD_u8 byte = str[0]; - MD_u8 byte_class = md_utf8_class[byte >> 3]; + DecodedCodepoint result = {~((u32)0), 1}; + u8 byte = str[0]; + u8 byte_class = md_utf8_class[byte >> 3]; switch (byte_class) { case 1: @@ -1327,11 +1327,11 @@ MD_DecodeCodepointFromUtf8(MD_u8 *str, MD_u64 max) { if (2 <= max) { - MD_u8 cont_byte = str[1]; + u8 cont_byte = str[1]; if (md_utf8_class[cont_byte >> 3] == 0) { - result.codepoint = (byte & MD_bitmask5) << 6; - result.codepoint |= (cont_byte & MD_bitmask6); + result.codepoint = (byte & bitmask5) << 6; + result.codepoint |= (cont_byte & bitmask6); result.advance = 2; } } @@ -1341,13 +1341,13 @@ MD_DecodeCodepointFromUtf8(MD_u8 *str, MD_u64 max) { if (3 <= max) { - MD_u8 cont_byte[2] = {str[1], str[2]}; + u8 cont_byte[2] = {str[1], str[2]}; if (md_utf8_class[cont_byte[0] >> 3] == 0 && md_utf8_class[cont_byte[1] >> 3] == 0) { - result.codepoint = (byte & MD_bitmask4) << 12; - result.codepoint |= ((cont_byte[0] & MD_bitmask6) << 6); - result.codepoint |= (cont_byte[1] & MD_bitmask6); + result.codepoint = (byte & bitmask4) << 12; + result.codepoint |= ((cont_byte[0] & bitmask6) << 6); + result.codepoint |= (cont_byte[1] & bitmask6); result.advance = 3; } } @@ -1357,15 +1357,15 @@ MD_DecodeCodepointFromUtf8(MD_u8 *str, MD_u64 max) { if (4 <= max) { - MD_u8 cont_byte[3] = {str[1], str[2], str[3]}; + u8 cont_byte[3] = {str[1], str[2], str[3]}; if (md_utf8_class[cont_byte[0] >> 3] == 0 && md_utf8_class[cont_byte[1] >> 3] == 0 && md_utf8_class[cont_byte[2] >> 3] == 0) { - result.codepoint = (byte & MD_bitmask3) << 18; - result.codepoint |= ((cont_byte[0] & MD_bitmask6) << 12); - result.codepoint |= ((cont_byte[1] & MD_bitmask6) << 6); - result.codepoint |= (cont_byte[2] & MD_bitmask6); + result.codepoint = (byte & bitmask3) << 18; + result.codepoint |= ((cont_byte[0] & bitmask6) << 12); + result.codepoint |= ((cont_byte[1] & bitmask6) << 6); + result.codepoint |= (cont_byte[2] & bitmask6); result.advance = 4; } } @@ -1375,10 +1375,10 @@ MD_DecodeCodepointFromUtf8(MD_u8 *str, MD_u64 max) return(result); } -MD_FUNCTION MD_DecodedCodepoint -MD_DecodeCodepointFromUtf16(MD_u16 *out, MD_u64 max) +FUNCTION DecodedCodepoint +DecodeCodepointFromUtf16(u16 *out, u64 max) { - MD_DecodedCodepoint result = {~((MD_u32)0), 1}; + DecodedCodepoint result = {~((u32)0), 1}; result.codepoint = out[0]; result.advance = 1; if (1 < max && 0xD800 <= out[0] && out[0] < 0xDC00 && 0xDC00 <= out[1] && out[1] < 0xE000) @@ -1389,35 +1389,35 @@ MD_DecodeCodepointFromUtf16(MD_u16 *out, MD_u64 max) return(result); } -MD_FUNCTION MD_u32 -MD_Utf8FromCodepoint(MD_u8 *out, MD_u32 codepoint) +FUNCTION u32 +Utf8FromCodepoint(u8 *out, u32 codepoint) { -#define MD_bit8 0x80 - MD_u32 advance = 0; +#define bit8 0x80 + u32 advance = 0; if (codepoint <= 0x7F) { - out[0] = (MD_u8)codepoint; + out[0] = (u8)codepoint; advance = 1; } else if (codepoint <= 0x7FF) { - out[0] = (MD_bitmask2 << 6) | ((codepoint >> 6) & MD_bitmask5); - out[1] = MD_bit8 | (codepoint & MD_bitmask6); + out[0] = (bitmask2 << 6) | ((codepoint >> 6) & bitmask5); + out[1] = bit8 | (codepoint & bitmask6); advance = 2; } else if (codepoint <= 0xFFFF) { - out[0] = (MD_bitmask3 << 5) | ((codepoint >> 12) & MD_bitmask4); - out[1] = MD_bit8 | ((codepoint >> 6) & MD_bitmask6); - out[2] = MD_bit8 | ( codepoint & MD_bitmask6); + out[0] = (bitmask3 << 5) | ((codepoint >> 12) & bitmask4); + out[1] = bit8 | ((codepoint >> 6) & bitmask6); + out[2] = bit8 | ( codepoint & bitmask6); advance = 3; } else if (codepoint <= 0x10FFFF) { - out[0] = (MD_bitmask4 << 3) | ((codepoint >> 18) & MD_bitmask3); - out[1] = MD_bit8 | ((codepoint >> 12) & MD_bitmask6); - out[2] = MD_bit8 | ((codepoint >> 6) & MD_bitmask6); - out[3] = MD_bit8 | ( codepoint & MD_bitmask6); + out[0] = (bitmask4 << 3) | ((codepoint >> 18) & bitmask3); + out[1] = bit8 | ((codepoint >> 12) & bitmask6); + out[2] = bit8 | ((codepoint >> 6) & bitmask6); + out[3] = bit8 | ( codepoint & bitmask6); advance = 4; } else @@ -1428,115 +1428,115 @@ MD_Utf8FromCodepoint(MD_u8 *out, MD_u32 codepoint) return(advance); } -MD_FUNCTION MD_u32 -MD_Utf16FromCodepoint(MD_u16 *out, MD_u32 codepoint) +FUNCTION u32 +Utf16FromCodepoint(u16 *out, u32 codepoint) { - MD_u32 advance = 1; - if (codepoint == ~((MD_u32)0)) + u32 advance = 1; + if (codepoint == ~((u32)0)) { - out[0] = (MD_u16)'?'; + out[0] = (u16)'?'; } else if (codepoint < 0x10000) { - out[0] = (MD_u16)codepoint; + out[0] = (u16)codepoint; } else { - MD_u64 v = codepoint - 0x10000; + u64 v = codepoint - 0x10000; out[0] = 0xD800 + (v >> 10); - out[1] = 0xDC00 + (v & MD_bitmask10); + out[1] = 0xDC00 + (v & bitmask10); advance = 2; } return(advance); } -MD_FUNCTION MD_String8 -MD_S8FromS16(MD_Arena *arena, MD_String16 in) +FUNCTION String8 +S8FromS16(Arena *arena, String16 in) { - MD_u64 cap = in.size*3; - MD_u8 *str = MD_PushArrayZero(arena, MD_u8, cap + 1); - MD_u16 *ptr = in.str; - MD_u16 *opl = ptr + in.size; - MD_u64 size = 0; - MD_DecodedCodepoint consume; + u64 cap = in.size*3; + u8 *str = PushArrayZero(arena, u8, cap + 1); + u16 *ptr = in.str; + u16 *opl = ptr + in.size; + u64 size = 0; + DecodedCodepoint consume; for (;ptr < opl;) { - consume = MD_DecodeCodepointFromUtf16(ptr, opl - ptr); + consume = DecodeCodepointFromUtf16(ptr, opl - ptr); ptr += consume.advance; - size += MD_Utf8FromCodepoint(str + size, consume.codepoint); + size += Utf8FromCodepoint(str + size, consume.codepoint); } str[size] = 0; - MD_ArenaPutBack(arena, cap - size); // := ((cap + 1) - (size + 1)) - return(MD_S8(str, size)); + ArenaPutBack(arena, cap - size); // := ((cap + 1) - (size + 1)) + return(S8(str, size)); } -MD_FUNCTION MD_String16 -MD_S16FromS8(MD_Arena *arena, MD_String8 in) +FUNCTION String16 +S16FromS8(Arena *arena, String8 in) { - MD_u64 cap = in.size*2; - MD_u16 *str = MD_PushArrayZero(arena, MD_u16, cap + 1); - MD_u8 *ptr = in.str; - MD_u8 *opl = ptr + in.size; - MD_u64 size = 0; - MD_DecodedCodepoint consume; + u64 cap = in.size*2; + u16 *str = PushArrayZero(arena, u16, cap + 1); + u8 *ptr = in.str; + u8 *opl = ptr + in.size; + u64 size = 0; + DecodedCodepoint consume; for (;ptr < opl;) { - consume = MD_DecodeCodepointFromUtf8(ptr, opl - ptr); + consume = DecodeCodepointFromUtf8(ptr, opl - ptr); ptr += consume.advance; - size += MD_Utf16FromCodepoint(str + size, consume.codepoint); + size += Utf16FromCodepoint(str + size, consume.codepoint); } str[size] = 0; - MD_ArenaPutBack(arena, 2*(cap - size)); // := 2*((cap + 1) - (size + 1)) - MD_String16 result = {str, size}; + ArenaPutBack(arena, 2*(cap - size)); // := 2*((cap + 1) - (size + 1)) + String16 result = {str, size}; return(result); } -MD_FUNCTION MD_String8 -MD_S8FromS32(MD_Arena *arena, MD_String32 in) +FUNCTION String8 +S8FromS32(Arena *arena, String32 in) { - MD_u64 cap = in.size*4; - MD_u8 *str = MD_PushArrayZero(arena, MD_u8, cap + 1); - MD_u32 *ptr = in.str; - MD_u32 *opl = ptr + in.size; - MD_u64 size = 0; - MD_DecodedCodepoint consume; + u64 cap = in.size*4; + u8 *str = PushArrayZero(arena, u8, cap + 1); + u32 *ptr = in.str; + u32 *opl = ptr + in.size; + u64 size = 0; + DecodedCodepoint consume; for (;ptr < opl; ptr += 1) { - size += MD_Utf8FromCodepoint(str + size, *ptr); + size += Utf8FromCodepoint(str + size, *ptr); } str[size] = 0; - MD_ArenaPutBack(arena, cap - size); // := ((cap + 1) - (size + 1)) - return(MD_S8(str, size)); + ArenaPutBack(arena, cap - size); // := ((cap + 1) - (size + 1)) + return(S8(str, size)); } -MD_FUNCTION MD_String32 -MD_S32FromS8(MD_Arena *arena, MD_String8 in) +FUNCTION String32 +S32FromS8(Arena *arena, String8 in) { - MD_u64 cap = in.size; - MD_u32 *str = MD_PushArrayZero(arena, MD_u32, cap + 1); - MD_u8 *ptr = in.str; - MD_u8 *opl = ptr + in.size; - MD_u64 size = 0; - MD_DecodedCodepoint consume; + u64 cap = in.size; + u32 *str = PushArrayZero(arena, u32, cap + 1); + u8 *ptr = in.str; + u8 *opl = ptr + in.size; + u64 size = 0; + DecodedCodepoint consume; for (;ptr < opl;) { - consume = MD_DecodeCodepointFromUtf8(ptr, opl - ptr); + consume = DecodeCodepointFromUtf8(ptr, opl - ptr); ptr += consume.advance; str[size] = consume.codepoint; size += 1; } str[size] = 0; - MD_ArenaPutBack(arena, 4*(cap - size)); // := 4*((cap + 1) - (size + 1)) - MD_String32 result = {str, size}; + ArenaPutBack(arena, 4*(cap - size)); // := 4*((cap + 1) - (size + 1)) + String32 result = {str, size}; return(result); } //~ File Name Strings -MD_FUNCTION MD_String8 -MD_PathChopLastPeriod(MD_String8 string) +FUNCTION String8 +PathChopLastPeriod(String8 string) { - MD_u64 period_pos = MD_S8FindSubstring(string, MD_S8Lit("."), 0, MD_MatchFlag_FindLast); + u64 period_pos = S8FindSubstring(string, S8Lit("."), 0, MatchFlag_FindLast); if(period_pos < string.size) { string.size = period_pos; @@ -1544,12 +1544,12 @@ MD_PathChopLastPeriod(MD_String8 string) return string; } -MD_FUNCTION MD_String8 -MD_PathSkipLastSlash(MD_String8 string) +FUNCTION String8 +PathSkipLastSlash(String8 string) { - MD_u64 slash_pos = MD_S8FindSubstring(string, MD_S8Lit("/"), 0, - MD_StringMatchFlag_SlashInsensitive| - MD_MatchFlag_FindLast); + u64 slash_pos = S8FindSubstring(string, S8Lit("/"), 0, + StringMatchFlag_SlashInsensitive| + MatchFlag_FindLast); if(slash_pos < string.size) { string.str += slash_pos+1; @@ -1558,10 +1558,10 @@ MD_PathSkipLastSlash(MD_String8 string) return string; } -MD_FUNCTION MD_String8 -MD_PathSkipLastPeriod(MD_String8 string) +FUNCTION String8 +PathSkipLastPeriod(String8 string) { - MD_u64 period_pos = MD_S8FindSubstring(string, MD_S8Lit("."), 0, MD_MatchFlag_FindLast); + u64 period_pos = S8FindSubstring(string, S8Lit("."), 0, MatchFlag_FindLast); if(period_pos < string.size) { string.str += period_pos+1; @@ -1570,12 +1570,12 @@ MD_PathSkipLastPeriod(MD_String8 string) return string; } -MD_FUNCTION MD_String8 -MD_PathChopLastSlash(MD_String8 string) +FUNCTION String8 +PathChopLastSlash(String8 string) { - MD_u64 slash_pos = MD_S8FindSubstring(string, MD_S8Lit("/"), 0, - MD_StringMatchFlag_SlashInsensitive| - MD_MatchFlag_FindLast); + u64 slash_pos = S8FindSubstring(string, S8Lit("/"), 0, + StringMatchFlag_SlashInsensitive| + MatchFlag_FindLast); if(slash_pos < string.size) { string.size = slash_pos; @@ -1583,28 +1583,28 @@ MD_PathChopLastSlash(MD_String8 string) return string; } -MD_FUNCTION MD_String8 -MD_S8SkipWhitespace(MD_String8 string) +FUNCTION String8 +S8SkipWhitespace(String8 string) { - for(MD_u64 i = 0; i < string.size; i += 1) + for(u64 i = 0; i < string.size; i += 1) { - if(!MD_CharIsSpace(string.str[i])) + if(!CharIsSpace(string.str[i])) { - string = MD_S8Skip(string, i); + string = S8Skip(string, i); break; } } return string; } -MD_FUNCTION MD_String8 -MD_S8ChopWhitespace(MD_String8 string) +FUNCTION String8 +S8ChopWhitespace(String8 string) { - for(MD_u64 i = string.size-1; i < string.size; i -= 1) + for(u64 i = string.size-1; i < string.size; i -= 1) { - if(!MD_CharIsSpace(string.str[i])) + if(!CharIsSpace(string.str[i])) { - string = MD_S8Prefix(string, i+1); + string = S8Prefix(string, i+1); break; } } @@ -1613,32 +1613,32 @@ MD_S8ChopWhitespace(MD_String8 string) //~ Numeric Strings -MD_GLOBAL MD_u8 md_char_to_value[] = { +GLOBAL u8 md_char_to_value[] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, 0x08,0x09,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, }; -MD_GLOBAL MD_u8 md_char_is_integer[] = { +GLOBAL u8 md_char_is_integer[] = { 0,0,0,0,0,0,1,1, 1,0,0,0,1,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, }; -MD_FUNCTION MD_b32 -MD_StringIsU64(MD_String8 string, MD_u32 radix) +FUNCTION b32 +StringIsU64(String8 string, u32 radix) { - MD_b32 result = 0; + b32 result = 0; if (string.size > 0) { result = 1; - for (MD_u8 *ptr = string.str, *opl = string.str + string.size; + for (u8 *ptr = string.str, *opl = string.str + string.size; ptr < opl; ptr += 1) { - MD_u8 c = *ptr; + u8 c = *ptr; if (!md_char_is_integer[c >> 3]) { result = 0; @@ -1654,27 +1654,27 @@ MD_StringIsU64(MD_String8 string, MD_u32 radix) return(result); } -MD_FUNCTION MD_b32 -MD_StringIsCStyleInt(MD_String8 string) +FUNCTION b32 +StringIsCStyleInt(String8 string) { - MD_u8 *ptr = string.str; - MD_u8 *opl = string.str + string.size; + u8 *ptr = string.str; + u8 *opl = string.str + string.size; // consume sign for (;ptr < opl && (*ptr == '+' || *ptr == '-'); ptr += 1); // radix from prefix - MD_u64 radix = 10; + u64 radix = 10; if (ptr < opl) { - MD_u8 c0 = *ptr; + u8 c0 = *ptr; if (c0 == '0') { ptr += 1; radix = 8; if (ptr < opl) { - MD_u8 c1 = *ptr; + u8 c1 = *ptr; if (c1 == 'x') { ptr += 1; @@ -1690,36 +1690,36 @@ MD_StringIsCStyleInt(MD_String8 string) } // check integer "digits" - MD_String8 digits_substr = MD_S8Range(ptr, opl); - MD_b32 result = MD_StringIsU64(digits_substr, radix); + String8 digits_substr = S8Range(ptr, opl); + b32 result = StringIsU64(digits_substr, radix); return(result); } -MD_FUNCTION MD_u64 -MD_U64FromString(MD_String8 string, MD_u32 radix) +FUNCTION u64 +U64FromString(String8 string, u32 radix) { - MD_Assert(2 <= radix && radix <= 16); - MD_u64 value = 0; - for (MD_u64 i = 0; i < string.size; i += 1) + Assert(2 <= radix && radix <= 16); + u64 value = 0; + for (u64 i = 0; i < string.size; i += 1) { value *= radix; - MD_u8 c = string.str[i]; + u8 c = string.str[i]; value += md_char_to_value[(c - 0x30)&0x1F]; } return(value); } -MD_FUNCTION MD_i64 -MD_CStyleIntFromString(MD_String8 string) +FUNCTION i64 +CStyleIntFromString(String8 string) { - MD_u64 p = 0; + u64 p = 0; // consume sign - MD_i64 sign = +1; + i64 sign = +1; if (p < string.size) { - MD_u8 c = string.str[p]; + u8 c = string.str[p]; if (c == '-') { sign = -1; @@ -1732,17 +1732,17 @@ MD_CStyleIntFromString(MD_String8 string) } // radix from prefix - MD_u64 radix = 10; + u64 radix = 10; if (p < string.size) { - MD_u8 c0 = string.str[p]; + u8 c0 = string.str[p]; if (c0 == '0') { p += 1; radix = 8; if (p < string.size) { - MD_u8 c1 = string.str[p]; + u8 c1 = string.str[p]; if (c1 == 'x') { p += 1; @@ -1758,36 +1758,36 @@ MD_CStyleIntFromString(MD_String8 string) } // consume integer "digits" - MD_String8 digits_substr = MD_S8Skip(string, p); - MD_u64 n = MD_U64FromString(digits_substr, radix); + String8 digits_substr = S8Skip(string, p); + u64 n = U64FromString(digits_substr, radix); // combine result - MD_i64 result = sign*n; + i64 result = sign*n; return(result); } -MD_FUNCTION MD_f64 -MD_F64FromString(MD_String8 string) +FUNCTION f64 +F64FromString(String8 string) { char str[64]; - MD_u64 str_size = string.size; + u64 str_size = string.size; if (str_size > sizeof(str) - 1) { str_size = sizeof(str) - 1; } - MD_MemoryCopy(str, string.str, str_size); + MemoryCopy(str, string.str, str_size); str[str_size] = 0; return(atof(str)); } -MD_FUNCTION MD_String8 -MD_CStyleHexStringFromU64(MD_Arena *arena, MD_u64 x, MD_b32 caps) +FUNCTION String8 +CStyleHexStringFromU64(Arena *arena, u64 x, b32 caps) { static char md_int_value_to_char[] = "0123456789abcdef"; - MD_u8 buffer[10]; - MD_u8 *opl = buffer + 10; - MD_u8 *ptr = opl; + u8 buffer[10]; + u8 *opl = buffer + 10; + u8 *ptr = opl; if (x == 0) { ptr -= 1; @@ -1797,12 +1797,12 @@ MD_CStyleHexStringFromU64(MD_Arena *arena, MD_u64 x, MD_b32 caps) { for (;;) { - MD_u32 val = x%16; + u32 val = x%16; x /= 16; - MD_u8 c = (MD_u8)md_int_value_to_char[val]; + u8 c = (u8)md_int_value_to_char[val]; if (caps) { - c = MD_CharToUpper(c); + c = CharToUpper(c); } ptr -= 1; *ptr = c; @@ -1817,21 +1817,21 @@ MD_CStyleHexStringFromU64(MD_Arena *arena, MD_u64 x, MD_b32 caps) ptr -= 1; *ptr = '0'; - MD_String8 result = MD_ZERO_STRUCT; - result.size = (MD_u64)(ptr - buffer); - result.str = MD_PushArray(arena, MD_u8, result.size + 1); - MD_MemoryCopy(result.str, buffer, result.size); + String8 result = ZERO_STRUCT; + result.size = (u64)(ptr - buffer); + result.str = PushArray(arena, u8, result.size + 1); + MemoryCopy(result.str, buffer, result.size); result.str[result.size] =0; return(result); } //~ Enum/Flag Strings -MD_FUNCTION MD_String8 -MD_StringFromNodeKind(MD_NodeKind kind) +FUNCTION String8 +StringFromNodeKind(NodeKind kind) { - // NOTE(rjf): @maintenance Must be kept in sync with MD_NodeKind enum. - static char *cstrs[MD_NodeKind_COUNT] = + // NOTE(rjf): @maintenance Must be kept in sync with NodeKind enum. + static char *cstrs[NodeKind_COUNT] = { "Nil", @@ -1844,13 +1844,13 @@ MD_StringFromNodeKind(MD_NodeKind kind) "List", "Reference", }; - return MD_S8CString(cstrs[kind]); + return S8CString(cstrs[kind]); } -MD_FUNCTION MD_String8List -MD_StringListFromNodeFlags(MD_Arena *arena, MD_NodeFlags flags) +FUNCTION String8List +StringListFromNodeFlags(Arena *arena, NodeFlags flags) { - // NOTE(rjf): @maintenance Must be kept in sync with MD_NodeFlags enum. + // NOTE(rjf): @maintenance Must be kept in sync with NodeFlags enum. static char *flag_cstrs[] = { "HasParenLeft", @@ -1876,13 +1876,13 @@ MD_StringListFromNodeFlags(MD_Arena *arena, MD_NodeFlags flags) "StringLiteral", }; - MD_String8List list = MD_ZERO_STRUCT; - MD_u64 bits = sizeof(flags) * 8; - for(MD_u64 i = 0; i < bits && i < MD_ArrayCount(flag_cstrs); i += 1) + String8List list = ZERO_STRUCT; + u64 bits = sizeof(flags) * 8; + for(u64 i = 0; i < bits && i < ArrayCount(flag_cstrs); i += 1) { if(flags & (1ull << i)) { - MD_S8ListPush(arena, &list, MD_S8CString(flag_cstrs[i])); + S8ListPush(arena, &list, S8CString(flag_cstrs[i])); } } return list; @@ -1890,11 +1890,11 @@ MD_StringListFromNodeFlags(MD_Arena *arena, MD_NodeFlags flags) //~ Map Table Data Structure -MD_FUNCTION MD_u64 -MD_HashStr(MD_String8 string) +FUNCTION u64 +HashStr(String8 string) { - MD_u64 result = 5381; - for(MD_u64 i = 0; i < string.size; i += 1) + u64 result = 5381; + for(u64 i = 0; i < string.size; i += 1) { result = ((result << 5) + result) + string.str[i]; } @@ -1903,39 +1903,39 @@ MD_HashStr(MD_String8 string) // NOTE(mal): Generic 64-bit hash function (https://nullprogram.com/blog/2018/07/31/) // Reversible, so no collisions. Assumes all bits of the pointer matter. -MD_FUNCTION MD_u64 -MD_HashPtr(void *p) +FUNCTION u64 +HashPtr(void *p) { - MD_u64 h = (MD_u64)p; + u64 h = (u64)p; h = (h ^ (h >> 30)) * 0xbf58476d1ce4e5b9; h = (h ^ (h >> 27)) * 0x94d049bb133111eb; h = h ^ (h >> 31); return h; } -MD_FUNCTION MD_Map -MD_MapMakeBucketCount(MD_Arena *arena, MD_u64 bucket_count) +FUNCTION Map +MapMakeBucketCount(Arena *arena, u64 bucket_count) { - MD_Map result = {0}; + Map result = {0}; result.bucket_count = bucket_count; - result.buckets = MD_PushArrayZero(arena, MD_MapBucket, bucket_count); + result.buckets = PushArrayZero(arena, MapBucket, bucket_count); return(result); } -MD_FUNCTION MD_Map -MD_MapMake(MD_Arena *arena) +FUNCTION Map +MapMake(Arena *arena) { - MD_Map result = MD_MapMakeBucketCount(arena, 4093); + Map result = MapMakeBucketCount(arena, 4093); return(result); } -MD_FUNCTION MD_MapKey -MD_MapKeyStr(MD_String8 string) +FUNCTION MapKey +MapKeyStr(String8 string) { - MD_MapKey result = {0}; + MapKey result = {0}; if (string.size != 0) { - result.hash = MD_HashStr(string); + result.hash = HashStr(string); result.size = string.size; if (string.size > 0) { @@ -1945,40 +1945,40 @@ MD_MapKeyStr(MD_String8 string) return(result); } -MD_FUNCTION MD_MapKey -MD_MapKeyPtr(void *ptr) +FUNCTION MapKey +MapKeyPtr(void *ptr) { - MD_MapKey result = {0}; + MapKey result = {0}; if (ptr != 0) { - result.hash = MD_HashPtr(ptr); + result.hash = HashPtr(ptr); result.size = 0; result.ptr = ptr; } return(result); } -MD_FUNCTION MD_MapSlot* -MD_MapLookup(MD_Map *map, MD_MapKey key) +FUNCTION MapSlot* +MapLookup(Map *map, MapKey key) { - MD_MapSlot *result = 0; + MapSlot *result = 0; if (map->bucket_count > 0) { - MD_u64 index = key.hash%map->bucket_count; - result = MD_MapScan(map->buckets[index].first, key); + u64 index = key.hash%map->bucket_count; + result = MapScan(map->buckets[index].first, key); } return(result); } -MD_FUNCTION MD_MapSlot* -MD_MapScan(MD_MapSlot *first_slot, MD_MapKey key) +FUNCTION MapSlot* +MapScan(MapSlot *first_slot, MapKey key) { - MD_MapSlot *result = 0; + MapSlot *result = 0; if (first_slot != 0) { - MD_b32 ptr_kind = (key.size == 0); - MD_String8 key_string = MD_S8((MD_u8*)key.ptr, key.size); - for (MD_MapSlot *slot = first_slot; + b32 ptr_kind = (key.size == 0); + String8 key_string = S8((u8*)key.ptr, key.size); + for (MapSlot *slot = first_slot; slot != 0; slot = slot->next) { @@ -1994,8 +1994,8 @@ MD_MapScan(MD_MapSlot *first_slot, MD_MapKey key) } else { - MD_String8 slot_string = MD_S8((MD_u8*)slot->key.ptr, slot->key.size); - if (MD_S8Match(slot_string, key_string, 0)) + String8 slot_string = S8((u8*)slot->key.ptr, slot->key.size); + if (S8Match(slot_string, key_string, 0)) { result = slot; break; @@ -2007,16 +2007,16 @@ MD_MapScan(MD_MapSlot *first_slot, MD_MapKey key) return(result); } -MD_FUNCTION MD_MapSlot* -MD_MapInsert(MD_Arena *arena, MD_Map *map, MD_MapKey key, void *val) +FUNCTION MapSlot* +MapInsert(Arena *arena, Map *map, MapKey key, void *val) { - MD_MapSlot *result = 0; + MapSlot *result = 0; if (map->bucket_count > 0) { - MD_u64 index = key.hash%map->bucket_count; - MD_MapSlot *slot = MD_PushArrayZero(arena, MD_MapSlot, 1); - MD_MapBucket *bucket = &map->buckets[index]; - MD_QueuePush(bucket->first, bucket->last, slot); + u64 index = key.hash%map->bucket_count; + MapSlot *slot = PushArrayZero(arena, MapSlot, 1); + MapBucket *bucket = &map->buckets[index]; + QueuePush(bucket->first, bucket->last, slot); slot->key = key; slot->val = val; result = slot; @@ -2024,53 +2024,53 @@ MD_MapInsert(MD_Arena *arena, MD_Map *map, MD_MapKey key, void *val) return(result); } -MD_FUNCTION MD_MapSlot* -MD_MapOverwrite(MD_Arena *arena, MD_Map *map, MD_MapKey key, void *val) +FUNCTION MapSlot* +MapOverwrite(Arena *arena, Map *map, MapKey key, void *val) { - MD_MapSlot *result = MD_MapLookup(map, key); + MapSlot *result = MapLookup(map, key); if (result != 0) { result->val = val; } else { - result = MD_MapInsert(arena, map, key, val); + result = MapInsert(arena, map, key, val); } return(result); } //~ Parsing -MD_FUNCTION MD_Token -MD_TokenFromString(MD_String8 string) +FUNCTION Token +TokenFromString(String8 string) { - MD_Token token = MD_ZERO_STRUCT; + Token token = ZERO_STRUCT; - MD_u8 *one_past_last = string.str + string.size; - MD_u8 *first = string.str; + u8 *one_past_last = string.str + string.size; + u8 *first = string.str; if(first < one_past_last) { - MD_u8 *at = first; - MD_u32 skip_n = 0; - MD_u32 chop_n = 0; + u8 *at = first; + u32 skip_n = 0; + u32 chop_n = 0; -#define MD_TokenizerScan(cond) for (; at < one_past_last && (cond); at += 1) +#define TokenizerScan(cond) for (; at < one_past_last && (cond); at += 1) switch (*at) { // NOTE(allen): Whitespace parsing case '\n': { - token.kind = MD_TokenKind_Newline; + token.kind = TokenKind_Newline; at += 1; }break; case ' ': case '\r': case '\t': case '\f': case '\v': { - token.kind = MD_TokenKind_Whitespace; + token.kind = TokenKind_Whitespace; at += 1; - MD_TokenizerScan(*at == ' ' || *at == '\r' || *at == '\t' || *at == '\f' || *at == '\v'); + TokenizerScan(*at == ' ' || *at == '\r' || *at == '\t' || *at == '\f' || *at == '\v'); }break; // NOTE(allen): Comment parsing @@ -2083,15 +2083,15 @@ MD_TokenFromString(MD_String8 string) // trim off the first '//' skip_n = 2; at += 2; - token.kind = MD_TokenKind_Comment; - MD_TokenizerScan(*at != '\n' && *at != '\r'); + token.kind = TokenKind_Comment; + TokenizerScan(*at != '\n' && *at != '\r'); } else if (at[1] == '*') { // trim off the first '/*' skip_n = 2; at += 2; - token.kind = MD_TokenKind_BrokenComment; + token.kind = TokenKind_BrokenComment; int counter = 1; for (;at < one_past_last && counter > 0; at += 1) { @@ -2111,7 +2111,7 @@ MD_TokenFromString(MD_String8 string) } if(counter == 0) { - token.kind = MD_TokenKind_Comment; + token.kind = TokenKind_Comment; chop_n = 2; } } @@ -2124,18 +2124,18 @@ MD_TokenFromString(MD_String8 string) case '\'': case '`': { - token.kind = MD_TokenKind_BrokenStringLiteral; + token.kind = TokenKind_BrokenStringLiteral; // determine delimiter setup - MD_u8 d = *at; - MD_b32 is_triplet = (at + 2 < one_past_last && at[1] == d && at[2] == d); + u8 d = *at; + b32 is_triplet = (at + 2 < one_past_last && at[1] == d && at[2] == d); // lex triple-delimiter string if (is_triplet) { skip_n = 3; at += 3; - MD_u32 consecutive_d = 0; + u32 consecutive_d = 0; for (;;) { // fail condition @@ -2152,7 +2152,7 @@ MD_TokenFromString(MD_String8 string) if (consecutive_d == 3) { chop_n = 3; - token.kind = MD_TokenKind_StringLiteral; + token.kind = TokenKind_StringLiteral; break; } } @@ -2188,7 +2188,7 @@ MD_TokenFromString(MD_String8 string) { at += 1; chop_n = 1; - token.kind = MD_TokenKind_StringLiteral; + token.kind = TokenKind_StringLiteral; break; } @@ -2215,17 +2215,17 @@ MD_TokenFromString(MD_String8 string) } //- rjf: set relevant node flags on token - token.node_flags |= MD_NodeFlag_StringLiteral; + token.node_flags |= NodeFlag_StringLiteral; switch(d) { - case '\'': token.node_flags |= MD_NodeFlag_StringSingleQuote; break; - case '"': token.node_flags |= MD_NodeFlag_StringDoubleQuote; break; - case '`': token.node_flags |= MD_NodeFlag_StringTick; break; + case '\'': token.node_flags |= NodeFlag_StringSingleQuote; break; + case '"': token.node_flags |= NodeFlag_StringDoubleQuote; break; + case '`': token.node_flags |= NodeFlag_StringTick; break; default: break; } if(is_triplet) { - token.node_flags |= MD_NodeFlag_StringTriplet; + token.node_flags |= NodeFlag_StringTriplet; } }break; @@ -2233,23 +2233,23 @@ MD_TokenFromString(MD_String8 string) // NOTE(allen): Identifiers, Numbers, Symbols default: { - if (MD_CharIsAlpha(*at) || *at == '_') + if (CharIsAlpha(*at) || *at == '_') { - token.node_flags |= MD_NodeFlag_Identifier; - token.kind = MD_TokenKind_Identifier; + token.node_flags |= NodeFlag_Identifier; + token.kind = TokenKind_Identifier; at += 1; - MD_TokenizerScan(MD_CharIsAlpha(*at) || MD_CharIsDigit(*at) || *at == '_'); + TokenizerScan(CharIsAlpha(*at) || CharIsDigit(*at) || *at == '_'); } - else if (MD_CharIsDigit(*at)) + else if (CharIsDigit(*at)) { - token.node_flags |= MD_NodeFlag_Numeric; - token.kind = MD_TokenKind_Numeric; + token.node_flags |= NodeFlag_Numeric; + token.kind = TokenKind_Numeric; at += 1; for (; at < one_past_last;) { - MD_b32 good = 0; + b32 good = 0; if (*at == 'e' || *at == 'E') { good = 1; @@ -2259,7 +2259,7 @@ MD_TokenFromString(MD_String8 string) at += 1; } } - else if (MD_CharIsAlpha(*at) || MD_CharIsDigit(*at) || *at == '.' || *at == '_') + else if (CharIsAlpha(*at) || CharIsDigit(*at) || *at == '.' || *at == '_') { good = 1; at += 1; @@ -2271,48 +2271,48 @@ MD_TokenFromString(MD_String8 string) } } - else if (MD_CharIsUnreservedSymbol(*at)) + else if (CharIsUnreservedSymbol(*at)) { symbol_lex: - token.node_flags |= MD_NodeFlag_Symbol; - token.kind = MD_TokenKind_Symbol; + token.node_flags |= NodeFlag_Symbol; + token.kind = TokenKind_Symbol; at += 1; - MD_TokenizerScan(MD_CharIsUnreservedSymbol(*at)); + TokenizerScan(CharIsUnreservedSymbol(*at)); } - else if (MD_CharIsReservedSymbol(*at)) + else if (CharIsReservedSymbol(*at)) { - token.kind = MD_TokenKind_Reserved; + token.kind = TokenKind_Reserved; at += 1; } else { - token.kind = MD_TokenKind_BadCharacter; + token.kind = TokenKind_BadCharacter; at += 1; } }break; } - token.raw_string = MD_S8Range(first, at); - token.string = MD_S8Substring(token.raw_string, skip_n, token.raw_string.size - chop_n); + token.raw_string = S8Range(first, at); + token.string = S8Substring(token.raw_string, skip_n, token.raw_string.size - chop_n); -#undef MD_TokenizerScan +#undef TokenizerScan } return token; } -MD_FUNCTION MD_u64 -MD_LexAdvanceFromSkips(MD_String8 string, MD_TokenKind skip_kinds) +FUNCTION u64 +LexAdvanceFromSkips(String8 string, TokenKind skip_kinds) { - MD_u64 result = string.size; - MD_u64 p = 0; + u64 result = string.size; + u64 p = 0; for (;;) { - MD_Token token = MD_TokenFromString(MD_S8Skip(string, p)); + Token token = TokenFromString(S8Skip(string, p)); if ((skip_kinds & token.kind) == 0) { result = p; @@ -2323,45 +2323,45 @@ MD_LexAdvanceFromSkips(MD_String8 string, MD_TokenKind skip_kinds) return(result); } -MD_FUNCTION MD_ParseResult -MD_ParseResultZero(void) +FUNCTION ParseResult +ParseResultZero(void) { - MD_ParseResult result = MD_ZERO_STRUCT; - result.node = MD_NilNode(); + ParseResult result = ZERO_STRUCT; + result.node = NilNode(); return result; } -MD_FUNCTION MD_ParseResult -MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *parent, - MD_ParseSetRule rule) +FUNCTION ParseResult +ParseNodeSet(Arena *arena, String8 string, u64 offset, Node *parent, + ParseSetRule rule) { - MD_ParseResult result = MD_ParseResultZero(); - MD_u64 off = offset; + ParseResult result = ParseResultZero(); + u64 off = offset; //- rjf: fill data from set opener - MD_Token initial_token = MD_TokenFromString(MD_S8Skip(string, offset)); - MD_u8 set_opener = 0; - MD_NodeFlags set_opener_flags = 0; - MD_b32 close_with_brace = 0; - MD_b32 close_with_paren = 0; - MD_b32 close_with_separator = 0; - MD_b32 parse_all = 0; + Token initial_token = TokenFromString(S8Skip(string, offset)); + u8 set_opener = 0; + NodeFlags set_opener_flags = 0; + b32 close_with_brace = 0; + b32 close_with_paren = 0; + b32 close_with_separator = 0; + b32 parse_all = 0; switch(rule) { default: break; - case MD_ParseSetRule_EndOnDelimiter: + case ParseSetRule_EndOnDelimiter: { - MD_u64 opener_check_off = off; - opener_check_off += MD_LexAdvanceFromSkips(MD_S8Skip(string, opener_check_off), MD_TokenGroup_Irregular); - initial_token = MD_TokenFromString(MD_S8Skip(string, opener_check_off)); - if(initial_token.kind == MD_TokenKind_Reserved) + u64 opener_check_off = off; + opener_check_off += LexAdvanceFromSkips(S8Skip(string, opener_check_off), TokenGroup_Irregular); + initial_token = TokenFromString(S8Skip(string, opener_check_off)); + if(initial_token.kind == TokenKind_Reserved) { - MD_u8 c = initial_token.raw_string.str[0]; + u8 c = initial_token.raw_string.str[0]; if(c == '{') { set_opener = '{'; - set_opener_flags |= MD_NodeFlag_HasBraceLeft; + set_opener_flags |= NodeFlag_HasBraceLeft; opener_check_off += initial_token.raw_string.size; off = opener_check_off; close_with_brace = 1; @@ -2369,7 +2369,7 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare else if(c == '(') { set_opener = '('; - set_opener_flags |= MD_NodeFlag_HasParenLeft; + set_opener_flags |= NodeFlag_HasParenLeft; opener_check_off += initial_token.raw_string.size; off = opener_check_off; close_with_paren = 1; @@ -2377,7 +2377,7 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare else if(c == '[') { set_opener = '['; - set_opener_flags |= MD_NodeFlag_HasBracketLeft; + set_opener_flags |= NodeFlag_HasBracketLeft; opener_check_off += initial_token.raw_string.size; off = opener_check_off; close_with_paren = 1; @@ -2393,7 +2393,7 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare } }break; - case MD_ParseSetRule_Global: + case ParseSetRule_Global: { parse_all = 1; }break; @@ -2403,23 +2403,23 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare parent->flags |= set_opener_flags; //- rjf: parse children - MD_b32 got_closer = 0; - MD_u64 parsed_child_count = 0; + b32 got_closer = 0; + u64 parsed_child_count = 0; if(set_opener != 0 || close_with_separator || parse_all) { - MD_NodeFlags next_child_flags = 0; + NodeFlags next_child_flags = 0; for(;off < string.size;) { //- rjf: check for separator closers if(close_with_separator) { - MD_u64 closer_check_off = off; + u64 closer_check_off = off; //- rjf: check newlines { - MD_Token potential_closer = MD_TokenFromString(MD_S8Skip(string, closer_check_off)); - if(potential_closer.kind == MD_TokenKind_Newline) + Token potential_closer = TokenFromString(S8Skip(string, closer_check_off)); + if(potential_closer.kind == TokenKind_Newline) { closer_check_off += potential_closer.raw_string.size; off = closer_check_off; @@ -2433,8 +2433,8 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare } // NOTE(rjf): terminate after double newline if we have 0 children - MD_Token next_closer = MD_TokenFromString(MD_S8Skip(string, closer_check_off)); - if(next_closer.kind == MD_TokenKind_Newline) + Token next_closer = TokenFromString(S8Skip(string, closer_check_off)); + if(next_closer.kind == TokenKind_Newline) { closer_check_off += next_closer.raw_string.size; off = closer_check_off; @@ -2446,11 +2446,11 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare //- rjf: check separators and possible braces from higher parents { - closer_check_off += MD_LexAdvanceFromSkips(MD_S8Skip(string, off), MD_TokenGroup_Irregular); - MD_Token potential_closer = MD_TokenFromString(MD_S8Skip(string, closer_check_off)); - if(potential_closer.kind == MD_TokenKind_Reserved) + closer_check_off += LexAdvanceFromSkips(S8Skip(string, off), TokenGroup_Irregular); + Token potential_closer = TokenFromString(S8Skip(string, closer_check_off)); + if(potential_closer.kind == TokenKind_Reserved) { - MD_u8 c = potential_closer.raw_string.str[0]; + u8 c = potential_closer.raw_string.str[0]; if(c == ',' || c == ';') { off = closer_check_off; @@ -2469,17 +2469,17 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare //- rjf: check for non-separator closers if(!close_with_separator && !parse_all) { - MD_u64 closer_check_off = off; - closer_check_off += MD_LexAdvanceFromSkips(MD_S8Skip(string, off), MD_TokenGroup_Irregular); - MD_Token potential_closer = MD_TokenFromString(MD_S8Skip(string, closer_check_off)); - if(potential_closer.kind == MD_TokenKind_Reserved) + u64 closer_check_off = off; + closer_check_off += LexAdvanceFromSkips(S8Skip(string, off), TokenGroup_Irregular); + Token potential_closer = TokenFromString(S8Skip(string, closer_check_off)); + if(potential_closer.kind == TokenKind_Reserved) { - MD_u8 c = potential_closer.raw_string.str[0]; + u8 c = potential_closer.raw_string.str[0]; if(close_with_brace && c == '}') { closer_check_off += potential_closer.raw_string.size; off = closer_check_off; - parent->flags |= MD_NodeFlag_HasBraceRight; + parent->flags |= NodeFlag_HasBraceRight; got_closer = 1; break; } @@ -2487,7 +2487,7 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare { closer_check_off += potential_closer.raw_string.size; off = closer_check_off; - parent->flags |= MD_NodeFlag_HasBracketRight; + parent->flags |= NodeFlag_HasBracketRight; got_closer = 1; break; } @@ -2495,7 +2495,7 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare { closer_check_off += potential_closer.raw_string.size; off = closer_check_off; - parent->flags |= MD_NodeFlag_HasParenRight; + parent->flags |= NodeFlag_HasParenRight; got_closer = 1; break; } @@ -2503,50 +2503,50 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare } //- rjf: parse next child - MD_ParseResult child_parse = MD_ParseOneNode(arena, string, off); - MD_MessageListConcat(&result.errors, &child_parse.errors); + ParseResult child_parse = ParseOneNode(arena, string, off); + MessageListConcat(&result.errors, &child_parse.errors); off += child_parse.string_advance; //- rjf: hook child into parent - if(!MD_NodeIsNil(child_parse.node)) + if(!NodeIsNil(child_parse.node)) { // NOTE(rjf): @error No unnamed set children of implicitly-delimited sets if(close_with_separator && child_parse.node->string.size == 0 && - child_parse.node->flags & (MD_NodeFlag_HasParenLeft | - MD_NodeFlag_HasParenRight | - MD_NodeFlag_HasBracketLeft | - MD_NodeFlag_HasBracketRight | - MD_NodeFlag_HasBraceLeft | - MD_NodeFlag_HasBraceRight )) + child_parse.node->flags & (NodeFlag_HasParenLeft | + NodeFlag_HasParenRight | + NodeFlag_HasBracketLeft | + NodeFlag_HasBracketRight | + NodeFlag_HasBraceLeft | + NodeFlag_HasBraceRight )) { - MD_String8 error_str = MD_S8Lit("Unnamed set children of implicitly-delimited sets are not legal."); - MD_Message *error = MD_MakeNodeError(arena, child_parse.node, MD_MessageKind_Warning, + String8 error_str = S8Lit("Unnamed set children of implicitly-delimited sets are not legal."); + Message *error = MakeNodeError(arena, child_parse.node, MessageKind_Warning, error_str); - MD_MessageListPush(&result.errors, error); + MessageListPush(&result.errors, error); } - MD_PushChild(parent, child_parse.node); + PushChild(parent, child_parse.node); parsed_child_count += 1; } //- rjf: check trailing separator - MD_NodeFlags trailing_separator_flags = 0; + NodeFlags trailing_separator_flags = 0; if(!close_with_separator) { - off += MD_LexAdvanceFromSkips(MD_S8Skip(string, off), MD_TokenGroup_Irregular); - MD_Token trailing_separator = MD_TokenFromString(MD_S8Skip(string, off)); - if (trailing_separator.kind == MD_TokenKind_Reserved) + off += LexAdvanceFromSkips(S8Skip(string, off), TokenGroup_Irregular); + Token trailing_separator = TokenFromString(S8Skip(string, off)); + if (trailing_separator.kind == TokenKind_Reserved) { - MD_u8 c = trailing_separator.string.str[0]; + u8 c = trailing_separator.string.str[0]; if(c == ',') { - trailing_separator_flags |= MD_NodeFlag_IsBeforeComma; + trailing_separator_flags |= NodeFlag_IsBeforeComma; off += trailing_separator.raw_string.size; } else if(c == ';') { - trailing_separator_flags |= MD_NodeFlag_IsBeforeSemicolon; + trailing_separator_flags |= NodeFlag_IsBeforeSemicolon; off += trailing_separator.raw_string.size; } } @@ -2556,7 +2556,7 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare child_parse.node->flags |= next_child_flags | trailing_separator_flags; //- rjf: setup next_child_flags - next_child_flags = MD_NodeFlag_AfterFromBefore(trailing_separator_flags); + next_child_flags = NodeFlag_AfterFromBefore(trailing_separator_flags); } } end_parse:; @@ -2565,19 +2565,19 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare if(set_opener != 0 && got_closer == 0) { // NOTE(rjf): @error We didn't get a closer for the set - MD_String8 error_str = MD_S8Fmt(arena, "Unbalanced \"%c\"", set_opener); - MD_Message *error = MD_MakeTokenError(arena, string, initial_token, - MD_MessageKind_FatalError, error_str); - MD_MessageListPush(&result.errors, error); + String8 error_str = S8Fmt(arena, "Unbalanced \"%c\"", set_opener); + Message *error = MakeTokenError(arena, string, initial_token, + MessageKind_FatalError, error_str); + MessageListPush(&result.errors, error); } //- rjf: push empty implicit set error, if(close_with_separator && parsed_child_count == 0) { // NOTE(rjf): @error No empty implicitly-delimited sets - MD_Message *error = MD_MakeTokenError(arena, string, initial_token, MD_MessageKind_Error, - MD_S8Lit("Empty implicitly-delimited node list")); - MD_MessageListPush(&result.errors, error); + Message *error = MakeTokenError(arena, string, initial_token, MessageKind_Error, + S8Lit("Empty implicitly-delimited node list")); + MessageListPush(&result.errors, error); } //- rjf: fill result info @@ -2587,39 +2587,39 @@ MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *pare return result; } -MD_FUNCTION MD_ParseResult -MD_ParseOneNode(MD_Arena *arena, MD_String8 string, MD_u64 offset) +FUNCTION ParseResult +ParseOneNode(Arena *arena, String8 string, u64 offset) { - MD_ParseResult result = MD_ParseResultZero(); - MD_u64 off = offset; + ParseResult result = ParseResultZero(); + u64 off = offset; //- rjf: parse pre-comment - MD_String8 prev_comment = MD_ZERO_STRUCT; + String8 prev_comment = ZERO_STRUCT; { - MD_Token comment_token = MD_ZERO_STRUCT; + Token comment_token = ZERO_STRUCT; for(;off < string.size;) { - MD_Token token = MD_TokenFromString(MD_S8Skip(string, off)); - if(token.kind == MD_TokenKind_Comment) + Token token = TokenFromString(S8Skip(string, off)); + if(token.kind == TokenKind_Comment) { off += token.raw_string.size; comment_token = token; } - else if(token.kind == MD_TokenKind_Newline) + else if(token.kind == TokenKind_Newline) { off += token.raw_string.size; - MD_Token next_token = MD_TokenFromString(MD_S8Skip(string, off)); - if(next_token.kind == MD_TokenKind_Comment) + Token next_token = TokenFromString(S8Skip(string, off)); + if(next_token.kind == TokenKind_Comment) { // NOTE(mal): If more than one comment, use the last comment comment_token = next_token; } - else if(next_token.kind == MD_TokenKind_Newline) + else if(next_token.kind == TokenKind_Newline) { - MD_MemoryZeroStruct(&comment_token); + MemoryZeroStruct(&comment_token); } } - else if((token.kind & MD_TokenGroup_Whitespace) != 0) + else if((token.kind & TokenGroup_Whitespace) != 0) { off += token.raw_string.size; } @@ -2632,15 +2632,15 @@ MD_ParseOneNode(MD_Arena *arena, MD_String8 string, MD_u64 offset) } //- rjf: parse tag list - MD_Node *first_tag = MD_NilNode(); - MD_Node *last_tag = MD_NilNode(); + Node *first_tag = NilNode(); + Node *last_tag = NilNode(); { for(;off < string.size;) { //- rjf: parse @ symbol, signifying start of tag - off += MD_LexAdvanceFromSkips(MD_S8Skip(string, off), MD_TokenGroup_Irregular); - MD_Token next_token = MD_TokenFromString(MD_S8Skip(string, off)); - if(next_token.kind != MD_TokenKind_Reserved || + off += LexAdvanceFromSkips(S8Skip(string, off), TokenGroup_Irregular); + Token next_token = TokenFromString(S8Skip(string, off)); + if(next_token.kind != TokenKind_Reserved || next_token.string.str[0] != '@') { break; @@ -2648,74 +2648,74 @@ MD_ParseOneNode(MD_Arena *arena, MD_String8 string, MD_u64 offset) off += next_token.raw_string.size; //- rjf: parse string of tag node - MD_Token name = MD_TokenFromString(MD_S8Skip(string, off)); - MD_u64 name_off = off; - if((name.kind & MD_TokenGroup_Label) == 0) + Token name = TokenFromString(S8Skip(string, off)); + u64 name_off = off; + if((name.kind & TokenGroup_Label) == 0) { // NOTE(rjf): @error Improper token for tag string - MD_String8 error_str = MD_S8Fmt(arena, "\"%.*s\" is not a proper tag label", - MD_S8VArg(name.raw_string)); - MD_Message *error = MD_MakeTokenError(arena, string, name, MD_MessageKind_Error, error_str); - MD_MessageListPush(&result.errors, error); + String8 error_str = S8Fmt(arena, "\"%.*s\" is not a proper tag label", + S8VArg(name.raw_string)); + Message *error = MakeTokenError(arena, string, name, MessageKind_Error, error_str); + MessageListPush(&result.errors, error); break; } off += name.raw_string.size; //- rjf: build tag - MD_Node *tag = MD_MakeNode(arena, MD_NodeKind_Tag, name.string, name.raw_string, name_off); + Node *tag = MakeNode(arena, NodeKind_Tag, name.string, name.raw_string, name_off); //- rjf: parse tag arguments - MD_Token open_paren = MD_TokenFromString(MD_S8Skip(string, off)); - MD_ParseResult args_parse = MD_ParseResultZero(); - if(open_paren.kind == MD_TokenKind_Reserved && + Token open_paren = TokenFromString(S8Skip(string, off)); + ParseResult args_parse = ParseResultZero(); + if(open_paren.kind == TokenKind_Reserved && open_paren.string.str[0] == '(') { - args_parse = MD_ParseNodeSet(arena, string, off, tag, MD_ParseSetRule_EndOnDelimiter); - MD_MessageListConcat(&result.errors, &args_parse.errors); + args_parse = ParseNodeSet(arena, string, off, tag, ParseSetRule_EndOnDelimiter); + MessageListConcat(&result.errors, &args_parse.errors); } off += args_parse.string_advance; //- rjf: push tag to result - MD_NodeDblPushBack(first_tag, last_tag, tag); + NodeDblPushBack(first_tag, last_tag, tag); } } //- rjf: parse node - MD_Node *parsed_node = MD_NilNode(); - MD_ParseResult children_parse = MD_ParseResultZero(); + Node *parsed_node = NilNode(); + ParseResult children_parse = ParseResultZero(); retry:; { //- rjf: try to parse an unnamed set - off += MD_LexAdvanceFromSkips(MD_S8Skip(string, off), MD_TokenGroup_Irregular); - MD_Token unnamed_set_opener = MD_TokenFromString(MD_S8Skip(string, off)); - if(unnamed_set_opener.kind == MD_TokenKind_Reserved) + off += LexAdvanceFromSkips(S8Skip(string, off), TokenGroup_Irregular); + Token unnamed_set_opener = TokenFromString(S8Skip(string, off)); + if(unnamed_set_opener.kind == TokenKind_Reserved) { - MD_u8 c = unnamed_set_opener.string.str[0]; + u8 c = unnamed_set_opener.string.str[0]; if (c == '(' || c == '{' || c == '[') { - parsed_node = MD_MakeNode(arena, MD_NodeKind_Main, MD_S8Lit(""), MD_S8Lit(""), + parsed_node = MakeNode(arena, NodeKind_Main, S8Lit(""), S8Lit(""), unnamed_set_opener.raw_string.str - string.str); - children_parse = MD_ParseNodeSet(arena, string, off, parsed_node, - MD_ParseSetRule_EndOnDelimiter); + children_parse = ParseNodeSet(arena, string, off, parsed_node, + ParseSetRule_EndOnDelimiter); off += children_parse.string_advance; - MD_MessageListConcat(&result.errors, &children_parse.errors); + MessageListConcat(&result.errors, &children_parse.errors); } else if (c == ')' || c == '}' || c == ']') { // NOTE(rjf): @error Unexpected set closing symbol - MD_String8 error_str = MD_S8Fmt(arena, "Unbalanced \"%c\"", c); - MD_Message *error = MD_MakeTokenError(arena, string, unnamed_set_opener, - MD_MessageKind_FatalError, error_str); - MD_MessageListPush(&result.errors, error); + String8 error_str = S8Fmt(arena, "Unbalanced \"%c\"", c); + Message *error = MakeTokenError(arena, string, unnamed_set_opener, + MessageKind_FatalError, error_str); + MessageListPush(&result.errors, error); off += unnamed_set_opener.raw_string.size; } else { // NOTE(rjf): @error Unexpected reserved symbol - MD_String8 error_str = MD_S8Fmt(arena, "Unexpected reserved symbol \"%c\"", c); - MD_Message *error = MD_MakeTokenError(arena, string, unnamed_set_opener, - MD_MessageKind_Error, error_str); - MD_MessageListPush(&result.errors, error); + String8 error_str = S8Fmt(arena, "Unexpected reserved symbol \"%c\"", c); + Message *error = MakeTokenError(arena, string, unnamed_set_opener, + MessageKind_Error, error_str); + MessageListPush(&result.errors, error); off += unnamed_set_opener.raw_string.size; } goto end_parse; @@ -2723,76 +2723,76 @@ MD_ParseOneNode(MD_Arena *arena, MD_String8 string, MD_u64 offset) } //- rjf: try to parse regular node, with/without children - off += MD_LexAdvanceFromSkips(MD_S8Skip(string, off), MD_TokenGroup_Irregular); - MD_Token label_name = MD_TokenFromString(MD_S8Skip(string, off)); - if((label_name.kind & MD_TokenGroup_Label) != 0) + off += LexAdvanceFromSkips(S8Skip(string, off), TokenGroup_Irregular); + Token label_name = TokenFromString(S8Skip(string, off)); + if((label_name.kind & TokenGroup_Label) != 0) { off += label_name.raw_string.size; - parsed_node = MD_MakeNode(arena, MD_NodeKind_Main, label_name.string, label_name.raw_string, + parsed_node = MakeNode(arena, NodeKind_Main, label_name.string, label_name.raw_string, label_name.raw_string.str - string.str); parsed_node->flags |= label_name.node_flags; //- rjf: try to parse children for this node - MD_u64 colon_check_off = off; - colon_check_off += MD_LexAdvanceFromSkips(MD_S8Skip(string, colon_check_off), MD_TokenGroup_Irregular); - MD_Token colon = MD_TokenFromString(MD_S8Skip(string, colon_check_off)); - if(colon.kind == MD_TokenKind_Reserved && + u64 colon_check_off = off; + colon_check_off += LexAdvanceFromSkips(S8Skip(string, colon_check_off), TokenGroup_Irregular); + Token colon = TokenFromString(S8Skip(string, colon_check_off)); + if(colon.kind == TokenKind_Reserved && colon.string.str[0] == ':') { colon_check_off += colon.raw_string.size; off = colon_check_off; - children_parse = MD_ParseNodeSet(arena, string, off, parsed_node, - MD_ParseSetRule_EndOnDelimiter); + children_parse = ParseNodeSet(arena, string, off, parsed_node, + ParseSetRule_EndOnDelimiter); off += children_parse.string_advance; - MD_MessageListConcat(&result.errors, &children_parse.errors); + MessageListConcat(&result.errors, &children_parse.errors); } goto end_parse; } //- rjf: collect bad token - MD_Token bad_token = MD_TokenFromString(MD_S8Skip(string, off)); - if(bad_token.kind & MD_TokenGroup_Error) + Token bad_token = TokenFromString(S8Skip(string, off)); + if(bad_token.kind & TokenGroup_Error) { off += bad_token.raw_string.size; switch (bad_token.kind) { - case MD_TokenKind_BadCharacter: + case TokenKind_BadCharacter: { - MD_String8List bytes = {0}; + String8List bytes = {0}; for(int i_byte = 0; i_byte < bad_token.raw_string.size; ++i_byte) { - MD_u8 b = bad_token.raw_string.str[i_byte]; - MD_S8ListPush(arena, &bytes, MD_CStyleHexStringFromU64(arena, b, 1)); + u8 b = bad_token.raw_string.str[i_byte]; + S8ListPush(arena, &bytes, CStyleHexStringFromU64(arena, b, 1)); } - MD_StringJoin join = MD_ZERO_STRUCT; - join.mid = MD_S8Lit(" "); - MD_String8 byte_string = MD_S8ListJoin(arena, bytes, &join); + StringJoin join = ZERO_STRUCT; + join.mid = S8Lit(" "); + String8 byte_string = S8ListJoin(arena, bytes, &join); // NOTE(rjf): @error Bad character - MD_String8 error_str = MD_S8Fmt(arena, "Non-ASCII character \"%.*s\"", - MD_S8VArg(byte_string)); - MD_Message *error = MD_MakeTokenError(arena, string, bad_token, MD_MessageKind_Error, + String8 error_str = S8Fmt(arena, "Non-ASCII character \"%.*s\"", + S8VArg(byte_string)); + Message *error = MakeTokenError(arena, string, bad_token, MessageKind_Error, error_str); - MD_MessageListPush(&result.errors, error); + MessageListPush(&result.errors, error); }break; - case MD_TokenKind_BrokenComment: + case TokenKind_BrokenComment: { // NOTE(rjf): @error Broken Comments - MD_Message *error = MD_MakeTokenError(arena, string, bad_token, MD_MessageKind_Error, - MD_S8Lit("Unterminated comment")); - MD_MessageListPush(&result.errors, error); + Message *error = MakeTokenError(arena, string, bad_token, MessageKind_Error, + S8Lit("Unterminated comment")); + MessageListPush(&result.errors, error); }break; - case MD_TokenKind_BrokenStringLiteral: + case TokenKind_BrokenStringLiteral: { // NOTE(rjf): @error Broken String Literals - MD_Message *error = MD_MakeTokenError(arena, string, bad_token, MD_MessageKind_Error, - MD_S8Lit("Unterminated string literal")); - MD_MessageListPush(&result.errors, error); + Message *error = MakeTokenError(arena, string, bad_token, MessageKind_Error, + S8Lit("Unterminated string literal")); + MessageListPush(&result.errors, error); }break; } goto retry; @@ -2802,24 +2802,24 @@ MD_ParseOneNode(MD_Arena *arena, MD_String8 string, MD_u64 offset) end_parse:; //- rjf: parse comments after nodes. - MD_String8 next_comment = MD_ZERO_STRUCT; + String8 next_comment = ZERO_STRUCT; { - MD_Token comment_token = MD_ZERO_STRUCT; + Token comment_token = ZERO_STRUCT; for(;;) { - MD_Token token = MD_TokenFromString(MD_S8Skip(string, off)); - if(token.kind == MD_TokenKind_Comment) + Token token = TokenFromString(S8Skip(string, off)); + if(token.kind == TokenKind_Comment) { comment_token = token; off += token.raw_string.size; break; } - else if(token.kind == MD_TokenKind_Newline) + else if(token.kind == TokenKind_Newline) { break; } - else if((token.kind & MD_TokenGroup_Whitespace) != 0) + else if((token.kind & TokenGroup_Whitespace) != 0) { off += token.raw_string.size; } @@ -2835,11 +2835,11 @@ MD_ParseOneNode(MD_Arena *arena, MD_String8 string, MD_u64 offset) parsed_node->prev_comment = prev_comment; parsed_node->next_comment = next_comment; result.node = parsed_node; - if(!MD_NodeIsNil(result.node)) + if(!NodeIsNil(result.node)) { result.node->first_tag = first_tag; result.node->last_tag = last_tag; - for(MD_Node *tag = first_tag; !MD_NodeIsNil(tag); tag = tag->next) + for(Node *tag = first_tag; !NodeIsNil(tag); tag = tag->next) { tag->parent = result.node; } @@ -2849,15 +2849,15 @@ MD_ParseOneNode(MD_Arena *arena, MD_String8 string, MD_u64 offset) return result; } -MD_FUNCTION MD_ParseResult -MD_ParseWholeString(MD_Arena *arena, MD_String8 filename, MD_String8 contents) +FUNCTION ParseResult +ParseWholeString(Arena *arena, String8 filename, String8 contents) { - MD_Node *root = MD_MakeNode(arena, MD_NodeKind_File, filename, contents, 0); - MD_ParseResult result = MD_ParseNodeSet(arena, contents, 0, root, MD_ParseSetRule_Global); + Node *root = MakeNode(arena, NodeKind_File, filename, contents, 0); + ParseResult result = ParseNodeSet(arena, contents, 0, root, ParseSetRule_Global); result.node = root; - for(MD_Message *error = result.errors.first; error != 0; error = error->next) + for(Message *error = result.errors.first; error != 0; error = error->next) { - if(MD_NodeIsNil(error->node->parent)) + if(NodeIsNil(error->node->parent)) { error->node->parent = root; } @@ -2865,55 +2865,55 @@ MD_ParseWholeString(MD_Arena *arena, MD_String8 filename, MD_String8 contents) return result; } -MD_FUNCTION MD_ParseResult -MD_ParseWholeFile(MD_Arena *arena, MD_String8 filename) +FUNCTION ParseResult +ParseWholeFile(Arena *arena, String8 filename) { - MD_String8 file_contents = MD_LoadEntireFile(arena, filename); - MD_ParseResult parse = MD_ParseWholeString(arena, filename, file_contents); + String8 file_contents = LoadEntireFile(arena, filename); + ParseResult parse = ParseWholeString(arena, filename, file_contents); if(file_contents.str == 0) { // NOTE(rjf): @error File failing to load - MD_String8 error_str = MD_S8Fmt(arena, "Could not read file \"%.*s\"", MD_S8VArg(filename)); - MD_Message *error = MD_MakeNodeError(arena, parse.node, MD_MessageKind_FatalError, + String8 error_str = S8Fmt(arena, "Could not read file \"%.*s\"", S8VArg(filename)); + Message *error = MakeNodeError(arena, parse.node, MessageKind_FatalError, error_str); - MD_MessageListPush(&parse.errors, error); + MessageListPush(&parse.errors, error); } return parse; } //~ Messages (Errors/Warnings) -MD_FUNCTION MD_Node* -MD_MakeErrorMarkerNode(MD_Arena *arena, MD_String8 parse_contents, MD_u64 offset) +FUNCTION Node* +MakeErrorMarkerNode(Arena *arena, String8 parse_contents, u64 offset) { - MD_Node *result = MD_MakeNode(arena, MD_NodeKind_ErrorMarker, MD_S8Lit(""), parse_contents, + Node *result = MakeNode(arena, NodeKind_ErrorMarker, S8Lit(""), parse_contents, offset); return(result); } -MD_FUNCTION MD_Message* -MD_MakeNodeError(MD_Arena *arena, MD_Node *node, MD_MessageKind kind, MD_String8 str) +FUNCTION Message* +MakeNodeError(Arena *arena, Node *node, MessageKind kind, String8 str) { - MD_Message *error = MD_PushArrayZero(arena, MD_Message, 1); + Message *error = PushArrayZero(arena, Message, 1); error->node = node; error->kind = kind; error->string = str; return error; } -MD_FUNCTION MD_Message * -MD_MakeTokenError(MD_Arena *arena, MD_String8 parse_contents, MD_Token token, - MD_MessageKind kind, MD_String8 str) +FUNCTION Message * +MakeTokenError(Arena *arena, String8 parse_contents, Token token, + MessageKind kind, String8 str) { - MD_u64 offset = token.raw_string.str - parse_contents.str; - MD_Node *err_node = MD_MakeErrorMarkerNode(arena, parse_contents, offset); - return MD_MakeNodeError(arena, err_node, kind, str); + u64 offset = token.raw_string.str - parse_contents.str; + Node *err_node = MakeErrorMarkerNode(arena, parse_contents, offset); + return MakeNodeError(arena, err_node, kind, str); } -MD_FUNCTION void -MD_MessageListPush(MD_MessageList *list, MD_Message *message) +FUNCTION void +MessageListPush(MessageList *list, Message *message) { - MD_QueuePush(list->first, list->last, message); + QueuePush(list->first, list->last, message); if(message->kind > list->max_message_kind) { list->max_message_kind = message->kind; @@ -2921,8 +2921,8 @@ MD_MessageListPush(MD_MessageList *list, MD_Message *message) list->node_count += 1; } -MD_FUNCTION void -MD_MessageListConcat(MD_MessageList *list, MD_MessageList *to_push) +FUNCTION void +MessageListConcat(MessageList *list, MessageList *to_push) { if(to_push->node_count != 0) { @@ -2940,23 +2940,23 @@ MD_MessageListConcat(MD_MessageList *list, MD_MessageList *to_push) { *list = *to_push; } - MD_MemoryZeroStruct(to_push); + MemoryZeroStruct(to_push); } } //~ Location Conversions -MD_FUNCTION MD_CodeLoc -MD_CodeLocFromFileOffset(MD_String8 filename, MD_u8 *base, MD_u64 offset) +FUNCTION CodeLoc +CodeLocFromFileOffset(String8 filename, u8 *base, u64 offset) { - MD_CodeLoc loc; + CodeLoc loc; loc.filename = filename; loc.line = 1; loc.column = 1; if(base != 0) { - MD_u8 *at = base + offset; - for(MD_u64 i = 0; base+i < at && base[i]; i += 1) + u8 *at = base + offset; + for(u64 i = 0; base+i < at && base[i]; i += 1) { if(base[i] == '\n') { @@ -2972,91 +2972,91 @@ MD_CodeLocFromFileOffset(MD_String8 filename, MD_u8 *base, MD_u64 offset) return loc; } -MD_FUNCTION MD_CodeLoc -MD_CodeLocFromNode(MD_Node *node) +FUNCTION CodeLoc +CodeLocFromNode(Node *node) { - MD_Node *file_root = MD_NilNode(); - for(MD_Node *parent = node->parent; !MD_NodeIsNil(parent); parent = parent->parent) + Node *file_root = NilNode(); + for(Node *parent = node->parent; !NodeIsNil(parent); parent = parent->parent) { - if(parent->kind == MD_NodeKind_File) + if(parent->kind == NodeKind_File) { file_root = parent; break; } } - MD_Node *first_tag = file_root->first_tag; - MD_CodeLoc loc = {0}; - if(MD_NodeIsNil(first_tag)) + Node *first_tag = file_root->first_tag; + CodeLoc loc = {0}; + if(NodeIsNil(first_tag)) { - loc = MD_CodeLocFromFileOffset(file_root->string, file_root->raw_string.str, node->offset); + loc = CodeLocFromFileOffset(file_root->string, file_root->raw_string.str, node->offset); } else { - loc = MD_CodeLocFromFileOffset(file_root->string, first_tag->raw_string.str, node->offset); + loc = CodeLocFromFileOffset(file_root->string, first_tag->raw_string.str, node->offset); } return loc; } //~ Tree/List Building -MD_FUNCTION MD_b32 -MD_NodeIsNil(MD_Node *node) +FUNCTION b32 +NodeIsNil(Node *node) { - return(node == 0 || node == &_md_nil_node || node->kind == MD_NodeKind_Nil); + return(node == 0 || node == &_md_nil_node || node->kind == NodeKind_Nil); } -MD_FUNCTION MD_Node * -MD_NilNode(void) { return &_md_nil_node; } +FUNCTION Node * +NilNode(void) { return &_md_nil_node; } -MD_FUNCTION MD_Node * -MD_MakeNode(MD_Arena *arena, MD_NodeKind kind, MD_String8 string, MD_String8 raw_string, - MD_u64 offset) +FUNCTION Node * +MakeNode(Arena *arena, NodeKind kind, String8 string, String8 raw_string, + u64 offset) { - MD_Node *node = MD_PushArrayZero(arena, MD_Node, 1); + Node *node = PushArrayZero(arena, Node, 1); node->kind = kind; node->string = string; node->raw_string = raw_string; node->next = node->prev = node->parent = node->first_child = node->last_child = - node->first_tag = node->last_tag = node->ref_target = MD_NilNode(); + node->first_tag = node->last_tag = node->ref_target = NilNode(); node->offset = offset; return node; } -MD_FUNCTION void -MD_PushChild(MD_Node *parent, MD_Node *new_child) +FUNCTION void +PushChild(Node *parent, Node *new_child) { - if (!MD_NodeIsNil(new_child)) + if (!NodeIsNil(new_child)) { - MD_NodeDblPushBack(parent->first_child, parent->last_child, new_child); + NodeDblPushBack(parent->first_child, parent->last_child, new_child); new_child->parent = parent; } } -MD_FUNCTION void -MD_PushTag(MD_Node *node, MD_Node *tag) +FUNCTION void +PushTag(Node *node, Node *tag) { - if (!MD_NodeIsNil(tag)) + if (!NodeIsNil(tag)) { - MD_NodeDblPushBack(node->first_tag, node->last_tag, tag); + NodeDblPushBack(node->first_tag, node->last_tag, tag); tag->parent = node; } } -MD_FUNCTION MD_Node* -MD_MakeList(MD_Arena *arena) +FUNCTION Node* +MakeList(Arena *arena) { - MD_String8 empty = {0}; - MD_Node *result = MD_MakeNode(arena, MD_NodeKind_List, empty, empty, 0); + String8 empty = {0}; + Node *result = MakeNode(arena, NodeKind_List, empty, empty, 0); return(result); } -MD_FUNCTION void -MD_ListConcatInPlace(MD_Node *list, MD_Node *to_push) +FUNCTION void +ListConcatInPlace(Node *list, Node *to_push) { - if (!MD_NodeIsNil(to_push->first_child)) + if (!NodeIsNil(to_push->first_child)) { - if (!MD_NodeIsNil(list->first_child)) + if (!NodeIsNil(list->first_child)) { list->last_child->next = to_push->first_child; list->last_child = to_push->last_child; @@ -3066,29 +3066,29 @@ MD_ListConcatInPlace(MD_Node *list, MD_Node *to_push) list->first_child = to_push->first_child; list->last_child = to_push->last_child; } - to_push->first_child = to_push->last_child = MD_NilNode(); + to_push->first_child = to_push->last_child = NilNode(); } } -MD_FUNCTION MD_Node* -MD_PushNewReference(MD_Arena *arena, MD_Node *list, MD_Node *target) +FUNCTION Node* +PushNewReference(Arena *arena, Node *list, Node *target) { - MD_Node *n = MD_MakeNode(arena, MD_NodeKind_Reference, target->string, target->raw_string, + Node *n = MakeNode(arena, NodeKind_Reference, target->string, target->raw_string, target->offset); n->ref_target = target; - MD_PushChild(list, n); + PushChild(list, n); return(n); } //~ Introspection Helpers -MD_FUNCTION MD_Node * -MD_FirstNodeWithString(MD_Node *first, MD_String8 string, MD_MatchFlags flags) +FUNCTION Node * +FirstNodeWithString(Node *first, String8 string, MatchFlags flags) { - MD_Node *result = MD_NilNode(); - for(MD_Node *node = first; !MD_NodeIsNil(node); node = node->next) + Node *result = NilNode(); + for(Node *node = first; !NodeIsNil(node); node = node->next) { - if(MD_S8Match(string, node->string, flags)) + if(S8Match(string, node->string, flags)) { result = node; break; @@ -3097,14 +3097,14 @@ MD_FirstNodeWithString(MD_Node *first, MD_String8 string, MD_MatchFlags flags) return result; } -MD_FUNCTION MD_Node * -MD_NodeAtIndex(MD_Node *first, int n) +FUNCTION Node * +NodeAtIndex(Node *first, int n) { - MD_Node *result = MD_NilNode(); + Node *result = NilNode(); if(n >= 0) { int idx = 0; - for(MD_Node *node = first; !MD_NodeIsNil(node); node = node->next, idx += 1) + for(Node *node = first; !NodeIsNil(node); node = node->next, idx += 1) { if(idx == n) { @@ -3116,11 +3116,11 @@ MD_NodeAtIndex(MD_Node *first, int n) return result; } -MD_FUNCTION MD_Node * -MD_FirstNodeWithFlags(MD_Node *first, MD_NodeFlags flags) +FUNCTION Node * +FirstNodeWithFlags(Node *first, NodeFlags flags) { - MD_Node *result = MD_NilNode(); - for(MD_Node *n = first; !MD_NodeIsNil(n); n = n->next) + Node *result = NilNode(); + for(Node *n = first; !NodeIsNil(n); n = n->next) { if(n->flags & flags) { @@ -3131,211 +3131,211 @@ MD_FirstNodeWithFlags(MD_Node *first, MD_NodeFlags flags) return result; } -MD_FUNCTION int -MD_IndexFromNode(MD_Node *node) +FUNCTION int +IndexFromNode(Node *node) { int idx = 0; - for(MD_Node *last = node->prev; !MD_NodeIsNil(last); last = last->prev, idx += 1); + for(Node *last = node->prev; !NodeIsNil(last); last = last->prev, idx += 1); return idx; } -MD_FUNCTION MD_Node * -MD_RootFromNode(MD_Node *node) +FUNCTION Node * +RootFromNode(Node *node) { - MD_Node *parent = node; - for(MD_Node *p = parent; !MD_NodeIsNil(p); p = p->parent) + Node *parent = node; + for(Node *p = parent; !NodeIsNil(p); p = p->parent) { parent = p; } return parent; } -MD_FUNCTION MD_Node * -MD_ChildFromString(MD_Node *node, MD_String8 child_string, MD_MatchFlags flags) +FUNCTION Node * +MD_ChildFromString(Node *node, String8 child_string, MatchFlags flags) { - return MD_FirstNodeWithString(node->first_child, child_string, flags); + return FirstNodeWithString(node->first_child, child_string, flags); } -MD_FUNCTION MD_Node * -MD_TagFromString(MD_Node *node, MD_String8 tag_string, MD_MatchFlags flags) +FUNCTION Node * +TagFromString(Node *node, String8 tag_string, MatchFlags flags) { - return MD_FirstNodeWithString(node->first_tag, tag_string, flags); + return FirstNodeWithString(node->first_tag, tag_string, flags); } -MD_FUNCTION MD_Node * -MD_ChildFromIndex(MD_Node *node, int n) +FUNCTION Node * +ChildFromIndex(Node *node, int n) { - return MD_NodeAtIndex(node->first_child, n); + return NodeAtIndex(node->first_child, n); } -MD_FUNCTION MD_Node * -MD_TagFromIndex(MD_Node *node, int n) +FUNCTION Node * +TagFromIndex(Node *node, int n) { - return MD_NodeAtIndex(node->first_tag, n); + return NodeAtIndex(node->first_tag, n); } -MD_FUNCTION MD_Node * -MD_TagArgFromIndex(MD_Node *node, MD_String8 tag_string, MD_MatchFlags flags, int n) +FUNCTION Node * +TagArgFromIndex(Node *node, String8 tag_string, MatchFlags flags, int n) { - MD_Node *tag = MD_TagFromString(node, tag_string, flags); - return MD_ChildFromIndex(tag, n); + Node *tag = TagFromString(node, tag_string, flags); + return ChildFromIndex(tag, n); } -MD_FUNCTION MD_Node * -MD_TagArgFromString(MD_Node *node, MD_String8 tag_string, MD_MatchFlags tag_str_flags, MD_String8 arg_string, MD_MatchFlags arg_str_flags) +FUNCTION Node * +TagArgFromString(Node *node, String8 tag_string, MatchFlags tag_str_flags, String8 arg_string, MatchFlags arg_str_flags) { - MD_Node *tag = MD_TagFromString(node, tag_string, tag_str_flags); - MD_Node *arg = MD_ChildFromString(tag, arg_string, arg_str_flags); + Node *tag = TagFromString(node, tag_string, tag_str_flags); + Node *arg = MD_ChildFromString(tag, arg_string, arg_str_flags); return arg; } -MD_FUNCTION MD_b32 -MD_NodeHasChild(MD_Node *node, MD_String8 string, MD_MatchFlags flags) +FUNCTION b32 +NodeHasChild(Node *node, String8 string, MatchFlags flags) { - return !MD_NodeIsNil(MD_ChildFromString(node, string, flags)); + return !NodeIsNil(MD_ChildFromString(node, string, flags)); } -MD_FUNCTION MD_b32 -MD_NodeHasTag(MD_Node *node, MD_String8 string, MD_MatchFlags flags) +FUNCTION b32 +NodeHasTag(Node *node, String8 string, MatchFlags flags) { - return !MD_NodeIsNil(MD_TagFromString(node, string, flags)); + return !NodeIsNil(TagFromString(node, string, flags)); } -MD_FUNCTION MD_i64 -MD_ChildCountFromNode(MD_Node *node) +FUNCTION i64 +ChildCountFromNode(Node *node) { - MD_i64 result = 0; - for(MD_EachNode(child, node->first_child)) + i64 result = 0; + for(EachNode(child, node->first_child)) { result += 1; } return result; } -MD_FUNCTION MD_i64 -MD_TagCountFromNode(MD_Node *node) +FUNCTION i64 +TagCountFromNode(Node *node) { - MD_i64 result = 0; - for(MD_EachNode(tag, node->first_tag)) + i64 result = 0; + for(EachNode(tag, node->first_tag)) { result += 1; } return result; } -MD_FUNCTION MD_Node * -MD_ResolveNodeFromReference(MD_Node *node) +FUNCTION Node * +ResolveNodeFromReference(Node *node) { - MD_u64 safety = 100; - for(; safety > 0 && node->kind == MD_NodeKind_Reference; + u64 safety = 100; + for(; safety > 0 && node->kind == NodeKind_Reference; safety -= 1, node = node->ref_target); - MD_Node *result = node; + Node *result = node; return(result); } -MD_FUNCTION MD_Node* -MD_NodeNextWithLimit(MD_Node *node, MD_Node *opl) +FUNCTION Node* +NodeNextWithLimit(Node *node, Node *opl) { node = node->next; if (node == opl) { - node = MD_NilNode(); + node = NilNode(); } return(node); } -MD_FUNCTION MD_String8 -MD_PrevCommentFromNode(MD_Node *node) +FUNCTION String8 +PrevCommentFromNode(Node *node) { return(node->prev_comment); } -MD_FUNCTION MD_String8 -MD_NextCommentFromNode(MD_Node *node) +FUNCTION String8 +NextCommentFromNode(Node *node) { return(node->next_comment); } //~ Error/Warning Helpers -MD_FUNCTION MD_String8 -MD_StringFromMessageKind(MD_MessageKind kind) +FUNCTION String8 +StringFromMessageKind(MessageKind kind) { - MD_String8 result = MD_ZERO_STRUCT; + String8 result = ZERO_STRUCT; switch (kind) { default: break; - case MD_MessageKind_Note: result = MD_S8Lit("note"); break; - case MD_MessageKind_Warning: result = MD_S8Lit("warning"); break; - case MD_MessageKind_Error: result = MD_S8Lit("error"); break; - case MD_MessageKind_FatalError: result = MD_S8Lit("fatal error"); break; + case MessageKind_Note: result = S8Lit("note"); break; + case MessageKind_Warning: result = S8Lit("warning"); break; + case MessageKind_Error: result = S8Lit("error"); break; + case MessageKind_FatalError: result = S8Lit("fatal error"); break; } return(result); } -MD_FUNCTION MD_String8 -MD_FormatMessage(MD_Arena *arena, MD_CodeLoc loc, MD_MessageKind kind, MD_String8 string) +FUNCTION String8 +MD_FormatMessage(Arena *arena, CodeLoc loc, MessageKind kind, String8 string) { - MD_String8 kind_string = MD_StringFromMessageKind(kind); - MD_String8 result = MD_S8Fmt(arena, "" MD_FmtCodeLoc " %.*s: %.*s\n", - MD_CodeLocVArg(loc), MD_S8VArg(kind_string), MD_S8VArg(string)); + String8 kind_string = StringFromMessageKind(kind); + String8 result = S8Fmt(arena, "" FmtCodeLoc " %.*s: %.*s\n", + CodeLocVArg(loc), S8VArg(kind_string), S8VArg(string)); return(result); } -#if !MD_DISABLE_PRINT_HELPERS +#if !DISABLE_PRINT_HELPERS -MD_FUNCTION void -MD_PrintMessage(FILE *file, MD_CodeLoc code_loc, MD_MessageKind kind, MD_String8 string) +FUNCTION void +PrintMessage(FILE *file, CodeLoc code_loc, MessageKind kind, String8 string) { - MD_ArenaTemp scratch = MD_GetScratch(0, 0); - MD_String8 message = MD_FormatMessage(scratch.arena, code_loc, kind, string); + ArenaTemp scratch = GetScratch(0, 0); + String8 message = MD_FormatMessage(scratch.arena, code_loc, kind, string); fwrite(message.str, message.size, 1, file); - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); } -MD_FUNCTION void -MD_PrintMessageFmt(FILE *file, MD_CodeLoc code_loc, MD_MessageKind kind, char *fmt, ...) +FUNCTION void +PrintMessageFmt(FILE *file, CodeLoc code_loc, MessageKind kind, char *fmt, ...) { - MD_ArenaTemp scratch = MD_GetScratch(0, 0); + ArenaTemp scratch = GetScratch(0, 0); va_list args; va_start(args, fmt); - MD_String8 string = MD_S8FmtV(scratch.arena, fmt, args); + String8 string = S8FmtV(scratch.arena, fmt, args); va_end(args); - MD_String8 message = MD_FormatMessage(scratch.arena, code_loc, kind, string); + String8 message = MD_FormatMessage(scratch.arena, code_loc, kind, string); fwrite(message.str, message.size, 1, file); - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); } #endif //~ Tree Comparison/Verification -MD_FUNCTION MD_b32 -MD_NodeMatch(MD_Node *a, MD_Node *b, MD_MatchFlags flags) +FUNCTION b32 +NodeMatch(Node *a, Node *b, MatchFlags flags) { - MD_b32 result = 0; - if(a->kind == b->kind && MD_S8Match(a->string, b->string, flags)) + b32 result = 0; + if(a->kind == b->kind && S8Match(a->string, b->string, flags)) { result = 1; - if(result && flags & MD_NodeMatchFlag_NodeFlags) + if(result && flags & NodeMatchFlag_NodeFlags) { result = result && a->flags == b->flags; } - if(result && a->kind != MD_NodeKind_Tag && (flags & MD_NodeMatchFlag_Tags)) + if(result && a->kind != NodeKind_Tag && (flags & NodeMatchFlag_Tags)) { - for(MD_Node *a_tag = a->first_tag, *b_tag = b->first_tag; - !MD_NodeIsNil(a_tag) || !MD_NodeIsNil(b_tag); + for(Node *a_tag = a->first_tag, *b_tag = b->first_tag; + !NodeIsNil(a_tag) || !NodeIsNil(b_tag); a_tag = a_tag->next, b_tag = b_tag->next) { - if(MD_NodeMatch(a_tag, b_tag, flags)) + if(NodeMatch(a_tag, b_tag, flags)) { - if(flags & MD_NodeMatchFlag_TagArguments) + if(flags & NodeMatchFlag_TagArguments) { - for(MD_Node *a_tag_arg = a_tag->first_child, *b_tag_arg = b_tag->first_child; - !MD_NodeIsNil(a_tag_arg) || !MD_NodeIsNil(b_tag_arg); + for(Node *a_tag_arg = a_tag->first_child, *b_tag_arg = b_tag->first_child; + !NodeIsNil(a_tag_arg) || !NodeIsNil(b_tag_arg); a_tag_arg = a_tag_arg->next, b_tag_arg = b_tag_arg->next) { - if(!MD_NodeDeepMatch(a_tag_arg, b_tag_arg, flags)) + if(!NodeDeepMatch(a_tag_arg, b_tag_arg, flags)) { result = 0; goto end; @@ -3355,17 +3355,17 @@ MD_NodeMatch(MD_Node *a, MD_Node *b, MD_MatchFlags flags) return result; } -MD_FUNCTION MD_b32 -MD_NodeDeepMatch(MD_Node *a, MD_Node *b, MD_MatchFlags flags) +FUNCTION b32 +NodeDeepMatch(Node *a, Node *b, MatchFlags flags) { - MD_b32 result = MD_NodeMatch(a, b, flags); + b32 result = NodeMatch(a, b, flags); if(result) { - for(MD_Node *a_child = a->first_child, *b_child = b->first_child; - !MD_NodeIsNil(a_child) || !MD_NodeIsNil(b_child); + for(Node *a_child = a->first_child, *b_child = b->first_child; + !NodeIsNil(a_child) || !NodeIsNil(b_child); a_child = a_child->next, b_child = b_child->next) { - if(!MD_NodeDeepMatch(a_child, b_child, flags)) + if(!NodeDeepMatch(a_child, b_child, flags)) { result = 0; goto end; @@ -3378,13 +3378,13 @@ MD_NodeDeepMatch(MD_Node *a, MD_Node *b, MD_MatchFlags flags) //~ Expression Parsing -MD_FUNCTION void -MD_ExprOprPush(MD_Arena *arena, MD_ExprOprList *list, - MD_ExprOprKind kind, MD_u64 precedence, MD_String8 string, - MD_u32 op_id, void *op_ptr) +FUNCTION void +ExprOprPush(Arena *arena, ExprOprList *list, + ExprOprKind kind, u64 precedence, String8 string, + u32 op_id, void *op_ptr) { - MD_ExprOpr *op = MD_PushArrayZero(arena, MD_ExprOpr, 1); - MD_QueuePush(list->first, list->last, op); + ExprOpr *op = PushArrayZero(arena, ExprOpr, 1); + QueuePush(list->first, list->last, op); list->count += 1; op->op_id = op_id; op->kind = kind; @@ -3393,93 +3393,93 @@ MD_ExprOprPush(MD_Arena *arena, MD_ExprOprList *list, op->op_ptr = op_ptr; } -MD_GLOBAL MD_BakeOperatorErrorHandler md_bake_operator_error_handler = 0; +GLOBAL BakeOperatorErrorHandler md_bake_operator_error_handler = 0; -MD_FUNCTION MD_BakeOperatorErrorHandler -MD_ExprSetBakeOperatorErrorHandler(MD_BakeOperatorErrorHandler handler){ - MD_BakeOperatorErrorHandler old_handler = md_bake_operator_error_handler; +FUNCTION BakeOperatorErrorHandler +ExprSetBakeOperatorErrorHandler(BakeOperatorErrorHandler handler){ + BakeOperatorErrorHandler old_handler = md_bake_operator_error_handler; md_bake_operator_error_handler = handler; return old_handler; } -MD_FUNCTION MD_ExprOprTable -MD_ExprBakeOprTableFromList(MD_Arena *arena, MD_ExprOprList *list) +FUNCTION ExprOprTable +ExprBakeOprTableFromList(Arena *arena, ExprOprList *list) { - MD_ExprOprTable result = MD_ZERO_STRUCT; + ExprOprTable result = ZERO_STRUCT; // TODO(allen): @upgrade_potential(minor) - for(MD_ExprOpr *op = list->first; + for(ExprOpr *op = list->first; op != 0; op = op->next) { - MD_ExprOprKind op_kind = op->kind; - MD_String8 op_s = op->string; + ExprOprKind op_kind = op->kind; + String8 op_s = op->string; // error checking - MD_String8 error_str = MD_ZERO_STRUCT; + String8 error_str = ZERO_STRUCT; - MD_Token op_token = MD_TokenFromString(op_s); - MD_b32 is_setlike_op = + Token op_token = TokenFromString(op_s); + b32 is_setlike_op = (op_s.size == 2 && - (MD_S8Match(op_s, MD_S8Lit("[]"), 0) || MD_S8Match(op_s, MD_S8Lit("()"), 0) || - MD_S8Match(op_s, MD_S8Lit("[)"), 0) || MD_S8Match(op_s, MD_S8Lit("(]"), 0) || - MD_S8Match(op_s, MD_S8Lit("{}"), 0))); + (S8Match(op_s, S8Lit("[]"), 0) || S8Match(op_s, S8Lit("()"), 0) || + S8Match(op_s, S8Lit("[)"), 0) || S8Match(op_s, S8Lit("(]"), 0) || + S8Match(op_s, S8Lit("{}"), 0))); - if(op_kind != MD_ExprOprKind_Prefix && op_kind != MD_ExprOprKind_Postfix && - op_kind != MD_ExprOprKind_Binary && op_kind != MD_ExprOprKind_BinaryRightAssociative) + if(op_kind != ExprOprKind_Prefix && op_kind != ExprOprKind_Postfix && + op_kind != ExprOprKind_Binary && op_kind != ExprOprKind_BinaryRightAssociative) { - error_str = MD_S8Fmt(arena, "Ignored operator \"%.*s\" because its kind value (%d) does not match " - "any valid operator kind", MD_S8VArg(op_s), op_kind); + error_str = S8Fmt(arena, "Ignored operator \"%.*s\" because its kind value (%d) does not match " + "any valid operator kind", S8VArg(op_s), op_kind); } - else if(is_setlike_op && op_kind != MD_ExprOprKind_Postfix) + else if(is_setlike_op && op_kind != ExprOprKind_Postfix) { error_str = - MD_S8Fmt(arena, "Ignored operator \"%.*s\". \"%.*s\" is only allowed as unary postfix", - MD_S8VArg(op_s), MD_S8VArg(op_s)); + S8Fmt(arena, "Ignored operator \"%.*s\". \"%.*s\" is only allowed as unary postfix", + S8VArg(op_s), S8VArg(op_s)); } else if(!is_setlike_op && - (op_token.kind != MD_TokenKind_Identifier && op_token.kind != MD_TokenKind_Symbol)) + (op_token.kind != TokenKind_Identifier && op_token.kind != TokenKind_Symbol)) { - error_str = MD_S8Fmt(arena, "Ignored operator \"%.*s\" because it is neither a symbol " - "nor an identifier token", MD_S8VArg(op_s)); + error_str = S8Fmt(arena, "Ignored operator \"%.*s\" because it is neither a symbol " + "nor an identifier token", S8VArg(op_s)); } else if(!is_setlike_op && op_token.string.size < op_s.size) { - error_str = MD_S8Fmt(arena, "Ignored operator \"%.*s\" because its prefix \"%.*s\" " + error_str = S8Fmt(arena, "Ignored operator \"%.*s\" because its prefix \"%.*s\" " "constitutes a standalone operator", - MD_S8VArg(op_s), MD_S8VArg(op_token.string)); + S8VArg(op_s), S8VArg(op_token.string)); } else { - for(MD_ExprOpr *op2 = list->first; + for(ExprOpr *op2 = list->first; op2 != op; op2 = op2->next) { // NOTE(mal): O(n^2) - MD_ExprOprKind op2_kind = op2->kind; - MD_String8 op2_s = op2->string; + ExprOprKind op2_kind = op2->kind; + String8 op2_s = op2->string; if(op->precedence == op2->precedence && - ((op_kind == MD_ExprOprKind_Binary && - op2_kind == MD_ExprOprKind_BinaryRightAssociative) || - (op_kind == MD_ExprOprKind_BinaryRightAssociative && - op2_kind == MD_ExprOprKind_Binary))) + ((op_kind == ExprOprKind_Binary && + op2_kind == ExprOprKind_BinaryRightAssociative) || + (op_kind == ExprOprKind_BinaryRightAssociative && + op2_kind == ExprOprKind_Binary))) { error_str = - MD_S8Fmt(arena, "Ignored binary operator \"%.*s\" because another binary operator" - "has the same precedence and different associativity", MD_S8VArg(op_s)); + S8Fmt(arena, "Ignored binary operator \"%.*s\" because another binary operator" + "has the same precedence and different associativity", S8VArg(op_s)); } - else if(MD_S8Match(op_s, op2_s, 0)) + else if(S8Match(op_s, op2_s, 0)) { if(op_kind == op2_kind) { - error_str = MD_S8Fmt(arena, "Ignored repeat operator \"%.*s\"", MD_S8VArg(op_s)); + error_str = S8Fmt(arena, "Ignored repeat operator \"%.*s\"", S8VArg(op_s)); } - else if(op_kind != MD_ExprOprKind_Prefix && op2_kind != MD_ExprOprKind_Prefix) + else if(op_kind != ExprOprKind_Prefix && op2_kind != ExprOprKind_Prefix) { error_str = - MD_S8Fmt(arena, "Ignored conflicting repeat operator \"%.*s\". There can't be" + S8Fmt(arena, "Ignored conflicting repeat operator \"%.*s\". There can't be" "more than one posfix/binary operator associated to the same token", - MD_S8VArg(op_s)); + S8VArg(op_s)); } } } @@ -3488,16 +3488,16 @@ MD_ExprBakeOprTableFromList(MD_Arena *arena, MD_ExprOprList *list) // save error if(error_str.size != 0 && md_bake_operator_error_handler) { - md_bake_operator_error_handler(MD_MessageKind_Warning, error_str); + md_bake_operator_error_handler(MessageKind_Warning, error_str); } // save list else { - MD_ExprOprList *list = result.table + op_kind; - MD_ExprOpr *op_node_copy = MD_PushArray(arena, MD_ExprOpr, 1); + ExprOprList *list = result.table + op_kind; + ExprOpr *op_node_copy = PushArray(arena, ExprOpr, 1); *op_node_copy = *op; - MD_QueuePush(list->first, list->last, op_node_copy); + QueuePush(list->first, list->last, op_node_copy); list->count += 1; } } @@ -3505,25 +3505,25 @@ MD_ExprBakeOprTableFromList(MD_Arena *arena, MD_ExprOprList *list) return(result); } -MD_FUNCTION MD_ExprOpr* -MD_ExprOprFromKindString(MD_ExprOprTable *table, MD_ExprOprKind kind, MD_String8 s) +FUNCTION ExprOpr* +ExprOprFromKindString(ExprOprTable *table, ExprOprKind kind, String8 s) { // TODO(allen): @upgrade_potential - // NOTE(mal): Look for operator on one or all (kind == MD_ExprOprKind_Null) tables - MD_ExprOpr *result = 0; - for(MD_ExprOprKind cur_kind = (MD_ExprOprKind)(MD_ExprOprKind_Null + 1); - cur_kind < MD_ExprOprKind_COUNT; - cur_kind = (MD_ExprOprKind)(cur_kind + 1)) + // NOTE(mal): Look for operator on one or all (kind == ExprOprKind_Null) tables + ExprOpr *result = 0; + for(ExprOprKind cur_kind = (ExprOprKind)(ExprOprKind_Null + 1); + cur_kind < ExprOprKind_COUNT; + cur_kind = (ExprOprKind)(cur_kind + 1)) { - if(kind == MD_ExprOprKind_Null || kind == cur_kind) + if(kind == ExprOprKind_Null || kind == cur_kind) { - MD_ExprOprList *op_list = table->table+cur_kind; - for(MD_ExprOpr *op = op_list->first; + ExprOprList *op_list = table->table+cur_kind; + for(ExprOpr *op = op_list->first; op != 0; op = op->next) { - if(MD_S8Match(op->string, s, 0)) + if(S8Match(op->string, s, 0)) { result = op; goto dbl_break; @@ -3535,34 +3535,34 @@ MD_ExprOprFromKindString(MD_ExprOprTable *table, MD_ExprOprKind kind, MD_String8 return result; } -MD_FUNCTION MD_ExprParseResult -MD_ExprParse(MD_Arena *arena, MD_ExprOprTable *op_table, MD_Node *first, MD_Node *opl) +FUNCTION ExprParseResult +ExprParse(Arena *arena, ExprOprTable *op_table, Node *first, Node *opl) { // setup a context - MD_ExprParseCtx ctx = MD_ExprParse_MakeContext(op_table); + ExprParseCtx ctx = ExprParse_MakeContext(op_table); // parse the top level - MD_Expr *expr = MD_ExprParse_TopLevel(arena, &ctx, first, opl); + Expr *expr = ExprParse_TopLevel(arena, &ctx, first, opl); // fill result - MD_ExprParseResult result = {0}; + ExprParseResult result = {0}; result.expr = expr; result.errors = ctx.errors; return(result); } -MD_FUNCTION MD_Expr* -MD_Expr_NewLeaf(MD_Arena *arena, MD_Node *node) +FUNCTION Expr* +Expr_NewLeaf(Arena *arena, Node *node) { - MD_Expr *result = MD_PushArrayZero(arena, MD_Expr, 1); + Expr *result = PushArrayZero(arena, Expr, 1); result->md_node = node; return(result); } -MD_FUNCTION MD_Expr* -MD_Expr_NewOpr(MD_Arena *arena, MD_ExprOpr *op, MD_Node *op_node, MD_Expr *l, MD_Expr *r) +FUNCTION Expr* +Expr_NewOpr(Arena *arena, ExprOpr *op, Node *op_node, Expr *l, Expr *r) { - MD_Expr *result = MD_PushArrayZero(arena, MD_Expr, 1); + Expr *result = PushArrayZero(arena, Expr, 1); result->op = op; result->md_node = op_node; result->parent = 0; @@ -3570,185 +3570,185 @@ MD_Expr_NewOpr(MD_Arena *arena, MD_ExprOpr *op, MD_Node *op_node, MD_Expr *l, MD result->right = r; if (l != 0) { - MD_Assert(l->parent == 0); + Assert(l->parent == 0); l->parent = result; } if(r != 0) { - MD_Assert(r->parent == 0); + Assert(r->parent == 0); r->parent = result; } return(result); } -MD_FUNCTION MD_ExprParseCtx -MD_ExprParse_MakeContext(MD_ExprOprTable *op_table) +FUNCTION ExprParseCtx +ExprParse_MakeContext(ExprOprTable *op_table) { - MD_ExprParseCtx result = MD_ZERO_STRUCT; + ExprParseCtx result = ZERO_STRUCT; result.op_table = op_table; - result.accel.postfix_set_ops[0] = MD_ExprOprFromKindString(op_table, MD_ExprOprKind_Postfix, MD_S8Lit("()")); - result.accel.postfix_set_flags[0] = MD_NodeFlag_HasParenLeft | MD_NodeFlag_HasParenRight; + result.accel.postfix_set_ops[0] = ExprOprFromKindString(op_table, ExprOprKind_Postfix, S8Lit("()")); + result.accel.postfix_set_flags[0] = NodeFlag_HasParenLeft | NodeFlag_HasParenRight; - result.accel.postfix_set_ops[1] = MD_ExprOprFromKindString(op_table, MD_ExprOprKind_Postfix, MD_S8Lit("[]")); - result.accel.postfix_set_flags[1] = MD_NodeFlag_HasBracketLeft | MD_NodeFlag_HasBracketRight; + result.accel.postfix_set_ops[1] = ExprOprFromKindString(op_table, ExprOprKind_Postfix, S8Lit("[]")); + result.accel.postfix_set_flags[1] = NodeFlag_HasBracketLeft | NodeFlag_HasBracketRight; - result.accel.postfix_set_ops[2] = MD_ExprOprFromKindString(op_table, MD_ExprOprKind_Postfix, MD_S8Lit("{}")); - result.accel.postfix_set_flags[2] = MD_NodeFlag_HasBraceLeft | MD_NodeFlag_HasBraceRight; + result.accel.postfix_set_ops[2] = ExprOprFromKindString(op_table, ExprOprKind_Postfix, S8Lit("{}")); + result.accel.postfix_set_flags[2] = NodeFlag_HasBraceLeft | NodeFlag_HasBraceRight; - result.accel.postfix_set_ops[3] = MD_ExprOprFromKindString(op_table, MD_ExprOprKind_Postfix, MD_S8Lit("[)")); - result.accel.postfix_set_flags[3] = MD_NodeFlag_HasBracketLeft | MD_NodeFlag_HasParenRight; + result.accel.postfix_set_ops[3] = ExprOprFromKindString(op_table, ExprOprKind_Postfix, S8Lit("[)")); + result.accel.postfix_set_flags[3] = NodeFlag_HasBracketLeft | NodeFlag_HasParenRight; - result.accel.postfix_set_ops[4] = MD_ExprOprFromKindString(op_table, MD_ExprOprKind_Postfix, MD_S8Lit("(]")); - result.accel.postfix_set_flags[4] = MD_NodeFlag_HasParenLeft | MD_NodeFlag_HasBracketRight; + result.accel.postfix_set_ops[4] = ExprOprFromKindString(op_table, ExprOprKind_Postfix, S8Lit("(]")); + result.accel.postfix_set_flags[4] = NodeFlag_HasParenLeft | NodeFlag_HasBracketRight; return(result); } -MD_FUNCTION MD_Expr* -MD_ExprParse_TopLevel(MD_Arena *arena, MD_ExprParseCtx *ctx, MD_Node *first, MD_Node *opl) +FUNCTION Expr* +ExprParse_TopLevel(Arena *arena, ExprParseCtx *ctx, Node *first, Node *opl) { // parse the node range - MD_Node *iter = first; - MD_Expr *expr = MD_ExprParse_MinPrecedence(arena, ctx, &iter, first, opl, 0); + Node *iter = first; + Expr *expr = ExprParse_MinPrecedence(arena, ctx, &iter, first, opl, 0); // check for failed-to-reach-end error - if(ctx->errors.max_message_kind == MD_MessageKind_Null) + if(ctx->errors.max_message_kind == MessageKind_Null) { - MD_Node *stop_node = iter; - if(!MD_NodeIsNil(stop_node)) + Node *stop_node = iter; + if(!NodeIsNil(stop_node)) { - MD_String8 error_str = MD_S8Lit("Expected binary or unary postfix operator."); - MD_Message *error = MD_MakeNodeError(arena,stop_node,MD_MessageKind_FatalError,error_str); - MD_MessageListPush(&ctx->errors, error); + String8 error_str = S8Lit("Expected binary or unary postfix operator."); + Message *error = MakeNodeError(arena,stop_node,MessageKind_FatalError,error_str); + MessageListPush(&ctx->errors, error); } } return(expr); } -MD_FUNCTION MD_b32 -MD_ExprParse_OprConsume(MD_ExprParseCtx *ctx, MD_Node **iter, MD_Node *opl, - MD_ExprOprKind kind, MD_u32 min_precedence, MD_ExprOpr **op_out) +FUNCTION b32 +ExprParse_OprConsume(ExprParseCtx *ctx, Node **iter, Node *opl, + ExprOprKind kind, u32 min_precedence, ExprOpr **op_out) { - MD_b32 result = 0; - MD_Node *node = *iter; - if(!MD_NodeIsNil(node)) + b32 result = 0; + Node *node = *iter; + if(!NodeIsNil(node)) { - MD_ExprOpr *op = MD_ExprOprFromKindString(ctx->op_table, kind, node->string); + ExprOpr *op = ExprOprFromKindString(ctx->op_table, kind, node->string); if(op != 0 && op->precedence >= min_precedence) { result = 1; *op_out = op; - *iter= MD_NodeNextWithLimit(*iter, opl); + *iter= NodeNextWithLimit(*iter, opl); } } return result; } -MD_FUNCTION MD_Expr* -MD_ExprParse_Atom(MD_Arena *arena, MD_ExprParseCtx *ctx, MD_Node **iter, - MD_Node *first, MD_Node *opl) +FUNCTION Expr* +ExprParse_Atom(Arena *arena, ExprParseCtx *ctx, Node **iter, + Node *first, Node *opl) { // TODO(allen): nil - MD_Expr* result = 0; + Expr* result = 0; - MD_Node *node = *iter; - MD_ExprOpr *op = 0; + Node *node = *iter; + ExprOpr *op = 0; - if(MD_NodeIsNil(node)) + if(NodeIsNil(node)) { - MD_Node *last = first; + Node *last = first; for (;last->next != opl; last = last->next); - MD_Node *error_node = last->next; - if (MD_NodeIsNil(error_node)) + Node *error_node = last->next; + if (NodeIsNil(error_node)) { - MD_Node *root = MD_RootFromNode(node); - MD_String8 parse_contents = root->raw_string; - MD_u64 offset = last->offset + last->raw_string.size; - error_node = MD_MakeErrorMarkerNode(arena, parse_contents, offset); + Node *root = RootFromNode(node); + String8 parse_contents = root->raw_string; + u64 offset = last->offset + last->raw_string.size; + error_node = MakeErrorMarkerNode(arena, parse_contents, offset); } - MD_String8 error_str = MD_S8Lit("Unexpected end of expression."); - MD_Message *error = MD_MakeNodeError(arena, error_node, MD_MessageKind_FatalError, + String8 error_str = S8Lit("Unexpected end of expression."); + Message *error = MakeNodeError(arena, error_node, MessageKind_FatalError, error_str); - MD_MessageListPush(&ctx->errors, error); + MessageListPush(&ctx->errors, error); } - else if((node->flags & MD_NodeFlag_HasParenLeft) && - (node->flags & MD_NodeFlag_HasParenRight)) + else if((node->flags & NodeFlag_HasParenLeft) && + (node->flags & NodeFlag_HasParenRight)) { // NOTE(mal): Parens - *iter = MD_NodeNextWithLimit(*iter, opl); - result = MD_ExprParse_TopLevel(arena, ctx, node->first_child, MD_NilNode()); + *iter = NodeNextWithLimit(*iter, opl); + result = ExprParse_TopLevel(arena, ctx, node->first_child, NilNode()); } - else if(((node->flags & MD_NodeFlag_HasBraceLeft) && (node->flags & MD_NodeFlag_HasBraceRight)) || - ((node->flags & MD_NodeFlag_HasBracketLeft) && (node->flags & MD_NodeFlag_HasBracketRight)) || - ((node->flags & MD_NodeFlag_HasBracketLeft) && (node->flags & MD_NodeFlag_HasParenRight)) || - ((node->flags & MD_NodeFlag_HasParenLeft) && (node->flags & MD_NodeFlag_HasBracketRight))) + else if(((node->flags & NodeFlag_HasBraceLeft) && (node->flags & NodeFlag_HasBraceRight)) || + ((node->flags & NodeFlag_HasBracketLeft) && (node->flags & NodeFlag_HasBracketRight)) || + ((node->flags & NodeFlag_HasBracketLeft) && (node->flags & NodeFlag_HasParenRight)) || + ((node->flags & NodeFlag_HasParenLeft) && (node->flags & NodeFlag_HasBracketRight))) { // NOTE(mal): Unparsed leaf sets ({...}, [...], [...), (...]) - *iter = MD_NodeNextWithLimit(*iter, opl); - result = MD_Expr_NewLeaf(arena, node); + *iter = NodeNextWithLimit(*iter, opl); + result = Expr_NewLeaf(arena, node); } - else if(MD_ExprParse_OprConsume(ctx, iter, opl, MD_ExprOprKind_Prefix, 1, &op)) + else if(ExprParse_OprConsume(ctx, iter, opl, ExprOprKind_Prefix, 1, &op)) { - MD_u32 min_precedence = op->precedence + 1; - MD_Expr *sub_expr = - MD_ExprParse_MinPrecedence(arena, ctx, iter, first, opl, min_precedence); - if(ctx->errors.max_message_kind == MD_MessageKind_Null) + u32 min_precedence = op->precedence + 1; + Expr *sub_expr = + ExprParse_MinPrecedence(arena, ctx, iter, first, opl, min_precedence); + if(ctx->errors.max_message_kind == MessageKind_Null) { - result = MD_Expr_NewOpr(arena, op, node, sub_expr, 0); + result = Expr_NewOpr(arena, op, node, sub_expr, 0); } } - else if(MD_ExprParse_OprConsume(ctx, iter, opl, MD_ExprOprKind_Null, 1, &op)) + else if(ExprParse_OprConsume(ctx, iter, opl, ExprOprKind_Null, 1, &op)) { - MD_String8 error_str = MD_S8Fmt(arena, "Expected leaf. Got operator \"%.*s\".", MD_S8VArg(node->string)); + String8 error_str = S8Fmt(arena, "Expected leaf. Got operator \"%.*s\".", S8VArg(node->string)); - MD_Message *error = MD_MakeNodeError(arena, node, MD_MessageKind_FatalError, error_str); - MD_MessageListPush(&ctx->errors, error); + Message *error = MakeNodeError(arena, node, MessageKind_FatalError, error_str); + MessageListPush(&ctx->errors, error); } else if(node->flags & - (MD_NodeFlag_HasParenLeft|MD_NodeFlag_HasParenRight|MD_NodeFlag_HasBracketLeft| - MD_NodeFlag_HasBracketRight|MD_NodeFlag_HasBraceLeft|MD_NodeFlag_HasBraceRight)) + (NodeFlag_HasParenLeft|NodeFlag_HasParenRight|NodeFlag_HasBracketLeft| + NodeFlag_HasBracketRight|NodeFlag_HasBraceLeft|NodeFlag_HasBraceRight)) { - MD_String8 error_str = MD_S8Fmt(arena, "Unexpected set.", MD_S8VArg(node->string)); - MD_Message *error = MD_MakeNodeError(arena, node, MD_MessageKind_FatalError, error_str); - MD_MessageListPush(&ctx->errors, error); + String8 error_str = S8Fmt(arena, "Unexpected set.", S8VArg(node->string)); + Message *error = MakeNodeError(arena, node, MessageKind_FatalError, error_str); + MessageListPush(&ctx->errors, error); } else{ // NOTE(mal): leaf - *iter = MD_NodeNextWithLimit(*iter, opl); - result = MD_Expr_NewLeaf(arena, node); + *iter = NodeNextWithLimit(*iter, opl); + result = Expr_NewLeaf(arena, node); } return(result); } -MD_FUNCTION MD_Expr* -MD_ExprParse_MinPrecedence(MD_Arena *arena, MD_ExprParseCtx *ctx, - MD_Node **iter, MD_Node *first, MD_Node *opl, - MD_u32 min_precedence) +FUNCTION Expr* +ExprParse_MinPrecedence(Arena *arena, ExprParseCtx *ctx, + Node **iter, Node *first, Node *opl, + u32 min_precedence) { // TODO(allen): nil - MD_Expr* result = 0; + Expr* result = 0; - result = MD_ExprParse_Atom(arena, ctx, iter, first, opl); - if(ctx->errors.max_message_kind == MD_MessageKind_Null) + result = ExprParse_Atom(arena, ctx, iter, first, opl); + if(ctx->errors.max_message_kind == MessageKind_Null) { - for (;!MD_NodeIsNil(*iter);) + for (;!NodeIsNil(*iter);) { - MD_Node *node = *iter; - MD_ExprOpr *op = 0; + Node *node = *iter; + ExprOpr *op = 0; - if(MD_ExprParse_OprConsume(ctx, iter, opl, MD_ExprOprKind_Binary, + if(ExprParse_OprConsume(ctx, iter, opl, ExprOprKind_Binary, min_precedence, &op) || - MD_ExprParse_OprConsume(ctx, iter, opl, MD_ExprOprKind_BinaryRightAssociative, + ExprParse_OprConsume(ctx, iter, opl, ExprOprKind_BinaryRightAssociative, min_precedence, &op)) { - MD_u32 next_min_precedence = op->precedence + (op->kind == MD_ExprOprKind_Binary); - MD_Expr *sub_expr = - MD_ExprParse_MinPrecedence(arena, ctx, iter, first, opl, next_min_precedence); - if(ctx->errors.max_message_kind == MD_MessageKind_Null) + u32 next_min_precedence = op->precedence + (op->kind == ExprOprKind_Binary); + Expr *sub_expr = + ExprParse_MinPrecedence(arena, ctx, iter, first, opl, next_min_precedence); + if(ctx->errors.max_message_kind == MessageKind_Null) { - result = MD_Expr_NewOpr(arena, op, node, result, sub_expr); + result = Expr_NewOpr(arena, op, node, result, sub_expr); } else{ break; @@ -3757,17 +3757,17 @@ MD_ExprParse_MinPrecedence(MD_Arena *arena, MD_ExprParseCtx *ctx, else { - MD_b32 found_postfix_setlike_operator = 0; - for(MD_u32 i_op = 0; - i_op < MD_ArrayCount(ctx->accel.postfix_set_ops); + b32 found_postfix_setlike_operator = 0; + for(u32 i_op = 0; + i_op < ArrayCount(ctx->accel.postfix_set_ops); ++i_op) { - MD_ExprOpr *op = ctx->accel.postfix_set_ops[i_op]; + ExprOpr *op = ctx->accel.postfix_set_ops[i_op]; if(op && op->precedence >= min_precedence && node->flags == ctx->accel.postfix_set_flags[i_op]) { - *iter = MD_NodeNextWithLimit(*iter, opl); - result = MD_Expr_NewOpr(arena, op, node, result, 0); + *iter = NodeNextWithLimit(*iter, opl); + result = Expr_NewOpr(arena, op, node, result, 0); found_postfix_setlike_operator = 1; break; } @@ -3775,10 +3775,10 @@ MD_ExprParse_MinPrecedence(MD_Arena *arena, MD_ExprParseCtx *ctx, if(!found_postfix_setlike_operator) { - if(MD_ExprParse_OprConsume(ctx, iter, opl, MD_ExprOprKind_Postfix, + if(ExprParse_OprConsume(ctx, iter, opl, ExprOprKind_Postfix, min_precedence, &op)) { - result = MD_Expr_NewOpr(arena, op, node, result, 0); + result = Expr_NewOpr(arena, op, node, result, 0); } else { @@ -3799,233 +3799,233 @@ MD_ExprParse_MinPrecedence(MD_Arena *arena, MD_ExprParseCtx *ctx, //~ String Generation -MD_FUNCTION void -MD_DebugDumpFromNode(MD_Arena *arena, MD_String8List *out, MD_Node *node, - int indent, MD_String8 indent_string, MD_GenerateFlags flags) +FUNCTION void +DebugDumpFromNode(Arena *arena, String8List *out, Node *node, + int indent, String8 indent_string, GenerateFlags flags) { -#define MD_PrintIndent(_indent_level) do\ +#define PrintIndent(_indent_level) do\ {\ for(int i = 0; i < (_indent_level); i += 1)\ {\ -MD_S8ListPush(arena, out, indent_string);\ +S8ListPush(arena, out, indent_string);\ }\ }while(0) //- rjf: prev-comment - if(flags & MD_GenerateFlag_Comments && node->prev_comment.size != 0) + if(flags & GenerateFlag_Comments && node->prev_comment.size != 0) { - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, MD_S8Lit("/*\n")); - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, node->prev_comment); - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, MD_S8Lit("\n")); - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, MD_S8Lit("*/\n")); + PrintIndent(indent); + S8ListPush(arena, out, S8Lit("/*\n")); + PrintIndent(indent); + S8ListPush(arena, out, node->prev_comment); + PrintIndent(indent); + S8ListPush(arena, out, S8Lit("\n")); + PrintIndent(indent); + S8ListPush(arena, out, S8Lit("*/\n")); } //- rjf: tags of node - if(flags & MD_GenerateFlag_Tags) + if(flags & GenerateFlag_Tags) { - for(MD_EachNode(tag, node->first_tag)) + for(EachNode(tag, node->first_tag)) { - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, MD_S8Lit("@")); - MD_S8ListPush(arena, out, tag->string); - if(flags & MD_GenerateFlag_TagArguments && !MD_NodeIsNil(tag->first_child)) + PrintIndent(indent); + S8ListPush(arena, out, S8Lit("@")); + S8ListPush(arena, out, tag->string); + if(flags & GenerateFlag_TagArguments && !NodeIsNil(tag->first_child)) { int tag_arg_indent = indent + 1 + tag->string.size + 1; - MD_S8ListPush(arena, out, MD_S8Lit("(")); - for(MD_EachNode(child, tag->first_child)) + S8ListPush(arena, out, S8Lit("(")); + for(EachNode(child, tag->first_child)) { int child_indent = tag_arg_indent; - if(MD_NodeIsNil(child->prev)) + if(NodeIsNil(child->prev)) { child_indent = 0; } - MD_DebugDumpFromNode(arena, out, child, child_indent, MD_S8Lit(" "), flags); - if(!MD_NodeIsNil(child->next)) + DebugDumpFromNode(arena, out, child, child_indent, S8Lit(" "), flags); + if(!NodeIsNil(child->next)) { - MD_S8ListPush(arena, out, MD_S8Lit(",\n")); + S8ListPush(arena, out, S8Lit(",\n")); } } - MD_S8ListPush(arena, out, MD_S8Lit(")\n")); + S8ListPush(arena, out, S8Lit(")\n")); } else { - MD_S8ListPush(arena, out, MD_S8Lit("\n")); + S8ListPush(arena, out, S8Lit("\n")); } } } //- rjf: node kind - if(flags & MD_GenerateFlag_NodeKind) + if(flags & GenerateFlag_NodeKind) { - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, MD_S8Lit("// kind: \"")); - MD_S8ListPush(arena, out, MD_StringFromNodeKind(node->kind)); - MD_S8ListPush(arena, out, MD_S8Lit("\"\n")); + PrintIndent(indent); + S8ListPush(arena, out, S8Lit("// kind: \"")); + S8ListPush(arena, out, StringFromNodeKind(node->kind)); + S8ListPush(arena, out, S8Lit("\"\n")); } //- rjf: node flags - if(flags & MD_GenerateFlag_NodeFlags) - { - MD_PrintIndent(indent); - MD_ArenaTemp scratch = MD_GetScratch(&arena, 1); - MD_String8List flag_strs = MD_StringListFromNodeFlags(scratch.arena, node->flags); - MD_StringJoin join = { MD_S8Lit(""), MD_S8Lit("|"), MD_S8Lit("") }; - MD_String8 flag_str = MD_S8ListJoin(arena, flag_strs, &join); - MD_S8ListPush(arena, out, MD_S8Lit("// flags: \"")); - MD_S8ListPush(arena, out, flag_str); - MD_S8ListPush(arena, out, MD_S8Lit("\"\n")); - MD_ReleaseScratch(scratch); + if(flags & GenerateFlag_NodeFlags) + { + PrintIndent(indent); + ArenaTemp scratch = GetScratch(&arena, 1); + String8List flag_strs = StringListFromNodeFlags(scratch.arena, node->flags); + StringJoin join = { S8Lit(""), S8Lit("|"), S8Lit("") }; + String8 flag_str = S8ListJoin(arena, flag_strs, &join); + S8ListPush(arena, out, S8Lit("// flags: \"")); + S8ListPush(arena, out, flag_str); + S8ListPush(arena, out, S8Lit("\"\n")); + ReleaseScratch(scratch); } //- rjf: location - if(flags & MD_GenerateFlag_Location) + if(flags & GenerateFlag_Location) { - MD_PrintIndent(indent); - MD_CodeLoc loc = MD_CodeLocFromNode(node); - MD_String8 string = MD_S8Fmt(arena, "// location: %.*s:%i:%i\n", MD_S8VArg(loc.filename), (int)loc.line, (int)loc.column); - MD_S8ListPush(arena, out, string); + PrintIndent(indent); + CodeLoc loc = CodeLocFromNode(node); + String8 string = S8Fmt(arena, "// location: %.*s:%i:%i\n", S8VArg(loc.filename), (int)loc.line, (int)loc.column); + S8ListPush(arena, out, string); } //- rjf: name of node if(node->string.size != 0) { - MD_PrintIndent(indent); - if(node->kind == MD_NodeKind_File) + PrintIndent(indent); + if(node->kind == NodeKind_File) { - MD_S8ListPush(arena, out, MD_S8Lit("`")); - MD_S8ListPush(arena, out, node->string); - MD_S8ListPush(arena, out, MD_S8Lit("`")); + S8ListPush(arena, out, S8Lit("`")); + S8ListPush(arena, out, node->string); + S8ListPush(arena, out, S8Lit("`")); } else { - MD_S8ListPush(arena, out, node->raw_string); + S8ListPush(arena, out, node->raw_string); } } //- rjf: children list - if(flags & MD_GenerateFlag_Children && !MD_NodeIsNil(node->first_child)) + if(flags & GenerateFlag_Children && !NodeIsNil(node->first_child)) { if(node->string.size != 0) { - MD_S8ListPush(arena, out, MD_S8Lit(":\n")); + S8ListPush(arena, out, S8Lit(":\n")); } - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, MD_S8Lit("{\n")); - for(MD_EachNode(child, node->first_child)) + PrintIndent(indent); + S8ListPush(arena, out, S8Lit("{\n")); + for(EachNode(child, node->first_child)) { - MD_DebugDumpFromNode(arena, out, child, indent+1, indent_string, flags); - MD_S8ListPush(arena, out, MD_S8Lit(",\n")); + DebugDumpFromNode(arena, out, child, indent+1, indent_string, flags); + S8ListPush(arena, out, S8Lit(",\n")); } - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, MD_S8Lit("}")); + PrintIndent(indent); + S8ListPush(arena, out, S8Lit("}")); } //- rjf: next-comment - if(flags & MD_GenerateFlag_Comments && node->next_comment.size != 0) + if(flags & GenerateFlag_Comments && node->next_comment.size != 0) { - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, MD_S8Lit("\n/*\n")); - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, node->next_comment); - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, MD_S8Lit("\n")); - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, MD_S8Lit("*/\n")); + PrintIndent(indent); + S8ListPush(arena, out, S8Lit("\n/*\n")); + PrintIndent(indent); + S8ListPush(arena, out, node->next_comment); + PrintIndent(indent); + S8ListPush(arena, out, S8Lit("\n")); + PrintIndent(indent); + S8ListPush(arena, out, S8Lit("*/\n")); } -#undef MD_PrintIndent +#undef PrintIndent } -MD_FUNCTION void -MD_ReconstructionFromNode(MD_Arena *arena, MD_String8List *out, MD_Node *node, - int indent, MD_String8 indent_string) +FUNCTION void +ReconstructionFromNode(Arena *arena, String8List *out, Node *node, + int indent, String8 indent_string) { - MD_CodeLoc code_loc = MD_CodeLocFromNode(node); + CodeLoc code_loc = CodeLocFromNode(node); -#define MD_PrintIndent(_indent_level) do\ +#define PrintIndent(_indent_level) do\ {\ for(int i = 0; i < (_indent_level); i += 1)\ {\ -MD_S8ListPush(arena, out, indent_string);\ +S8ListPush(arena, out, indent_string);\ }\ }while(0) //- rjf: prev-comment if(node->prev_comment.size != 0) { - MD_String8 comment = MD_S8SkipWhitespace(MD_S8ChopWhitespace(node->prev_comment)); - MD_b32 requires_multiline = MD_S8FindSubstring(comment, MD_S8Lit("\n"), 0, 0) < comment.size; - MD_PrintIndent(indent); + String8 comment = S8SkipWhitespace(S8ChopWhitespace(node->prev_comment)); + b32 requires_multiline = S8FindSubstring(comment, S8Lit("\n"), 0, 0) < comment.size; + PrintIndent(indent); if(requires_multiline) { - MD_S8ListPush(arena, out, MD_S8Lit("/*\n")); + S8ListPush(arena, out, S8Lit("/*\n")); } else { - MD_S8ListPush(arena, out, MD_S8Lit("// ")); + S8ListPush(arena, out, S8Lit("// ")); } - MD_S8ListPush(arena, out, comment); + S8ListPush(arena, out, comment); if(requires_multiline) { - MD_S8ListPush(arena, out, MD_S8Lit("\n*/\n")); + S8ListPush(arena, out, S8Lit("\n*/\n")); } else { - MD_S8ListPush(arena, out, MD_S8Lit("\n")); + S8ListPush(arena, out, S8Lit("\n")); } } //- rjf: tags of node - MD_u32 tag_first_line = MD_CodeLocFromNode(node->first_tag).line; - MD_u32 tag_last_line = tag_first_line; + u32 tag_first_line = CodeLocFromNode(node->first_tag).line; + u32 tag_last_line = tag_first_line; { - for(MD_EachNode(tag, node->first_tag)) + for(EachNode(tag, node->first_tag)) { - MD_u32 tag_line = MD_CodeLocFromNode(tag).line; + u32 tag_line = CodeLocFromNode(tag).line; if(tag_line != tag_last_line) { - MD_S8ListPush(arena, out, MD_S8Lit("\n")); + S8ListPush(arena, out, S8Lit("\n")); tag_last_line = tag_line; } - else if(!MD_NodeIsNil(tag->prev)) + else if(!NodeIsNil(tag->prev)) { - MD_S8ListPush(arena, out, MD_S8Lit(" ")); + S8ListPush(arena, out, S8Lit(" ")); } - MD_PrintIndent(indent); - MD_S8ListPush(arena, out, MD_S8Lit("@")); - MD_S8ListPush(arena, out, tag->string); - if(!MD_NodeIsNil(tag->first_child)) + PrintIndent(indent); + S8ListPush(arena, out, S8Lit("@")); + S8ListPush(arena, out, tag->string); + if(!NodeIsNil(tag->first_child)) { int tag_arg_indent = indent + 1 + tag->string.size + 1; - MD_S8ListPush(arena, out, MD_S8Lit("(")); - MD_u32 last_line = MD_CodeLocFromNode(tag).line; - for(MD_EachNode(child, tag->first_child)) + S8ListPush(arena, out, S8Lit("(")); + u32 last_line = CodeLocFromNode(tag).line; + for(EachNode(child, tag->first_child)) { - MD_CodeLoc child_loc = MD_CodeLocFromNode(child); + CodeLoc child_loc = CodeLocFromNode(child); if(child_loc.line != last_line) { - MD_S8ListPush(arena, out, MD_S8Lit("\n")); - MD_PrintIndent(indent); + S8ListPush(arena, out, S8Lit("\n")); + PrintIndent(indent); } last_line = child_loc.line; int child_indent = tag_arg_indent; - if(MD_NodeIsNil(child->prev)) + if(NodeIsNil(child->prev)) { child_indent = 0; } - MD_ReconstructionFromNode(arena, out, child, child_indent, MD_S8Lit(" ")); - if(!MD_NodeIsNil(child->next)) + ReconstructionFromNode(arena, out, child, child_indent, S8Lit(" ")); + if(!NodeIsNil(child->next)) { - MD_S8ListPush(arena, out, MD_S8Lit(",\n")); + S8ListPush(arena, out, S8Lit(",\n")); } } - MD_S8ListPush(arena, out, MD_S8Lit(")")); + S8ListPush(arena, out, S8Lit(")")); } } } @@ -4035,47 +4035,47 @@ MD_S8ListPush(arena, out, indent_string);\ { if(tag_first_line != tag_last_line) { - MD_S8ListPush(arena, out, MD_S8Lit("\n")); - MD_PrintIndent(indent); + S8ListPush(arena, out, S8Lit("\n")); + PrintIndent(indent); } - else if(!MD_NodeIsNil(node->first_tag) || !MD_NodeIsNil(node->prev)) + else if(!NodeIsNil(node->first_tag) || !NodeIsNil(node->prev)) { - MD_S8ListPush(arena, out, MD_S8Lit(" ")); + S8ListPush(arena, out, S8Lit(" ")); } - if(node->kind == MD_NodeKind_File) + if(node->kind == NodeKind_File) { - MD_S8ListPush(arena, out, MD_S8Lit("`")); - MD_S8ListPush(arena, out, node->string); - MD_S8ListPush(arena, out, MD_S8Lit("`")); + S8ListPush(arena, out, S8Lit("`")); + S8ListPush(arena, out, node->string); + S8ListPush(arena, out, S8Lit("`")); } else { - MD_S8ListPush(arena, out, node->raw_string); + S8ListPush(arena, out, node->raw_string); } } //- rjf: children list - if(!MD_NodeIsNil(node->first_child)) + if(!NodeIsNil(node->first_child)) { if(node->string.size != 0) { - MD_S8ListPush(arena, out, MD_S8Lit(":")); + S8ListPush(arena, out, S8Lit(":")); } // rjf: figure out opener/closer symbols - MD_u8 opener_char = 0; - MD_u8 closer_char = 0; - if(node->flags & MD_NodeFlag_HasParenLeft) { opener_char = '('; } - else if(node->flags & MD_NodeFlag_HasBracketLeft) { opener_char = '['; } - else if(node->flags & MD_NodeFlag_HasBraceLeft) { opener_char = '{'; } - if(node->flags & MD_NodeFlag_HasParenRight) { closer_char = ')'; } - else if(node->flags & MD_NodeFlag_HasBracketRight){ closer_char = ']'; } - else if(node->flags & MD_NodeFlag_HasBraceRight) { closer_char = '}'; } + u8 opener_char = 0; + u8 closer_char = 0; + if(node->flags & NodeFlag_HasParenLeft) { opener_char = '('; } + else if(node->flags & NodeFlag_HasBracketLeft) { opener_char = '['; } + else if(node->flags & NodeFlag_HasBraceLeft) { opener_char = '{'; } + if(node->flags & NodeFlag_HasParenRight) { closer_char = ')'; } + else if(node->flags & NodeFlag_HasBracketRight){ closer_char = ']'; } + else if(node->flags & NodeFlag_HasBraceRight) { closer_char = '}'; } - MD_b32 multiline = 0; - for(MD_EachNode(child, node->first_child)) + b32 multiline = 0; + for(EachNode(child, node->first_child)) { - MD_CodeLoc child_loc = MD_CodeLocFromNode(child); + CodeLoc child_loc = CodeLocFromNode(child); if(child_loc.line != code_loc.line) { multiline = 1; @@ -4087,158 +4087,158 @@ MD_S8ListPush(arena, out, indent_string);\ { if(multiline) { - MD_S8ListPush(arena, out, MD_S8Lit("\n")); - MD_PrintIndent(indent); + S8ListPush(arena, out, S8Lit("\n")); + PrintIndent(indent); } else { - MD_S8ListPush(arena, out, MD_S8Lit(" ")); + S8ListPush(arena, out, S8Lit(" ")); } - MD_S8ListPush(arena, out, MD_S8(&opener_char, 1)); + S8ListPush(arena, out, S8(&opener_char, 1)); if(multiline) { - MD_S8ListPush(arena, out, MD_S8Lit("\n")); - MD_PrintIndent(indent+1); + S8ListPush(arena, out, S8Lit("\n")); + PrintIndent(indent+1); } } - MD_u32 last_line = MD_CodeLocFromNode(node->first_child).line; - for(MD_EachNode(child, node->first_child)) + u32 last_line = CodeLocFromNode(node->first_child).line; + for(EachNode(child, node->first_child)) { int child_indent = 0; - MD_CodeLoc child_loc = MD_CodeLocFromNode(child); + CodeLoc child_loc = CodeLocFromNode(child); if(child_loc.line != last_line) { - MD_S8ListPush(arena, out, MD_S8Lit("\n")); - MD_PrintIndent(indent); + S8ListPush(arena, out, S8Lit("\n")); + PrintIndent(indent); child_indent = indent+1; } last_line = child_loc.line; - MD_ReconstructionFromNode(arena, out, child, child_indent, indent_string); + ReconstructionFromNode(arena, out, child, child_indent, indent_string); } - MD_PrintIndent(indent); + PrintIndent(indent); if(closer_char != 0) { if(last_line != code_loc.line) { - MD_S8ListPush(arena, out, MD_S8Lit("\n")); - MD_PrintIndent(indent); + S8ListPush(arena, out, S8Lit("\n")); + PrintIndent(indent); } else { - MD_S8ListPush(arena, out, MD_S8Lit(" ")); + S8ListPush(arena, out, S8Lit(" ")); } - MD_S8ListPush(arena, out, MD_S8(&closer_char, 1)); + S8ListPush(arena, out, S8(&closer_char, 1)); } } //- rjf: trailing separator symbols - if(node->flags & MD_NodeFlag_IsBeforeSemicolon) + if(node->flags & NodeFlag_IsBeforeSemicolon) { - MD_S8ListPush(arena, out, MD_S8Lit(";")); + S8ListPush(arena, out, S8Lit(";")); } - else if(node->flags & MD_NodeFlag_IsBeforeComma) + else if(node->flags & NodeFlag_IsBeforeComma) { - MD_S8ListPush(arena, out, MD_S8Lit(",")); + S8ListPush(arena, out, S8Lit(",")); } //- rjf: next-comment // TODO(rjf): @node_comments if(node->next_comment.size != 0) { - MD_String8 comment = MD_S8SkipWhitespace(MD_S8ChopWhitespace(node->next_comment)); - MD_b32 requires_multiline = MD_S8FindSubstring(comment, MD_S8Lit("\n"), 0, 0) < comment.size; - MD_PrintIndent(indent); + String8 comment = S8SkipWhitespace(S8ChopWhitespace(node->next_comment)); + b32 requires_multiline = S8FindSubstring(comment, S8Lit("\n"), 0, 0) < comment.size; + PrintIndent(indent); if(requires_multiline) { - MD_S8ListPush(arena, out, MD_S8Lit("/*\n")); + S8ListPush(arena, out, S8Lit("/*\n")); } else { - MD_S8ListPush(arena, out, MD_S8Lit("// ")); + S8ListPush(arena, out, S8Lit("// ")); } - MD_S8ListPush(arena, out, comment); + S8ListPush(arena, out, comment); if(requires_multiline) { - MD_S8ListPush(arena, out, MD_S8Lit("\n*/\n")); + S8ListPush(arena, out, S8Lit("\n*/\n")); } else { - MD_S8ListPush(arena, out, MD_S8Lit("\n")); + S8ListPush(arena, out, S8Lit("\n")); } } -#undef MD_PrintIndent +#undef PrintIndent } -#if !MD_DISABLE_PRINT_HELPERS -MD_FUNCTION void -MD_PrintDebugDumpFromNode(FILE *file, MD_Node *node, MD_GenerateFlags flags) +#if !DISABLE_PRINT_HELPERS +FUNCTION void +PrintDebugDumpFromNode(FILE *file, Node *node, GenerateFlags flags) { - MD_ArenaTemp scratch = MD_GetScratch(0, 0); - MD_String8List list = {0}; - MD_DebugDumpFromNode(scratch.arena, &list, node, - 0, MD_S8Lit(" "), flags); - MD_String8 string = MD_S8ListJoin(scratch.arena, list, 0); + ArenaTemp scratch = GetScratch(0, 0); + String8List list = {0}; + DebugDumpFromNode(scratch.arena, &list, node, + 0, S8Lit(" "), flags); + String8 string = S8ListJoin(scratch.arena, list, 0); fwrite(string.str, string.size, 1, file); - MD_ReleaseScratch(scratch); + ReleaseScratch(scratch); } #endif //~ Command Line Argument Helper -MD_FUNCTION MD_String8List -MD_StringListFromArgCV(MD_Arena *arena, int argument_count, char **arguments) +FUNCTION String8List +StringListFromArgCV(Arena *arena, int argument_count, char **arguments) { - MD_String8List options = MD_ZERO_STRUCT; + String8List options = ZERO_STRUCT; for(int i = 1; i < argument_count; i += 1) { - MD_S8ListPush(arena, &options, MD_S8CString(arguments[i])); + S8ListPush(arena, &options, S8CString(arguments[i])); } return options; } -MD_FUNCTION MD_CmdLine -MD_MakeCmdLineFromOptions(MD_Arena *arena, MD_String8List options) +FUNCTION CmdLine +MakeCmdLineFromOptions(Arena *arena, String8List options) { - MD_CmdLine cmdln = MD_ZERO_STRUCT; - MD_b32 parsing_only_inputs = 0; + CmdLine cmdln = ZERO_STRUCT; + b32 parsing_only_inputs = 0; - for(MD_String8Node *n = options.first, *next = 0; + for(String8Node *n = options.first, *next = 0; n; n = next) { next = n->next; //- rjf: figure out whether or not this is an option by checking for `-` or `--` // from the beginning of the string - MD_String8 option_name = MD_ZERO_STRUCT; - if(MD_S8Match(n->string, MD_S8Lit("--"), 0)) + String8 option_name = ZERO_STRUCT; + if(S8Match(n->string, S8Lit("--"), 0)) { parsing_only_inputs = 1; } - else if(MD_S8Match(MD_S8Prefix(n->string, 2), MD_S8Lit("--"), 0)) + else if(S8Match(S8Prefix(n->string, 2), S8Lit("--"), 0)) { - option_name = MD_S8Skip(n->string, 2); + option_name = S8Skip(n->string, 2); } - else if(MD_S8Match(MD_S8Prefix(n->string, 1), MD_S8Lit("-"), 0)) + else if(S8Match(S8Prefix(n->string, 1), S8Lit("-"), 0)) { - option_name = MD_S8Skip(n->string, 1); + option_name = S8Skip(n->string, 1); } //- rjf: trim off anything after a `:` or `=`, use that as the first value string - MD_String8 first_value = MD_ZERO_STRUCT; - MD_b32 has_many_values = 0; + String8 first_value = ZERO_STRUCT; + b32 has_many_values = 0; if(option_name.size != 0) { - MD_u64 colon_signifier_pos = MD_S8FindSubstring(option_name, MD_S8Lit(":"), 0, 0); - MD_u64 equal_signifier_pos = MD_S8FindSubstring(option_name, MD_S8Lit("="), 0, 0); - MD_u64 signifier_pos = MD_Min(colon_signifier_pos, equal_signifier_pos); + u64 colon_signifier_pos = S8FindSubstring(option_name, S8Lit(":"), 0, 0); + u64 equal_signifier_pos = S8FindSubstring(option_name, S8Lit("="), 0, 0); + u64 signifier_pos = Min(colon_signifier_pos, equal_signifier_pos); if(signifier_pos < option_name.size) { - first_value = MD_S8Skip(option_name, signifier_pos+1); - option_name = MD_S8Prefix(option_name, signifier_pos); - if(MD_S8Match(MD_S8Suffix(first_value, 1), MD_S8Lit(","), 0)) + first_value = S8Skip(option_name, signifier_pos+1); + option_name = S8Prefix(option_name, signifier_pos); + if(S8Match(S8Suffix(first_value, 1), S8Lit(","), 0)) { has_many_values = 1; } @@ -4248,31 +4248,31 @@ MD_MakeCmdLineFromOptions(MD_Arena *arena, MD_String8List options) //- rjf: gather arguments if(option_name.size != 0 && !parsing_only_inputs) { - MD_String8List option_values = MD_ZERO_STRUCT; + String8List option_values = ZERO_STRUCT; //- rjf: push first value if(first_value.size != 0) { - MD_S8ListPush(arena, &option_values, first_value); + S8ListPush(arena, &option_values, first_value); } //- rjf: scan next string values, add them to option values until we hit a lack // of a ',' between values if(has_many_values) { - for(MD_String8Node *v = next; v; v = v->next, next = v) + for(String8Node *v = next; v; v = v->next, next = v) { - MD_String8 value_str = v->string; - MD_b32 next_has_arguments = MD_S8Match(MD_S8Suffix(value_str, 1), MD_S8Lit(","), 0); - MD_b32 in_quotes = 0; - MD_u64 start = 0; - for(MD_u64 i = 0; i <= value_str.size; i += 1) + String8 value_str = v->string; + b32 next_has_arguments = S8Match(S8Suffix(value_str, 1), S8Lit(","), 0); + b32 in_quotes = 0; + u64 start = 0; + for(u64 i = 0; i <= value_str.size; i += 1) { if(i == value_str.size || (value_str.str[i] == ',' && in_quotes == 0)) { if(start != i) { - MD_S8ListPush(arena, &option_values, MD_S8Substring(value_str, start, i)); + S8ListPush(arena, &option_values, S8Substring(value_str, start, i)); } start = i+1; } @@ -4290,7 +4290,7 @@ MD_MakeCmdLineFromOptions(MD_Arena *arena, MD_String8List options) //- rjf: insert the fully parsed option { - MD_CmdLineOption *opt = MD_PushArrayZero(arena, MD_CmdLineOption, 1); + CmdLineOption *opt = PushArrayZero(arena, CmdLineOption, 1); opt->name = option_name; opt->values = option_values; if(cmdln.last_option == 0) @@ -4308,20 +4308,20 @@ MD_MakeCmdLineFromOptions(MD_Arena *arena, MD_String8List options) //- rjf: this argument is not an option, push it to regular inputs list. else { - MD_S8ListPush(arena, &cmdln.inputs, n->string); + S8ListPush(arena, &cmdln.inputs, n->string); } } return cmdln; } -MD_FUNCTION MD_String8List -MD_CmdLineValuesFromString(MD_CmdLine cmdln, MD_String8 name) +FUNCTION String8List +CmdLineValuesFromString(CmdLine cmdln, String8 name) { - MD_String8List values = MD_ZERO_STRUCT; - for(MD_CmdLineOption *opt = cmdln.first_option; opt; opt = opt->next) + String8List values = ZERO_STRUCT; + for(CmdLineOption *opt = cmdln.first_option; opt; opt = opt->next) { - if(MD_S8Match(opt->name, name, 0)) + if(S8Match(opt->name, name, 0)) { values = opt->values; break; @@ -4330,13 +4330,13 @@ MD_CmdLineValuesFromString(MD_CmdLine cmdln, MD_String8 name) return values; } -MD_FUNCTION MD_b32 -MD_CmdLineB32FromString(MD_CmdLine cmdln, MD_String8 name) +FUNCTION b32 +CmdLineB32FromString(CmdLine cmdln, String8 name) { - MD_b32 result = 0; - for(MD_CmdLineOption *opt = cmdln.first_option; opt; opt = opt->next) + b32 result = 0; + for(CmdLineOption *opt = cmdln.first_option; opt; opt = opt->next) { - if(MD_S8Match(opt->name, name, 0)) + if(S8Match(opt->name, name, 0)) { result = 1; break; @@ -4345,59 +4345,59 @@ MD_CmdLineB32FromString(MD_CmdLine cmdln, MD_String8 name) return result; } -MD_FUNCTION MD_i64 -MD_CmdLineI64FromString(MD_CmdLine cmdln, MD_String8 name) +FUNCTION i64 +CmdLineI64FromString(CmdLine cmdln, String8 name) { - MD_String8List values = MD_CmdLineValuesFromString(cmdln, name); - MD_ArenaTemp scratch = MD_GetScratch(0, 0); - MD_String8 value_str = MD_S8ListJoin(scratch.arena, values, 0); - MD_i64 result = MD_CStyleIntFromString(value_str); - MD_ReleaseScratch(scratch); + String8List values = CmdLineValuesFromString(cmdln, name); + ArenaTemp scratch = GetScratch(0, 0); + String8 value_str = S8ListJoin(scratch.arena, values, 0); + i64 result = CStyleIntFromString(value_str); + ReleaseScratch(scratch); return(result); } //~ File System -MD_FUNCTION MD_String8 -MD_LoadEntireFile(MD_Arena *arena, MD_String8 filename) +FUNCTION String8 +LoadEntireFile(Arena *arena, String8 filename) { - MD_String8 result = MD_ZERO_STRUCT; -#if defined(MD_IMPL_LoadEntireFile) - result = MD_IMPL_LoadEntireFile(arena, filename); + String8 result = ZERO_STRUCT; +#if defined(IMPL_LoadEntireFile) + result = IMPL_LoadEntireFile(arena, filename); #endif return(result); } -MD_FUNCTION MD_b32 -MD_FileIterBegin(MD_FileIter *it, MD_String8 path) +FUNCTION b32 +FileIterBegin(FileIter *it, String8 path) { -#if !defined(MD_IMPL_FileIterBegin) +#if !defined(IMPL_FileIterBegin) return(0); #else - return(MD_IMPL_FileIterBegin(it, path)); + return(IMPL_FileIterBegin(it, path)); #endif } -MD_FUNCTION MD_FileInfo -MD_FileIterNext(MD_Arena *arena, MD_FileIter *it) +FUNCTION FileInfo +FileIterNext(Arena *arena, FileIter *it) { -#if !defined(MD_IMPL_FileIterNext) - MD_FileInfo result = {0}; +#if !defined(IMPL_FileIterNext) + FileInfo result = {0}; return(result); #else - return(MD_IMPL_FileIterNext(arena, it)); + return(IMPL_FileIterNext(arena, it)); #endif } -MD_FUNCTION void -MD_FileIterEnd(MD_FileIter *it) +FUNCTION void +FileIterEnd(FileIter *it) { -#if defined(MD_IMPL_FileIterEnd) - MD_IMPL_FileIterEnd(it); +#if defined(IMPL_FileIterEnd) + IMPL_FileIterEnd(it); #endif } -#endif // MD_C +#endif // C /* Copyright 2021 Dion Systems LLC diff --git a/thirdparty/md.h b/thirdparty/md.h index 0a41691..24882b1 100644 --- a/thirdparty/md.h +++ b/thirdparty/md.h @@ -52,37 +52,37 @@ #ifndef MD_H #define MD_H -#define MD_VERSION_MAJ 1 -#define MD_VERSION_MIN 0 +#define VERSION_MAJ 1 +#define VERSION_MIN 0 //~ Set default values for controls -#if !defined(MD_DEFAULT_BASIC_TYPES) -# define MD_DEFAULT_BASIC_TYPES 1 +#if !defined(DEFAULT_BASIC_TYPES) +# define DEFAULT_BASIC_TYPES 1 #endif -#if !defined(MD_DEFAULT_MEMSET) -# define MD_DEFAULT_MEMSET 1 +#if !defined(DEFAULT_MEMSET) +# define DEFAULT_MEMSET 1 #endif -#if !defined(MD_DEFAULT_FILE_LOAD) -# define MD_DEFAULT_FILE_LOAD 1 +#if !defined(DEFAULT_FILE_LOAD) +# define DEFAULT_FILE_LOAD 1 #endif -#if !defined(MD_DEFAULT_FILE_ITER) -# define MD_DEFAULT_FILE_ITER 1 +#if !defined(DEFAULT_FILE_ITER) +# define DEFAULT_FILE_ITER 1 #endif -#if !defined(MD_DEFAULT_MEMORY) -# define MD_DEFAULT_MEMORY 1 +#if !defined(DEFAULT_MEMORY) +# define DEFAULT_MEMORY 1 #endif -#if !defined(MD_DEFAULT_ARENA) -# define MD_DEFAULT_ARENA 1 +#if !defined(DEFAULT_ARENA) +# define DEFAULT_ARENA 1 #endif -#if !defined(MD_DEFAULT_SCRATCH) -# define MD_DEFAULT_SCRATCH 1 +#if !defined(DEFAULT_SCRATCH) +# define DEFAULT_SCRATCH 1 #endif -#if !defined(MD_DEFAULT_SPRINTF) -# define MD_DEFAULT_SPRINTF 1 +#if !defined(DEFAULT_SPRINTF) +# define DEFAULT_SPRINTF 1 #endif -#if !defined(MD_DISABLE_PRINT_HELPERS) -# define MD_DISABLE_PRINT_HELPERS 0 +#if !defined(DISABLE_PRINT_HELPERS) +# define DISABLE_PRINT_HELPERS 0 #endif @@ -92,90 +92,90 @@ #if defined(__clang__) -# define MD_COMPILER_CLANG 1 +# define COMPILER_CLANG 1 # if defined(__APPLE__) && defined(__MACH__) -# define MD_OS_MAC 1 +# define OS_MAC 1 # elif defined(__gnu_linux__) -# define MD_OS_LINUX 1 +# define OS_LINUX 1 # elif defined(_WIN32) -# define MD_OS_WINDOWS 1 +# define OS_WINDOWS 1 # else # error This compiler/platform combo is not supported yet # endif # if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) -# define MD_ARCH_X64 1 +# define ARCH_X64 1 # elif defined(i386) || defined(__i386) || defined(__i386__) -# define MD_ARCH_X86 1 +# define ARCH_X86 1 # elif defined(__aarch64__) -# define MD_ARCH_ARM64 1 +# define ARCH_ARM64 1 # elif defined(__arm__) -# define MD_ARCH_ARM32 1 +# define ARCH_ARM32 1 # else # error architecture not supported yet # endif #elif defined(_MSC_VER) -# define MD_COMPILER_CL 1 +# define COMPILER_CL 1 # if defined(_WIN32) -# define MD_OS_WINDOWS 1 +# define OS_WINDOWS 1 # else # error This compiler/platform combo is not supported yet # endif # if defined(_M_AMD64) -# define MD_ARCH_X64 1 +# define ARCH_X64 1 # elif defined(_M_IX86) -# define MD_ARCH_X86 1 +# define ARCH_X86 1 # elif defined(_M_ARM64) -# define MD_ARCH_ARM64 1 +# define ARCH_ARM64 1 # elif defined(_M_ARM) -# define MD_ARCH_ARM32 1 +# define ARCH_ARM32 1 # else # error architecture not supported yet # endif # if _MSC_VER >= 1920 -# define MD_COMPILER_CL_YEAR 2019 +# define COMPILER_CL_YEAR 2019 # elif _MSC_VER >= 1910 -# define MD_COMPILER_CL_YEAR 2017 +# define COMPILER_CL_YEAR 2017 # elif _MSC_VER >= 1900 -# define MD_COMPILER_CL_YEAR 2015 +# define COMPILER_CL_YEAR 2015 # elif _MSC_VER >= 1800 -# define MD_COMPILER_CL_YEAR 2013 +# define COMPILER_CL_YEAR 2013 # elif _MSC_VER >= 1700 -# define MD_COMPILER_CL_YEAR 2012 +# define COMPILER_CL_YEAR 2012 # elif _MSC_VER >= 1600 -# define MD_COMPILER_CL_YEAR 2010 +# define COMPILER_CL_YEAR 2010 # elif _MSC_VER >= 1500 -# define MD_COMPILER_CL_YEAR 2008 +# define COMPILER_CL_YEAR 2008 # elif _MSC_VER >= 1400 -# define MD_COMPILER_CL_YEAR 2005 +# define COMPILER_CL_YEAR 2005 # else -# define MD_COMPILER_CL_YEAR 0 +# define COMPILER_CL_YEAR 0 # endif #elif defined(__GNUC__) || defined(__GNUG__) -# define MD_COMPILER_GCC 1 +# define COMPILER_GCC 1 # if defined(__gnu_linux__) -# define MD_OS_LINUX 1 +# define OS_LINUX 1 # else # error This compiler/platform combo is not supported yet # endif # if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) -# define MD_ARCH_X64 1 +# define ARCH_X64 1 # elif defined(i386) || defined(__i386) || defined(__i386__) -# define MD_ARCH_X86 1 +# define ARCH_X86 1 # elif defined(__aarch64__) -# define MD_ARCH_ARM64 1 +# define ARCH_ARM64 1 # elif defined(__arm__) -# define MD_ARCH_ARM32 1 +# define ARCH_ARM32 1 # else # error architecture not supported yet # endif @@ -184,133 +184,133 @@ # error This compiler is not supported yet #endif -#if defined(MD_ARCH_X64) -# define MD_ARCH_64BIT 1 -#elif defined(MD_ARCH_X86) -# define MD_ARCH_32BIT 1 +#if defined(ARCH_X64) +# define ARCH_64BIT 1 +#elif defined(ARCH_X86) +# define ARCH_32BIT 1 #endif #if defined(__cplusplus) -# define MD_LANG_CPP 1 +# define LANG_CPP 1 // We can't get this 100% correct thanks to Microsoft's compiler. -// So this check lets us pre-define MD_CPP_VERSION if we have to. -# if !defined(MD_CPP_VERSION) -# if defined(MD_COMPILER_CL) +// So this check lets us pre-define CPP_VERSION if we have to. +# if !defined(CPP_VERSION) +# if defined(COMPILER_CL) // CL is annoying and didn't update __cplusplus over time // If it is available _MSVC_LANG serves the same role # if defined(_MSVC_LANG) # if _MSVC_LANG <= 199711L -# define MD_CPP_VERSION 98 +# define CPP_VERSION 98 # elif _MSVC_LANG <= 201103L -# define MD_CPP_VERSION 11 +# define CPP_VERSION 11 # elif _MSVC_LANG <= 201402L -# define MD_CPP_VERSION 14 +# define CPP_VERSION 14 # elif _MSVC_LANG <= 201703L -# define MD_CPP_VERSION 17 +# define CPP_VERSION 17 # elif _MSVC_LANG <= 202002L -# define MD_CPP_VERSION 20 +# define CPP_VERSION 20 # else -# define MD_CPP_VERSION 23 +# define CPP_VERSION 23 # endif // If we don't have _MSVC_LANG we can guess from the compiler version # else -# if MD_COMPILER_CL_YEAR <= 2010 -# define MD_CPP_VERSION 98 -# elif MD_COMPILER_CL_YEAR <= 2015 -# define MD_CPP_VERSION 11 +# if COMPILER_CL_YEAR <= 2010 +# define CPP_VERSION 98 +# elif COMPILER_CL_YEAR <= 2015 +# define CPP_VERSION 11 # else -# define MD_CPP_VERSION 17 +# define CPP_VERSION 17 # endif # endif # else // Other compilers use __cplusplus correctly # if __cplusplus <= 199711L -# define MD_CPP_VERSION 98 +# define CPP_VERSION 98 # elif __cplusplus <= 201103L -# define MD_CPP_VERSION 11 +# define CPP_VERSION 11 # elif __cplusplus <= 201402L -# define MD_CPP_VERSION 14 +# define CPP_VERSION 14 # elif __cplusplus <= 201703L -# define MD_CPP_VERSION 17 +# define CPP_VERSION 17 # elif __cplusplus <= 202002L -# define MD_CPP_VERSION 20 +# define CPP_VERSION 20 # else -# define MD_CPP_VERSION 23 +# define CPP_VERSION 23 # endif # endif # endif #else -# define MD_LANG_C 1 +# define LANG_C 1 #endif // zeroify -#if !defined(MD_ARCH_32BIT) -# define MD_ARCH_32BIT 0 +#if !defined(ARCH_32BIT) +# define ARCH_32BIT 0 #endif -#if !defined(MD_ARCH_64BIT) -# define MD_ARCH_64BIT 0 +#if !defined(ARCH_64BIT) +# define ARCH_64BIT 0 #endif -#if !defined(MD_ARCH_X64) -# define MD_ARCH_X64 0 +#if !defined(ARCH_X64) +# define ARCH_X64 0 #endif -#if !defined(MD_ARCH_X86) -# define MD_ARCH_X86 0 +#if !defined(ARCH_X86) +# define ARCH_X86 0 #endif -#if !defined(MD_ARCH_ARM64) -# define MD_ARCH_ARM64 0 +#if !defined(ARCH_ARM64) +# define ARCH_ARM64 0 #endif -#if !defined(MD_ARCH_ARM32) -# define MD_ARCH_ARM32 0 +#if !defined(ARCH_ARM32) +# define ARCH_ARM32 0 #endif -#if !defined(MD_COMPILER_CL) -# define MD_COMPILER_CL 0 +#if !defined(COMPILER_CL) +# define COMPILER_CL 0 #endif -#if !defined(MD_COMPILER_GCC) -# define MD_COMPILER_GCC 0 +#if !defined(COMPILER_GCC) +# define COMPILER_GCC 0 #endif -#if !defined(MD_COMPILER_CLANG) -# define MD_COMPILER_CLANG 0 +#if !defined(COMPILER_CLANG) +# define COMPILER_CLANG 0 #endif -#if !defined(MD_OS_WINDOWS) -# define MD_OS_WINDOWS 0 +#if !defined(OS_WINDOWS) +# define OS_WINDOWS 0 #endif -#if !defined(MD_OS_LINUX) -# define MD_OS_LINUX 0 +#if !defined(OS_LINUX) +# define OS_LINUX 0 #endif -#if !defined(MD_OS_MAC) -# define MD_OS_MAC 0 +#if !defined(OS_MAC) +# define OS_MAC 0 #endif -#if !defined(MD_LANG_C) -# define MD_LANG_C 0 +#if !defined(LANG_C) +# define LANG_C 0 #endif -#if !defined(MD_LANG_CPP) -# define MD_LANG_CPP 0 +#if !defined(LANG_CPP) +# define LANG_CPP 0 #endif -#if !defined(MD_CPP_VERSION) -# define MD_CPP_VERSION 0 +#if !defined(CPP_VERSION) +# define CPP_VERSION 0 #endif -#if MD_LANG_CPP -# define MD_ZERO_STRUCT {} +#if LANG_CPP +# define ZERO_STRUCT {} #else -# define MD_ZERO_STRUCT {0} +# define ZERO_STRUCT {0} #endif -#if MD_LANG_C -# define MD_C_LINKAGE_BEGIN -# define MD_C_LINKAGE_END +#if LANG_C +# define C_LINKAGE_BEGIN +# define C_LINKAGE_END #else -# define MD_C_LINKAGE_BEGIN extern "C"{ -# define MD_C_LINKAGE_END } +# define C_LINKAGE_BEGIN extern "C"{ +# define C_LINKAGE_END } #endif -#if MD_COMPILER_CL -# define MD_THREAD_LOCAL __declspec(thread) -#elif MD_COMPILER_GCC || MD_COMPILER_CLANG -# define MD_THREAD_LOCAL __thread +#if COMPILER_CL +# define THREAD_LOCAL __declspec(thread) +#elif COMPILER_GCC || COMPILER_CLANG +# define THREAD_LOCAL __thread #endif //~///////////////////////////////////////////////////////////////////////////// @@ -319,50 +319,50 @@ //~ Linkage Wrappers -#if !defined(MD_FUNCTION) -# define MD_FUNCTION +#if !defined(FUNCTION) +# define FUNCTION #endif -#if !defined(MD_GLOBAL) -# define MD_GLOBAL static +#if !defined(GLOBAL) +# define GLOBAL static #endif //~ Basic Utilities -#define MD_Assert(c) if (!(c)) { *(volatile MD_u64 *)0 = 0; } -#define MD_StaticAssert(c,label) MD_u8 MD_static_assert_##label[(c)?(1):(-1)] -#define MD_ArrayCount(a) (sizeof(a) / sizeof((a)[0])) +#define Assert(c) if (!(c)) { *(volatile u64 *)0 = 0; } +#define StaticAssert(c,label) u8 static_assert_##label[(c)?(1):(-1)] +#define ArrayCount(a) (sizeof(a) / sizeof((a)[0])) -#define MD_Min(a,b) (((a)<(b))?(a):(b)) -#define MD_Max(a,b) (((a)>(b))?(a):(b)) -#define MD_ClampBot(a,b) MD_Max(a,b) -#define MD_ClampTop(a,b) MD_Min(a,b) +#define Min(a,b) (((a)<(b))?(a):(b)) +#define Max(a,b) (((a)>(b))?(a):(b)) +#define ClampBot(a,b) Max(a,b) +#define ClampTop(a,b) Min(a,b) -#define MD_AlignPow2(x,b) (((x)+((b)-1))&(~((b)-1))) +#define AlignPow2(x,b) (((x)+((b)-1))&(~((b)-1))) //~ Linked List Macros // terminator modes -#define MD_CheckNull(p) ((p)==0) -#define MD_SetNull(p) ((p)=0) -#define MD_CheckNil(p) (MD_NodeIsNil(p)) -#define MD_SetNil(p) ((p)=MD_NilNode()) +#define CheckNull(p) ((p)==0) +#define SetNull(p) ((p)=0) +#define CheckNil(p) (NodeIsNil(p)) +#define SetNil(p) ((p)=NilNode()) // implementations -#define MD_QueuePush_NZ(f,l,n,next,zchk,zset) (zchk(f)?\ +#define QueuePush_NZ(f,l,n,next,zchk,zset) (zchk(f)?\ (f)=(l)=(n):\ ((l)->next=(n),(l)=(n),zset((n)->next))) -#define MD_QueuePop_NZ(f,l,next,zset) ((f)==(l)?\ +#define QueuePop_NZ(f,l,next,zset) ((f)==(l)?\ (zset(f),zset(l)):\ ((f)=(f)->next)) -#define MD_StackPush_N(f,n,next) ((n)->next=(f),(f)=(n)) -#define MD_StackPop_NZ(f,next,zchk) (zchk(f)?0:((f)=(f)->next)) +#define StackPush_N(f,n,next) ((n)->next=(f),(f)=(n)) +#define StackPop_NZ(f,next,zchk) (zchk(f)?0:((f)=(f)->next)) -#define MD_DblPushBack_NPZ(f,l,n,next,prev,zchk,zset) \ +#define DblPushBack_NPZ(f,l,n,next,prev,zchk,zset) \ (zchk(f)?\ ((f)=(l)=(n),zset((n)->next),zset((n)->prev)):\ ((n)->prev=(l),(l)->next=(n),(l)=(n),zset((n)->next))) -#define MD_DblRemove_NPZ(f,l,n,next,prev,zchk,zset) (((f)==(n))?\ +#define DblRemove_NPZ(f,l,n,next,prev,zchk,zset) (((f)==(n))?\ ((f)=(f)->next, (zchk(f) ? (zset(l)) : zset((f)->prev))):\ ((l)==(n))?\ ((l)=(l)->prev, (zchk(l) ? (zset(f)) : zset((l)->next))):\ @@ -371,30 +371,30 @@ // compositions -#define MD_QueuePush(f,l,n) MD_QueuePush_NZ(f,l,n,next,MD_CheckNull,MD_SetNull) -#define MD_QueuePop(f,l) MD_QueuePop_NZ(f,l,next,MD_SetNull) -#define MD_StackPush(f,n) MD_StackPush_N(f,n,next) -#define MD_StackPop(f) MD_StackPop_NZ(f,next,MD_CheckNull) -#define MD_DblPushBack(f,l,n) MD_DblPushBack_NPZ(f,l,n,next,prev,MD_CheckNull,MD_SetNull) -#define MD_DblPushFront(f,l,n) MD_DblPushBack_NPZ(l,f,n,prev,next,MD_CheckNull,MD_SetNull) -#define MD_DblRemove(f,l,n) MD_DblRemove_NPZ(f,l,n,next,prev,MD_CheckNull,MD_SetNull) +#define QueuePush(f,l,n) QueuePush_NZ(f,l,n,next,CheckNull,SetNull) +#define QueuePop(f,l) QueuePop_NZ(f,l,next,SetNull) +#define StackPush(f,n) StackPush_N(f,n,next) +#define StackPop(f) StackPop_NZ(f,next,CheckNull) +#define DblPushBack(f,l,n) DblPushBack_NPZ(f,l,n,next,prev,CheckNull,SetNull) +#define DblPushFront(f,l,n) DblPushBack_NPZ(l,f,n,prev,next,CheckNull,SetNull) +#define DblRemove(f,l,n) DblRemove_NPZ(f,l,n,next,prev,CheckNull,SetNull) -#define MD_NodeDblPushBack(f,l,n) MD_DblPushBack_NPZ(f,l,n,next,prev,MD_CheckNil,MD_SetNil) -#define MD_NodeDblPushFront(f,l,n) MD_DblPushBack_NPZ(l,f,n,prev,next,MD_CheckNil,MD_SetNil) -#define MD_NodeDblRemove(f,l,n) MD_DblRemove_NPZ(f,l,n,next,prev,MD_CheckNil,MD_SetNil) +#define NodeDblPushBack(f,l,n) DblPushBack_NPZ(f,l,n,next,prev,CheckNil,SetNil) +#define NodeDblPushFront(f,l,n) DblPushBack_NPZ(l,f,n,prev,next,CheckNil,SetNil) +#define NodeDblRemove(f,l,n) DblRemove_NPZ(f,l,n,next,prev,CheckNil,SetNil) //~ Memory Operations -#define MD_MemorySet(p,v,z) (MD_IMPL_Memset(p,v,z)) -#define MD_MemoryZero(p,z) (MD_IMPL_Memset(p,0,z)) -#define MD_MemoryZeroStruct(p) (MD_IMPL_Memset(p,0,sizeof(*(p)))) -#define MD_MemoryCopy(d,s,z) (MD_IMPL_Memmove(d,s,z)) +#define MemorySet(p,v,z) (IMPL_Memset(p,v,z)) +#define MemoryZero(p,z) (IMPL_Memset(p,0,z)) +#define MemoryZeroStruct(p) (IMPL_Memset(p,0,sizeof(*(p)))) +#define MemoryCopy(d,s,z) (IMPL_Memmove(d,s,z)) //~ sprintf -#if MD_DEFAULT_SPRINTF +#if DEFAULT_SPRINTF #define STB_SPRINTF_DECORATE(name) md_stbsp_##name -#define MD_IMPL_Vsnprintf md_stbsp_vsnprintf +#define IMPL_Vsnprintf md_stbsp_vsnprintf #include "md_stb_sprintf.h" #endif @@ -406,520 +406,520 @@ #include -#if defined(MD_DEFAULT_BASIC_TYPES) +#if defined(DEFAULT_BASIC_TYPES) #include -typedef int8_t MD_i8; -typedef int16_t MD_i16; -typedef int32_t MD_i32; -typedef int64_t MD_i64; -typedef uint8_t MD_u8; -typedef uint16_t MD_u16; -typedef uint32_t MD_u32; -typedef uint64_t MD_u64; -typedef float MD_f32; -typedef double MD_f64; +typedef int8_t i8; +typedef int16_t i16; +typedef int32_t i32; +typedef int64_t i64; +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; +typedef uint64_t u64; +typedef float f32; +typedef double f64; #endif -typedef MD_i8 MD_b8; -typedef MD_i16 MD_b16; -typedef MD_i32 MD_b32; -typedef MD_i64 MD_b64; +typedef i8 b8; +typedef i16 b16; +typedef i32 b32; +typedef i64 b64; //~ Default Arena -#if MD_DEFAULT_ARENA +#if DEFAULT_ARENA -typedef struct MD_ArenaDefault MD_ArenaDefault; -struct MD_ArenaDefault +typedef struct ArenaDefault ArenaDefault; +struct ArenaDefault { - MD_ArenaDefault *prev; - MD_ArenaDefault *current; - MD_u64 base_pos; - MD_u64 pos; - MD_u64 cmt; - MD_u64 cap; - MD_u64 align; + ArenaDefault *prev; + ArenaDefault *current; + u64 base_pos; + u64 pos; + u64 cmt; + u64 cap; + u64 align; }; -#define MD_IMPL_Arena MD_ArenaDefault +#define IMPL_Arena ArenaDefault #endif //~ Abstract Arena -#if !defined(MD_IMPL_Arena) -# error Missing implementation for MD_IMPL_Arena +#if !defined(IMPL_Arena) +# error Missing implementation for IMPL_Arena #endif -typedef MD_IMPL_Arena MD_Arena; +typedef IMPL_Arena Arena; //~ Arena Helpers -typedef struct MD_ArenaTemp MD_ArenaTemp; -struct MD_ArenaTemp +typedef struct ArenaTemp ArenaTemp; +struct ArenaTemp { - MD_Arena *arena; - MD_u64 pos; + Arena *arena; + u64 pos; }; //~ Basic Unicode string types. -typedef struct MD_String8 MD_String8; -struct MD_String8 +typedef struct String8 String8; +struct String8 { - MD_u8 *str; - MD_u64 size; + u8 *str; + u64 size; }; -typedef struct MD_String16 MD_String16; -struct MD_String16 +typedef struct String16 String16; +struct String16 { - MD_u16 *str; - MD_u64 size; + u16 *str; + u64 size; }; -typedef struct MD_String32 MD_String32; -struct MD_String32 +typedef struct String32 String32; +struct String32 { - MD_u32 *str; - MD_u64 size; + u32 *str; + u64 size; }; -typedef struct MD_String8Node MD_String8Node; -struct MD_String8Node +typedef struct String8Node String8Node; +struct String8Node { - MD_String8Node *next; - MD_String8 string; + String8Node *next; + String8 string; }; -typedef struct MD_String8List MD_String8List; -struct MD_String8List +typedef struct String8List String8List; +struct String8List { - MD_u64 node_count; - MD_u64 total_size; - MD_String8Node *first; - MD_String8Node *last; + u64 node_count; + u64 total_size; + String8Node *first; + String8Node *last; }; -typedef struct MD_StringJoin MD_StringJoin; -struct MD_StringJoin +typedef struct StringJoin StringJoin; +struct StringJoin { - MD_String8 pre; - MD_String8 mid; - MD_String8 post; + String8 pre; + String8 mid; + String8 post; }; // NOTE(rjf): @maintenance These three flag types must not overlap. -typedef MD_u32 MD_MatchFlags; -typedef MD_u32 MD_StringMatchFlags; -typedef MD_u32 MD_NodeMatchFlags; +typedef u32 MatchFlags; +typedef u32 StringMatchFlags; +typedef u32 NodeMatchFlags; enum { - MD_MatchFlag_FindLast = (1<<0), + MatchFlag_FindLast = (1<<0), }; enum { - MD_StringMatchFlag_CaseInsensitive = (1<<4), - MD_StringMatchFlag_RightSideSloppy = (1<<5), - MD_StringMatchFlag_SlashInsensitive = (1<<6), + StringMatchFlag_CaseInsensitive = (1<<4), + StringMatchFlag_RightSideSloppy = (1<<5), + StringMatchFlag_SlashInsensitive = (1<<6), }; enum { - MD_NodeMatchFlag_Tags = (1<<16), - MD_NodeMatchFlag_TagArguments = (1<<17), - MD_NodeMatchFlag_NodeFlags = (1<<18), + NodeMatchFlag_Tags = (1<<16), + NodeMatchFlag_TagArguments = (1<<17), + NodeMatchFlag_NodeFlags = (1<<18), }; -typedef struct MD_DecodedCodepoint MD_DecodedCodepoint; -struct MD_DecodedCodepoint +typedef struct DecodedCodepoint DecodedCodepoint; +struct DecodedCodepoint { - MD_u32 codepoint; - MD_u32 advance; + u32 codepoint; + u32 advance; }; -typedef enum MD_IdentifierStyle +typedef enum IdentifierStyle { - MD_IdentifierStyle_UpperCamelCase, - MD_IdentifierStyle_LowerCamelCase, - MD_IdentifierStyle_UpperCase, - MD_IdentifierStyle_LowerCase, + IdentifierStyle_UpperCamelCase, + IdentifierStyle_LowerCamelCase, + IdentifierStyle_UpperCase, + IdentifierStyle_LowerCase, } -MD_IdentifierStyle; +IdentifierStyle; //~ Node types that are used to build all ASTs. -typedef enum MD_NodeKind +typedef enum NodeKind { - // NOTE(rjf): @maintenance Must be kept in sync with MD_StringFromNodeKind. + // NOTE(rjf): @maintenance Must be kept in sync with StringFromNodeKind. - MD_NodeKind_Nil, + NodeKind_Nil, // NOTE(rjf): Generated by parser - MD_NodeKind_File, - MD_NodeKind_ErrorMarker, + NodeKind_File, + NodeKind_ErrorMarker, // NOTE(rjf): Parsed from user Metadesk code - MD_NodeKind_Main, - MD_NodeKind_Tag, + NodeKind_Main, + NodeKind_Tag, // NOTE(rjf): User-created data structures - MD_NodeKind_List, - MD_NodeKind_Reference, + NodeKind_List, + NodeKind_Reference, - MD_NodeKind_COUNT, + NodeKind_COUNT, } -MD_NodeKind; +NodeKind; -typedef MD_u64 MD_NodeFlags; -#define MD_NodeFlag_AfterFromBefore(f) ((f) << 1) +typedef u64 NodeFlags; +#define NodeFlag_AfterFromBefore(f) ((f) << 1) enum { - // NOTE(rjf): @maintenance Must be kept in sync with MD_StringListFromNodeFlags. + // NOTE(rjf): @maintenance Must be kept in sync with StringListFromNodeFlags. - // NOTE(rjf): @maintenance Because of MD_NodeFlag_AfterFromBefore, it is + // NOTE(rjf): @maintenance Because of NodeFlag_AfterFromBefore, it is // *required* that every single pair of "Before*" or "After*" flags be in // the correct order which is that the Before* flag comes first, and the // After* flag comes immediately after (After* being the more significant // bit). - MD_NodeFlag_HasParenLeft = (1<<0), - MD_NodeFlag_HasParenRight = (1<<1), - MD_NodeFlag_HasBracketLeft = (1<<2), - MD_NodeFlag_HasBracketRight = (1<<3), - MD_NodeFlag_HasBraceLeft = (1<<4), - MD_NodeFlag_HasBraceRight = (1<<5), + NodeFlag_HasParenLeft = (1<<0), + NodeFlag_HasParenRight = (1<<1), + NodeFlag_HasBracketLeft = (1<<2), + NodeFlag_HasBracketRight = (1<<3), + NodeFlag_HasBraceLeft = (1<<4), + NodeFlag_HasBraceRight = (1<<5), - MD_NodeFlag_MaskSetDelimiters = (0x3F<<0), + NodeFlag_MaskSetDelimiters = (0x3F<<0), - MD_NodeFlag_IsBeforeSemicolon = (1<<6), - MD_NodeFlag_IsAfterSemicolon = (1<<7), - MD_NodeFlag_IsBeforeComma = (1<<8), - MD_NodeFlag_IsAfterComma = (1<<9), + NodeFlag_IsBeforeSemicolon = (1<<6), + NodeFlag_IsAfterSemicolon = (1<<7), + NodeFlag_IsBeforeComma = (1<<8), + NodeFlag_IsAfterComma = (1<<9), - MD_NodeFlag_MaskSeperators = (0xF<<6), + NodeFlag_MaskSeperators = (0xF<<6), - MD_NodeFlag_StringSingleQuote = (1<<10), - MD_NodeFlag_StringDoubleQuote = (1<<11), - MD_NodeFlag_StringTick = (1<<12), - MD_NodeFlag_StringTriplet = (1<<13), + NodeFlag_StringSingleQuote = (1<<10), + NodeFlag_StringDoubleQuote = (1<<11), + NodeFlag_StringTick = (1<<12), + NodeFlag_StringTriplet = (1<<13), - MD_NodeFlag_MaskStringDelimiters = (0xF<<10), + NodeFlag_MaskStringDelimiters = (0xF<<10), - MD_NodeFlag_Numeric = (1<<14), - MD_NodeFlag_Identifier = (1<<15), - MD_NodeFlag_StringLiteral = (1<<16), - MD_NodeFlag_Symbol = (1<<17), + NodeFlag_Numeric = (1<<14), + NodeFlag_Identifier = (1<<15), + NodeFlag_StringLiteral = (1<<16), + NodeFlag_Symbol = (1<<17), - MD_NodeFlag_MaskLabelKind = (0xF<<14), + NodeFlag_MaskLabelKind = (0xF<<14), }; -typedef struct MD_Node MD_Node; -struct MD_Node +typedef struct Node Node; +struct Node { // Tree relationship data. - MD_Node *next; - MD_Node *prev; - MD_Node *parent; - MD_Node *first_child; - MD_Node *last_child; + Node *next; + Node *prev; + Node *parent; + Node *first_child; + Node *last_child; // Tag list. - MD_Node *first_tag; - MD_Node *last_tag; + Node *first_tag; + Node *last_tag; // Node info. - MD_NodeKind kind; - MD_NodeFlags flags; - MD_String8 string; - MD_String8 raw_string; + NodeKind kind; + NodeFlags flags; + String8 string; + String8 raw_string; // Source code location information. - MD_u64 offset; + u64 offset; // Reference. - MD_Node *ref_target; + Node *ref_target; // Comments. // @usage prev_comment/next_comment should be considered "hidden". Rely on - // the functions MD_PrevCommentFromNode/MD_NextCommentFromNode to access + // the functions PrevCommentFromNode/NextCommentFromNode to access // these. Directly access to these is likely to break in a future version. - MD_String8 prev_comment; - MD_String8 next_comment; + String8 prev_comment; + String8 next_comment; }; //~ Code Location Info. -typedef struct MD_CodeLoc MD_CodeLoc; -struct MD_CodeLoc +typedef struct CodeLoc CodeLoc; +struct CodeLoc { - MD_String8 filename; - MD_u32 line; - MD_u32 column; + String8 filename; + u32 line; + u32 column; }; //~ String-To-Ptr and Ptr-To-Ptr tables -typedef struct MD_MapKey MD_MapKey; -struct MD_MapKey +typedef struct MapKey MapKey; +struct MapKey { - MD_u64 hash; - MD_u64 size; + u64 hash; + u64 size; void *ptr; }; -typedef struct MD_MapSlot MD_MapSlot; -struct MD_MapSlot +typedef struct MapSlot MapSlot; +struct MapSlot { - MD_MapSlot *next; - MD_MapKey key; + MapSlot *next; + MapKey key; void *val; }; -typedef struct MD_MapBucket MD_MapBucket; -struct MD_MapBucket +typedef struct MapBucket MapBucket; +struct MapBucket { - MD_MapSlot *first; - MD_MapSlot *last; + MapSlot *first; + MapSlot *last; }; -typedef struct MD_Map MD_Map; -struct MD_Map +typedef struct Map Map; +struct Map { - MD_MapBucket *buckets; - MD_u64 bucket_count; + MapBucket *buckets; + u64 bucket_count; }; //~ Tokens -typedef MD_u32 MD_TokenKind; +typedef u32 TokenKind; enum { - MD_TokenKind_Identifier = (1<<0), - MD_TokenKind_Numeric = (1<<1), - MD_TokenKind_StringLiteral = (1<<2), - MD_TokenKind_Symbol = (1<<3), - MD_TokenKind_Reserved = (1<<4), - MD_TokenKind_Comment = (1<<5), - MD_TokenKind_Whitespace = (1<<6), - MD_TokenKind_Newline = (1<<7), - MD_TokenKind_BrokenComment = (1<<8), - MD_TokenKind_BrokenStringLiteral = (1<<9), - MD_TokenKind_BadCharacter = (1<<10), + TokenKind_Identifier = (1<<0), + TokenKind_Numeric = (1<<1), + TokenKind_StringLiteral = (1<<2), + TokenKind_Symbol = (1<<3), + TokenKind_Reserved = (1<<4), + TokenKind_Comment = (1<<5), + TokenKind_Whitespace = (1<<6), + TokenKind_Newline = (1<<7), + TokenKind_BrokenComment = (1<<8), + TokenKind_BrokenStringLiteral = (1<<9), + TokenKind_BadCharacter = (1<<10), }; -typedef MD_u32 MD_TokenGroups; +typedef u32 MD_TokenGroups; enum { - MD_TokenGroup_Comment = MD_TokenKind_Comment, - MD_TokenGroup_Whitespace = (MD_TokenKind_Whitespace| - MD_TokenKind_Newline), - MD_TokenGroup_Irregular = (MD_TokenGroup_Comment| - MD_TokenGroup_Whitespace), - MD_TokenGroup_Regular = ~MD_TokenGroup_Irregular, - MD_TokenGroup_Label = (MD_TokenKind_Identifier| - MD_TokenKind_Numeric| - MD_TokenKind_StringLiteral| - MD_TokenKind_Symbol), - MD_TokenGroup_Error = (MD_TokenKind_BrokenComment| - MD_TokenKind_BrokenStringLiteral| - MD_TokenKind_BadCharacter), + TokenGroup_Comment = TokenKind_Comment, + TokenGroup_Whitespace = (TokenKind_Whitespace| + TokenKind_Newline), + TokenGroup_Irregular = (TokenGroup_Comment| + TokenGroup_Whitespace), + TokenGroup_Regular = ~TokenGroup_Irregular, + TokenGroup_Label = (TokenKind_Identifier| + TokenKind_Numeric| + TokenKind_StringLiteral| + TokenKind_Symbol), + TokenGroup_Error = (TokenKind_BrokenComment| + TokenKind_BrokenStringLiteral| + TokenKind_BadCharacter), }; -typedef struct MD_Token MD_Token; -struct MD_Token +typedef struct Token Token; +struct Token { - MD_TokenKind kind; - MD_NodeFlags node_flags; - MD_String8 string; - MD_String8 raw_string; + TokenKind kind; + NodeFlags node_flags; + String8 string; + String8 raw_string; }; //~ Parsing State -typedef enum MD_MessageKind +typedef enum MessageKind { // NOTE(rjf): @maintenance This enum needs to be sorted in order of // severity. - MD_MessageKind_Null, - MD_MessageKind_Note, - MD_MessageKind_Warning, - MD_MessageKind_Error, - MD_MessageKind_FatalError, + MessageKind_Null, + MessageKind_Note, + MessageKind_Warning, + MessageKind_Error, + MessageKind_FatalError, } -MD_MessageKind; +MessageKind; -typedef struct MD_Message MD_Message; -struct MD_Message +typedef struct Message Message; +struct Message { - MD_Message *next; - MD_Node *node; - MD_MessageKind kind; - MD_String8 string; + Message *next; + Node *node; + MessageKind kind; + String8 string; void *user_ptr; }; -typedef struct MD_MessageList MD_MessageList; -struct MD_MessageList +typedef struct MessageList MessageList; +struct MessageList { - MD_MessageKind max_message_kind; + MessageKind max_message_kind; // TODO(allen): rename - MD_u64 node_count; - MD_Message *first; - MD_Message *last; + u64 node_count; + Message *first; + Message *last; }; -typedef enum MD_ParseSetRule +typedef enum ParseSetRule { - MD_ParseSetRule_EndOnDelimiter, - MD_ParseSetRule_Global, -} MD_ParseSetRule; + ParseSetRule_EndOnDelimiter, + ParseSetRule_Global, +} ParseSetRule; -typedef struct MD_ParseResult MD_ParseResult; -struct MD_ParseResult +typedef struct ParseResult ParseResult; +struct ParseResult { - MD_Node *node; - MD_u64 string_advance; - MD_MessageList errors; + Node *node; + u64 string_advance; + MessageList errors; }; //~ Expression Parsing -typedef enum MD_ExprOprKind +typedef enum ExprOprKind { - MD_ExprOprKind_Null, - MD_ExprOprKind_Prefix, - MD_ExprOprKind_Postfix, - MD_ExprOprKind_Binary, - MD_ExprOprKind_BinaryRightAssociative, - MD_ExprOprKind_COUNT, -} MD_ExprOprKind; - -typedef struct MD_ExprOpr MD_ExprOpr; -struct MD_ExprOpr + ExprOprKind_Null, + ExprOprKind_Prefix, + ExprOprKind_Postfix, + ExprOprKind_Binary, + ExprOprKind_BinaryRightAssociative, + ExprOprKind_COUNT, +} ExprOprKind; + +typedef struct ExprOpr ExprOpr; +struct ExprOpr { - struct MD_ExprOpr *next; - MD_u32 op_id; - MD_ExprOprKind kind; - MD_u32 precedence; - MD_String8 string; + struct ExprOpr *next; + u32 op_id; + ExprOprKind kind; + u32 precedence; + String8 string; void *op_ptr; }; -typedef struct MD_ExprOprList MD_ExprOprList; -struct MD_ExprOprList +typedef struct ExprOprList ExprOprList; +struct ExprOprList { - MD_ExprOpr *first; - MD_ExprOpr *last; - MD_u64 count; + ExprOpr *first; + ExprOpr *last; + u64 count; }; -typedef struct MD_ExprOprTable MD_ExprOprTable; -struct MD_ExprOprTable +typedef struct ExprOprTable ExprOprTable; +struct ExprOprTable { // TODO(mal): @upgrade_potential Hash? - MD_ExprOprList table[MD_ExprOprKind_COUNT]; + ExprOprList table[ExprOprKind_COUNT]; }; -typedef struct MD_Expr MD_Expr; -struct MD_Expr +typedef struct Expr Expr; +struct Expr { - struct MD_Expr *parent; + struct Expr *parent; union { - struct MD_Expr *left; - struct MD_Expr *unary_operand; + struct Expr *left; + struct Expr *unary_operand; }; - struct MD_Expr *right; - MD_ExprOpr *op; - MD_Node *md_node; + struct Expr *right; + ExprOpr *op; + Node *md_node; }; -typedef struct MD_ExprParseResult MD_ExprParseResult; -struct MD_ExprParseResult +typedef struct ExprParseResult ExprParseResult; +struct ExprParseResult { - MD_Expr *expr; - MD_MessageList errors; + Expr *expr; + MessageList errors; }; -// TODO(allen): nil MD_Expr +// TODO(allen): nil Expr -typedef struct MD_ExprParseCtx MD_ExprParseCtx; -struct MD_ExprParseCtx +typedef struct ExprParseCtx ExprParseCtx; +struct ExprParseCtx { - MD_ExprOprTable *op_table; + ExprOprTable *op_table; -#define MD_POSTFIX_SETLIKE_OP_COUNT 5 // (), [], {}, [), (] +#define POSTFIX_SETLIKE_OP_COUNT 5 // (), [], {}, [), (] struct { - MD_ExprOpr *postfix_set_ops[MD_POSTFIX_SETLIKE_OP_COUNT]; - MD_NodeFlags postfix_set_flags[MD_POSTFIX_SETLIKE_OP_COUNT]; + ExprOpr *postfix_set_ops[POSTFIX_SETLIKE_OP_COUNT]; + NodeFlags postfix_set_flags[POSTFIX_SETLIKE_OP_COUNT]; } accel; -#undef MD_POSTFIX_SETLIKE_OP_COUNT +#undef POSTFIX_SETLIKE_OP_COUNT - MD_MessageList errors; + MessageList errors; }; -typedef void (*MD_BakeOperatorErrorHandler)(MD_MessageKind kind, MD_String8 s); +typedef void (*BakeOperatorErrorHandler)(MessageKind kind, String8 s); //~ String Generation Types -typedef MD_u32 MD_GenerateFlags; +typedef u32 GenerateFlags; enum { - MD_GenerateFlag_Tags = (1<<0), - MD_GenerateFlag_TagArguments = (1<<1), - MD_GenerateFlag_Children = (1<<2), - MD_GenerateFlag_Comments = (1<<3), - MD_GenerateFlag_NodeKind = (1<<4), - MD_GenerateFlag_NodeFlags = (1<<5), - MD_GenerateFlag_Location = (1<<6), + GenerateFlag_Tags = (1<<0), + GenerateFlag_TagArguments = (1<<1), + GenerateFlag_Children = (1<<2), + GenerateFlag_Comments = (1<<3), + GenerateFlag_NodeKind = (1<<4), + GenerateFlag_NodeFlags = (1<<5), + GenerateFlag_Location = (1<<6), - MD_GenerateFlags_Tree = (MD_GenerateFlag_Tags | - MD_GenerateFlag_TagArguments | - MD_GenerateFlag_Children), - MD_GenerateFlags_All = 0xffffffff, + GenerateFlags_Tree = (GenerateFlag_Tags | + GenerateFlag_TagArguments | + GenerateFlag_Children), + GenerateFlags_All = 0xffffffff, }; //~ Command line parsing helper types. -typedef struct MD_CmdLineOption MD_CmdLineOption; -struct MD_CmdLineOption +typedef struct CmdLineOption CmdLineOption; +struct CmdLineOption { - MD_CmdLineOption *next; - MD_String8 name; - MD_String8List values; + CmdLineOption *next; + String8 name; + String8List values; }; -typedef struct MD_CmdLine MD_CmdLine; -struct MD_CmdLine +typedef struct CmdLine CmdLine; +struct CmdLine { - MD_String8List inputs; - MD_CmdLineOption *first_option; - MD_CmdLineOption *last_option; + String8List inputs; + CmdLineOption *first_option; + CmdLineOption *last_option; }; //~ File system access types. -typedef MD_u32 MD_FileFlags; +typedef u32 FileFlags; enum { - MD_FileFlag_Directory = (1<<0), + FileFlag_Directory = (1<<0), }; -typedef struct MD_FileInfo MD_FileInfo; -struct MD_FileInfo +typedef struct FileInfo FileInfo; +struct FileInfo { - MD_FileFlags flags; - MD_String8 filename; - MD_u64 file_size; + FileFlags flags; + String8 filename; + u64 file_size; }; -typedef struct MD_FileIter MD_FileIter; -struct MD_FileIter +typedef struct FileIter FileIter; +struct FileIter { // This is opaque state to store OS-specific file-system iteration data. - MD_u8 opaque[640]; + u8 opaque[640]; }; //~///////////////////////////////////////////////////////////////////////////// @@ -928,313 +928,313 @@ struct MD_FileIter //~ Arena -MD_FUNCTION MD_Arena* MD_ArenaAlloc(void); -MD_FUNCTION void MD_ArenaRelease(MD_Arena *arena); +FUNCTION Arena* ArenaAlloc(void); +FUNCTION void ArenaRelease(Arena *arena); -MD_FUNCTION void* MD_ArenaPush(MD_Arena *arena, MD_u64 size); -MD_FUNCTION void MD_ArenaPutBack(MD_Arena *arena, MD_u64 size); -MD_FUNCTION void MD_ArenaSetAlign(MD_Arena *arena, MD_u64 boundary); -MD_FUNCTION void MD_ArenaPushAlign(MD_Arena *arena, MD_u64 boundary); -MD_FUNCTION void MD_ArenaClear(MD_Arena *arena); +FUNCTION void* ArenaPush(Arena *arena, u64 size); +FUNCTION void ArenaPutBack(Arena *arena, u64 size); +FUNCTION void ArenaSetAlign(Arena *arena, u64 boundary); +FUNCTION void ArenaPushAlign(Arena *arena, u64 boundary); +FUNCTION void ArenaClear(Arena *arena); -#define MD_PushArray(a,T,c) (T*)(MD_ArenaPush((a), sizeof(T)*(c))) -#define MD_PushArrayZero(a,T,c) (T*)(MD_MemoryZero(MD_PushArray(a,T,c), sizeof(T)*(c))) +#define PushArray(a,T,c) (T*)(ArenaPush((a), sizeof(T)*(c))) +#define PushArrayZero(a,T,c) (T*)(MemoryZero(PushArray(a,T,c), sizeof(T)*(c))) -MD_FUNCTION MD_ArenaTemp MD_ArenaBeginTemp(MD_Arena *arena); -MD_FUNCTION void MD_ArenaEndTemp(MD_ArenaTemp temp); +FUNCTION ArenaTemp ArenaBeginTemp(Arena *arena); +FUNCTION void ArenaEndTemp(ArenaTemp temp); //~ Arena Scratch Pool -MD_FUNCTION MD_ArenaTemp MD_GetScratch(MD_Arena **conflicts, MD_u64 count); +FUNCTION ArenaTemp GetScratch(Arena **conflicts, u64 count); -#define MD_ReleaseScratch(scratch) MD_ArenaEndTemp(scratch) +#define ReleaseScratch(scratch) ArenaEndTemp(scratch) //~ Characters -MD_FUNCTION MD_b32 MD_CharIsAlpha(MD_u8 c); -MD_FUNCTION MD_b32 MD_CharIsAlphaUpper(MD_u8 c); -MD_FUNCTION MD_b32 MD_CharIsAlphaLower(MD_u8 c); -MD_FUNCTION MD_b32 MD_CharIsDigit(MD_u8 c); -MD_FUNCTION MD_b32 MD_CharIsUnreservedSymbol(MD_u8 c); -MD_FUNCTION MD_b32 MD_CharIsReservedSymbol(MD_u8 c); -MD_FUNCTION MD_b32 MD_CharIsSpace(MD_u8 c); -MD_FUNCTION MD_u8 MD_CharToUpper(MD_u8 c); -MD_FUNCTION MD_u8 MD_CharToLower(MD_u8 c); -MD_FUNCTION MD_u8 MD_CharToForwardSlash(MD_u8 c); +FUNCTION b32 CharIsAlpha(u8 c); +FUNCTION b32 CharIsAlphaUpper(u8 c); +FUNCTION b32 CharIsAlphaLower(u8 c); +FUNCTION b32 CharIsDigit(u8 c); +FUNCTION b32 CharIsUnreservedSymbol(u8 c); +FUNCTION b32 CharIsReservedSymbol(u8 c); +FUNCTION b32 CharIsSpace(u8 c); +FUNCTION u8 CharToUpper(u8 c); +FUNCTION u8 CharToLower(u8 c); +FUNCTION u8 CharToForwardSlash(u8 c); //~ Strings -MD_FUNCTION MD_u64 MD_CalculateCStringLength(char *cstr); +FUNCTION u64 CalculateCStringLength(char *cstr); -MD_FUNCTION MD_String8 MD_S8(MD_u8 *str, MD_u64 size); -#define MD_S8CString(s) MD_S8((MD_u8 *)(s), MD_CalculateCStringLength(s)) +FUNCTION String8 S8(u8 *str, u64 size); +#define S8CString(s) S8((u8 *)(s), CalculateCStringLength(s)) -#if MD_LANG_C -# define MD_S8Lit(s) (MD_String8){(MD_u8 *)(s), sizeof(s)-1} -#elif MD_LANG_CPP -# define MD_S8Lit(s) MD_S8((MD_u8*)(s), sizeof(s) - 1) +#if LANG_C +# define S8Lit(s) (String8){(u8 *)(s), sizeof(s)-1} +#elif LANG_CPP +# define S8Lit(s) S8((u8*)(s), sizeof(s) - 1) #endif -#define MD_S8LitComp(s) {(MD_u8 *)(s), sizeof(s)-1} +#define S8LitComp(s) {(u8 *)(s), sizeof(s)-1} -#if MD_CPP_VERSION >= 11 -static inline MD_String8 +#if CPP_VERSION >= 11 +static inline String8 operator "" _md(const char *s, size_t size) { - MD_String8 str = MD_S8((MD_u8 *)s, (MD_u64)size); + String8 str = S8((u8 *)s, (u64)size); return str; } #endif -MD_FUNCTION MD_String8 MD_S8Range(MD_u8 *first, MD_u8 *opl); +FUNCTION String8 S8Range(u8 *first, u8 *opl); -MD_FUNCTION MD_String8 MD_S8Substring(MD_String8 str, MD_u64 min, MD_u64 max); -MD_FUNCTION MD_String8 MD_S8Skip(MD_String8 str, MD_u64 min); -MD_FUNCTION MD_String8 MD_S8Chop(MD_String8 str, MD_u64 nmax); -MD_FUNCTION MD_String8 MD_S8Prefix(MD_String8 str, MD_u64 size); -MD_FUNCTION MD_String8 MD_S8Suffix(MD_String8 str, MD_u64 size); +FUNCTION String8 S8Substring(String8 str, u64 min, u64 max); +FUNCTION String8 S8Skip(String8 str, u64 min); +FUNCTION String8 S8Chop(String8 str, u64 nmax); +FUNCTION String8 S8Prefix(String8 str, u64 size); +FUNCTION String8 S8Suffix(String8 str, u64 size); -MD_FUNCTION MD_b32 MD_S8Match(MD_String8 a, MD_String8 b, MD_MatchFlags flags); -MD_FUNCTION MD_u64 MD_S8FindSubstring(MD_String8 str, MD_String8 substring, - MD_u64 start_pos, MD_MatchFlags flags); +FUNCTION b32 S8Match(String8 a, String8 b, MatchFlags flags); +FUNCTION u64 S8FindSubstring(String8 str, String8 substring, + u64 start_pos, MatchFlags flags); -MD_FUNCTION MD_String8 MD_S8Copy(MD_Arena *arena, MD_String8 string); -MD_FUNCTION MD_String8 MD_S8FmtV(MD_Arena *arena, char *fmt, va_list args); +FUNCTION String8 S8Copy(Arena *arena, String8 string); +FUNCTION String8 S8FmtV(Arena *arena, char *fmt, va_list args); -MD_FUNCTION MD_String8 MD_S8Fmt(MD_Arena *arena, char *fmt, ...); +FUNCTION String8 S8Fmt(Arena *arena, char *fmt, ...); -#define MD_S8VArg(s) (int)(s).size, (s).str +#define S8VArg(s) (int)(s).size, (s).str -MD_FUNCTION void MD_S8ListPush(MD_Arena *arena, MD_String8List *list, - MD_String8 string); -MD_FUNCTION void MD_S8ListPushFmt(MD_Arena *arena, MD_String8List *list, +FUNCTION void S8ListPush(Arena *arena, String8List *list, + String8 string); +FUNCTION void S8ListPushFmt(Arena *arena, String8List *list, char *fmt, ...); -MD_FUNCTION void MD_S8ListConcat(MD_String8List *list, MD_String8List *to_push); -MD_FUNCTION MD_String8List MD_S8Split(MD_Arena *arena, MD_String8 string, int split_count, - MD_String8 *splits); -MD_FUNCTION MD_String8 MD_S8ListJoin(MD_Arena *arena, MD_String8List list, - MD_StringJoin *join); +FUNCTION void S8ListConcat(String8List *list, String8List *to_push); +FUNCTION String8List S8Split(Arena *arena, String8 string, int split_count, + String8 *splits); +FUNCTION String8 S8ListJoin(Arena *arena, String8List list, + StringJoin *join); -MD_FUNCTION MD_String8 MD_S8Stylize(MD_Arena *arena, MD_String8 string, - MD_IdentifierStyle style, MD_String8 separator); +FUNCTION String8 S8Stylize(Arena *arena, String8 string, + IdentifierStyle style, String8 separator); //~ Unicode Conversions -MD_FUNCTION MD_DecodedCodepoint MD_DecodeCodepointFromUtf8(MD_u8 *str, MD_u64 max); -MD_FUNCTION MD_DecodedCodepoint MD_DecodeCodepointFromUtf16(MD_u16 *str, MD_u64 max); -MD_FUNCTION MD_u32 MD_Utf8FromCodepoint(MD_u8 *out, MD_u32 codepoint); -MD_FUNCTION MD_u32 MD_Utf16FromCodepoint(MD_u16 *out, MD_u32 codepoint); -MD_FUNCTION MD_String8 MD_S8FromS16(MD_Arena *arena, MD_String16 str); -MD_FUNCTION MD_String16 MD_S16FromS8(MD_Arena *arena, MD_String8 str); -MD_FUNCTION MD_String8 MD_S8FromS32(MD_Arena *arena, MD_String32 str); -MD_FUNCTION MD_String32 MD_S32FromS8(MD_Arena *arena, MD_String8 str); +FUNCTION DecodedCodepoint DecodeCodepointFromUtf8(u8 *str, u64 max); +FUNCTION DecodedCodepoint DecodeCodepointFromUtf16(u16 *str, u64 max); +FUNCTION u32 Utf8FromCodepoint(u8 *out, u32 codepoint); +FUNCTION u32 Utf16FromCodepoint(u16 *out, u32 codepoint); +FUNCTION String8 S8FromS16(Arena *arena, String16 str); +FUNCTION String16 S16FromS8(Arena *arena, String8 str); +FUNCTION String8 S8FromS32(Arena *arena, String32 str); +FUNCTION String32 S32FromS8(Arena *arena, String8 str); //~ String Skipping/Chopping Helpers // This is intended for removing extensions. -MD_FUNCTION MD_String8 MD_PathChopLastPeriod(MD_String8 string); +FUNCTION String8 PathChopLastPeriod(String8 string); // This is intended for removing everything but the filename. -MD_FUNCTION MD_String8 MD_PathSkipLastSlash(MD_String8 string); +FUNCTION String8 PathSkipLastSlash(String8 string); // This is intended for getting an extension from a filename. -MD_FUNCTION MD_String8 MD_PathSkipLastPeriod(MD_String8 string); +FUNCTION String8 PathSkipLastPeriod(String8 string); // This is intended for getting the folder string from a full path. -MD_FUNCTION MD_String8 MD_PathChopLastSlash(MD_String8 string); +FUNCTION String8 PathChopLastSlash(String8 string); -MD_FUNCTION MD_String8 MD_S8SkipWhitespace(MD_String8 string); -MD_FUNCTION MD_String8 MD_S8ChopWhitespace(MD_String8 string); +FUNCTION String8 S8SkipWhitespace(String8 string); +FUNCTION String8 S8ChopWhitespace(String8 string); //~ Numeric Strings -MD_FUNCTION MD_b32 MD_StringIsU64(MD_String8 string, MD_u32 radix); -MD_FUNCTION MD_b32 MD_StringIsCStyleInt(MD_String8 string); +FUNCTION b32 StringIsU64(String8 string, u32 radix); +FUNCTION b32 StringIsCStyleInt(String8 string); -MD_FUNCTION MD_u64 MD_U64FromString(MD_String8 string, MD_u32 radix); -MD_FUNCTION MD_i64 MD_CStyleIntFromString(MD_String8 string); -MD_FUNCTION MD_f64 MD_F64FromString(MD_String8 string); +FUNCTION u64 U64FromString(String8 string, u32 radix); +FUNCTION i64 CStyleIntFromString(String8 string); +FUNCTION f64 F64FromString(String8 string); -MD_FUNCTION MD_String8 MD_CStyleHexStringFromU64(MD_Arena *arena, MD_u64 x, MD_b32 caps); +FUNCTION String8 CStyleHexStringFromU64(Arena *arena, u64 x, b32 caps); //~ Enum/Flag Strings -MD_FUNCTION MD_String8 MD_StringFromNodeKind(MD_NodeKind kind); -MD_FUNCTION MD_String8List MD_StringListFromNodeFlags(MD_Arena *arena, MD_NodeFlags flags); +FUNCTION String8 StringFromNodeKind(NodeKind kind); +FUNCTION String8List StringListFromNodeFlags(Arena *arena, NodeFlags flags); //~ Map Table Data Structure -MD_FUNCTION MD_u64 MD_HashStr(MD_String8 string); -MD_FUNCTION MD_u64 MD_HashPtr(void *p); - -MD_FUNCTION MD_Map MD_MapMakeBucketCount(MD_Arena *arena, MD_u64 bucket_count); -MD_FUNCTION MD_Map MD_MapMake(MD_Arena *arena); -MD_FUNCTION MD_MapKey MD_MapKeyStr(MD_String8 string); -MD_FUNCTION MD_MapKey MD_MapKeyPtr(void *ptr); -MD_FUNCTION MD_MapSlot* MD_MapLookup(MD_Map *map, MD_MapKey key); -MD_FUNCTION MD_MapSlot* MD_MapScan(MD_MapSlot *first_slot, MD_MapKey key); -MD_FUNCTION MD_MapSlot* MD_MapInsert(MD_Arena *arena, MD_Map *map, MD_MapKey key, void *val); -MD_FUNCTION MD_MapSlot* MD_MapOverwrite(MD_Arena *arena, MD_Map *map, MD_MapKey key, +FUNCTION u64 HashStr(String8 string); +FUNCTION u64 HashPtr(void *p); + +FUNCTION Map MapMakeBucketCount(Arena *arena, u64 bucket_count); +FUNCTION Map MapMake(Arena *arena); +FUNCTION MapKey MapKeyStr(String8 string); +FUNCTION MapKey MapKeyPtr(void *ptr); +FUNCTION MapSlot* MapLookup(Map *map, MapKey key); +FUNCTION MapSlot* MapScan(MapSlot *first_slot, MapKey key); +FUNCTION MapSlot* MapInsert(Arena *arena, Map *map, MapKey key, void *val); +FUNCTION MapSlot* MapOverwrite(Arena *arena, Map *map, MapKey key, void *val); //~ Parsing -MD_FUNCTION MD_Token MD_TokenFromString(MD_String8 string); -MD_FUNCTION MD_u64 MD_LexAdvanceFromSkips(MD_String8 string, MD_TokenKind skip_kinds); -MD_FUNCTION MD_ParseResult MD_ParseResultZero(void); -MD_FUNCTION MD_ParseResult MD_ParseNodeSet(MD_Arena *arena, MD_String8 string, MD_u64 offset, MD_Node *parent, - MD_ParseSetRule rule); -MD_FUNCTION MD_ParseResult MD_ParseOneNode(MD_Arena *arena, MD_String8 string, MD_u64 offset); -MD_FUNCTION MD_ParseResult MD_ParseWholeString(MD_Arena *arena, MD_String8 filename, MD_String8 contents); +FUNCTION Token TokenFromString(String8 string); +FUNCTION u64 LexAdvanceFromSkips(String8 string, TokenKind skip_kinds); +FUNCTION ParseResult ParseResultZero(void); +FUNCTION ParseResult ParseNodeSet(Arena *arena, String8 string, u64 offset, Node *parent, + ParseSetRule rule); +FUNCTION ParseResult ParseOneNode(Arena *arena, String8 string, u64 offset); +FUNCTION ParseResult ParseWholeString(Arena *arena, String8 filename, String8 contents); -MD_FUNCTION MD_ParseResult MD_ParseWholeFile(MD_Arena *arena, MD_String8 filename); +FUNCTION ParseResult ParseWholeFile(Arena *arena, String8 filename); //~ Messages (Errors/Warnings) -MD_FUNCTION MD_Node* MD_MakeErrorMarkerNode(MD_Arena *arena, MD_String8 parse_contents, - MD_u64 offset); +FUNCTION Node* MakeErrorMarkerNode(Arena *arena, String8 parse_contents, + u64 offset); -MD_FUNCTION MD_Message*MD_MakeNodeError(MD_Arena *arena, MD_Node *node, - MD_MessageKind kind, MD_String8 str); -MD_FUNCTION MD_Message*MD_MakeDetachedError(MD_Arena *arena, MD_MessageKind kind, - MD_String8 str, void *ptr); -MD_FUNCTION MD_Message*MD_MakeTokenError(MD_Arena *arena, MD_String8 parse_contents, - MD_Token token, MD_MessageKind kind, - MD_String8 str); +FUNCTION Message*MakeNodeError(Arena *arena, Node *node, + MessageKind kind, String8 str); +FUNCTION Message*MakeDetachedError(Arena *arena, MessageKind kind, + String8 str, void *ptr); +FUNCTION Message*MakeTokenError(Arena *arena, String8 parse_contents, + Token token, MessageKind kind, + String8 str); -MD_FUNCTION void MD_MessageListPush(MD_MessageList *list, MD_Message *message); -MD_FUNCTION void MD_MessageListConcat(MD_MessageList *list, MD_MessageList *to_push); +FUNCTION void MessageListPush(MessageList *list, Message *message); +FUNCTION void MessageListConcat(MessageList *list, MessageList *to_push); //~ Location Conversion -MD_FUNCTION MD_CodeLoc MD_CodeLocFromFileOffset(MD_String8 filename, MD_u8 *base, MD_u64 offset); -MD_FUNCTION MD_CodeLoc MD_CodeLocFromNode(MD_Node *node); +FUNCTION CodeLoc CodeLocFromFileOffset(String8 filename, u8 *base, u64 offset); +FUNCTION CodeLoc CodeLocFromNode(Node *node); //~ Tree/List Building -MD_FUNCTION MD_b32 MD_NodeIsNil(MD_Node *node); -MD_FUNCTION MD_Node *MD_NilNode(void); -MD_FUNCTION MD_Node *MD_MakeNode(MD_Arena *arena, MD_NodeKind kind, MD_String8 string, - MD_String8 raw_string, MD_u64 offset); -MD_FUNCTION void MD_PushChild(MD_Node *parent, MD_Node *new_child); -MD_FUNCTION void MD_PushTag(MD_Node *node, MD_Node *tag); +FUNCTION b32 NodeIsNil(Node *node); +FUNCTION Node *NilNode(void); +FUNCTION Node *MakeNode(Arena *arena, NodeKind kind, String8 string, + String8 raw_string, u64 offset); +FUNCTION void PushChild(Node *parent, Node *new_child); +FUNCTION void PushTag(Node *node, Node *tag); -MD_FUNCTION MD_Node *MD_MakeList(MD_Arena *arena); -MD_FUNCTION void MD_ListConcatInPlace(MD_Node *list, MD_Node *to_push); -MD_FUNCTION MD_Node *MD_PushNewReference(MD_Arena *arena, MD_Node *list, MD_Node *target); +FUNCTION Node *MakeList(Arena *arena); +FUNCTION void ListConcatInPlace(Node *list, Node *to_push); +FUNCTION Node *PushNewReference(Arena *arena, Node *list, Node *target); //~ Introspection Helpers // These calls are for getting info from nodes, and introspecting // on trees that are returned to you by the parser. -MD_FUNCTION MD_Node * MD_FirstNodeWithString(MD_Node *first, MD_String8 string, MD_MatchFlags flags); -MD_FUNCTION MD_Node * MD_NodeAtIndex(MD_Node *first, int n); -MD_FUNCTION MD_Node * MD_FirstNodeWithFlags(MD_Node *first, MD_NodeFlags flags); -MD_FUNCTION int MD_IndexFromNode(MD_Node *node); -MD_FUNCTION MD_Node * MD_RootFromNode(MD_Node *node); -MD_FUNCTION MD_Node * MD_ChildFromString(MD_Node *node, MD_String8 child_string, MD_MatchFlags flags); -MD_FUNCTION MD_Node * MD_TagFromString(MD_Node *node, MD_String8 tag_string, MD_MatchFlags flags); -MD_FUNCTION MD_Node * MD_ChildFromIndex(MD_Node *node, int n); -MD_FUNCTION MD_Node * MD_TagFromIndex(MD_Node *node, int n); -MD_FUNCTION MD_Node * MD_TagArgFromIndex(MD_Node *node, MD_String8 tag_string, MD_MatchFlags flags, int n); -MD_FUNCTION MD_Node * MD_TagArgFromString(MD_Node *node, MD_String8 tag_string, MD_MatchFlags tag_str_flags, MD_String8 arg_string, MD_MatchFlags arg_str_flags); -MD_FUNCTION MD_b32 MD_NodeHasChild(MD_Node *node, MD_String8 string, MD_MatchFlags flags); -MD_FUNCTION MD_b32 MD_NodeHasTag(MD_Node *node, MD_String8 string, MD_MatchFlags flags); -MD_FUNCTION MD_i64 MD_ChildCountFromNode(MD_Node *node); -MD_FUNCTION MD_i64 MD_TagCountFromNode(MD_Node *node); -MD_FUNCTION MD_Node * MD_ResolveNodeFromReference(MD_Node *node); -MD_FUNCTION MD_Node* MD_NodeNextWithLimit(MD_Node *node, MD_Node *opl); - -MD_FUNCTION MD_String8 MD_PrevCommentFromNode(MD_Node *node); -MD_FUNCTION MD_String8 MD_NextCommentFromNode(MD_Node *node); +FUNCTION Node * FirstNodeWithString(Node *first, String8 string, MatchFlags flags); +FUNCTION Node * NodeAtIndex(Node *first, int n); +FUNCTION Node * FirstNodeWithFlags(Node *first, NodeFlags flags); +FUNCTION int IndexFromNode(Node *node); +FUNCTION Node * RootFromNode(Node *node); +FUNCTION Node * MD_ChildFromString(Node *node, String8 child_string, MatchFlags flags); +FUNCTION Node * TagFromString(Node *node, String8 tag_string, MatchFlags flags); +FUNCTION Node * ChildFromIndex(Node *node, int n); +FUNCTION Node * TagFromIndex(Node *node, int n); +FUNCTION Node * TagArgFromIndex(Node *node, String8 tag_string, MatchFlags flags, int n); +FUNCTION Node * TagArgFromString(Node *node, String8 tag_string, MatchFlags tag_str_flags, String8 arg_string, MatchFlags arg_str_flags); +FUNCTION b32 NodeHasChild(Node *node, String8 string, MatchFlags flags); +FUNCTION b32 NodeHasTag(Node *node, String8 string, MatchFlags flags); +FUNCTION i64 ChildCountFromNode(Node *node); +FUNCTION i64 TagCountFromNode(Node *node); +FUNCTION Node * ResolveNodeFromReference(Node *node); +FUNCTION Node* NodeNextWithLimit(Node *node, Node *opl); + +FUNCTION String8 PrevCommentFromNode(Node *node); +FUNCTION String8 NextCommentFromNode(Node *node); // NOTE(rjf): For-Loop Helpers -#define MD_EachNode(it, first) MD_Node *it = (first); !MD_NodeIsNil(it); it = it->next +#define EachNode(it, first) Node *it = (first); !NodeIsNil(it); it = it->next //~ Error/Warning Helpers -MD_FUNCTION MD_String8 MD_StringFromMessageKind(MD_MessageKind kind); +FUNCTION String8 StringFromMessageKind(MessageKind kind); -#define MD_FmtCodeLoc "%.*s:%i:%i:" -#define MD_CodeLocVArg(loc) MD_S8VArg((loc).filename), (loc).line, (loc).column +#define FmtCodeLoc "%.*s:%i:%i:" +#define CodeLocVArg(loc) S8VArg((loc).filename), (loc).line, (loc).column -MD_FUNCTION MD_String8 MD_FormatMessage(MD_Arena *arena, MD_CodeLoc loc, MD_MessageKind kind, - MD_String8 string); +FUNCTION String8 MD_FormatMessage(Arena *arena, CodeLoc loc, MessageKind kind, + String8 string); -#if !MD_DISABLE_PRINT_HELPERS +#if !DISABLE_PRINT_HELPERS #include -MD_FUNCTION void MD_PrintMessage(FILE *file, MD_CodeLoc loc, MD_MessageKind kind, - MD_String8 string); -MD_FUNCTION void MD_PrintMessageFmt(FILE *file, MD_CodeLoc code_loc, MD_MessageKind kind, +FUNCTION void PrintMessage(FILE *file, CodeLoc loc, MessageKind kind, + String8 string); +FUNCTION void PrintMessageFmt(FILE *file, CodeLoc code_loc, MessageKind kind, char *fmt, ...); -#define MD_PrintGenNoteCComment(f) fprintf((f), "// generated by %s:%d\n", __FILE__, __LINE__) +#define PrintGenNoteCComment(f) fprintf((f), "// generated by %s:%d\n", __FILE__, __LINE__) #endif //~ Tree Comparison/Verification -MD_FUNCTION MD_b32 MD_NodeMatch(MD_Node *a, MD_Node *b, MD_MatchFlags flags); -MD_FUNCTION MD_b32 MD_NodeDeepMatch(MD_Node *a, MD_Node *b, MD_MatchFlags flags); +FUNCTION b32 NodeMatch(Node *a, Node *b, MatchFlags flags); +FUNCTION b32 NodeDeepMatch(Node *a, Node *b, MatchFlags flags); //~ Expression Parsing -MD_FUNCTION void MD_ExprOprPush(MD_Arena *arena, MD_ExprOprList *list, - MD_ExprOprKind kind, MD_u64 precedence, - MD_String8 op_string, - MD_u32 op_id, void *op_ptr); +FUNCTION void ExprOprPush(Arena *arena, ExprOprList *list, + ExprOprKind kind, u64 precedence, + String8 op_string, + u32 op_id, void *op_ptr); -MD_FUNCTION MD_ExprOprTable MD_ExprBakeOprTableFromList(MD_Arena *arena, - MD_ExprOprList *list); -MD_FUNCTION MD_ExprOpr* MD_ExprOprFromKindString(MD_ExprOprTable *table, - MD_ExprOprKind kind, MD_String8 s); +FUNCTION ExprOprTable ExprBakeOprTableFromList(Arena *arena, + ExprOprList *list); +FUNCTION ExprOpr* ExprOprFromKindString(ExprOprTable *table, + ExprOprKind kind, String8 s); -MD_FUNCTION MD_ExprParseResult MD_ExprParse(MD_Arena *arena, MD_ExprOprTable *op_table, - MD_Node *first, MD_Node *one_past_last); +FUNCTION ExprParseResult ExprParse(Arena *arena, ExprOprTable *op_table, + Node *first, Node *one_past_last); -MD_FUNCTION MD_Expr* MD_Expr_NewLeaf(MD_Arena *arena, MD_Node *node); -MD_FUNCTION MD_Expr* MD_Expr_NewOpr(MD_Arena *arena, MD_ExprOpr *op, MD_Node *op_node, - MD_Expr *left, MD_Expr *right); +FUNCTION Expr* Expr_NewLeaf(Arena *arena, Node *node); +FUNCTION Expr* Expr_NewOpr(Arena *arena, ExprOpr *op, Node *op_node, + Expr *left, Expr *right); -MD_FUNCTION MD_ExprParseCtx MD_ExprParse_MakeContext(MD_ExprOprTable *table); +FUNCTION ExprParseCtx ExprParse_MakeContext(ExprOprTable *table); -MD_FUNCTION MD_Expr* MD_ExprParse_TopLevel(MD_Arena *arena, MD_ExprParseCtx *ctx, - MD_Node *first, MD_Node *opl); -MD_FUNCTION MD_b32 MD_ExprParse_OprConsume(MD_ExprParseCtx *ctx, - MD_Node **iter, MD_Node *opl, - MD_ExprOprKind kind, - MD_u32 min_precedence, - MD_ExprOpr **op_out); -MD_FUNCTION MD_Expr* MD_ExprParse_Atom(MD_Arena *arena, MD_ExprParseCtx *ctx, - MD_Node **iter, MD_Node *first, MD_Node *opl); -MD_FUNCTION MD_Expr* MD_ExprParse_MinPrecedence(MD_Arena *arena, MD_ExprParseCtx *ctx, - MD_Node **iter, MD_Node *first, MD_Node *opl, - MD_u32 min_precedence); +FUNCTION Expr* ExprParse_TopLevel(Arena *arena, ExprParseCtx *ctx, + Node *first, Node *opl); +FUNCTION b32 ExprParse_OprConsume(ExprParseCtx *ctx, + Node **iter, Node *opl, + ExprOprKind kind, + u32 min_precedence, + ExprOpr **op_out); +FUNCTION Expr* ExprParse_Atom(Arena *arena, ExprParseCtx *ctx, + Node **iter, Node *first, Node *opl); +FUNCTION Expr* ExprParse_MinPrecedence(Arena *arena, ExprParseCtx *ctx, + Node **iter, Node *first, Node *opl, + u32 min_precedence); //~ String Generation -MD_FUNCTION void MD_DebugDumpFromNode(MD_Arena *arena, MD_String8List *out, MD_Node *node, - int indent, MD_String8 indent_string, - MD_GenerateFlags flags); -MD_FUNCTION void MD_ReconstructionFromNode(MD_Arena *arena, MD_String8List *out, MD_Node *node, - int indent, MD_String8 indent_string); +FUNCTION void DebugDumpFromNode(Arena *arena, String8List *out, Node *node, + int indent, String8 indent_string, + GenerateFlags flags); +FUNCTION void ReconstructionFromNode(Arena *arena, String8List *out, Node *node, + int indent, String8 indent_string); //~ Command Line Argument Helper -MD_FUNCTION MD_String8List MD_StringListFromArgCV(MD_Arena *arena, int argument_count, +FUNCTION String8List StringListFromArgCV(Arena *arena, int argument_count, char **arguments); -MD_FUNCTION MD_CmdLine MD_MakeCmdLineFromOptions(MD_Arena *arena, MD_String8List options); -MD_FUNCTION MD_String8List MD_CmdLineValuesFromString(MD_CmdLine cmdln, MD_String8 name); -MD_FUNCTION MD_b32 MD_CmdLineB32FromString(MD_CmdLine cmdln, MD_String8 name); -MD_FUNCTION MD_i64 MD_CmdLineI64FromString(MD_CmdLine cmdln, MD_String8 name); +FUNCTION CmdLine MakeCmdLineFromOptions(Arena *arena, String8List options); +FUNCTION String8List CmdLineValuesFromString(CmdLine cmdln, String8 name); +FUNCTION b32 CmdLineB32FromString(CmdLine cmdln, String8 name); +FUNCTION i64 CmdLineI64FromString(CmdLine cmdln, String8 name); //~ File System -MD_FUNCTION MD_String8 MD_LoadEntireFile(MD_Arena *arena, MD_String8 filename); -MD_FUNCTION MD_b32 MD_FileIterBegin(MD_FileIter *it, MD_String8 path); -MD_FUNCTION MD_FileInfo MD_FileIterNext(MD_Arena *arena, MD_FileIter *it); -MD_FUNCTION void MD_FileIterEnd(MD_FileIter *it); +FUNCTION String8 LoadEntireFile(Arena *arena, String8 filename); +FUNCTION b32 FileIterBegin(FileIter *it, String8 path); +FUNCTION FileInfo FileIterNext(Arena *arena, FileIter *it); +FUNCTION void FileIterEnd(FileIter *it); #endif // MD_H diff --git a/thirdparty/md_stb_sprintf.h b/thirdparty/md_stb_sprintf.h index 1567671..69fe300 100644 --- a/thirdparty/md_stb_sprintf.h +++ b/thirdparty/md_stb_sprintf.h @@ -582,12 +582,12 @@ cl = lg; \ // copy the string in goto scopy; - //~ rjf: METADESK ADDITION: %S for MD_String8's + //~ rjf: METADESK ADDITION: %S for String8's - case 'S': // MD_String8 + case 'S': // String8 { //- rjf: pull out string - MD_String8 str = va_arg(va, MD_String8); + String8 str = va_arg(va, String8); //- rjf: get string length s = (char *)str.str; diff --git a/todo.txt b/todo.txt index fec4110..4f61be0 100644 --- a/todo.txt +++ b/todo.txt @@ -2,7 +2,6 @@ Urgent: - angel doesn't have characters near you -- Remove (MD_) prefix from project - Furcate functionality in npc entity into feature flags, streamline creation of entities/things from blender -> game, things. Make rock thing. - Fix camera angle on forest map, probably introduce custom camera angles per map - In debugtools show number of arenas allocated, and total megabytes allocated in arenas