commit 5a2e3dcec45de3cca9b5aa35895bda15f1bd3ca7 Author: Krzosa Karol Date: Sat Apr 13 15:29:53 2024 +0200 Init new repository diff --git a/.github/workflows/run_tests.yaml b/.github/workflows/run_tests.yaml new file mode 100644 index 0000000..f226b84 --- /dev/null +++ b/.github/workflows/run_tests.yaml @@ -0,0 +1,25 @@ +on: [push] +jobs: + run-and-compile-ubuntu: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: sudo apt install g++ + - run: sudo apt install clang + - run: g++ -o bld src/build_tool/main.cpp -g -lm && ./bld + run-and-compile-mac: + runs-on: macos-latest + steps: + - uses: actions/checkout@v4 + - run: brew install llvm + - run: clang++ src/build_tool/main.cpp -std=c++11 -o bld && ./bld + run-and-compile-windows: + runs-on: windows-latest + steps: + - name: Setup MSVC Developer Command Prompt + uses: TheMrMilchmann/setup-msvc-dev@v3.0.0 + with: + arch: x64 + - uses: actions/checkout@v4 + - run: cl.exe src/build_tool/main.cpp /Fe:bld.exe && bld.exe + shell: cmd \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b320a46 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +build/ +private.bat +todo.txt +*.sublime-project +*.sublime-workspace +*.rdbg +*.wasm diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2f69c3d --- /dev/null +++ b/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2024 Krzosa Karol + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..acfd04d --- /dev/null +++ b/README.md @@ -0,0 +1,674 @@ +# Compiler front-end in a single-header-file C library + +I have no illusions here, this is not the next big language. What I propose is very simple, "a return to C", a language that is smaller but with modern features, distributed as a dependency free, easy to use single-header-file library. Add compiler checks, generate code, do whatever floats your boat. Enjoy. + +- **User has full control over compilation!** +- **No dependencies, permissive license, single file that compile both in C and C++!** +- **Simpler then C:** core of the language is 4000 loc and entire package 11k loc. +- **Statically typed, procedural and MODERN:** it's a mix of Go/Odin/Jai with "return to C" as ideal. +- **Complete:** it supports conditional compilation, modularity via packages etc. +- **State of art error handling techniques** like AST poisoning, proper parsing recovery, catches tons of errors without misreporting! +- **Great C integration:** using C libraries feels native, the language compiles easily to C with great debug info. + +**Library is in beta so I reserve the right to change things!** + +## Example or [you can try the language online](https://krzosa.xyz/playground.html) + +``` odin +import "raylib"; + +main :: proc(): int { + InitWindow(800, 600, "Thing"); + SetTargetFPS(60); + + for !WindowShouldClose() { + BeginDrawing(); + ClearBackground(RAYWHITE); + DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY); + EndDrawing(); + } + CloseWindow(); + return 0; +} +``` + +**Program examples:** + +- [Hello world](examples/hello_world) +- [Text editor](examples/text_editor) +- [Path-finding visualizer](examples/pathfinding_visualizer) + +**Examples of hooking into the compilation:** + +- [Generating type information](examples/generate_type_info) +- [Adding printf checks](examples/add_printf_format_check) +- [Adding instrumentation to every procedure](examples/add_instrumentation) +- [Adding a generic dynamic array using AST modification](examples/add_dynamic_array_macro) + +**Other:** + +- [Using the language as a data format (with type safety)](examples/use_as_data_format_with_typechecking) + +## How to integrate + +To create the implementation do this in **one** of your C or C++ files: + +``` c +#define LIB_COMPILER_IMPLEMENTATION +#include "lib_compiler.h" +``` + +## How to build the compiler executable + +Simply compile one file with whatever compiler you want: + +``` bash +clang tools/lcompile.c -o lc.exe +``` + +Once you have the executable you can compile examples and stuff: + +``` bash +lc.exe examples/create_raylib_window +``` + +When in doubt: `./lc.exe --help`. + +## How to run the test suite + +``` bash +clang++ src/build_tool/main.cpp -o bld.exe +./bld.exe +``` + +You only need to compile the build tool once. Afterwards just call `./bld.exe`. There are multiple testing options so checkout: `./bld.exe --help`. + +## Further plans + +My priority is to improve the C user API, harden the compiler, accommodate things that I didn't foresee and stuff like that. + +Sometime in the future I want to implement a bytecode backend so that the language can be used like Lua as a nice scripting language. + +I'm also considering the addition of overloaded procedures because it would greatly aid in writing macros. + +# Language overview + +The language is strictly procedural, I have taken most of the inspiration from C, Golang, Ion, Jai and Odin. There are no classes, methods etc. only procedures and data types. + +## Packages + +Package is a real directory on your disk that contains source files. It's also an aggregation of declarations - functions, constants, variables, types which you can `import` into your program. + +``` odin +import "libc"; +import RL "raylib"; + +main :: proc(): int { + RL.SetClipboardText("**magic**"); + printf("**magic**"); + return 0; +} +``` + + + + + +## Constants + +By which I mean the literal values but also the named declarations. There are 3 constant types in the language: untyped ints, untyped floats and untyped strings. The "untyped" here means that the type is inferred from context. There are no suffixes like 'ull', no random overflows and the values are also bounds checked for safety. If you have ever used Go, I have a good news for you, you are already familiar with this concept. + +``` odin +binary :: 0b10000110; +hex1 :: 0xabcd3245; +hex2 :: 0xABCD3245; +decimal :: 1235204950; +floating_point :: 2342.44230; + +boolean :: false; +nil_val :: nil; + +string_val :: "Something"; +raw_string :: ` +{ + "cool_json": "yes", + "cool_array": ["a", "b", 32], +} +`; +``` + +## Types + +The type system is strict, most conversions require explicit casts. + +``` odin +a: int = 10; +b: long = :long(a); // all of these assignments require a cast +c: float = :float(a); +d: short = :short(a); +e: llong = 1234; // untyped constants automatically fit into the context + // no matter the type +``` + +There is one exception which is the `*void` type. It has very permissive semantics. + +``` odin +i1: int; +v : *void = &i1; +i2: *int = v; +``` + +When using regular pointers, again, casts are necessary. + +``` odin +i1: *int = nil; +i2: *float = :*float(i1); +``` + +Compound types are read from left to right. This creates a nice mirroring between spoken and the symbolic language: + +``` odin +a: *int; // a: pointer '*' to an int +b: [32]*int; // an: array of 32 pointers to int +c: *proc(): int; // a: pointer to a proc type that returns int +``` + +## Structs and unions + +``` odin +Node :: struct { + v1: Value; + v2: Value; +} + +Value :: union { + i64: llong; + u64: ullong; +} +``` + +## Basic types + +The language uses exactly the same types as C for greater compatibility. I don't want to go against the current. I want the language to be as simple as possible. + +``` odin +c: char; uc: uchar; s: short; us: ushort; +i: int; ui: uint; l: long; ul: ulong; +ll: llong; ull: ullong; f: float; d: double; +b: bool; +``` + +## Typedefs + +Typedef allows you to create an alias to an existsing type but with additional layer of type safety. `my_int` is not an `int`, it's a different type and so it requires a cast. + +``` +my_int :: typedef int; + +i: int = 10; +mi: my_int = :my_int(i); // requires a cast +``` + +A simple alias can be defined by adding a '@weak' note: + +``` +my_int: typedef int; @weak + +i: int = 10; +mi: my_int = i; +``` + +## Compound expressions + +These are expressions meant for initializing structs and unions. + +- Particular members can be targeted by name. +- Members that were not mentioned are initialized to zero. + +``` odin +Vector2 :: struct { x: float; y: float; } +Camera2D :: struct { + offset: Vector2; + target: Vector2; + rotation: float; + zoom: float; +} + +Camera: Camera2D = { + offset = {100, 100}, + zoom = 1.0, +}; + +SecondCamera := :Camera2D{{1, 1}, zoom = 1.0}; +``` + +## Arrays and compound expressions + +``` odin +array: [100]int; // array of 100 integers + +inited_array: [100]int = { + 0, + [4] = 4, + [50] = 50, + [99] = 99, + // remaining values are '0'ed +}; +``` + +## Named and default procedure arguments + +``` odin +RED :: 0xff0000ff; +DrawRectangle :: proc(x: int, y: int, w: int, h: int, color: uint = RED); + +main :: proc(): int { + DrawRectangle(x = 100, y = 100, w = 50, h = 50); + return 0; +} +``` + +## Simulating enums + +The language doesn't have enums but similar feature can be easily simulated. Operator '^' allows you to generate a list of enumerated constants: 1, 2, 3 ... using typedef you can create a simple integer type with additional type safety. + +``` +TextKind :: typedef int; +TEXT_INVALID :: 0; +TEXT_BOLD :: ^; // 1 +TEXT_CURSIVE :: ^; // 2 +TEXT_NORMAL :: ^; // 3 +``` + +## Enumerating bit flags + +Operator '<<' allows you to generate a list of enumerated flags: 0b1, 0b10, 0b100 ... + +``` +EntityProps :: typedef uint; +ENTITY_CAN_BURN :: 0b1; +ENTITY_CAN_MOVE :: <<; // 0b10 +ENTITY_CAN_BE_SHOCKED :: <<; // 0b100 +ENTITY_WALKING :: <<; // 0b1000 +``` + +## `*char` and String types + +The language by default is very `*char` friendly. Strings default to the cstring type which functions in exactly the same way as in C. It functions as an array of bytes which is null terminated by a null `0`. + +But the language also has it's own String type: + +``` +String :: struct { + str: *char; + len: int; +} +``` + +Untyped strings work well with both: + +``` odin +a: String = "sized string"; +b: *char = "c string"; +c: = "this defaults to *char"; +``` + +`String` is a structure so you need to index it using `.str` or `.len`. + +``` odin +test :: proc() { + a: *char = "C string"; + c := a[1]; + + b: String = "Len string"; + c = b.str[1]; + len := b.len; @unused +} +``` + +A `lengthof` operator can be used to learn how big a constant string is, this also works for arrays: + +``` odin +str :: "String"; +len :: lengthof(str); +``` + +## Pointer arithmetic + +``` odin +import "libc"; + +test :: proc() { + a: *int = malloc(sizeof(:int) * 10); + c: *int = addptr(a, 4); + d: *int = &a[4]; + // there is no: (a + 4) +} +``` + +## Casting between types + +``` +a: float = :float(10); + +b := &a; +c := :*int(b); +``` + +## If statement + +``` odin +if_statement_showcase :: proc(cond: int) { + if cond == 1 { + // + } else if cond == 2 { + // + } else { + // + } +} +``` + +## Switch statement + +``` odin +import "libc"; +switch_statement_showcase :: proc(value: int) +{ + switch value + { + case 0,4,8: + { + printf("0, 4, 8\n"); + } + case 1, 2, 3: + { + printf("1, 2, 3\n"); + } @fallthrough + case 5: + { + printf("this activates when 1, 2, 3 and 5\n"); + } + default: printf("default case"); + } +} +``` + +## For loop + +``` odin +for_loop_showcase :: proc() { + + // infinite loop + for { + /* .. */ + } + + cond := true; + for cond { + break; + } + + for i := 0; i < 4; i += 1 { + // + } + + i := 0; + for i < 4 { + i += 1; + } + + i = 0; + for i < 4; i += 1 { + // + } +} +``` + +## Labeled loops, breaks and continues + +You can label a loop and use that label to control the outer loop. + +``` odin +test :: proc() { + cond := true; + outer_loop: for cond { + for cond { + break outer_loop; // continue works too + } + } +} +``` + +## Defer statement + +A defer statement allows to postpone a certain action to the end of scope. For example - you might allocate memory and use defer just bellow your allocation to free the memory. This free will be deferred, it will happen a bit later. + +``` odin +import "libc"; +test :: proc() { + // it's useful to keep certain pairs of actions together: + file := fopen("data.txt", "rb"); + if (file) { + defer fclose(file); + // .. do things + } +} +``` + +## Notes + +You can annotate declarations, statements etc. This puts metadata on the AST which you can access from a metaprogram. + +``` odin +// a note that starts with '#', doesn't bind to anything, it basically acts as a directive. +#do_something(a, b, c); + + +Data :: struct { + a: int; + b: *int; +} @serialize // binds to AST of Data +``` + +The language uses notes to implement a bunch of features, for example: + +``` odin +#static_assert(sizeof(:int) == 4); + + +test :: proc() { + // ... +} @build_if(LC_OS == OS_WINDOWS) +``` + +## Conditional compilation + +It's important for a low level language to have some form of platform awareness. We don't have includes and preprocessor here so I decided to implement a construct that works during parsing stage. It discards declarations and doesn't let them into typechecking based on the evaluation of the inner expression. + +'#build_if' can appear at the top of the file, it decides whether to compile that particular file or not: + +``` odin +#build_if(LC_OS == OS_WINDOWS); +``` + +'@build_if' can be bound to any top level declaration. + +``` odin +LONG_MAX :: 0xFFFFFFFF; @build_if(LC_OS == OS_WINDOWS) +LONG_MAX :: 0xFFFFFFFFFFFFFFFF; @build_if(LC_OS == OS_MAC || LC_OS == OS_LINUX) +``` + +## Builtins (like sizeof) + +``` odin +a := sizeof(:int); +b := alignof(:int); + +A :: struct { a: int; b: int; } +c := offsetof(:A, b); + +d := lengthof("asd"); +e := typeof(d); + +#static_assert(offsetof(:A, b) == 4); +``` + +## Raw C code when targeting the C generator + +``` odin +#`#include `; + +global_variable := 0; + +main :: proc(): int { + a: *int = #`malloc(32)`; + #`a[0] = lc_package_global_variable`; + return a[0]; +} +``` + +## Any and typeof + +``` odin +Any :: struct { + type: int; + data: *void; +} +``` + +``` odin +test :: proc() { + a: Any = 32; + b: Any = "thing"; + c: Any = b; + + i: int = 10; + d: Any = &i; +} +``` + +``` odin +print :: proc(v: Any) { + switch(v.type) { + case typeof(:int): { + val := :*int(v.data); + // .. + } + case typeof(:float): { + val := :*float(v.data); + // .. + } + } +} + +main :: proc() { + print(32); + print("asd"); +} +``` + +## Variadic arguments with Any promotion + +``` odin +import "libc"; + +any_vargs :: proc(fmt: *char, ...Any) { + va: va_list; + va_start(va, fmt); + + for i := 0; fmt[i]; i += 1 { + if fmt[i] == '%' { + arg := va_arg_any(va); + + if arg.type == typeof(:int) { + val := :*int(arg.data); + // .. + } else { + // .. + } + } + } + + va_end(va); +} + +main :: proc() { + any_vargs("testing % %", 32, "thing"); +} +``` + +## Comments + +``` odin +// I'm a line comment + +/* I'm a block comment + /* + I can even nest! + */ +*/ +``` + +## Doc comments + +``` odin +/** package + +This is a package doc comment, + there can only be 1 per package, + it appears at top of the file. +It binds to the package AST. + +*/ + +/** file + +This is a file doc comment, + there can only be 1 per file, + it appears at top of the file under package doc comment. +It binds to the file AST. + +*/ + +/** + +This is a top level declaration doc comment, + 1 per declaration, + it appears above the declaration. +It binds to the declaration AST. + +*/ +A :: proc(): int { + return 0; +} +``` + +## Packed structs + +``` odin +A :: struct { + a: short; + b: char; + c: int; + d: char; + e: llong; + f: uchar; +} @packed +``` + +## Useful resources for compiler development + +* https://c3.handmade.network/blog/p/8632-handling_parsing_and_semantic_errors_in_a_compiler - great article by Christoffer Lerno (C3 author) about handling errors in compilers. +* https://www.youtube.com/watch?v=bNJhtKPugSQ - Walter Bright (D author) talks about AST poisoning here. +* https://bitwise.handmade.network/ - series by Per Vognsen where he actually creates a C like language, very helpful, very hands on! +* https://hero.handmade.network/episode/code/day206/ - this episode of handmade hero started me on the entire compiler journey, a long, long time ago. +* https://www.youtube.com/watch?v=TH9VCN6UkyQ&list=PLmV5I2fxaiCKfxMBrNsU1kgKJXD3PkyxO - I have re-watched this playlist many this, searching for keywords and ideas. Jonathan Blow's compiler was a big inspiration of mine when learning programming languages. +* A Retargetable C Compiler: Design and Implementation by Christopher W. Fraser and David R. Hanson - sometimes looked at this as a reference to figure stuff out. Very helpful resource on compiler construction, the way it's written reads more like documentation but you use what you have. +* Compiler Construction by Niklaus Wirth - https://people.inf.ethz.ch/wirth/CompilerConstruction/index.html - have to learn to read Pascal / Oberon but he goes over implementing all the stages of the compiler. Wirth's project of implementing an entire hardware / software stack is really inspiring. +* https://github.com/rui314/chibicc - great resource for learning how to write a very dumb x64 backend. I like the format, you go over git commits, doesn't work well on github though, with Sublime Merge it's a pleasure to follow. +* https://go.dev/blog/constants - article on golang type system, untyped types, constants that kind of stuff. +* https://github.com/JoshuaManton/sif - looked at this as a reference from time to time, author seems like a Jonathan Blow fan so it was a good resource informed by similar resources as I used. +* https://github.com/gingerbill/odin - I sometimes peeked at the compiler to figure stuff out when I was confused. +https://c3.handmade.network/blog - Christoffer Lerno (C3 author) blog. +* https://github.com/c3lang/c3c - I sometimes looked at C3 compiler as a reference, the author also let me use his bigint library, thanks a lot! :) diff --git a/build.bat b/build.bat new file mode 100644 index 0000000..fc8ae12 --- /dev/null +++ b/build.bat @@ -0,0 +1,11 @@ +@echo off + +if not exist build\bld.exe ( + mkdir build + cd build + cl -Fe:bld.exe ../src/build_tool/main.cpp -FC -WX -W3 -wd4200 -wd4244 -diagnostics:column -nologo -Zi -D_CRT_SECURE_NO_WARNINGS + cd .. +) + +rem ubuntu run ./build.sh +build\bld.exe diff --git a/build_file.cpp b/build_file.cpp new file mode 100644 index 0000000..9de7d1f --- /dev/null +++ b/build_file.cpp @@ -0,0 +1,311 @@ +/* This build file runs all the tests, compiles them using all +available compilers, cleans the house and walks the dog. Wowie. +*/ +#include "src/build_tool/library.cpp" + +#define LC_USE_CUSTOM_ARENA +#define LC_Arena MA_Arena +#define LC__PushSizeNonZeroed MA__PushSizeNonZeroed +#define LC__PushSize MA__PushSize +#define LC_InitArena MA_Init +#define LC_DeallocateArena MA_DeallocateArena +#define LC_BootstrapArena MA_Bootstrap +#define LC_TempArena MA_Temp +#define LC_BeginTemp MA_BeginTemp +#define LC_EndTemp MA_EndTemp + +#define LC_String S8_String +#include "src/compiler/lib_compiler.c" + +#include + +bool UseClang; +bool UseCL; +bool UseTCC; +bool UseGCC; +bool QuickRun; +bool BuildX64Sandbox; +bool BreakpointOnError; +S8_List TestsToRun; +bool UseColoredIO; +int ThreadCount = 24; +bool PrintAllFunctions; + +S8_String RaylibLIB; +S8_String RaylibDLL; + +#include "src/build_file/ast_verify.cpp" +#include "src/build_file/test_readme.cpp" +#include "src/build_file/testsuite.cpp" +#include "src/build_file/package_compiler.cpp" + +#include "examples/add_printf_format_check/build.cpp" +#include "examples/pathfinding_visualizer/build.cpp" +#include "examples/generate_type_info/build.cpp" +#include "examples/add_dynamic_array_macro/build.cpp" +#include "examples/text_editor/build.cpp" +#include "examples/hello_world/build.cpp" +#include "examples/sandbox/build.cpp" +#include "examples/create_raylib_window/build.cpp" +#include "examples/add_instrumentation/build.cpp" +#include "examples/use_as_data_format_with_typechecking/build.cpp" +#include "examples/add_source_location_macro/build.cpp" + +int main(int argc, char **argv) { + MA_InitScratch(); + + MA_Scratch scratch; + UseColoredIO = OS_EnableTerminalColors(); + + { + CmdParser p = MakeCmdParser(scratch, argc, argv, "I'm a build tool for this codebase, by default I build the entire test suite"); + AddBool(&p, &BuildX64Sandbox, "build-x64-sandbox", "build the x64 sandbox program using msvc"); + AddBool(&p, &QuickRun, "quick", "build tests using tcc compiler only"); + AddBool(&p, &BreakpointOnError, "breakpoint", "breakpoint if a compiler error is thrown"); + AddBool(&p, &PrintAllFunctions, "print-functions", "prints all functions marked with LC_FUNCTION"); + AddInt(&p, &ThreadCount, "threads", "number of threads to use when running the test suite"); + AddList(&p, &TestsToRun, "tests", "run only these particular tests"); + if (!ParseCmd(Perm, &p)) return 0; + } + + // + // Find compilers in the path + // + { + char *path_string = getenv("PATH"); + Array path = Split(path_string, IF_WINDOWS_ELSE(";", ":")); + + char *end = IF_WINDOWS_ELSE(".exe", ""); + For(path) { + S8_String clpath = Fmt("%.*s/cl%s", S8_Expand(it), end); + S8_String clangpath = Fmt("%.*s/clang%s", S8_Expand(it), end); + S8_String tccpath = Fmt("%.*s/tcc%s", S8_Expand(it), end); + S8_String gccpath = Fmt("%.*s/gcc%s", S8_Expand(it), end); + + if (OS_FileExists(clpath)) UseCL = true; + if (OS_FileExists(clangpath)) UseClang = true; + if (OS_FileExists(tccpath)) UseTCC = true; +#if OS_WINDOWS == 0 + if (OS_FileExists(gccpath)) UseGCC = true; +#endif + } + } + + if (UseClang == false && UseCL == false && UseTCC == false && UseGCC == false) { + IO_FatalErrorf("Found no supported compiler on the PATH! Make sure to have GCC, Clang, CL/MSVC or TCC on the PATH"); + } + + if (QuickRun) { + if (!UseTCC) IO_FatalErrorf("TCC is not on the path"); + UseClang = false; + UseCL = false; + UseGCC = false; + UseTCC = true; + } + + RaylibLIB = OS_GetAbsolutePath(Perm, "../pkgs/raylib/raylib-5.0_win64_msvc16/lib/raylibdll.lib"); + RaylibDLL = OS_GetAbsolutePath(Perm, "../pkgs/raylib/raylib-5.0_win64_msvc16/lib/raylib.dll"); + + if (BuildX64Sandbox) { + PushDir("x64_sandbox"); + S8_String cc = "cl"; + + Array flags = {MA_GetAllocator(scratch)}; + flags += "/MP /Zi -D_CRT_SECURE_NO_WARNINGS"; + flags += "/FC /WX /W3 /wd4200 /diagnostics:column /nologo"; + flags += "/GF /Gm- /Oi"; + flags += "/GR- /EHa-"; + flags += "/D_DEBUG -RTC1 -Od"; + flags += Fmt("/Fe:x64main.exe"); + OS_DeleteFile("x64main.pdb"); + Run(cc + "../../src/x64/x64main.cpp" + flags); + return 0; + } + + PackageCompiler(); + IO_Printf("Compiler packed successfully: lib_compiler.h\n"); + + if (ShouldRun("test_readme")) { + TestReadme(); + } + + OS_MakeDir("examples"); + if (ShouldRun("add_printf_format_check")) { + bool result = add_printf_format_check(); + if (result) IO_Printf("%-50s - OK\n", "add_printf_format_check"); + else IO_Printf("%-50s - ERROR\n", "add_printf_format_check"); + } + + if (ShouldRun("generate_type_info")) { + bool result = generate_type_info(); + if (result) IO_Printf("%-50s - OK\n", "generate_type_info"); + else IO_Printf("%-50s - ERROR\n", "generate_type_info"); + } + + if (ShouldRun("add_dynamic_array_macro")) { + bool result = add_dynamic_array_macro(); + if (result) IO_Printf("%-50s - OK\n", "add_dynamic_array_macro"); + else IO_Printf("%-50s - ERROR\n", "add_dynamic_array_macro"); + } + + if (ShouldRun("text_editor")) { + bool result = text_editor(); + if (result) IO_Printf("%-50s - OK\n", "text_editor"); + else IO_Printf("%-50s - ERROR\n", "text_editor"); + } + + if (ShouldRun("pathfinding_visualizer")) { + bool result = pathfinding_visualizer(); + if (result) IO_Printf("%-50s - OK\n", "pathfinding_visualizer"); + else IO_Printf("%-50s - ERROR\n", "pathfinding_visualizer"); + } + + if (ShouldRun("hello_world")) { + bool result = hello_world(); + if (result) IO_Printf("%-50s - OK\n", "hello_world"); + else IO_Printf("%-50s - ERROR\n", "hello_world"); + } + + if (!ShouldRun("sandbox")) { + bool result = sandbox(); + if (result) IO_Printf("%-50s - OK\n", "sandbox"); + else IO_Printf("%-50s - ERROR\n", "sandbox"); + } + + if (ShouldRun("create_raylib_window")) { + bool result = create_raylib_window(); + if (result) IO_Printf("%-50s - OK\n", "create_raylib_window"); + else IO_Printf("%-50s - ERROR\n", "create_raylib_window"); + } + + if (ShouldRun("add_instrumentation")) { + bool result = add_instrumentation(); + if (result) IO_Printf("%-50s - OK\n", "add_instrumentation"); + else IO_Printf("%-50s - ERROR\n", "add_instrumentation"); + } + + if (!ShouldRun("wasm_playground") && UseClang) { + OS_MakeDir("wasm_playground"); + int result = Run("clang --target=wasm32 -mbulk-memory -Oz -Wno-writable-strings --no-standard-libraries -Wl,--strip-all -Wl,--import-memory -Wl,--no-entry -o wasm_playground/playground.wasm ../src/wasm_playground/wasm_main.c -DOS_WASM=1"); + + S8_String index = OS_ReadFile(scratch, "../src/wasm_playground/index.html"); + S8_List programs = S8_MakeEmptyList(); + + OS_SetWorkingDir("wasm_playground"); // so that RegisterDir("../../pkgs") works + for (OS_FileIter it = OS_IterateFiles(scratch, "../../src/wasm_playground/"); OS_IsValid(it); OS_Advance(&it)) { + if (S8_EndsWith(it.filename, ".lc", false)) { + RunTestFile({TestKind_File, it.absolute_path, it.filename, "not_needed", true}); + + S8_String file = OS_ReadFile(scratch, it.absolute_path); + file = S8_ReplaceAll(scratch, file, S8_Lit("\\"), S8_Lit("\\\\"), true); + S8_AddF(scratch, &programs, "`%.*s`,\n", S8_Expand(file)); + } + } + OS_SetWorkingDir(".."); + + S8_String programs_string = S8_Merge(scratch, programs); + S8_String new_index = S8_ReplaceAll(scratch, index, "", programs_string, false); + + OS_WriteFile("wasm_playground/playground.html", new_index); + OS_CopyFile("../src/wasm_playground/run_server.bat", "wasm_playground/run_server.bat", true); + + if (result == 0) IO_Printf("%-50s - OK\n", "wasm_playground"); + else IO_Printf("%-50s - ERROR\n", "wasm_playground"); + } + + if (ShouldRun("use_as_data_format_with_typechecking")) { + bool result = use_as_data_format_with_typechecking(); + if (result) IO_Printf("%-50s - OK\n", "use_as_data_format_with_typechecking"); + else IO_Printf("%-50s - ERROR\n", "use_as_data_format_with_typechecking"); + } + + if (ShouldRun("add_source_location_macro")) { + bool result = add_source_location_macro(); + if (result) IO_Printf("%-50s - OK\n", "add_source_location_macro"); + else IO_Printf("%-50s - ERROR\n", "add_source_location_macro"); + } + + Array processes = {MA_GetAllocator(scratch)}; + if (ShouldRun("compilation")) { + // + // Test if things compile in C and C++ mode on all available compilers + // + S8_String working_dir = PushDir("targets"); + Array files = {MA_GetAllocator(scratch)}; + + files.add("../../../tests/compilation/test_compile_packed.c"); + files.add("../../../tests/compilation/test_compile_packed_cpp.c"); + files.add("../../../tests/compilation/test_compile_with_core.c"); + files.add("../../../tests/compilation/test_compile_with_core_cpp.cpp"); + files.add("../../../tests/compilation/test_compile_header.cpp"); + files.add("../../../tools/lcompile.c"); + + For(files) { + S8_String name_no_ext = S8_GetNameNoExt(it); + S8_String exe = Fmt("%.*s.exe", S8_Expand(name_no_ext)); + S8_String file_to_compile = it; + bool is_cpp = S8_EndsWith(it, ".cpp"); + + if (UseCL) { + S8_String cc = "cl"; + + Array flags = {MA_GetAllocator(scratch)}; + flags += "/Zi -D_CRT_SECURE_NO_WARNINGS"; + flags += "/FC /WX /W3 /wd4200 /diagnostics:column /nologo"; + flags += Fmt("/Fe:%.*s /Fd:%.*s.pdb", S8_Expand(exe), S8_Expand(name_no_ext)); + + Array link = {MA_GetAllocator(scratch)}; + link += "/link /incremental:no"; + + S8_String dir = Fmt("%.*s_cl_debug_" OS_NAME, S8_Expand(name_no_ext)); + Process p = RunEx(cc + file_to_compile + flags, dir); + processes.add(p); + } + + if (UseClang) { + S8_String cc = "clang"; + + Array flags = {MA_GetAllocator(scratch)}; + flags += "-g -Wno-write-strings"; + flags += "-fdiagnostics-absolute-paths"; + flags += "-fsanitize=address"; + if (is_cpp) flags += "-std=c++11"; + IF_LINUX(flags += "-lm";) + flags += Fmt("-o %.*s", S8_Expand(exe)); + + S8_String dir = Fmt("%.*s_clang_debug_" OS_NAME, S8_Expand(name_no_ext)); + Process p = RunEx(cc + file_to_compile + flags, dir); + processes.add(p); + } + + if (UseGCC) { + S8_String cc = "gcc"; + + Array flags = {MA_GetAllocator(scratch)}; + flags += "-g -Wno-write-strings"; + flags += "-fsanitize=address"; + if (is_cpp) flags += "-std=c++11"; + IF_LINUX(flags += "-lm";) + flags += Fmt("-o %.*s", S8_Expand(exe)); + + S8_String dir = Fmt("%.*s_gcc_debug_" OS_NAME, S8_Expand(name_no_ext)); + Process p = RunEx(cc + file_to_compile + flags, dir); + processes.add(p); + } + } + OS_SetWorkingDir(working_dir); + } + + RunTests(); + + // + // Wait for compilation from before tests to finish + // + int result = 0; + For(processes) { + int exit_code = Wait(&it); + if (exit_code != 0) result = exit_code; + } + + return result; +} diff --git a/examples/add_dynamic_array_macro/build.cpp b/examples/add_dynamic_array_macro/build.cpp new file mode 100644 index 0000000..e5cc626 --- /dev/null +++ b/examples/add_dynamic_array_macro/build.cpp @@ -0,0 +1,173 @@ +bool add_dynamic_array_macro() { + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + LC_LangBegin(lang); + + LC_RegisterPackageDir("../pkgs"); + LC_RegisterPackageDir("../examples"); + + LC_Intern name = LC_ILit("add_dynamic_array_macro"); + LC_ParsePackagesUsingRegistry(name); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + Array array_of_to_gen = {MA_GetAllocator(L->arena)}; + + LC_Intern init_array = LC_ILit("init_array"); + LC_AST *init_array_ast = LC_ParseStmtf("{ init_array_base(REF, SIZE, sizeof(REF.data[0])); }"); + LC_AST *init_array_add_ast = LC_ParseStmtf("{ REF.data[REF.len] = ITEM; REF.len += 1; }"); + + LC_Intern add = LC_ILit("add"); + LC_AST *add_ast = LC_ParseStmtf( + "{" + " try_growing_array(REF, sizeof(REF.data[0]));" + " REF.data[REF.len] = ITEM;" + " REF.len += 1;" + "}"); + LC_Intern ITEM = LC_ILit("ITEM"); + LC_Intern REF = LC_ILit("REF"); + + LC_AST *package = LC_GetPackageByName(name); + LC_AST *first_ast = (LC_AST *)L->ast_arena->memory.data; + for (int i = 0; i < L->ast_count; i += 1) { + LC_AST *it = first_ast + i; + + // Detect and save to array every unique use of 'ArrayOfT' + if (it->kind == LC_ASTKind_TypespecIdent) { + S8_String name = S8_MakeFromChar((char *)it->eident.name); + if (S8_StartsWith(name, "ArrayOf")) { + S8_String s8 = S8_Skip(name, S8_Lit("ArrayOf").len); + LC_Intern type = LC_InternStrLen(s8.str, (int)s8.len); + + bool is_unique = true; + For2(in_array, array_of_to_gen) { + if (in_array == type) { + is_unique = false; + break; + } + } + + if (is_unique) array_of_to_gen.add(type); + } + } + + if (it->kind == LC_ASTKind_StmtExpr && it->sexpr.expr->kind == LC_ASTKind_ExprCall) { + LC_AST *name = it->sexpr.expr->ecompo.name; + LC_AST *call = it->sexpr.expr; + + if (name->kind != LC_ASTKind_ExprIdent) { + continue; + } + + if (name->eident.name == add) { + if (call->ecompo.size != 2) { + LC_ReportASTError(call, "wrong argument count in macro call"); + continue; + } + LC_AST *first_item = call->ecompo.first; + LC_AST *arr_ref = first_item->ecompo_item.expr; + LC_AST *item = first_item->next->ecompo_item.expr; + + LC_AST *macro = LC_CopyAST(L->arena, add_ast); + LC_ASTArray array = LC_FlattenAST(L->arena, macro); + + for (int m_i = 0; m_i < array.len; m_i += 1) { + LC_AST *m_it = array.data[m_i]; + if (m_it->kind == LC_ASTKind_ExprIdent) { + if (m_it->eident.name == ITEM) { + *m_it = *LC_CopyAST(L->arena, item); + } else if (m_it->eident.name == REF) { + *m_it = *LC_CopyAST(L->arena, arr_ref); + } + } + m_it->pos = it->pos; + } + + macro->next = it->next; + macro->prev = it->prev; + *it = *macro; + } + + if (name->eident.name == init_array) { + if (call->ecompo.size != 2) { + LC_ReportASTError(call, "wrong argument count in macro call"); + continue; + } + + LC_AST *first_item = call->ecompo.first; + LC_AST *arr_ref = first_item->ecompo_item.expr; + LC_AST *item = first_item->next->ecompo_item.expr; + + if (item->kind != LC_ASTKind_ExprCompound) { + LC_ReportASTError(item, "expected compound"); + continue; + } + + LC_AST *macro = LC_CopyAST(L->arena, init_array_ast); + LC_ASTArray array = LC_FlattenAST(L->arena, macro); + for (int m_i = 0; m_i < array.len; m_i += 1) { + LC_AST *m_it = array.data[m_i]; + if (m_it->kind != LC_ASTKind_ExprIdent) continue; + + if (m_it->eident.name == LC_ILit("SIZE")) { + // This is a bit dangerous here because through + // this call we are bumping L->ast_count += 1 + *m_it = *LC_CreateAST(item->pos, LC_ASTKind_ExprInt); + m_it->eatom.i = LC_Bigint_u64(item->ecompo.size); + } else if (m_it->eident.name == REF) { + *m_it = *LC_CopyAST(L->arena, arr_ref); + } + m_it->pos = it->pos; + } + + LC_ASTFor(item_it, item->ecompo.first) { + LC_AST *init_item = LC_CopyAST(L->arena, init_array_add_ast); + LC_ASTArray array = LC_FlattenAST(L->arena, init_item); + for (int m_i = 0; m_i < array.len; m_i += 1) { + LC_AST *m_it = array.data[m_i]; + + if (m_it->kind == LC_ASTKind_ExprIdent) { + if (m_it->eident.name == ITEM) { + *m_it = *LC_CopyAST(L->arena, item_it->ecompo_item.expr); + } else if (m_it->eident.name == REF) { + *m_it = *LC_CopyAST(L->arena, arr_ref); + } + } + m_it->pos = name->pos; + } + + LC_DLLAdd(macro->sblock.first, macro->sblock.last, init_item); + } + + macro->next = it->next; + macro->prev = it->prev; + *it = *macro; + } + } + } + + // @todo: take package into consideration, my current idea is to have a shared package + // that is going to be imported into every other package, for now we use only the current package + For(array_of_to_gen) { + LC_AST *ast = LC_ParseDeclf("ArrayOf%s :: struct { data: *%s; len: int; cap: int; }", (char *)it, (char *)it); + LC_AST *file = package->apackage.ffile; + + LC_DLLAdd(file->afile.fdecl, file->afile.ldecl, ast); + } + + LC_OrderAndResolveTopLevelDecls(name); + LC_ResolveAllProcBodies(); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + LC_String code = LC_GenerateUnityBuild(L->ordered_packages); + OS_MakeDir("examples/add_dynamic_array_macro"); + OS_WriteFile("examples/add_dynamic_array_macro/add_dynamic_array_macro.c", code); + + return true; +} \ No newline at end of file diff --git a/examples/add_dynamic_array_macro/main.lc b/examples/add_dynamic_array_macro/main.lc new file mode 100644 index 0000000..c9a9244 --- /dev/null +++ b/examples/add_dynamic_array_macro/main.lc @@ -0,0 +1,64 @@ +import "libc"; + +try_growing_array :: proc(arrp: *void, element_size: size_t) { + arr: *ArrayOfvoid = arrp; + if (arr.len + 1 > arr.cap) { + cap := arr.cap * 2; + if (cap == 0) cap = 16; + + arr.data = realloc(arr.data, element_size * :size_t(cap)); + arr.cap = cap; + } +} + +init_array_base :: proc(arrp: *void, size: int, element_size: size_t) { + arr: *ArrayOfvoid = arrp; + arr.data = malloc(element_size * :size_t(size * 2)); + arr.len = size * 2; +} + +main :: proc(): int { + { + arr: ArrayOfint; + init_array(&arr, {0, 1, 2, 3, 4, 6, 7, 9, 10}); + for i := 0; i < 10; i += 1 { + assert(arr.data[i] == i); + } + + + + for it := &arr.data[0]; it < &arr.data[arr.len]; it = &it[1] { + + } + } + + { + arr: ArrayOfint; + + for i := 0; i < 128; i += 1 { + add(&arr, i); + } + + for i := 0; i < 128; i += 1 { + assert(arr.data[i] == i); + } + } + + + { + arr: ArrayOffloat; + + for i: float = 0; i < 128; i += 1 { + add(&arr, i); + } + + for i := 0; i < 128; i += 1 { + i0 := :int(arr.data[i]); + assert(i0 == i); + } + + } + + + return 0; +} \ No newline at end of file diff --git a/examples/add_instrumentation/build.cpp b/examples/add_instrumentation/build.cpp new file mode 100644 index 0000000..ed5f20b --- /dev/null +++ b/examples/add_instrumentation/build.cpp @@ -0,0 +1,62 @@ +bool OnDeclParsed_AddInstrumentation(bool discard, LC_AST *n) { + if (discard) return discard; + + if (n->kind == LC_ASTKind_DeclProc && n->dproc.body) { + if (n->dbase.name == LC_ILit("BeginProc")) return false; + if (n->dbase.name == LC_ILit("EndProc")) return false; + + LC_AST *body = n->dproc.body; + + LC_AST *begin = LC_ParseStmtf("BeginProc(\"%s\", \"%s\", %d)", n->dbase.name, n->pos->lex->file, n->pos->line); + LC_AST *end = LC_ParseStmtf("defer EndProc();"); + + LC_DLLAddFront(body->sblock.first, body->sblock.last, end); + LC_DLLAddFront(body->sblock.first, body->sblock.last, begin); + } + return discard; +} + +bool add_instrumentation() { + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + lang->on_decl_parsed = OnDeclParsed_AddInstrumentation; + LC_LangBegin(lang); + + LC_RegisterPackageDir("../pkgs"); + LC_RegisterPackageDir("../examples"); + + LC_Intern name = LC_ILit("add_instrumentation"); + LC_ASTRefList packages = LC_ResolvePackageByName(name); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + DebugVerifyAST(packages); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + S8_String code = LC_GenerateUnityBuild(packages); + S8_String path = "examples/add_instrumentation/add_instrumentation.c"; + OS_MakeDir("examples"); + OS_MakeDir("examples/add_instrumentation"); + OS_WriteFile(path, code); + if (!UseCL) { + LC_LangEnd(lang); + return true; + } + + S8_String cmd = Fmt("cl %.*s -Zi -std:c11 -nologo -FC -Fd:examples/add_instrumentation/a.pdb -Fe:examples/add_instrumentation/add_instrumentation.exe %.*s", S8_Expand(path), S8_Expand(RaylibLIB)); + int errcode = Run(cmd); + if (errcode != 0) { + LC_LangEnd(lang); + return false; + } + // Run("examples/add_instrumentation/add_instrumentation.exe"); + + LC_LangEnd(lang); + return true; +} \ No newline at end of file diff --git a/examples/add_instrumentation/main.lc b/examples/add_instrumentation/main.lc new file mode 100644 index 0000000..bee6dcb --- /dev/null +++ b/examples/add_instrumentation/main.lc @@ -0,0 +1,13 @@ +import c "libc"; + +BeginProc :: proc(func: *char, file: *char, line: int) { + c.printf("begin timming proc: %s at %s:%d\n", func, file, line); +} + +EndProc :: proc() { + c.printf("end timming proc\n"); +} + +main :: proc(): int { + return 0; +} \ No newline at end of file diff --git a/examples/add_printf_format_check/build.cpp b/examples/add_printf_format_check/build.cpp new file mode 100644 index 0000000..e88b9f4 --- /dev/null +++ b/examples/add_printf_format_check/build.cpp @@ -0,0 +1,56 @@ +void OnExprResolved_CheckPrintf(LC_AST *n, LC_Operand *op); + +bool add_printf_format_check() { + bool result = false; + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + lang->user_data = (void *)&result; + lang->on_expr_resolved = OnExprResolved_CheckPrintf; + lang->on_message = LC_IgnoreMessage; + LC_LangBegin(lang); + LC_RegisterPackageDir("../pkgs"); + LC_RegisterPackageDir("../examples"); + + LC_Intern name = LC_ILit("add_printf_format_check"); + LC_ResolvePackageByName(name); + + LC_LangEnd(lang); + return result; +} + +void OnExprResolved_CheckPrintf(LC_AST *n, LC_Operand *op) { + if (n->kind == LC_ASTKind_ExprCall) { + LC_AST *name = n->ecompo.name; + if (name->kind == LC_ASTKind_ExprIdent) { + LC_Decl *decl = name->eident.resolved_decl; + if (decl->name == LC_ILit("printf")) { + LC_ResolvedCompo *items = n->ecompo.resolved_items; + LC_AST *string = items->first->expr; + IO_Assert(string->kind == LC_ASTKind_ExprString); + + char *c = (char *)string->eatom.name; + LC_ResolvedCompoItem *item = items->first->next; + for (int i = 0; c[i]; i += 1) { + if (c[i] == '%') { + if (item == NULL) { + LC_ReportASTError(n, "too few arguments passed"); + + // Test reports success if error thrown correctly + *(bool *)L->user_data = true; + return; + } + if (c[i + 1] == 'd') { + if (item->expr->type != L->tint) LC_ReportASTError(item->expr, "expected int type"); + item = item->next; + } else if (c[i + 1] == 's') { + if (item->expr->type != L->tpchar) LC_ReportASTError(item->expr, "expected *char type"); + item = item->next; + } + } + } + if (item != NULL) LC_ReportASTError(item->expr, "too many arguments passed"); + } + } + } +} diff --git a/examples/add_printf_format_check/main.lc b/examples/add_printf_format_check/main.lc new file mode 100644 index 0000000..90fe92c --- /dev/null +++ b/examples/add_printf_format_check/main.lc @@ -0,0 +1,6 @@ +import "libc"; + +main :: proc(): int { + printf("testing %d %s %d\n", 32, "str"); + return 0; +} \ No newline at end of file diff --git a/examples/add_source_location_macro/build.cpp b/examples/add_source_location_macro/build.cpp new file mode 100644 index 0000000..29c41b3 --- /dev/null +++ b/examples/add_source_location_macro/build.cpp @@ -0,0 +1,48 @@ +/* This function is called after compiler determined procedure type but +** before the arguments got verified. This opens up a window for call manipulation. +** +** I basically swoop in and add the {file, line} information to the call LC_AST before +** the arguments get resolved. +*/ +void ModifyCallsDuringResolution(LC_AST *n, LC_Type *type) { + LC_TypeMember *tm = type->tproc.args.last; + if (tm && tm->type->kind == LC_TypeKind_Struct && tm->type->decl->name == LC_ILit("SourceLoc")) { + LC_AST *call_item = LC_CreateAST(n->pos, LC_ASTKind_ExprCallItem); + call_item->ecompo_item.name = LC_ILit("source_loc"); + call_item->ecompo_item.expr = LC_ParseExprf("{\"%s\", %d}", n->pos->lex->file, n->pos->line); + LC_SetASTPosOnAll(call_item->ecompo_item.expr, n->pos); + + LC_DLLAdd(n->ecompo.first, n->ecompo.last, call_item); + n->ecompo.size += 1; + } +} + +bool add_source_location_macro() { + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + lang->before_call_args_resolved = ModifyCallsDuringResolution; + LC_LangBegin(lang); + LC_RegisterPackageDir("../examples/"); + LC_RegisterPackageDir("../pkgs"); + + LC_Intern name = LC_ILit("add_source_location_macro"); + LC_ASTRefList packages = LC_ResolvePackageByName(name); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + S8_String dir = "examples/add_source_location_macro"; + OS_MakeDir(dir); + S8_String cfile = "examples/add_source_location_macro/add_source_location_macro.c"; + S8_String code = LC_GenerateUnityBuild(packages); + OS_WriteFile(cfile, code); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + LC_LangEnd(lang); + return true; +} \ No newline at end of file diff --git a/examples/add_source_location_macro/main.lc b/examples/add_source_location_macro/main.lc new file mode 100644 index 0000000..e4634cf --- /dev/null +++ b/examples/add_source_location_macro/main.lc @@ -0,0 +1,16 @@ +import "libc"; + +SourceLoc :: struct { + file: String; + line: int; +} + +Allocate :: proc(size: int, source_loc: SourceLoc = {}): *void { + printf("%.*s:%d\n", source_loc.file.len, source_loc.file.str, source_loc.line); + return malloc(:size_t(size)); +} + +main :: proc(): int { + value: *int = Allocate(32); + return 0; +} \ No newline at end of file diff --git a/examples/create_raylib_window/build.cpp b/examples/create_raylib_window/build.cpp new file mode 100644 index 0000000..8fd4daf --- /dev/null +++ b/examples/create_raylib_window/build.cpp @@ -0,0 +1,30 @@ +bool create_raylib_window() { + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + LC_LangBegin(lang); + LC_RegisterPackageDir("../examples/"); + LC_RegisterPackageDir("../pkgs"); + + LC_Intern name = LC_ILit("create_raylib_window"); + LC_ASTRefList packages = LC_ResolvePackageByName(name); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + OS_MakeDir("examples/create_raylib_window"); + S8_String path = "examples/create_raylib_window/create_raylib_window.c"; + S8_String code = LC_GenerateUnityBuild(packages); + OS_WriteFile(path, code); + + bool success = true; + if (UseCL) { + OS_CopyFile(RaylibDLL, "examples/create_raylib_window/raylib.dll", true); + S8_String cmd = Fmt("cl %.*s -Zi -std:c11 -nologo -FC -Fd:examples/create_raylib_window/a.pdb -Fe:examples/create_raylib_window/create_raylib_window.exe %.*s", S8_Expand(path), S8_Expand(RaylibLIB)); + int errcode = Run(cmd); + if (errcode != 0) success = false; + } + + return success; +} \ No newline at end of file diff --git a/examples/create_raylib_window/main.lc b/examples/create_raylib_window/main.lc new file mode 100644 index 0000000..fa5c3b1 --- /dev/null +++ b/examples/create_raylib_window/main.lc @@ -0,0 +1,16 @@ +import RL "raylib"; + +main :: proc(): int { + RL.InitWindow(800, 600, "Thing"); + RL.SetTargetFPS(60); + + for !RL.WindowShouldClose() { + RL.BeginDrawing(); + RL.ClearBackground(RL.RAYWHITE); + RL.DrawText("Congrats! You created your first window!", 190, 200, 20, RL.LIGHTGRAY); + RL.EndDrawing(); + } + + RL.CloseWindow(); + return 0; +} \ No newline at end of file diff --git a/examples/generate_type_info/build.cpp b/examples/generate_type_info/build.cpp new file mode 100644 index 0000000..d5a3be3 --- /dev/null +++ b/examples/generate_type_info/build.cpp @@ -0,0 +1,64 @@ +bool generate_type_info() { + OS_DeleteFile("../examples/generate_type_info/generated.lc"); + + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + LC_LangBegin(lang); + + LC_RegisterPackageDir("../pkgs"); + LC_RegisterPackageDir("../examples"); + + LC_Intern name = LC_ILit("generate_type_info"); + + LC_ParsePackagesUsingRegistry(name); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + LC_OrderAndResolveTopLevelDecls(name); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + LC_BeginStringGen(L->arena); + LC_AST *package = LC_GetPackageByName(name); + + // Iterate through all the types and generate struct member information + LC_Type *first = (LC_Type *)L->type_arena->memory.data; + for (int i = 0; i < L->type_count; i += 1) { + LC_Type *type = first + i; + if (type->kind != LC_TypeKind_Struct) continue; + + LC_GenLinef("%s_Members := :[]StructMem{", (char *)type->decl->name); + L->printer.indent += 1; + + LC_TypeFor(it, type->tagg.mems.first) { + LC_GenLinef("{name = \"%s\", offset = %d},", (char *)it->name, it->offset); + } + + L->printer.indent -= 1; + LC_GenLinef("};"); + } + + S8_String code = LC_EndStringGen(L->arena); + S8_String path = OS_GetAbsolutePath(L->arena, "../examples/generate_type_info/generated.lc"); + OS_WriteFile(path, code); + + LC_ParseFile(package, path.str, code.str, 0); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + // Resolve decls again with new content added in + LC_OrderAndResolveTopLevelDecls(name); + LC_ResolveAllProcBodies(); + LC_FindUnusedLocalsAndRemoveUnusedGlobalDecls(); + + bool result = L->errors ? false : true; + LC_LangEnd(lang); + return result; +} \ No newline at end of file diff --git a/examples/generate_type_info/generated.lc b/examples/generate_type_info/generated.lc new file mode 100644 index 0000000..1aad15a --- /dev/null +++ b/examples/generate_type_info/generated.lc @@ -0,0 +1,13 @@ + +StructMem_Members := :[]StructMem{ + {name = "name", offset = 0}, + {name = "offset", offset = 8}, +}; +Typeinfo_Members := :[]StructMem{ + {name = "kind", offset = 0}, + {name = "name", offset = 8}, + {name = "size", offset = 16}, + {name = "align", offset = 20}, + {name = "child_count", offset = 24}, + {name = "struct_mems", offset = 32}, +}; \ No newline at end of file diff --git a/examples/generate_type_info/main.lc b/examples/generate_type_info/main.lc new file mode 100644 index 0000000..d8b8c31 --- /dev/null +++ b/examples/generate_type_info/main.lc @@ -0,0 +1,19 @@ +TypeKind :: typedef int; +TYPE_KIND_STRUCT :: 0; + +StructMem :: struct { + name: *char; + offset: int; +} + +Typeinfo :: struct { + kind: TypeKind; + name: *char; + + size: int; + align: int; + + child_count: int; + struct_mems: *StructMem; +} + diff --git a/examples/hello_world/build.cpp b/examples/hello_world/build.cpp new file mode 100644 index 0000000..836e46d --- /dev/null +++ b/examples/hello_world/build.cpp @@ -0,0 +1,29 @@ +bool hello_world() { + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + LC_LangBegin(lang); + LC_RegisterPackageDir("../examples/"); + LC_RegisterPackageDir("../pkgs"); + + LC_Intern name = LC_ILit("hello_world"); + LC_ASTRefList packages = LC_ResolvePackageByName(name); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + OS_MakeDir("examples/hello_world"); + S8_String code = LC_GenerateUnityBuild(packages); + S8_String path = "examples/hello_world/hello_world.c"; + OS_WriteFile(path, code); + + bool success = true; + if (UseCL) { + S8_String cmd = Fmt("cl %.*s -Zi -std:c11 -nologo -FC -Fd:examples/hello_world/hello_world.pdb -Fe:examples/hello_world/hello_world.exe %.*s", S8_Expand(path), S8_Expand(RaylibLIB)); + if (Run(cmd) != 0) success = false; + } + + LC_LangEnd(lang); + return success; +} \ No newline at end of file diff --git a/examples/hello_world/main.lc b/examples/hello_world/main.lc new file mode 100644 index 0000000..31d6396 --- /dev/null +++ b/examples/hello_world/main.lc @@ -0,0 +1,6 @@ +import "libc"; + +main :: proc(): int { + printf("hello world!\n"); + return 0; +} \ No newline at end of file diff --git a/examples/pathfinding_visualizer/array.lc b/examples/pathfinding_visualizer/array.lc new file mode 100644 index 0000000..75c5afa --- /dev/null +++ b/examples/pathfinding_visualizer/array.lc @@ -0,0 +1,147 @@ +AddActorToArray :: proc(arr: *ArrayOfActors, actor: Actor) { + if arr.len + 1 > arr.cap { + new_cap := arr.cap * 2; + if (new_cap == 0) new_cap = 16; + + arr.data = libc.realloc(arr.data, sizeof(:Actor) * :libc.size_t(new_cap)); + arr.cap = new_cap; + } + + arr.data[arr.len] = actor; + arr.len += 1; +} + +TryGrowingActorArray :: proc(a: *ArrayOfActors) { + if a.len + 1 > a.cap { + new_cap := a.cap * 2; + if (new_cap == 0) new_cap = 16; + a.data = libc.realloc(a.data, sizeof(:Actor) * :libc.size_t(new_cap)); + a.cap = new_cap; + } +} + +InsertActor :: proc(a: *ArrayOfActors, item: Actor, index: int) { + if index == a.len { + AddActorToArray(a, item); + return; + } + + Assert(index < a.len); + Assert(index >= 0); + + TryGrowingActorArray(a); + right_len := :libc.size_t(a.len - index); + libc.memmove(&a.data[index + 1], &a.data[index], sizeof(:Actor) * right_len); + a.data[index] = item; + a.len += 1; +} + +GetLastActor :: proc(a: ArrayOfActors): *Actor { + Assert(a.len > 0); + result := &a.data[a.len - 1]; + return result; +} + +// + +AddPath :: proc(arr: *ArrayOfPaths, actor: Path) { + if arr.len + 1 > arr.cap { + new_cap := arr.cap * 2; + if (new_cap == 0) new_cap = 16; + + arr.data = libc.realloc(arr.data, sizeof(:Path) * :libc.size_t(new_cap)); + arr.cap = new_cap; + } + + arr.data[arr.len] = actor; + arr.len += 1; +} + +TryGrowingPathArray :: proc(a: *ArrayOfPaths) { + if a.len + 1 > a.cap { + new_cap := a.cap * 2; + if (new_cap == 0) new_cap = 16; + a.data = libc.realloc(a.data, sizeof(:Path) * :libc.size_t(new_cap)); + a.cap = new_cap; + } +} + +InsertPath :: proc(a: *ArrayOfPaths, item: Path, index: int) { + if index == a.len { + AddPath(a, item); + return; + } + + Assert(index < a.len); + Assert(index >= 0); + + TryGrowingPathArray(a); + right_len := :libc.size_t(a.len - index); + libc.memmove(&a.data[index + 1], &a.data[index], sizeof(:Path) * right_len); + a.data[index] = item; + a.len += 1; +} + +InsertSortedPath :: proc(a: *ArrayOfPaths, item: Path) { + insert_index := -1; + for i := 0; i < a.len; i += 1 { + it := &a.data[i]; + if it.value_to_sort_by <= item.value_to_sort_by { + insert_index = i; + InsertPath(a, item, i); + break; + } + } + if insert_index == -1 { + AddPath(a, item); + } +} + +GetLastPath :: proc(a: ArrayOfPaths): *Path { + Assert(a.len > 0); + result := &a.data[a.len - 1]; + return result; +} + +PopPath :: proc(a: *ArrayOfPaths): Path { + a.len -= 1; + result := a.data[a.len]; + return result; +} + +// + +AddV2I :: proc(arr: *ArrayOfV2Is, item: V2I) { + if arr.len + 1 > arr.cap { + new_cap := arr.cap * 2; + if (new_cap == 0) new_cap = 16; + + arr.data = libc.realloc(arr.data, sizeof(:V2I) * :libc.size_t(new_cap)); + arr.cap = new_cap; + } + + arr.data[arr.len] = item; + arr.len += 1; +} + +// + +AddAnimationSetTile :: proc(arr: *ArrayOfAnimationSetTiles, item: AnimationSetTile) { + if arr.len + 1 > arr.cap { + new_cap := arr.cap * 2; + if (new_cap == 0) new_cap = 16; + + arr.data = libc.realloc(arr.data, sizeof(:AnimationSetTile) * :libc.size_t(new_cap)); + arr.cap = new_cap; + } + + arr.data[arr.len] = item; + arr.len += 1; +} + +UnorderedRemoveAnimationSetTile :: proc(a: *ArrayOfAnimationSetTiles, item: *AnimationSetTile) { + Assert(a.len > 0); + Assert(item >= a.data && item < &a.data[a.len]); + a.len -= 1; + *item = a.data[a.len]; +} diff --git a/examples/pathfinding_visualizer/build.cpp b/examples/pathfinding_visualizer/build.cpp new file mode 100644 index 0000000..ef0942b --- /dev/null +++ b/examples/pathfinding_visualizer/build.cpp @@ -0,0 +1,42 @@ +bool pathfinding_visualizer() { + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + LC_LangBegin(lang); + + LC_RegisterPackageDir("../examples/"); + LC_RegisterPackageDir("../pkgs"); + + LC_Intern name = LC_ILit("pathfinding_visualizer"); + LC_ASTRefList packages = LC_ResolvePackageByName(name); + LC_FindUnusedLocalsAndRemoveUnusedGlobalDecls(); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + DebugVerifyAST(packages); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + OS_MakeDir("examples"); + OS_MakeDir("examples/pathfinding_visualizer"); + S8_String code = LC_GenerateUnityBuild(packages); + S8_String path = "examples/pathfinding_visualizer/pathfinding_visualizer.c"; + OS_WriteFile(path, code); + + if (!UseCL) { + LC_LangEnd(lang); + return true; + } + + S8_String cmd = Fmt("cl %.*s -Zi -std:c11 -nologo -FC -Fd:examples/pathfinding_visualizer/a.pdb -Fe:examples/pathfinding_visualizer/pathfinding_visualizer.exe %.*s", S8_Expand(path), S8_Expand(RaylibLIB)); + int errcode = Run(cmd); + OS_CopyFile(RaylibDLL, "examples/pathfinding_visualizer/raylib.dll", true); + + LC_LangEnd(lang); + bool result = errcode == 0; + return result; +} \ No newline at end of file diff --git a/examples/pathfinding_visualizer/main.lc b/examples/pathfinding_visualizer/main.lc new file mode 100644 index 0000000..c135aec --- /dev/null +++ b/examples/pathfinding_visualizer/main.lc @@ -0,0 +1,266 @@ +import "raylib"; +import libc "libc"; +import "std_types"; + +WinX := 1280; +WinY := 720; +Mode := 0; +RectX :: 16; +RectY :: 16; +Dt: float; + +MouseX:= 0; +MouseY:= 0; +MouseP: Vector2 = {0, 0}; + +MouseSelecting := false; +MouseSelectionPivot: Vector2; +MouseSelectionBox: Rectangle; +MouseSelectedActors: ArrayOfActors; + +AnimationSetTiles: ArrayOfAnimationSetTiles; + +AnimationSetTile :: struct { + set: bool; + p: V2I; + t: float; +} + +ArrayOfAnimationSetTiles :: struct { + data: *AnimationSetTile; + len: int; + cap: int; +} + +main :: proc(): int { + InitMap(); + InitWindow(WinX, WinY, "pathfinding visualizer"); + SetTargetFPS(60); + + orange := ORANGE; + orange.a = 255/2; + brown := BROWN; + brown.a = 255/2; + dark_green := DARKGREEN; + dark_green.a = 255/2; + blue := BLUE; + blue.a = 255/2; + green := GREEN; + green.a = 255/2; + red := RED; + red.a = 255/2; + + actor_color := dark_green; + past_actor_color := blue; + target_color := red; + selection_box_color := green; + selected_color := selection_box_color; + + for !WindowShouldClose() { + WinX = GetScreenHeight(); + WinY = GetScreenWidth(); + MouseX = GetMouseX(); + MouseY = GetMouseY(); + MouseP = GetMousePosition(); + Dt = GetFrameTime(); + @unused map := &CurrentMap; + + MouseSelecting = false; + if IsMouseButtonDown(MOUSE_BUTTON_LEFT) { + MouseSelecting = true; + if IsMouseButtonPressed(MOUSE_BUTTON_LEFT) { + MouseSelectionPivot = MouseP; + } + + MouseSelectionBox = { + MouseSelectionPivot.x, + MouseSelectionPivot.y, + MouseP.x - MouseSelectionPivot.x, + MouseP.y - MouseSelectionPivot.y, + }; + + if MouseSelectionBox.width < 0 { + MouseSelectionBox.x += MouseSelectionBox.width; + MouseSelectionBox.width = -MouseSelectionBox.width; + } + if MouseSelectionBox.height < 0 { + MouseSelectionBox.y += MouseSelectionBox.height; + MouseSelectionBox.height = -MouseSelectionBox.height; + } + } + + if IsKeyPressed(KEY_F1) { + Mode = 0; + } + + if IsKeyPressed(KEY_F2) { + Mode = 1; + } + + if IsKeyPressed(KEY_F3) { + for i := 0; i < map.actors.len; i += 1 { + it := &map.actors.data[i]; + MoveTowardsTarget(it); + } + } + PathFindUpdate(map); + + if IsKeyPressed(KEY_F4) { + RandomizeActors(); + } + + BeginDrawing(); + ClearBackground(RAYWHITE); + + map_rectangle: Rectangle = {0, 0, :float(map.x) * RectX, :float(map.y) * RectY}; + DrawRectangleRec(map_rectangle, LIGHTGRAY); + + for x := 0; x < map.x; x += 1 { + for y := 0; y < map.y; y += 1 { + it := map.data[x + y*map.x]; + r : Rectangle = {:float(x) * RectX, :float(y) * RectY, RectX, RectY}; + r2: Rectangle = {r.x + 1, r.y + 1, r.width - 2, r.height - 2}; + + colliding := CheckCollisionPointRec(MouseP, r); + color := RAYWHITE; + if it == 1 { color = GRAY; } + + if Mode == 0 { + if colliding && IsMouseButtonDown(MOUSE_BUTTON_LEFT) { + AddAnimationSetTile(&AnimationSetTiles, {true, {x,y}}); + } + if colliding && IsMouseButtonDown(MOUSE_BUTTON_RIGHT) { + AddAnimationSetTile(&AnimationSetTiles, {false, {x,y}}); + } + if colliding { + color.a = 100; + } + } + + DrawRectangleRec(r2, color); + } + } + + for tile_i := 0; tile_i < AnimationSetTiles.len; tile_i += 1 { + tile_it := &AnimationSetTiles.data[tile_i]; + remove := false; + + t := tile_it.t; + if tile_it.set == false { + t = 1 - t; + } + + x := :float(tile_it.p.x) * RectX + 1; + y := :float(tile_it.p.y) * RectY + 1; + + w: float = RectX - 2; + h: float = RectY - 2; + wt := w * t; + ht := h * t; + wd := w - wt; + hd := h - ht; + + r: Rectangle = {x + wd/2, y + hd/2, wt, ht}; + DrawRectangleRec(r, GRAY); + + if tile_it.t > 1 { + map_tile := &map.data[tile_it.p.x + tile_it.p.y*map.x]; + if tile_it.set {*map_tile |= TILE_BLOCKER;} + else {*map_tile &= ~TILE_BLOCKER;} + + remove = true; + } + + tile_it.t += Dt*8; + if remove { + UnorderedRemoveAnimationSetTile(&AnimationSetTiles, tile_it); + tile_i -= 1; + } + } + + for actor_i := 0; actor_i < map.actors.len; actor_i += 1 { + actor_it := &map.actors.data[actor_i]; + target_r := Rect(actor_it.target_p); + + main_p := Circle(actor_it.p); + DrawCircleV(main_p, RectX/2, actor_color); + DrawRectangleRec(target_r, target_color); + + smaller_the_further: float; + for tile_i := actor_it.tiles_visited.len - 1; tile_i >= 0; tile_i -= 1 { + tile_it := &actor_it.tiles_visited.data[tile_i]; + p := Circle({tile_it.x, tile_it.y}); + DrawCircleV(p, RectX/2 - smaller_the_further, past_actor_color); + smaller_the_further += 0.5; + } + + for path_i := 0; path_i < actor_it.open_paths.len; path_i += 1 { + path_it := &actor_it.open_paths.data[path_i]; + path_r := Rect(path_it.p); + DrawRectangleRec(path_r, orange); + s := TextFormat("%d", :int(libc.sqrtf(:float(path_it.value_to_sort_by)))); + DrawText(s, :int(path_r.x), :int(path_r.y), 1, RAYWHITE); + } + + for path_i := 0; path_i < actor_it.close_paths.len; path_i += 1 { + path_it := &actor_it.close_paths.data[path_i]; + path_r := Rect(path_it.p); + DrawRectangleRec(path_r, brown); + } + + for path_i := 0; path_i < actor_it.history.len; path_i += 1 { + path_it := &actor_it.history.data[path_i]; + + p0 := Circle(path_it.came_from); + p1 := Circle(path_it.p); + + DrawLineEx(p0, p1, 5, LIGHTGRAY); + DrawCircleV(p0, 4, LIGHTGRAY); + DrawCircleV(p1, 4, LIGHTGRAY); + } + } + + if Mode == 1 { + for actor_i := 0; actor_i < MouseSelectedActors.len; actor_i += 1 { + actor_it := &MouseSelectedActors.data[actor_i]; + actor_box := Rect(actor_it.p); + DrawRectangleRec(actor_box, selected_color); + + if IsMouseButtonPressed(MOUSE_BUTTON_RIGHT) { + p := ScreenToMap(MouseP); + SetTargetP(actor_it, p); + } + } + + if MouseSelecting { + MouseSelectedActors.len = 0; + for actor_i := 0; actor_i < MouseSelectedActors.len; actor_i += 1 { + actor_it := &MouseSelectedActors.data[actor_i]; + actor_box := Rect(actor_it.p); + + if CheckCollisionRecs(actor_box, MouseSelectionBox) { + AddActorToArray(&MouseSelectedActors, *actor_it); + } + } + DrawRectangleRec(MouseSelectionBox, selection_box_color); + } + } + + text_size := 24; + text_p := 4; + text_y := text_size * 2; + + DrawText("F4 :: Randomize actors", text_p, text_y, text_size, GRAY); + text_y -= text_size; + DrawText("F3 :: Simulate actors", text_p, text_y, text_size, GRAY); + text_y -= text_size; + text: *char = "Mode(F1) :: Block placing"; + if Mode == 1 { text = "Mode(F2) :: Actor placing"; } + DrawText(text, text_p, text_y, text_size, GRAY); + text_y -= text_size; + + EndDrawing(); + } + + return 0; +} \ No newline at end of file diff --git a/examples/pathfinding_visualizer/map.lc b/examples/pathfinding_visualizer/map.lc new file mode 100644 index 0000000..86545c8 --- /dev/null +++ b/examples/pathfinding_visualizer/map.lc @@ -0,0 +1,286 @@ +CurrentMap: Map; + +Tile :: typedef int; +TILE_BLOCKER :: 1; +TILE_ACTOR_IS_STANDING :: <<; + +Map :: struct { + data: *Tile; + x: int; + y: int; + actors: ArrayOfActors; +} + +V2I :: struct { + x: int; + y: int; +} + +Actor :: struct { + p: V2I; + target_p: V2I; + map: *Map; + + open_paths: ArrayOfPaths; + close_paths: ArrayOfPaths; + tiles_visited: ArrayOfV2Is; + history: ArrayOfPaths; +} + +Path :: struct { + value_to_sort_by: int; + p: V2I; + came_from: V2I; +} + +ArrayOfActors :: struct { + data: *Actor; + len: int; + cap: int; +} + +ArrayOfPaths :: struct { + data: *Path; + len: int; + cap: int; +} + +ArrayOfV2Is :: struct { + data: *V2I; + len: int; + cap: int; +} + +Rect :: proc(p: V2I): Rectangle { + result: Rectangle = {:float(p.x) * RectX, :float(p.y) * RectY, RectX, RectY}; + return result; +} + +Circle :: proc(p: V2I): Vector2 { + result: Vector2 = {:float(p.x) * RectX + RectX/2, :float(p.y) * RectY + RectY/2}; + return result; +} + +ScreenToMap :: proc(p: Vector2): V2I { + x := p.x / RectX; + y := p.y / RectY; + + result: V2I = {:int(x), :int(y)}; + return result; +} + +MaxInt :: proc(x: int, y: int): int { + if x > y return x; + return y; +} + +Assert :: proc(x: bool) { + if (!x) { + libc.printf("assertion failed\n"); + libc.fflush(libc.stdout); + libc.debug_break(); + } +} + +InvalidCodepath :: proc() { + libc.printf("invalid codepath\n"); + libc.fflush(libc.stdout); + libc.debug_break(); +} + +AddActor :: proc(map: *Map, p: V2I): *Actor { + AddActorToArray(&map.actors, {p, p, map}); + map.data[p.x + p.y * map.x] |= TILE_ACTOR_IS_STANDING; + result := GetLastActor(map.actors); + return result; +} + +SetActorP :: proc(actor: *Actor, p: V2I) { + map := actor.map; + new_tile := &map.data[p.x + p.y * map.x]; + if *new_tile != 0 return; + + tile := &map.data[actor.p.x + actor.p.y * map.x]; + Assert((*tile & TILE_ACTOR_IS_STANDING) != 0); + *tile &= ~TILE_ACTOR_IS_STANDING; + + *new_tile |= TILE_ACTOR_IS_STANDING; + actor.p = p; + + actor.tiles_visited.len = 0; + actor.history.len = 0; + actor.open_paths.len = 0; + actor.close_paths.len = 0; +} + +SetTargetP :: proc(actor: *Actor, p: V2I) { + actor.target_p = p; + + actor.tiles_visited.len = 0; + actor.history.len = 0; + actor.open_paths.len = 0; + actor.close_paths.len = 0; +} + +GetRandomP :: proc(m: *Map): V2I { + result: V2I = {GetRandomInt(0, m.x - 1), GetRandomInt(0, m.y - 1)}; + return result; +} + +GetRandomUnblockedP :: proc(m: *Map): V2I { + for i := 0; i < 128; i += 1 { + p := GetRandomP(m); + if m.data[p.x + p.y * m.x] == 0 { + return p; + } + } + Assert(!:ullong(:*char("invalid codepath"))); + return {}; +} + +InitMap :: proc() { + CurrentMap.x = WinX / RectX; + CurrentMap.y = WinY / RectY; + + bytes := sizeof(:Tile) * CurrentMap.x * CurrentMap.y; + CurrentMap.data = libc.malloc(:libc.size_t(bytes)); + libc.memset(CurrentMap.data, 0, :libc.size_t(bytes)); + + actor := AddActor(&CurrentMap, GetRandomUnblockedP(&CurrentMap)); + actor.target_p = GetRandomUnblockedP(&CurrentMap); + + actor2 := AddActor(&CurrentMap, GetRandomUnblockedP(&CurrentMap)); + actor2.target_p = GetRandomUnblockedP(&CurrentMap); +} + +RandomizeActors :: proc() { + map := &CurrentMap; + for i := 0; i < map.actors.len; i += 1 { + it := &map.actors.data[i]; + p := GetRandomUnblockedP(&CurrentMap); + SetActorP(it, p); + it.target_p = GetRandomUnblockedP(&CurrentMap); + } +} + +InsertOpenPath :: proc(actor: *Actor, p: V2I, came_from: V2I, ignore_blocks: bool = false) { + if p.x < 0 || p.x >= actor.map.x return; + if p.y < 0 || p.y >= actor.map.y return; + if ignore_blocks == false && actor.map.data[p.x + p.y * actor.map.x] != 0 return; + + for i := 0; i < actor.close_paths.len; i += 1 { + it := &actor.close_paths.data[i]; + if it.p.x == p.x && it.p.y == p.y return; + } + + for i := 0; i < actor.open_paths.len; i += 1 { + it := &actor.open_paths.data[i]; + if it.p.x == p.x && it.p.y == p.y return; + } + + dx := actor.target_p.x - p.x; + dy := actor.target_p.y - p.y; + d := dx*dx + dy*dy; + InsertSortedPath(&actor.open_paths, {d, p, came_from}); +} + +GetCloseP :: proc(actor: *Actor, p: V2I): *Path { + for i := 0; i < actor.close_paths.len; i += 1 { + it := &actor.close_paths.data[i]; + if it.p.x == p.x && it.p.y == p.y return it; + } + InvalidCodepath(); + return nil; +} + +RecomputeHistory :: proc(actor: *Actor) { + if actor.close_paths.len > 1 { + actor.history.len = 0; + it := GetLastPath(actor.close_paths); + AddPath(&actor.history, *it); + for i := 0;;i += 1 { + if it.p.x == actor.p.x && it.p.y == actor.p.y { break; } + if i > 512 { actor.history.len = 0; break; } // @todo: Pop after this and error? + it = GetCloseP(actor, it.came_from); + AddPath(&actor.history, *it); + } + PopPath(&actor.history); + } +} + +MoveTowardsTarget :: proc(actor: *Actor) { + tile := &actor.map.data[actor.p.x + actor.p.y * actor.map.x]; + if actor.history.len > 0 { + step := PopPath(&actor.history); + new_tile := &actor.map.data[step.p.x + step.p.y * actor.map.x]; + if *new_tile == 0 { + AddV2I(&actor.tiles_visited, actor.p); + actor.p = step.p; + *tile &= ~TILE_ACTOR_IS_STANDING; + *new_tile |= TILE_ACTOR_IS_STANDING; + } + } +} + +PathFindUpdate :: proc(map: *Map) { + for actor_i := 0; actor_i < map.actors.len; actor_i += 1 { + actor_it := &map.actors.data[actor_i]; + for i := 0; i < actor_it.history.len; i += 1 { + history_it := &actor_it.history.data[i]; + + tile := actor_it.map.data[history_it.p.x + history_it.p.y * actor_it.map.x]; + if tile != 0 { + actor_it.close_paths.len = 0; + actor_it.open_paths.len = 0; + actor_it.history.len = 0; + break; + } + } + PathFind(actor_it); + } +} + +PathFindStep :: proc(s: *Actor, compute_history: bool = true): bool { + if s.open_paths.len == 0 { + // Reset if we didn't find solution + if s.close_paths.len != 0 { + last := GetLastPath(s.close_paths); + reached_target := last.p.x == s.target_p.x && last.p.y == s.target_p.y; + if reached_target == false { + s.close_paths.len = 0; + s.open_paths.len = 0; + s.history.len = 0; + } + } + + InsertOpenPath(s, s.p, s.p, ignore_blocks = true); + } + + if s.close_paths.len != 0 { + last := GetLastPath(s.close_paths); + reached_target := last.p.x == s.target_p.x && last.p.y == s.target_p.y; + if reached_target return true; + } + + it := PopPath(&s.open_paths); + AddPath(&s.close_paths, it); + + for y := -1; y <= 1; y += 1 { + for x := -1; x <= 1; x += 1 { + if x == 0 && y == 0 continue; + p: V2I = {it.p.x + x, it.p.y + y}; + InsertOpenPath(s, p, it.p); + } + } + + if compute_history RecomputeHistory(s); + return false; +} + +PathFind :: proc(actor: *Actor) { + for i := 0; i < 32; i += 1 { + done := PathFindStep(actor, false); + if done break; + } + RecomputeHistory(actor); +} \ No newline at end of file diff --git a/examples/pathfinding_visualizer/random.lc b/examples/pathfinding_visualizer/random.lc new file mode 100644 index 0000000..de9cafe --- /dev/null +++ b/examples/pathfinding_visualizer/random.lc @@ -0,0 +1,22 @@ +RandomSeedValue: RandomSeed = {121521923492}; +RandomSeed :: struct { + a: u64; +} + +GetRandomU64 :: proc(s: *RandomSeed): u64 { + x := s.a; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + s.a = x; + return x; +} + +GetRandomInt :: proc(min: int, max: int): int { + random := GetRandomU64(&RandomSeedValue); + range_size: u64 = :u64(max - min) + 1; + + result := :int(random % range_size); + result = result + min; + return result; +} diff --git a/examples/sandbox/arena.lc b/examples/sandbox/arena.lc new file mode 100644 index 0000000..3e61ddd --- /dev/null +++ b/examples/sandbox/arena.lc @@ -0,0 +1,68 @@ +import "std_types"; +import libc "libc"; + +PAGE_SIZE :: 4096; + +Arena :: struct { + data: *u8; + len: usize; + commit: usize; + reserve: usize; + alignment: usize; +} + +GetAlignOffset :: proc(size: usize, align: usize): usize { + mask: usize = align - 1; + val: usize = size & mask; + if val { + val = align - val; + } + return val; +} + +AlignUp :: proc(size: usize, align: usize): usize { + result := size + GetAlignOffset(size, align); + return result; +} + +InitArena :: proc(arena: *Arena, reserve: usize) { + aligned_reserve := AlignUp(reserve, PAGE_SIZE); + data := VReserve(aligned_reserve); + libc.assert(data != nil); + + if data { + arena.data = data; + arena.reserve = aligned_reserve; + arena.alignment = 8; + } +} + +PushSize :: proc(arena: *Arena, size: usize): *void { + libc.assert(arena.data != nil); + + pointer := :usize(arena.data) + arena.len + size; + align := GetAlignOffset(pointer, arena.alignment); + aligned_size := size + align; + + a := arena.len + aligned_size; + if a > arena.commit { + diff := a - arena.commit; + commit_size := AlignUp(diff, PAGE_SIZE*4); + libc.assert(commit_size + arena.commit <= arena.reserve); + + if VCommit(&arena.data[arena.commit], commit_size) { + arena.commit += commit_size; + } else { + libc.assert(false && "commit failed"[0]); + } + } + + arena.len += align; + result: *void = &arena.data[arena.len]; + arena.len += size; + return result; +} + +TestArena :: proc() { + arena: Arena; +} \ No newline at end of file diff --git a/examples/sandbox/arena_win32.lc b/examples/sandbox/arena_win32.lc new file mode 100644 index 0000000..2dd476d --- /dev/null +++ b/examples/sandbox/arena_win32.lc @@ -0,0 +1,28 @@ +#build_if(LC_OS == OS_WINDOWS); + +DWORD :: typedef u32; +SIZE_T :: typedef uintptr; +BOOL :: typedef int; + +MEM_RESERVE :: 0x00002000; +MEM_COMMIT :: 0x00001000; +PAGE_READWRITE :: 0x04; +VirtualAlloc :: proc(lpAddress: *void, dwSize: SIZE_T, flAllocationType: DWORD, flProtect: DWORD): *void; @api + +MEM_RELEASE :: 0x00008000; +MEM_DECOMMIT :: 0x00004000; +VirtualFree :: proc(lpAddress: *void, dwSize: SIZE_T, dwFreeType: DWORD): BOOL; @api + +VReserve :: proc(size: usize): *void { + result := VirtualAlloc(nil, :SIZE_T(size), MEM_RESERVE, PAGE_READWRITE); + return result; +} + +VCommit :: proc(p: *void, size: usize): bool { + result := VirtualAlloc(p, :SIZE_T(size), MEM_COMMIT, PAGE_READWRITE) != 0; + return result; +} + +VRelease :: proc(p: *void) { + VirtualFree(p, 0, MEM_RELEASE); +} \ No newline at end of file diff --git a/examples/sandbox/build.cpp b/examples/sandbox/build.cpp new file mode 100644 index 0000000..35ad1c2 --- /dev/null +++ b/examples/sandbox/build.cpp @@ -0,0 +1,121 @@ +namespace Sandbox { +Array TypesToGen; + +void RegisterMarkedTypes(LC_AST *n) { + if (n->kind == LC_ASTKind_TypespecIdent) { + S8_String name = S8_MakeFromChar((char *)n->eident.name); + S8_String array_of = "ArrayOf"; + if (S8_StartsWith(name, array_of)) { + if (name == "ArrayOfName") return; + + name = S8_Skip(name, array_of.len); + LC_Intern intern = LC_InternStrLen(name.str, (int)name.len); + + bool exists = false; + For(TypesToGen) { + if (intern == it) { + exists = true; + break; + } + } + if (!exists) { + TypesToGen.add(intern); + } + } + } +} + +void WalkAndRename(LC_ASTWalker *ctx, LC_AST *n) { + LC_Intern *p = NULL; + if (n->kind == LC_ASTKind_TypespecIdent || n->kind == LC_ASTKind_ExprIdent) { + p = &n->eident.name; + } + if (LC_IsDecl(n)) { + p = &n->dbase.name; + } + + if (p) { + LC_Intern user = *(LC_Intern *)ctx->user_data; + S8_String p8 = S8_MakeFromChar((char *)*p); + + if (S8_Seek(p8, "Name")) { + S8_String new_name = S8_ReplaceAll(L->arena, p8, "Name", S8_MakeFromChar((char *)user)); + *p = LC_InternStrLen(new_name.str, (int)new_name.len); + } + } +} + +void BeforeCallArgsResolved(LC_AST *n, LC_Type *type) { +} + +} // namespace Sandbox + +bool sandbox() { + using namespace Sandbox; + + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + lang->on_typespec_parsed = RegisterMarkedTypes; + lang->before_call_args_resolved = BeforeCallArgsResolved; + LC_LangBegin(lang); + + LC_RegisterPackageDir("../pkgs"); + LC_RegisterPackageDir("../examples"); + + LC_Intern name = LC_ILit("sandbox"); + LC_ParsePackagesUsingRegistry(name); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + TypesToGen.allocator = MA_GetAllocator(lang->arena); + + // + // Remove dynamic array file + // + LC_AST *package = LC_GetPackageByName(name); + LC_AST *dynamic_array_file = NULL; + LC_ASTFor(it, package->apackage.ffile) { + S8_String path = S8_MakeFromChar((char *)it->afile.x->file); + if (S8_EndsWith(path, "dynamic_array.lc")) { + dynamic_array_file = it; + DLL_QUEUE_REMOVE(package->apackage.ffile, package->apackage.lfile, it); + break; + } + } + + // Generate copies + LC_ASTWalker walker = LC_GetDefaultWalker(L->arena, WalkAndRename); + For(TypesToGen) { + LC_AST *new_array_file = LC_CopyAST(L->arena, dynamic_array_file); + + walker.user_data = (void *)⁢ + LC_WalkAST(&walker, new_array_file); + LC_DLLAdd(package->apackage.ffile, package->apackage.lfile, new_array_file); + } + + LC_OrderAndResolveTopLevelDecls(name); + LC_ResolveAllProcBodies(); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + S8_String code = LC_GenerateUnityBuild(L->ordered_packages); + S8_String path = "examples/sandbox/sandbox.c"; + + OS_MakeDir("examples/sandbox"); + OS_WriteFile(path, code); + LC_LangEnd(lang); + + if (UseCL) { + OS_CopyFile(RaylibDLL, "examples/sandbox/raylib.dll", true); + S8_String cmd = Fmt("cl %.*s -Zi -std:c11 -nologo -FC -Fd:examples/sandbox/a.pdb -Fe:examples/sandbox/sandbox.exe %.*s", S8_Expand(path), S8_Expand(RaylibLIB)); + int errcode = Run(cmd); + if (errcode != 0) return false; + } + + return true; +} \ No newline at end of file diff --git a/examples/sandbox/common.lc b/examples/sandbox/common.lc new file mode 100644 index 0000000..2a00b21 --- /dev/null +++ b/examples/sandbox/common.lc @@ -0,0 +1,96 @@ +FloatMin :: proc(a: float, b: float): float { + if (a > b) return b; + return a; +} + +FloatMax :: proc(a: float, b: float): float { + if (a > b) return a; + return a; +} + +FloatClamp :: proc(val: float, min: float, max: float): float { + if (val > max) return max; + if (val < min) return min; + return val; +} + +IntMin :: proc(a: int, b: int): int { + if (a > b) return b; + return a; +} + +IntMax :: proc(a: int, b: int): int { + if (a > b) return a; + return a; +} + +IntClamp :: proc(val: int, min: int, max: int): int { + if (val > max) return max; + if (val < min) return min; + return val; +} + +Rect2 :: struct { + min: Vector2; + max: Vector2; +} + +CutLeft :: proc(r: *Rect2, value: float): Rect2 { + minx := r.min.x; + r.min.x = FloatMin(r.max.x, r.min.x + value); + return :Rect2{ + { minx, r.min.y}, + {r.min.x, r.max.y}, + }; +} + +CutRight :: proc(r: *Rect2, value: float): Rect2 { + maxx := r.max.x; + r.max.x = FloatMax(r.max.x - value, r.min.x); + return :Rect2{ + {r.max.x, r.min.y}, + { maxx, r.max.y}, + }; +} + +CutBottom :: proc(r: *Rect2, value: float): Rect2 { // Y is down + maxy := r.max.y; + r.max.y = FloatMax(r.min.y, r.max.y - value); + return :Rect2{ + {r.min.x, r.max.y}, + {r.max.x, maxy}, + }; +} + +CutTop :: proc(r: *Rect2, value: float): Rect2 { // Y is down + miny := r.min.y; + r.min.y = FloatMin(r.min.y + value, r.max.y); + return :Rect2{ + {r.min.x, miny}, + {r.max.x, r.min.y}, + }; +} + +Shrink :: proc(r: Rect2, value: float): Rect2 { + r.min.x += value; + r.max.x -= value; + r.min.y += value; + r.max.y -= value; + return r; +} + +RectFromSize :: proc(pos: Vector2, size: Vector2): Rect2 { + result: Rect2 = {pos, Vector2Add(pos, size)}; + return result; +} + +GetRectSize :: proc(rect: Rect2): Vector2 { + result: Vector2 = {rect.max.x - rect.min.x, rect.max.y - rect.min.y}; + return result; +} + +RectToRectangle :: proc(rect: Rect2): Rectangle { + size := GetRectSize(rect); + result: Rectangle = {rect.min.x, rect.min.y, size.x, size.y}; + return result; +} \ No newline at end of file diff --git a/examples/sandbox/dynamic_array.lc b/examples/sandbox/dynamic_array.lc new file mode 100644 index 0000000..72943bf --- /dev/null +++ b/examples/sandbox/dynamic_array.lc @@ -0,0 +1,49 @@ +ArrayOfName :: struct { + data: *Name; + len: int; + cap: int; +} + +TryGrowingNameArray :: proc(arr: *ArrayOfName) { + if (arr.len + 1 > arr.cap) { + cap := arr.cap * 2; + if (cap == 0) cap = 16; + + arr.data = libc.realloc(arr.data, sizeof(arr.data[0]) * :libc.size_t(cap)); + arr.cap = cap; + } +} + +AddName :: proc(arr: *ArrayOfName, item: Name) { + TryGrowingNameArray(arr); + arr.data[arr.len] = item; + arr.len += 1; +} + +InsertName :: proc(a: *ArrayOfName, item: Name, index: int) { + if index == a.len { + AddName(a, item); + return; + } + + libc.assert(index < a.len); + libc.assert(index >= 0); + + TryGrowingNameArray(a); + right_len := :libc.size_t(a.len - index); + libc.memmove(&a.data[index + 1], &a.data[index], sizeof(a.data[0]) * right_len); + a.data[index] = item; + a.len += 1; +} + +GetLastName :: proc(a: ArrayOfName): *Name { + libc.assert(a.len > 0); + result := &a.data[a.len - 1]; + return result; +} + +PopName :: proc(a: *ArrayOfName): Name { + a.len -= 1; + result := a.data[a.len]; + return result; +} \ No newline at end of file diff --git a/examples/sandbox/main.lc b/examples/sandbox/main.lc new file mode 100644 index 0000000..4acb5a1 --- /dev/null +++ b/examples/sandbox/main.lc @@ -0,0 +1,93 @@ +import "raylib"; + +Tile :: struct { + value: int; +} + +Map :: struct { + tiles: *Tile; + x: int; + y: int; +} + +CreateMap :: proc(x: int, y: int, map: *int): Map { + result: Map = {x = x, y = y}; + result.tiles = MemAlloc(:uint(x*y) * sizeof(:Tile)); + + for i := 0; i < x*y; i += 1 { + result.tiles[i].value = map[i]; + } + return result; +} + +main :: proc(): int { + TestArena(); + return 0; + InitWindow(800, 600, "Thing"); + SetTargetFPS(60); + + XPIX :: 32; + YPIX :: 32; + + camera: Camera2D = { + zoom = 1.0, + }; + + _map_x :: 8; + _map_y :: 8; + map := CreateMap(_map_x, _map_y, &:[_map_x * _map_y]int{ + 1,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + 1,0,0,0,0,0,0,1, + 0,0,0,0,1,0,0,0, + 0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0, + }[0]); + + for !WindowShouldClose() { + if IsMouseButtonDown(MOUSE_BUTTON_LEFT) { + delta := GetMouseDelta(); + camera.offset = Vector2Add(camera.offset, delta); + } + + BeginDrawing(); + ClearBackground(RAYWHITE); + + BeginMode2D(camera); + for y_it := 0; y_it < map.y; y_it += 1 { + for x_it := 0; x_it < map.x; x_it += 1 { + tile := &map.tiles[x_it + y_it * map.x]; + original_rect := RectFromSize({XPIX * :float(x_it), YPIX * :float(y_it)}, {XPIX, YPIX}); + rect := Shrink(original_rect, 2); + + r := RectToRectangle(rect); + + min_screen := GetWorldToScreen2D(original_rect.min, camera); + size := GetRectSize(original_rect); + + screen_rect: Rectangle = {min_screen.x, min_screen.y, size.x, size.y}; + mouse_p := GetMousePosition(); + + if tile.value == 1 { + DrawRectangleRec(r, RED); + } else { + DrawRectangleRec(r, GREEN); + } + + if CheckCollisionPointRec(mouse_p, screen_rect) { + DrawRectangleRec(r, BLUE); + } + } + } + EndMode2D(); + + // DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY); + EndDrawing(); + } + + CloseWindow(); + return 0; +} + diff --git a/examples/text_editor/buffer.lc b/examples/text_editor/buffer.lc new file mode 100644 index 0000000..f703ea6 --- /dev/null +++ b/examples/text_editor/buffer.lc @@ -0,0 +1,249 @@ +Buffer :: struct { + data: *u8; + len: int; + cap: int; + + lines: Lines; +} + +Lines :: struct { + data: *Range; + len: int; + cap: int; +} + +Range :: struct { + min: int; + max: int; +} + +LineInfo :: struct { + number: int; + range: Range; +} + +GetRangeSize :: proc(range: Range): int { + result := range.max - range.min; + return result; +} + +ClampInt :: proc(val: int, min: int, max: int): int { + result := val; + if (val < min) result = min; + if (val > max) result = max; + return result; +} + +MinInt :: proc(a: int, b: int): int { + result := a; + if (a > b) result = b; + return result; +} + +MaxInt :: proc(a: int, b: int): int { + result := b; + if (a > b) result = a; + return result; +} + +AdjustUTF8PosUnsafe :: proc(buffer: *Buffer, pos: int, direction: int = 1): int { + for pos >= 0 && pos < buffer.len && IsUTF8ContinuationByte(buffer.data[pos]) { + pos += direction; + } + return pos; +} + +AdjustUTF8Pos :: proc(buffer: *Buffer, pos: int, direction: int = 1): int { + assert(direction == 1 || direction == -1); + pos = AdjustUTF8PosUnsafe(buffer, pos, direction); + pos = ClampInt(pos, 0, buffer.len - 1); + if (buffer.data) assert(!IsUTF8ContinuationByte(buffer.data[pos])); + return pos; +} + +AdjustRange :: proc(buffer: *Buffer, range: *Range) { + range.min = AdjustUTF8Pos(buffer, range.min, direction = -1); + range.max = AdjustUTF8Pos(buffer, range.max, direction = +1); +} + +ReplaceText :: proc(buffer: *Buffer, replace: Range, with: String) { + AdjustRange(buffer, &replace); + + new_buffer_len := buffer.len + :int(with.len) - GetRangeSize(replace); + new_buffer_size := new_buffer_len + 1; // possible addition of a null terminator + if new_buffer_size > buffer.cap { + new_buffer_cap := MaxInt(4096, new_buffer_size * 2); + new_buffer := malloc(:usize(new_buffer_cap)); + if (buffer.data) { + memcpy(new_buffer, buffer.data, :usize(buffer.len)); + free(buffer.data); + } + buffer.data = new_buffer; + buffer.cap = new_buffer_cap; + } + + old_text_range: Range = replace; + new_text_range: Range = {old_text_range.min, old_text_range.min + :int(with.len)}; + right_range: Range = {old_text_range.max, buffer.len}; + + memmove(&buffer.data[new_text_range.max], &buffer.data[right_range.min], :usize(GetRangeSize(right_range))); + memmove(&buffer.data[new_text_range.min], with.str, :usize(GetRangeSize(new_text_range))); + + buffer.len = new_buffer_len; + if buffer.len && buffer.data[buffer.len - 1] != 0 { + buffer.data[buffer.len] = 0; + buffer.len += 1; + assert(buffer.len <= buffer.cap); + } + + UpdateBufferLines(buffer); +} + +AddLine :: proc(lines: *Lines, line: Range) { + if lines.len + 1 > lines.cap { + new_cap := MaxInt(16, lines.cap * 2); + lines.data = realloc(lines.data, :usize(new_cap) * sizeof(:Range)); + lines.cap = new_cap; + } + lines.data[lines.len] = line; + lines.len += 1; +} + +UpdateBufferLines :: proc(buffer: *Buffer) { + buffer.lines.len = 0; + + line: Range = {0, 0}; + for i := 0; i < buffer.len; i += 1 { + if buffer.data[i] == '\n' { + AddLine(&buffer.lines, line); + line.min = i + 1; + line.max = i + 1; + } else { + line.max += 1; + } + } + + line.min = AdjustUTF8Pos(buffer, line.min); + line.max = AdjustUTF8Pos(buffer, line.max); + AddLine(&buffer.lines, line); +} + +AllocStringFromBuffer :: proc(buffer: *Buffer, range: Range, null_terminate: bool = false): String { + AdjustRange(buffer, &range); + size := GetRangeSize(range); + + alloc_size := :usize(size); + if (null_terminate) alloc_size += 1; + data := malloc(alloc_size); + memcpy(data, &buffer.data[range.min], :usize(size)); + + result: String = {data, size}; + if (null_terminate) result.str[result.len] = 0; + return result; +} + +GetStringFromBuffer :: proc(buffer: *Buffer, range: Range): String { + AdjustRange(buffer, &range); + size := GetRangeSize(range); + result: String = {:*char(&buffer.data[range.min]), size}; + return result; +} + +AddText :: proc(buffer: *Buffer, text: String) { + end_of_buffer: Range = {buffer.len - 1, buffer.len - 1}; + ReplaceText(buffer, end_of_buffer, text); +} + +FindLineOfPos :: proc(buffer: *Buffer, pos: int): LineInfo { + for i := 0; i < buffer.lines.len; i += 1 { + line := buffer.lines.data[i]; + if pos >= line.min && pos <= line.max { + return {i, line}; + } + } + return {}; +} + +IsLineValid :: proc(buffer: *Buffer, line: int): bool { + result := line >= 0 && line < buffer.lines.len; + return result; +} + +GetLine :: proc(buffer: *Buffer, line: int): LineInfo { + line = ClampInt(line, 0, buffer.lines.len - 1); + range := buffer.lines.data[line]; + return {line, range}; +} + +IsPosInBounds :: proc(buffer: *Buffer, pos: int): bool { + result := buffer.len != 0 && pos >= 0 && pos < buffer.len; + return result; +} + +GetChar :: proc(buffer: *Buffer, pos: int): u8 { + result: u8; + if IsPosInBounds(buffer, pos) { + result = buffer.data[pos]; + } + return result; +} + +GetUTF32 :: proc(buffer: *Buffer, pos: int, codepoint_size: *int = nil): u32 { + if !IsPosInBounds(buffer, pos) return 0; + p := &buffer.data[pos]; + max := buffer.len - pos; + utf32 := UTF8ToUTF32(:*uchar(p), max); + assert(utf32.error == 0); + if (utf32.error != 0) return 0; + if (codepoint_size) codepoint_size[0] = utf32.advance; + return utf32.out_str; +} + +IsWhitespace :: proc(w: u8): bool { + result := w == '\n' || w == ' ' || w == '\t' || w == '\v' || w == '\r'; + return result; +} + +SeekOnWordBoundary :: proc(buffer: *Buffer, pos: int, direction: int = GO_FORWARD): int { + assert(direction == GO_FORWARD || direction == GO_BACKWARD); + check_pos: int; + if direction == GO_FORWARD { + check_pos = AdjustUTF8Pos(buffer, pos + 1, direction); + pos = check_pos; + // this difference here because the Backward for loop is not inclusive. + // It doesn't move an inch forward after "pos" + // - - - - pos - - + // It goes backward on first Advance + } else { + check_pos = AdjustUTF8Pos(buffer, pos - 1, direction); + } + + cursor_char := GetChar(buffer, check_pos); + standing_on_whitespace := IsWhitespace(cursor_char); + seek_whitespace := standing_on_whitespace == false; + seek_word := standing_on_whitespace; + + end := buffer.len - 1; + if (direction == GO_BACKWARD) end = 0; + + result := end; + iter := Iterate(buffer, pos, end, direction); + prev_pos := iter.pos; + for IsValid(iter); Advance(&iter) { + if seek_word && !IsWhitespace(:u8(iter.item)) { + result = prev_pos; + break; + } + if seek_whitespace && IsWhitespace(:u8(iter.item)) { + if direction == GO_FORWARD { + result = iter.pos; + } else { + result = prev_pos; + } + break; + } + prev_pos = iter.pos; + } + + return result; +} \ No newline at end of file diff --git a/examples/text_editor/buffer_iter.lc b/examples/text_editor/buffer_iter.lc new file mode 100644 index 0000000..d133f18 --- /dev/null +++ b/examples/text_editor/buffer_iter.lc @@ -0,0 +1,54 @@ +GO_FORWARD :: 1; +GO_BACKWARD :: -1; + +BufferIter :: struct { + buffer: *Buffer; + pos: int; + end: int; + item: u32; + + utf8_codepoint_size: int; + direction: int; + codepoint_index: int; +} + +IsValid :: proc(iter: BufferIter): bool { + assert(iter.direction == GO_FORWARD || iter.direction == GO_BACKWARD); + + result := false; + if iter.direction == GO_BACKWARD { + result = iter.pos >= iter.end; + } else { + result = iter.pos < iter.end; + } + + if result { + assert(!IsUTF8ContinuationByte(GetChar(iter.buffer, iter.pos))); + assert(IsPosInBounds(iter.buffer, iter.pos)); + } + return result; +} + +Advance :: proc(iter: *BufferIter) { + assert(iter.direction == GO_FORWARD || iter.direction == GO_BACKWARD); + + iter.codepoint_index += 1; + if iter.direction == GO_FORWARD { + iter.pos += iter.utf8_codepoint_size; + } else { + iter.pos = AdjustUTF8PosUnsafe(iter.buffer, iter.pos - 1, GO_BACKWARD); + } + + if !IsValid(*iter) return; + iter.item = GetUTF32(iter.buffer, iter.pos, &iter.utf8_codepoint_size); +} + +Iterate :: proc(buffer: *Buffer, pos: int, end: int, direction: int = GO_FORWARD): BufferIter { + assert(!IsUTF8ContinuationByte(GetChar(buffer, pos))); + assert(!IsUTF8ContinuationByte(GetChar(buffer, end))); + assert(direction == GO_FORWARD || direction == GO_BACKWARD); + + result: BufferIter = {buffer = buffer, pos = pos, end = end, direction = direction, codepoint_index = -1}; + Advance(&result); + return result; +} \ No newline at end of file diff --git a/examples/text_editor/build.cpp b/examples/text_editor/build.cpp new file mode 100644 index 0000000..2d117bb --- /dev/null +++ b/examples/text_editor/build.cpp @@ -0,0 +1,34 @@ +bool text_editor() { + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + LC_LangBegin(lang); + defer { LC_LangEnd(lang); }; + + LC_RegisterPackageDir("../pkgs"); + LC_RegisterPackageDir("../examples"); + + LC_Intern name = LC_ILit("text_editor"); + LC_ASTRefList packages = LC_ResolvePackageByName(name); + if (L->errors) return false; + + DebugVerifyAST(packages); + if (L->errors) return false; + + LC_FindUnusedLocalsAndRemoveUnusedGlobalDecls(); + + OS_MakeDir("examples"); + OS_MakeDir("examples/text_editor"); + OS_CopyFile(RaylibDLL, "examples/text_editor/raylib.dll", true); + + S8_String code = LC_GenerateUnityBuild(packages); + S8_String path = "examples/text_editor/text_editor.c"; + OS_WriteFile(path, code); + + if (!UseCL) return true; + S8_String cmd = Fmt("cl %.*s -Zi -std:c11 -nologo -FC -Fd:examples/text_editor/a.pdb -Fe:examples/text_editor/text_editor.exe %.*s", S8_Expand(path), S8_Expand(RaylibLIB)); + int errcode = Run(cmd); + if (errcode != 0) return false; + + return true; +} \ No newline at end of file diff --git a/examples/text_editor/main.lc b/examples/text_editor/main.lc new file mode 100644 index 0000000..7af6307 --- /dev/null +++ b/examples/text_editor/main.lc @@ -0,0 +1,362 @@ +import "raylib"; +import "std_types"; +import "libc"; + +MainCursor: Selection; + +Selection :: struct { + a: int; + b: int; +} + +GetRange :: proc(s: Selection): Range { + result: Range = {MinInt(s.a, s.b), MaxInt(s.a, s.b)}; + return result; +} + +main :: proc(): int { + InitWindow(800, 600, "TextEditor"); + SetTargetFPS(60); + + font_size: float = 35; + font_spacing: float = 1; + font: Font = LoadFontEx("C:/Windows/Fonts/consola.ttf", :int(font_size), nil, 0); + + glyph_info: GlyphInfo = GetGlyphInfo(font, 'A'); + size := MeasureTextEx(font, "A", font_size, font_spacing); + Monosize = {:float(glyph_info.image.width), size.y}; + + buffer: Buffer; + AddText(&buffer, "1Testing and stuff 1Testing and stuff 1Testing and stuff 1Testing and stuff\n"); + AddText(&buffer, "2Testing and stuff\n"); + AddText(&buffer, "3Testing and stuff\n"); + AddText(&buffer, "4Testing and stuff\n"); + AddText(&buffer, "5Testing and stuff\n"); + AddText(&buffer, "6Testing and stuff\n"); + AddText(&buffer, "7Testing and stuff\n"); + AddText(&buffer, "8Testing and stuff\n"); + AddText(&buffer, "9Testing and stuff\n"); + AddText(&buffer, "1Testing and stuff\n"); + AddText(&buffer, "2Testing and stuff\n"); + AddText(&buffer, "3Testing and stuff\n"); + AddText(&buffer, "4Testing and stuff\n"); + AddText(&buffer, "5Testing and stuff\n"); + AddText(&buffer, "6Testing and stuff\n"); + AddText(&buffer, "7Testing and stuff\n"); + AddText(&buffer, "8Testing and stuff\n"); + AddText(&buffer, "9Testing and stuff\n"); + AddText(&buffer, "1Testing and stuff\n"); + AddText(&buffer, "22esting and stuff\n"); + AddText(&buffer, "3Testing and stuff\n"); + AddText(&buffer, "4Testing and stuff\n"); + AddText(&buffer, "5Testing and stuff\n"); + AddText(&buffer, "6Testing and stuff\n"); + AddText(&buffer, "7Testing and stuff\n"); + AddText(&buffer, "8Testing and stuff\n"); + AddText(&buffer, "9Testing and stuff\n"); + AddText(&buffer, "1Testing and stuff\n"); + AddText(&buffer, "2Testing and stuff\n"); + AddText(&buffer, "3Testing and stuff\n"); + AddText(&buffer, "4Testing and stuff\n"); + + for !WindowShouldClose() { + ScreenSize = {:f32(GetScreenWidth()), :f32(GetScreenHeight())}; + initial_cursor: Selection = MainCursor; + + if IsKeyPressed(KEY_LEFT) || IsKeyPressedRepeat(KEY_LEFT) { + if IsKeyDown(KEY_LEFT_SHIFT) { + if IsKeyDown(KEY_LEFT_CONTROL) { + MainCursor.b = SeekOnWordBoundary(&buffer, MainCursor.b, GO_BACKWARD); + } else { + MainCursor.b = MoveLeft(&buffer, MainCursor.b); + } + } else { + if IsKeyDown(KEY_LEFT_CONTROL) { + MainCursor.a = SeekOnWordBoundary(&buffer, MainCursor.a, GO_BACKWARD); + MainCursor.b = MainCursor.a; + } else { + MainCursor.a = MoveLeft(&buffer, MainCursor.a); + MainCursor.b = MainCursor.a; + } + } + } + + if IsKeyPressed(KEY_RIGHT) || IsKeyPressedRepeat(KEY_RIGHT) { + if IsKeyDown(KEY_LEFT_SHIFT) { + if IsKeyDown(KEY_LEFT_CONTROL) { + MainCursor.b = SeekOnWordBoundary(&buffer, MainCursor.b, GO_FORWARD); + } else { + MainCursor.b = MoveRight(&buffer, MainCursor.b); + } + } else { + if IsKeyDown(KEY_LEFT_CONTROL) { + MainCursor.a = SeekOnWordBoundary(&buffer, MainCursor.a, GO_FORWARD); + MainCursor.b = MainCursor.a; + } else { + MainCursor.a = MoveRight(&buffer, MainCursor.a); + MainCursor.b = MainCursor.a; + } + } + } + + if (IsKeyPressed(KEY_DOWN) || IsKeyPressedRepeat(KEY_DOWN)) { + if IsKeyDown(KEY_LEFT_SHIFT) { + MainCursor.b = MoveDown(&buffer, MainCursor.b); + } else { + range := GetRange(MainCursor); + if GetRangeSize(range) > 0 { + MainCursor.b = range.max; + MainCursor.a = range.max; + } + MainCursor.a = MoveDown(&buffer, MainCursor.a); + MainCursor.b = MainCursor.a; + } + } + + if (IsKeyPressed(KEY_UP) || IsKeyPressedRepeat(KEY_UP)) { + if IsKeyDown(KEY_LEFT_SHIFT) { + MainCursor.b = MoveUp(&buffer, MainCursor.b); + } else { + range := GetRange(MainCursor); + if GetRangeSize(range) > 0 { + MainCursor.b = range.min; + MainCursor.a = range.min; + } + MainCursor.a = MoveUp(&buffer, MainCursor.a); + MainCursor.b = MainCursor.a; + } + } + + if IsKeyPressed(KEY_BACKSPACE) || IsKeyPressedRepeat(KEY_BACKSPACE) { + range := GetRange(MainCursor); + range_size := GetRangeSize(range); + + if range_size == 0 { + if IsKeyDown(KEY_LEFT_CONTROL) { + left := SeekOnWordBoundary(&buffer, MainCursor.a, GO_BACKWARD); + ReplaceText(&buffer, {left, MainCursor.a}, ""); + MainCursor.a = left; + MainCursor.b = MainCursor.a; + } else { + left := MoveLeft(&buffer, MainCursor.a); + ReplaceText(&buffer, {left, MainCursor.a}, ""); + MainCursor.a = left; + MainCursor.b = MainCursor.a; + } + } else { + ReplaceText(&buffer, range, ""); + MainCursor.b = range.min; + MainCursor.a = MainCursor.b; + } + } + + if IsKeyPressed(KEY_DELETE) || IsKeyPressedRepeat(KEY_DELETE) { + range := GetRange(MainCursor); + range_size := GetRangeSize(range); + + if range_size == 0 { + if IsKeyDown(KEY_LEFT_CONTROL) { + right := SeekOnWordBoundary(&buffer, MainCursor.a); + ReplaceText(&buffer, {MainCursor.a, right}, ""); + } else { + right := MoveRight(&buffer, MainCursor.a); + ReplaceText(&buffer, {MainCursor.a, right}, ""); + } + MainCursor.b = MainCursor.a; + } else { + ReplaceText(&buffer, range, ""); + MainCursor.b = range.min; + MainCursor.a = MainCursor.b; + } + } + + if IsKeyPressed(KEY_ENTER) || IsKeyPressedRepeat(KEY_ENTER) { + ReplaceText(&buffer, GetRange(MainCursor), "\n"); + MainCursor.a = MoveRight(&buffer, MainCursor.a); + MainCursor.b = MainCursor.a; + } + + if IsKeyPressed(KEY_HOME) { + line := FindLineOfPos(&buffer, MainCursor.b); + if IsKeyDown(KEY_LEFT_SHIFT) { + MainCursor.b = line.range.min; + } else { + MainCursor.a = line.range.min; + MainCursor.b = line.range.min; + } + } + if IsKeyPressed(KEY_END) { + line := FindLineOfPos(&buffer, MainCursor.b); + if IsKeyDown(KEY_LEFT_SHIFT) { + MainCursor.b = line.range.max; + } else { + MainCursor.a = line.range.max; + MainCursor.b = line.range.max; + } + } + + if IsKeyPressed(KEY_PAGE_DOWN) || IsKeyPressedRepeat(KEY_PAGE_DOWN) { + vpos := CalculateVisualPos(&buffer, MainCursor.b); + move_by := :int(roundf(ScreenSize.y / Monosize.y)); + vpos.y += move_by; + MainCursor.b = CalculatePosFromVisualPos(&buffer, vpos); + if !IsKeyDown(KEY_LEFT_SHIFT) { + MainCursor.a = MainCursor.b; + } + } + if IsKeyPressed(KEY_PAGE_UP) || IsKeyPressedRepeat(KEY_PAGE_UP) { + vpos := CalculateVisualPos(&buffer, MainCursor.b); + move_by := :int(roundf(ScreenSize.y / Monosize.y)); + vpos.y -= move_by; + MainCursor.b = CalculatePosFromVisualPos(&buffer, vpos); + if !IsKeyDown(KEY_LEFT_SHIFT) { + MainCursor.a = MainCursor.b; + } + } + + mouse_p := GetMousePosition(); + if IsMouseButtonDown(MOUSE_BUTTON_LEFT) { + p := Vector2Add(mouse_p, Scroll); + p = Vector2Divide(p, Monosize); + x := :int(floorf(p.x)); + y := :int(floorf(p.y)); + MainCursor.a = CalculatePosFromVisualPos(&buffer, {x, y}); + MainCursor.b = MainCursor.a; + } + + if CheckCollisionPointRec(mouse_p, {0, 0, ScreenSize.x, ScreenSize.y}) { + SetMouseCursor(MOUSE_CURSOR_IBEAM); + } else { + SetMouseCursor(MOUSE_CURSOR_DEFAULT); + } + + for key := GetCharPressed(); key; key = GetCharPressed() { + selection_range := GetRange(MainCursor); + + result: UTF8_Result = UTF32ToUTF8(:u32(key)); + if result.error == 0 { + ReplaceText(&buffer, selection_range, {:*char(&result.out_str[0]), result.len}); + } else { + ReplaceText(&buffer, selection_range, "?"); + } + + range_size := GetRangeSize(selection_range); + if range_size != 0 { + MainCursor.a = selection_range.min; + MainCursor.b = selection_range.min; + } + MainCursor.a = MoveRight(&buffer, MainCursor.a); + MainCursor.b = MainCursor.a; + } + + // + // Scrolling + // + mouse_wheel := GetMouseWheelMove() * 16; + Scroll.y -= mouse_wheel; + + if initial_cursor.b != MainCursor.b { + cursor_vpos := CalculateVisualPos(&buffer, MainCursor.b); + + world_pos := CalculateWorldPosUnscrolled(cursor_vpos); + world_pos_cursor_end := Vector2Add(world_pos, Monosize); + + scrolled_begin := Scroll; + scrolled_end := Vector2Add(Scroll, ScreenSize); + + if world_pos_cursor_end.x > scrolled_end.x { + Scroll.x += world_pos_cursor_end.x - scrolled_end.x; + } + if world_pos.x < scrolled_begin.x { + Scroll.x -= scrolled_begin.x - world_pos.x; + } + if world_pos_cursor_end.y > scrolled_end.y { + Scroll.y += world_pos_cursor_end.y - scrolled_end.y; + } + if world_pos.y < scrolled_begin.y { + Scroll.y -= scrolled_begin.y - world_pos.y; + } + } + if (Scroll.x < 0) Scroll.x = 0; + if (Scroll.y < 0) Scroll.y = 0; + + + + BeginDrawing(); + ClearBackground(RAYWHITE); + + _miny := Scroll.y / Monosize.y; + _maxy := (Scroll.y + ScreenSize.y) / Monosize.y; + + _minx := Scroll.x / Monosize.x; + _maxx := (Scroll.x + ScreenSize.x) / Monosize.x; + + miny := :int(floorf(_miny)); + minx := :int(floorf(_minx)); + + maxy := :int(ceilf(_maxy)); + maxx := :int(ceilf(_maxx)); + + // Draw grid + { + for y := miny; y < maxy; y += 1 { + for x := minx; x < maxx; x += 1 { + p := CalculateWorldPos({x, y}); + rect := Rect2PSize(p.x, p.y, Monosize.x, Monosize.y); + rect = Shrink(rect, 1); + DrawRect(rect, {255, 0, 0, 40}); + } + } + } + + // Draw text + { + miny = ClampInt(miny, 0, buffer.lines.len - 1); + maxy = ClampInt(maxy, 0, buffer.lines.len - 1); + for y := miny; y <= maxy; y += 1 { + line := buffer.lines.data[y]; + + string := AllocStringFromBuffer(&buffer, line, null_terminate = true); + defer free(string.str); + + pos := CalculateWorldPos({0, y}); + DrawTextEx(font, string.str, pos, font_size, font_spacing, BLACK); + } + } + + // Draw selection + { + range := GetRange(MainCursor); + start_vpos := CalculateVisualPos(&buffer, range.min); + pos := start_vpos; + for iter := Iterate(&buffer, range.min, range.max); IsValid(iter); Advance(&iter) { + world_pos := CalculateWorldPos(pos); + rect := Rect2PSize(world_pos.x, world_pos.y, Monosize.x, Monosize.y); + DrawRect(rect, {0, 255, 0, 40}); + + pos.x += 1; + if iter.item == '\n' { + pos.x = 0; + pos.y += 1; + } + } + } + + // Draw cursor + { + c := CalculateVisualPos(&buffer, MainCursor.b); + p := CalculateWorldPos(c); + + cursor_size: f32 = Monosize.x * 0.2; + rect := Rect2PSize(p.x, p.y, Monosize.x, Monosize.y); + rect = CutLeft(&rect, cursor_size); + + DrawRect(rect, RED); + } + + + EndDrawing(); + } + CloseWindow(); + return 0; +} \ No newline at end of file diff --git a/examples/text_editor/rect2p.lc b/examples/text_editor/rect2p.lc new file mode 100644 index 0000000..ed3df06 --- /dev/null +++ b/examples/text_editor/rect2p.lc @@ -0,0 +1,79 @@ +Rect2P :: struct { + min: Vector2; + max: Vector2; +} + +F32_Max :: proc(a: f32, b: f32): f32 { + if a > b return a; + return b; +} + +F32_Min :: proc(a: f32, b: f32): f32 { + if a > b return b; + return a; +} + +F32_Clamp :: proc(val: f32, min: f32, max: f32): f32 { + if (val > max) return max; + if (val < min) return min; + return val; +} + +GetRectSize :: proc(rect: Rect2P): Vector2 { + result: Vector2 = {rect.max.x - rect.min.x, rect.max.y - rect.min.y}; + return result; +} + +CutLeft :: proc(r: *Rect2P, value: f32): Rect2P { + minx := r.min.x; + r.min.x = F32_Min(r.max.x, r.min.x + value); + return :Rect2P{ + { minx, r.min.y}, + {r.min.x, r.max.y}, + }; +} + +CutRight :: proc(r: *Rect2P, value: f32): Rect2P { + maxx := r.max.x; + r.max.x = F32_Max(r.max.x - value, r.min.x); + return :Rect2P{ + {r.max.x, r.min.y}, + { maxx, r.max.y}, + }; +} + +CutBottom :: proc(r: *Rect2P, value: f32): Rect2P { // Y is down + maxy := r.max.y; + r.max.y = F32_Max(r.min.y, r.max.y - value); + return :Rect2P{ + {r.min.x, r.max.y}, + {r.max.x, maxy}, + }; +} + +CutTop :: proc(r: *Rect2P, value: f32): Rect2P { // Y is down + miny := r.min.y; + r.min.y = F32_Min(r.min.y + value, r.max.y); + return :Rect2P{ + {r.min.x, miny}, + {r.max.x, r.min.y}, + }; +} + +Rect2PToRectangle :: proc(r: Rect2P): Rectangle { + result: Rectangle = {r.min.x, r.min.y, r.max.x - r.min.x, r.max.y - r.min.y}; + return result; +} + +Rect2PSize :: proc(x: f32, y: f32, w: f32, h: f32): Rect2P { + result: Rect2P = {{x, y}, {x+w, y+h}}; + return result; +} + +Shrink :: proc(r: Rect2P, v: f32): Rect2P { + r.min.x += v; + r.min.y += v; + r.max.x -= v; + r.max.y -= v; + return r; +} \ No newline at end of file diff --git a/examples/text_editor/unicode.lc b/examples/text_editor/unicode.lc new file mode 100644 index 0000000..149ba8a --- /dev/null +++ b/examples/text_editor/unicode.lc @@ -0,0 +1,94 @@ +UTF32_Result :: struct { + out_str: u32; + advance: int; + error: int; +} + +UTF8_Result :: struct { + out_str: [4]u8; + len: int; + error: int; +} + +IsUTF8ContinuationByte :: proc(c: u8): bool { + result := (c & 0b11000000) == 0b10000000; + return result; +} + +UTF8ToUTF32 :: proc(c: *uchar, max_advance: int): UTF32_Result { + result: UTF32_Result; + + if (c[0] & 0x80) == 0 { // Check if leftmost zero of first byte is unset + if max_advance >= 1 { + result.out_str = :u32(c[0]); + result.advance = 1; + } + else result.error = 1; + } + + else if (c[0] & 0xe0) == 0xc0 { + if (c[1] & 0xc0) == 0x80 { // Continuation byte required + if max_advance >= 2 { + result.out_str = (:u32(c[0] & 0x1f) << 6) | :u32(c[1] & 0x3f); + result.advance = 2; + } + else result.error = 2; + } + else result.error = 2; + } + + else if (c[0] & 0xf0) == 0xe0 { + if ((c[1] & 0xc0) == 0x80) && ((c[2] & 0xc0) == 0x80) { // Two continuation bytes required + if max_advance >= 3 { + result.out_str = (:u32(c[0] & 0xf) << 12) | (:u32(c[1] & 0x3f) << 6) | :u32(c[2] & 0x3f); + result.advance = 3; + } + else result.error = 3; + } + else result.error = 3; + } + + else if (c[0] & 0xf8) == 0xf0 { + if (c[1] & 0xc0) == 0x80 && (c[2] & 0xc0) == 0x80 && (c[3] & 0xc0) == 0x80 { // Three continuation bytes required + if max_advance >= 4 { + result.out_str = :u32(c[0] & 0xf) << 18 | :u32(c[1] & 0x3f) << 12 | :u32(c[2] & 0x3f) << 6 | :u32(c[3] & 0x3f); + result.advance = 4; + } + else result.error = 4; + } + else result.error = 4; + } + else result.error = 4; + + return result; +} + +UTF32ToUTF8 :: proc(codepoint: u32): UTF8_Result { + result: UTF8_Result; + + if codepoint <= 0x7F { + result.len = 1; + result.out_str[0] = :u8(codepoint); + } + else if codepoint <= 0x7FF { + result.len = 2; + result.out_str[0] = :u8 (0xc0 | 0x1f & (codepoint >> 6)); + result.out_str[1] = :u8 (0x80 | 0x3f & codepoint); + } + else if codepoint <= 0xFFFF { // 16 bit word + result.len = 3; + result.out_str[0] = :u8 (0xe0 | 0xf & (codepoint >> 12)); // 4 bits + result.out_str[1] = :u8 (0x80 | 0x3f & (codepoint >> 6)); // 6 bits + result.out_str[2] = :u8 (0x80 | 0x3f & codepoint); // 6 bits + } + else if codepoint <= 0x10FFFF { // 21 bit word + result.len = 4; + result.out_str[0] = :u8 (0xf0 | 0x7 & (codepoint >> 18)); // 3 bits + result.out_str[1] = :u8 (0x80 | 0x3f & (codepoint >> 12)); // 6 bits + result.out_str[2] = :u8 (0x80 | 0x3f & (codepoint >> 6)); // 6 bits + result.out_str[3] = :u8 (0x80 | 0x3f & codepoint); // 6 bits + } + else result.error = 1; + + return result; +} diff --git a/examples/text_editor/visual_pos.lc b/examples/text_editor/visual_pos.lc new file mode 100644 index 0000000..88bbb9a --- /dev/null +++ b/examples/text_editor/visual_pos.lc @@ -0,0 +1,76 @@ +Monosize: Vector2; +ScreenSize: Vector2; +Scroll: Vector2; + +Vec2I :: struct { + x: int; + y: int; +} + +MoveLeft :: proc(buffer: *Buffer, pos: int): int { + pos -= 1; + pos = AdjustUTF8Pos(buffer, pos, direction = -1); + return pos; +} + +MoveRight :: proc(buffer: *Buffer, pos: int): int { + pos += 1; + pos = AdjustUTF8Pos(buffer, pos, direction = +1); + return pos; +} + +CalculateVisualPos :: proc(buffer: *Buffer, pos: int): Vec2I { + line: LineInfo = FindLineOfPos(buffer, pos); + + iter := Iterate(buffer, line.range.min, line.range.max); + for IsValid(iter); Advance(&iter) { + if iter.pos == pos { + break; + } + } + + result: Vec2I = {iter.codepoint_index, line.number}; + return result; +} + +CalculatePosFromVisualPos :: proc(buffer: *Buffer, vpos: Vec2I): int { + line := GetLine(buffer, vpos.y); + iter := Iterate(buffer, line.range.min, line.range.max); + for IsValid(iter); Advance(&iter) { + if iter.codepoint_index == vpos.x { + break; + } + } + return iter.pos; +} + +CalculateWorldPosUnscrolled :: proc(vpos: Vec2I): Vector2 { + result: Vector2 = {Monosize.x * :f32(vpos.x), Monosize.y * :f32(vpos.y)}; + return result; +} + +CalculateWorldPos :: proc(vpos: Vec2I): Vector2 { + result: Vector2 = {Monosize.x * :f32(vpos.x) - Scroll.x, Monosize.y * :f32(vpos.y) - Scroll.y}; + return result; +} + +MoveDown :: proc(buffer: *Buffer, pos: int): int { + vpos := CalculateVisualPos(buffer, pos); + if !IsLineValid(buffer, vpos.y + 1) return pos; + + result := CalculatePosFromVisualPos(buffer, {vpos.x, vpos.y + 1}); + return result; +} + +MoveUp :: proc(buffer: *Buffer, pos: int): int { + vpos := CalculateVisualPos(buffer, pos); + if !IsLineValid(buffer, vpos.y - 1) return pos; + + result := CalculatePosFromVisualPos(buffer, {vpos.x, vpos.y - 1}); + return result; +} + +DrawRect :: proc(rec: Rect2P, color: Color) { + rectangle := Rect2PToRectangle(rec); + DrawRectangleRec(rectangle, color); +} diff --git a/examples/use_as_data_format_with_typechecking/build.cpp b/examples/use_as_data_format_with_typechecking/build.cpp new file mode 100644 index 0000000..865189e --- /dev/null +++ b/examples/use_as_data_format_with_typechecking/build.cpp @@ -0,0 +1,105 @@ +void OnExprResolved_MakeSureConstantsWork(LC_AST *n, LC_Operand *op); +bool use_as_data_format_with_typechecking() { + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + lang->on_expr_resolved = OnExprResolved_MakeSureConstantsWork; + LC_LangBegin(lang); + LC_RegisterPackageDir("../examples/"); + LC_RegisterPackageDir("../pkgs"); + + LC_Intern name = LC_ILit("use_as_data_format_with_typechecking"); + LC_ASTRefList packages = LC_ResolvePackageByName(name); + if (L->errors) { + LC_LangEnd(lang); + return false; + } + + LC_AST *package = LC_GetPackageByName(name); + + // Constants + { + LC_Decl *int_value = LC_FindDeclInScope(package->apackage.scope, LC_ILit("IntValue")); + int64_t IntValue = LC_Bigint_as_signed(&int_value->val.i); + IO_Assert(IntValue == 232); + } + + { + LC_Decl *decl = LC_FindDeclInScope(package->apackage.scope, LC_ILit("FloatValue")); + IO_Assert(decl->val.d == 13.0); + } + + { + LC_Decl *decl = LC_FindDeclInScope(package->apackage.scope, LC_ILit("SomeString")); + IO_Assert(decl->val.name == LC_ILit("Thing")); + } + + // Player + + int64_t LEVEL_BEGIN = -1; + { + LC_Decl *int_value = LC_FindDeclInScope(package->apackage.scope, LC_ILit("LEVEL_BEGIN")); + LEVEL_BEGIN = LC_Bigint_as_signed(&int_value->val.i); + IO_Assert(LEVEL_BEGIN == 2); + } + + { + /* @todo: + double DashSpeed = GetFloatValue(p, "Player.DashSpeed"); + double Hurtbox = GetFloatValue(p, "Player[0].Something.min.x"); + int64_t DashVFloorSnapDist = GetIntValue(p, "Player.DashVFloorSnapDist"); + + double Variable = GetFloatValue(p, "Variable"); + */ + + LC_Decl *decl = LC_FindDeclInScope(package->apackage.scope, LC_ILit("Player")); + LC_ResolvedCompo *items = decl->ast->dvar.expr->ecompo.resolved_items; + for (LC_ResolvedCompoItem *it = items->first; it; it = it->next) { + LC_Intern name = it->t->name; + + if (name == LC_ILit("DashSpeed")) { + double DashSpeed = it->expr->const_val.d; + IO_Assert(DashSpeed == 240.0); + } else if (name == LC_ILit("DashCooldown")) { + double DashCooldown = it->expr->const_val.d; + IO_Assert(DashCooldown > 0.19 && DashCooldown < 0.21); + } else if (name == LC_ILit("Level")) { + int64_t Level = LC_Bigint_as_signed(&it->expr->const_val.i); + IO_Assert(Level == LEVEL_BEGIN); + } + } + } + + { + LC_Decl *decl = LC_FindDeclInScope(package->apackage.scope, LC_ILit("Variable")); + IO_Assert(decl->val.d == 32.0); + } + + { + LC_Decl *decl = LC_FindDeclInScope(package->apackage.scope, LC_ILit("Reference")); + IO_Assert(decl->val.d == 64.0); + } + + LC_LangEnd(lang); + return true; +} + +void OnExprResolved_MakeSureConstantsWork(LC_AST *n, LC_Operand *op) { + switch (n->kind) { + case LC_ASTKind_ExprCast: + case LC_ASTKind_ExprAddPtr: + case LC_ASTKind_ExprIndex: + case LC_ASTKind_ExprGetPointerOfValue: + case LC_ASTKind_ExprGetValueOfPointer: + case LC_ASTKind_ExprCall: + LC_ReportASTError(n, "illegal expression kind"); + return; + default: { + } + } + + if (LC_IsFloat(op->type)) op->type = L->tuntypedfloat; + if (LC_IsInt(op->type)) op->type = L->tuntypedint; + if (LC_IsStr(op->type)) op->type = L->tuntypedstring; + op->flags |= LC_OPF_UTConst; +} \ No newline at end of file diff --git a/examples/use_as_data_format_with_typechecking/data.lc b/examples/use_as_data_format_with_typechecking/data.lc new file mode 100644 index 0000000..03a3005 --- /dev/null +++ b/examples/use_as_data_format_with_typechecking/data.lc @@ -0,0 +1,57 @@ +Vector2 :: struct { + x: float; + y: float; +} + +Hitbox :: struct { + min: Vector2; + max: Vector2; +} + +TPlayer :: struct { + DashSpeed: float; + EndDashSpeed: float; + EndDashUpMult: float; + DashTime: float; + DashCooldown: float; + DashRefillCooldown: float; + DashHJumpThruNudge: int; + DashCornerCorrection: int; + DashVFloorSnapDist: int; + DashAttackTime: float; + + Level: int; + NormalHitbox: Hitbox; + DuckHitbox: Hitbox; + + NormalHurtbox: Hitbox; + DuckHurtbox: Hitbox; +} + +Player: TPlayer = { + DashSpeed = 240, + EndDashSpeed = 160, + EndDashUpMult = 0.75, + DashTime = 0.15, + DashCooldown = 0.2, + DashRefillCooldown = 0.1, + DashHJumpThruNudge = 6, + DashCornerCorrection = 4, + DashVFloorSnapDist = 3, + DashAttackTime = 0.3, + + Level = LEVEL_BEGIN, + NormalHitbox = { { 1, 1 }, { 2, 2 } }, + NormalHurtbox = { min = { x = 1, y = 1 }, max = { 2 } }, +}; + +LEVEL_TUTORIAL :: 1; +LEVEL_BEGIN :: ^; + +IntValue :: 232; +FloatValue :: 13.0; +SomeString :: "Thing"; + +Variable: float = 32.0; +Reference := Variable + Variable; + diff --git a/lib_compiler.h b/lib_compiler.h new file mode 100644 index 0000000..18ed716 --- /dev/null +++ b/lib_compiler.h @@ -0,0 +1,11089 @@ +/* +This is a compiler frontend in a single-header-file library form. +In **beta** version so things may change between versions! + +# How to use + +In *one* of your C or C++ files to create the implementation: + +``` +#define LIB_COMPILER_IMPLEMENTATION +#include "lib_compiler.h" +``` + +In the rest of your files you can just include it like a regular +header. + +# Examples + +See online repository for code examples + +# Overrides + +You can override libc calls, the arena implementation using +preprocessor at compile time, here is an example of how you +would go about it: + +``` +#define LC_vsnprintf stbsp_vsnprintf +#define LC_MemoryZero(p, size) __builtin_memset(p, 0, size); +#define LC_MemoryCopy(dst, src, size) __builtin_memcpy(dst, src, size) + +#define LIB_COMPILER_IMPLEMENTATION +#include "lib_compiler.h" +``` + +Look for '@override' to find things that can be overridden using macro preprocessor +Look for '@api' to find the main functions that you are supposed to use +Look for '@configurable' to find runtime callbacks you can register and other settings + +# License (MIT) + +See end of file + +*/ +#ifndef LIB_COMPILER_HEADER +#define LIB_COMPILER_HEADER + +#define LIB_COMPILER_MAJOR 0 +#define LIB_COMPILER_MINOR 6 + +#include +#include +#include +#include + +#ifndef LC_THREAD_LOCAL // @override + #if defined(__cplusplus) && __cplusplus >= 201103L + #define LC_THREAD_LOCAL thread_local + #elif defined(__GNUC__) + #define LC_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define LC_THREAD_LOCAL __declspec(thread) + #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) + #define LC_THREAD_LOCAL _Thread_local + #elif defined(__TINYC__) + #define LC_THREAD_LOCAL _Thread_local + #else + #error Couldnt figure out thread local, needs to be provided manually + #endif +#endif + +#ifndef LC_FUNCTION // @override + #define LC_FUNCTION +#endif + +#ifndef LC_String // @override +typedef struct { + char *str; + int64_t len; +} LC_String; +#endif + +#ifndef LC_USE_CUSTOM_ARENA // @override +typedef struct LC_VMemory LC_VMemory; +typedef struct LC_TempArena LC_TempArena; +typedef struct LC_Arena LC_Arena; +typedef struct LC_SourceLoc LC_SourceLoc; + +struct LC_VMemory { + size_t commit; + size_t reserve; + uint8_t *data; +}; + +struct LC_Arena { + LC_VMemory memory; + int alignment; + size_t len; + size_t base_len; // When popping to 0 this is the minimum "len" value + // It's so that Bootstrapped arena won't delete itself when Reseting. +}; + +struct LC_TempArena { + LC_Arena *arena; + size_t pos; +}; +#endif + +typedef struct LC_MapEntry LC_MapEntry; +typedef struct LC_Map LC_Map; +typedef struct LC_AST LC_AST; +typedef struct LC_ASTPackage LC_ASTPackage; +typedef struct LC_ASTNoteList LC_ASTNoteList; +typedef struct LC_ExprCompo LC_ExprCompo; +typedef union LC_Val LC_Val; +typedef struct LC_ExprIdent LC_ExprIdent; +typedef struct LC_ExprUnary LC_ExprUnary; +typedef struct LC_ExprBinary LC_ExprBinary; +typedef struct LC_ExprField LC_ExprField; +typedef struct LC_ExprIndex LC_ExprIndex; +typedef struct LC_ExprCompoItem LC_ExprCompoItem; +typedef struct LC_ExprType LC_ExprType; +typedef struct LC_ExprCast LC_ExprCast; +typedef struct LC_ExprNote LC_ExprNote; +typedef struct LC_StmtBlock LC_StmtBlock; +typedef struct LC_StmtFor LC_StmtFor; +typedef struct LC_StmtDefer LC_StmtDefer; +typedef struct LC_StmtSwitch LC_StmtSwitch; +typedef struct LC_StmtCase LC_StmtCase; +typedef struct LC_StmtIf LC_StmtIf; +typedef struct LC_StmtBreak LC_StmtBreak; +typedef struct LC_StmtAssign LC_StmtAssign; +typedef struct LC_StmtExpr LC_StmtExpr; +typedef struct LC_StmtVar LC_StmtVar; +typedef struct LC_StmtConst LC_StmtConst; +typedef struct LC_StmtReturn LC_StmtReturn; +typedef struct LC_StmtNote LC_StmtNote; +typedef struct LC_TypespecArray LC_TypespecArray; +typedef struct LC_TypespecProc LC_TypespecProc; +typedef struct LC_TypespecAggMem LC_TypespecAggMem; +typedef struct LC_TypespecProcArg LC_TypespecProcArg; +typedef struct LC_DeclBase LC_DeclBase; +typedef struct LC_DeclProc LC_DeclProc; +typedef struct LC_DeclTypedef LC_DeclTypedef; +typedef struct LC_DeclAgg LC_DeclAgg; +typedef struct LC_DeclVar LC_DeclVar; +typedef struct LC_DeclConst LC_DeclConst; +typedef struct LC_DeclNote LC_DeclNote; +typedef union LC_ASTValue LC_ASTValue; +typedef struct LC_TypeAndVal LC_TypeAndVal; +typedef struct LC_TypeArray LC_TypeArray; +typedef struct LC_TypePtr LC_TypePtr; +typedef struct LC_TypeMemberList LC_TypeMemberList; +typedef struct LC_TypeProc LC_TypeProc; +typedef struct LC_TypeAgg LC_TypeAgg; +typedef union LC_TypeValue LC_TypeValue; +typedef struct LC_Type LC_Type; +typedef struct LC_TypeMember LC_TypeMember; +typedef struct LC_Decl LC_Decl; +typedef struct LC_DeclStack LC_DeclStack; +typedef struct LC_Map DeclScope; +typedef struct LC_ResolvedCompo LC_ResolvedCompo; +typedef struct LC_ResolvedCompoItem LC_ResolvedCompoItem; +typedef struct LC_ResolvedCompoArrayItem LC_ResolvedCompoArrayItem; +typedef struct LC_ResolvedArrayCompo LC_ResolvedArrayCompo; +typedef union LC_TokenVal LC_TokenVal; +typedef struct LC_Token LC_Token; +typedef struct LC_Lex LC_Lex; +typedef struct LC_Parser LC_Parser; +typedef struct LC_Resolver LC_Resolver; +typedef struct LC_Lang LC_Lang; +typedef struct LC_ASTRef LC_ASTRef; +typedef struct LC_ASTRefList LC_ASTRefList; +typedef struct LC_ASTFile LC_ASTFile; +typedef LC_Val Expr_Atom; +typedef LC_TypespecArray Typespec_Pointer; +typedef uintptr_t LC_Intern; +typedef struct LC_GlobImport LC_GlobImport; +typedef struct LC_UTF32Result LC_UTF32Result; +typedef struct LC_UTF8Result LC_UTF8Result; +typedef struct LC_UTF16Result LC_UTF16Result; + +typedef struct LC_StringNode LC_StringNode; +struct LC_StringNode { + LC_StringNode *next; + LC_String string; +}; + +typedef struct LC_StringList LC_StringList; +struct LC_StringList { + int64_t node_count; + int64_t char_count; + LC_StringNode *first; + LC_StringNode *last; +}; + +typedef struct LC_String16 { + wchar_t *str; + int64_t len; +} LC_String16; + +struct LC_MapEntry { + uint64_t key; + uint64_t value; +}; + +struct LC_Map { + LC_Arena *arena; + LC_MapEntry *entries; + int cap; + int len; +}; + +typedef struct LC_BigInt LC_BigInt; +struct LC_BigInt { + unsigned digit_count; + bool is_negative; + union { + uint64_t digit; + uint64_t *digits; + }; +}; + +typedef enum LC_ASTKind { + LC_ASTKind_Null, + LC_ASTKind_Error, + LC_ASTKind_Note, + LC_ASTKind_NoteList, + LC_ASTKind_File, + LC_ASTKind_Package, + LC_ASTKind_Ignore, + LC_ASTKind_TypespecProcArg, + LC_ASTKind_TypespecAggMem, + LC_ASTKind_ExprCallItem, + LC_ASTKind_ExprCompoundItem, + LC_ASTKind_ExprNote, // a: int = #`sizeof(int)`; + LC_ASTKind_StmtSwitchCase, + LC_ASTKind_StmtSwitchDefault, + LC_ASTKind_StmtElseIf, + LC_ASTKind_StmtElse, + LC_ASTKind_GlobImport, + LC_ASTKind_DeclNote, + LC_ASTKind_DeclProc, + LC_ASTKind_DeclStruct, + LC_ASTKind_DeclUnion, + LC_ASTKind_DeclVar, + LC_ASTKind_DeclConst, + LC_ASTKind_DeclTypedef, + LC_ASTKind_TypespecIdent, + LC_ASTKind_TypespecField, + LC_ASTKind_TypespecPointer, + LC_ASTKind_TypespecArray, + LC_ASTKind_TypespecProc, + LC_ASTKind_StmtBlock, + LC_ASTKind_StmtNote, + LC_ASTKind_StmtReturn, + LC_ASTKind_StmtBreak, + LC_ASTKind_StmtContinue, + LC_ASTKind_StmtDefer, + LC_ASTKind_StmtFor, + LC_ASTKind_StmtIf, + LC_ASTKind_StmtSwitch, + LC_ASTKind_StmtAssign, + LC_ASTKind_StmtExpr, + LC_ASTKind_StmtVar, + LC_ASTKind_StmtConst, + LC_ASTKind_ExprIdent, + LC_ASTKind_ExprString, + LC_ASTKind_ExprInt, + LC_ASTKind_ExprFloat, + LC_ASTKind_ExprBool, + LC_ASTKind_ExprType, + LC_ASTKind_ExprBinary, + LC_ASTKind_ExprUnary, + LC_ASTKind_ExprBuiltin, + LC_ASTKind_ExprCall, + LC_ASTKind_ExprCompound, + LC_ASTKind_ExprCast, + LC_ASTKind_ExprField, + LC_ASTKind_ExprIndex, + LC_ASTKind_ExprAddPtr, + LC_ASTKind_ExprGetValueOfPointer, + LC_ASTKind_ExprGetPointerOfValue, + LC_ASTKind_Count, + LC_ASTKind_FirstExpr = LC_ASTKind_ExprIdent, + LC_ASTKind_LastExpr = LC_ASTKind_ExprGetPointerOfValue, + LC_ASTKind_FirstStmt = LC_ASTKind_StmtBlock, + LC_ASTKind_LastStmt = LC_ASTKind_StmtConst, + LC_ASTKind_FirstTypespec = LC_ASTKind_TypespecIdent, + LC_ASTKind_LastTypespec = LC_ASTKind_TypespecProc, + LC_ASTKind_FirstDecl = LC_ASTKind_DeclProc, + LC_ASTKind_LastDecl = LC_ASTKind_DeclTypedef, +} LC_ASTKind; + +typedef enum LC_TypeKind { + LC_TypeKind_char, + LC_TypeKind_uchar, + LC_TypeKind_short, + LC_TypeKind_ushort, + LC_TypeKind_bool, + LC_TypeKind_int, + LC_TypeKind_uint, + LC_TypeKind_long, + LC_TypeKind_ulong, + LC_TypeKind_llong, + LC_TypeKind_ullong, + LC_TypeKind_float, + LC_TypeKind_double, + LC_TypeKind_void, + LC_TypeKind_Struct, + LC_TypeKind_Union, + LC_TypeKind_Pointer, + LC_TypeKind_Array, + LC_TypeKind_Proc, + LC_TypeKind_UntypedInt, + LC_TypeKind_UntypedFloat, + LC_TypeKind_UntypedString, + LC_TypeKind_Incomplete, + LC_TypeKind_Completing, + LC_TypeKind_Error, + T_TotalCount, + T_NumericCount = LC_TypeKind_void, + T_Count = LC_TypeKind_void + 1, +} LC_TypeKind; + +typedef enum LC_DeclState { + LC_DeclState_Unresolved, + LC_DeclState_Resolving, + LC_DeclState_Resolved, + LC_DeclState_ResolvedBody, // proc + LC_DeclState_Error, + LC_DeclState_Count, +} LC_DeclState; + +typedef enum LC_DeclKind { + LC_DeclKind_Error, + LC_DeclKind_Type, + LC_DeclKind_Const, + LC_DeclKind_Var, + LC_DeclKind_Proc, + LC_DeclKind_Import, + LC_DeclKind_Count, +} LC_DeclKind; + +typedef enum LC_TokenKind { + LC_TokenKind_EOF, + LC_TokenKind_Error, + LC_TokenKind_Comment, + LC_TokenKind_DocComment, + LC_TokenKind_FileDocComment, + LC_TokenKind_PackageDocComment, + LC_TokenKind_Note, + LC_TokenKind_Hash, + LC_TokenKind_Ident, + LC_TokenKind_Keyword, + LC_TokenKind_String, + LC_TokenKind_RawString, + LC_TokenKind_Int, + LC_TokenKind_Float, + LC_TokenKind_Unicode, + LC_TokenKind_OpenParen, + LC_TokenKind_CloseParen, + LC_TokenKind_OpenBrace, + LC_TokenKind_CloseBrace, + LC_TokenKind_OpenBracket, + LC_TokenKind_CloseBracket, + LC_TokenKind_Comma, + LC_TokenKind_Question, + LC_TokenKind_Semicolon, + LC_TokenKind_Dot, + LC_TokenKind_ThreeDots, + LC_TokenKind_Colon, + LC_TokenKind_Mul, + LC_TokenKind_Div, + LC_TokenKind_Mod, + LC_TokenKind_LeftShift, + LC_TokenKind_RightShift, + LC_TokenKind_Add, + LC_TokenKind_Sub, + LC_TokenKind_Equals, + LC_TokenKind_LesserThen, + LC_TokenKind_GreaterThen, + LC_TokenKind_LesserThenEq, + LC_TokenKind_GreaterThenEq, + LC_TokenKind_NotEquals, + LC_TokenKind_BitAnd, + LC_TokenKind_BitOr, + LC_TokenKind_BitXor, + LC_TokenKind_And, + LC_TokenKind_Or, + LC_TokenKind_AddPtr, + LC_TokenKind_Neg, + LC_TokenKind_Not, + LC_TokenKind_Assign, + LC_TokenKind_DivAssign, + LC_TokenKind_MulAssign, + LC_TokenKind_ModAssign, + LC_TokenKind_SubAssign, + LC_TokenKind_AddAssign, + LC_TokenKind_BitAndAssign, + LC_TokenKind_BitOrAssign, + LC_TokenKind_BitXorAssign, + LC_TokenKind_LeftShiftAssign, + LC_TokenKind_RightShiftAssign, + LC_TokenKind_Count, +} LC_TokenKind; + +struct LC_ASTFile { + LC_AST *package; + LC_Lex *x; + + LC_AST *fimport; + LC_AST *limport; + LC_AST *fdecl; + LC_AST *ldecl; + LC_AST *fdiscarded; + LC_AST *ldiscarded; // @build_if + + LC_Token *doc_comment; + + bool build_if; +}; + +struct LC_ASTPackage { + LC_Intern name; + LC_DeclState state; + LC_String path; + LC_StringList injected_filepaths; // to sidestep regular file finding, implement single file packages etc. + LC_AST *ffile; + LC_AST *lfile; + LC_AST *fdiscarded; + LC_AST *ldiscarded; // #build_if + + LC_Token *doc_comment; + + // These are resolved later: + // @todo: add foreign name? + LC_Decl *first_ordered; + LC_Decl *last_ordered; + DeclScope *scope; +}; + +struct LC_ASTNoteList { + LC_AST *first; + LC_AST *last; +}; + +struct LC_ResolvedCompo { + int count; + LC_ResolvedCompoItem *first; + LC_ResolvedCompoItem *last; +}; + +struct LC_ResolvedCompoItem { + LC_ResolvedCompoItem *next; + LC_AST *comp; // for proc this may be null because we might match default value + LC_AST *expr; // for proc this is very important, the result, ordered expression + LC_TypeMember *t; + bool varg; + bool defaultarg; +}; + +struct LC_ResolvedCompoArrayItem { + LC_ResolvedCompoArrayItem *next; + LC_AST *comp; + int index; +}; + +struct LC_ResolvedArrayCompo { + int count; + LC_ResolvedCompoArrayItem *first; + LC_ResolvedCompoArrayItem *last; +}; + +struct LC_ExprCompo { + LC_AST *name; // :name{thing} or name(thing) + LC_AST *first; // {LC_ExprCompoItem, LC_ExprCompoItem} + LC_AST *last; + int size; + union { + LC_ResolvedCompo *resolved_items; + LC_ResolvedArrayCompo *resolved_array_items; + }; +}; + +struct LC_ExprCompoItem { + LC_Intern name; + LC_AST *index; + LC_AST *expr; +}; + +// clang-format off +union LC_Val { LC_BigInt i; double d; LC_Intern name; }; +struct LC_ExprIdent { LC_Intern name; LC_Decl *resolved_decl; }; +struct LC_ExprUnary { LC_TokenKind op; LC_AST *expr; }; +struct LC_ExprBinary { LC_TokenKind op; LC_AST *left; LC_AST *right; }; +struct LC_ExprField { LC_AST *left; LC_Intern right; LC_Decl *resolved_decl; LC_Decl *parent_decl; }; +struct LC_ExprIndex { LC_AST *base; LC_AST *index; }; +struct LC_ExprType { LC_AST *type; }; +struct LC_ExprCast { LC_AST *type; LC_AST *expr; }; +struct LC_ExprNote { LC_AST *expr; }; // v := #c(``) + +typedef enum { SBLK_Norm, SBLK_Loop, SBLK_Proc, SBLK_Defer } LC_StmtBlockKind; +struct LC_StmtBlock { LC_AST *first; LC_AST *last; LC_AST *first_defer; LC_StmtBlockKind kind; LC_Intern name; }; +struct LC_StmtFor { LC_AST *init; LC_AST *cond; LC_AST *inc; LC_AST *body; }; +struct LC_StmtDefer { LC_AST *next; LC_AST *body; }; +struct LC_StmtSwitch { LC_AST *first; LC_AST *last; LC_AST *expr; int total_switch_case_count; }; +struct LC_StmtCase { LC_AST *first; LC_AST *last; LC_AST *body; }; +// 'else if' and 'else' is avaialable from 'first'. +// The else_if and else are also LC_StmtIf but +// have different kinds and don't use 'first', 'last' +struct LC_StmtIf { LC_AST *expr; LC_AST *body; LC_AST *first; LC_AST *last; }; +struct LC_StmtBreak { LC_Intern name; }; +struct LC_StmtAssign { LC_TokenKind op; LC_AST *left; LC_AST *right; }; +struct LC_StmtExpr { LC_AST *expr; }; +struct LC_StmtVar { LC_AST *expr; LC_AST *type; LC_Intern name; LC_Decl *resolved_decl; }; +struct LC_StmtConst { LC_AST *expr; LC_Intern name; }; +struct LC_StmtReturn { LC_AST *expr; }; +struct LC_StmtNote { LC_AST *expr; }; // #c(``) in block +struct LC_TypespecArray { LC_AST *base; LC_AST *index; }; +struct LC_TypespecProc { LC_AST *first; LC_AST *last; LC_AST *ret; bool vargs; bool vargs_any_promotion; }; +struct LC_TypespecAggMem { LC_Intern name; LC_AST *type; }; +struct LC_TypespecProcArg { LC_Intern name; LC_AST *type; LC_AST *expr; LC_Decl *resolved_decl; }; +struct LC_DeclBase { LC_Intern name; LC_Token *doc_comment; LC_Decl *resolved_decl; }; +struct LC_DeclProc { LC_DeclBase base; LC_AST *body; LC_AST *type; }; +struct LC_DeclTypedef { LC_DeclBase base; LC_AST *type; }; +struct LC_DeclAgg { LC_DeclBase base; LC_AST *first; LC_AST *last; }; +struct LC_DeclVar { LC_DeclBase base; LC_AST *expr; LC_AST *type; }; +struct LC_DeclConst { LC_DeclBase base; LC_AST *expr; }; +struct LC_DeclNote { LC_DeclBase base; LC_AST *expr; bool processed; }; // #c(``) in file note list +struct LC_GlobImport { LC_Intern name; LC_Intern path; bool resolved; LC_Decl *resolved_decl; }; + +struct LC_ASTRef { LC_ASTRef *next; LC_ASTRef *prev; LC_AST *ast; }; +struct LC_ASTRefList { LC_ASTRef *first; LC_ASTRef *last; }; +// clang-format on + +struct LC_TypeAndVal { + LC_Type *type; + union { + LC_Val v; + union { + LC_BigInt i; + double d; + LC_Intern name; + }; + }; +}; + +struct LC_AST { + LC_ASTKind kind; + uint32_t id; + LC_AST *next; + LC_AST *prev; + LC_AST *notes; + LC_Token *pos; + + LC_TypeAndVal const_val; + LC_Type *type; + union { + LC_ASTFile afile; + LC_ASTPackage apackage; + LC_ASTNoteList anote_list; + LC_ExprCompo anote; + LC_Val eatom; + LC_ExprIdent eident; + LC_ExprUnary eunary; + LC_ExprBinary ebinary; + LC_ExprField efield; + LC_ExprIndex eindex; + LC_ExprCompo ecompo; + LC_ExprCompoItem ecompo_item; + LC_ExprType etype; + LC_ExprCast ecast; + LC_ExprNote enote; + LC_StmtBlock sblock; + LC_StmtFor sfor; + LC_StmtDefer sdefer; + LC_StmtSwitch sswitch; + LC_StmtCase scase; + LC_StmtIf sif; + LC_StmtBreak sbreak; + LC_StmtBreak scontinue; + LC_StmtAssign sassign; + LC_StmtExpr sexpr; + LC_StmtVar svar; + LC_StmtConst sconst; + LC_StmtReturn sreturn; + LC_StmtNote snote; + LC_ExprIdent tident; + LC_TypespecArray tarray; + LC_TypespecArray tpointer; + LC_TypespecProc tproc; + LC_TypespecAggMem tagg_mem; + LC_TypespecProcArg tproc_arg; + LC_DeclBase dbase; + LC_DeclProc dproc; + LC_DeclTypedef dtypedef; + LC_DeclAgg dagg; + LC_DeclVar dvar; + LC_DeclConst dconst; + LC_DeclNote dnote; + LC_GlobImport gimport; + }; +}; + +struct LC_TypeArray { + LC_Type *base; + int size; +}; + +struct LC_TypePtr { + LC_Type *base; +}; + +struct LC_TypeMemberList { + LC_TypeMember *first; + LC_TypeMember *last; + int count; +}; + +struct LC_TypeProc { + LC_TypeMemberList args; + LC_Type *ret; + bool vargs; + bool vargs_any_promotion; +}; + +struct LC_TypeAgg { + LC_TypeMemberList mems; +}; + +struct LC_Type { + LC_TypeKind kind; + int size; + int align; + int is_unsigned; + int id; + int padding; + LC_Decl *decl; + union { + LC_TypeArray tarray; + LC_TypePtr tptr; + LC_TypeProc tproc; + LC_TypeAgg tagg; + LC_Type *tbase; + LC_Type *tutdefault; + }; +}; + +struct LC_TypeMember { + LC_TypeMember *next; + LC_TypeMember *prev; + LC_Intern name; + LC_Type *type; + LC_AST *default_value_expr; + LC_AST *ast; + int offset; +}; + +struct LC_Decl { + LC_DeclKind kind; + LC_DeclState state; + uint8_t is_foreign; + + LC_Decl *next; + LC_Decl *prev; + LC_Intern name; + LC_Intern foreign_name; + LC_AST *ast; + LC_AST *package; + + LC_TypeMember *type_member; + DeclScope *scope; + LC_Decl *typedef_renamed_type_decl; + union { + LC_TypeAndVal val; + struct { + LC_Type *type; + LC_Val v; + }; + }; +}; + +typedef struct { + LC_Arena *arena; + LC_AST **data; + int cap; + int len; +} LC_ASTArray; + +typedef struct LC_ASTWalker LC_ASTWalker; +typedef void LC_ASTWalkProc(LC_ASTWalker *, LC_AST *); +struct LC_ASTWalker { + LC_ASTArray stack; + + int inside_builtin; + int inside_discarded; + int inside_note; + + uint8_t visit_discarded; + uint8_t visit_notes; + uint8_t depth_first; + uint8_t dont_recurse; // breathfirst only + void *user_data; + LC_ASTWalkProc *proc; +}; + +struct LC_DeclStack { + LC_Decl **stack; + int len; + int cap; +}; + +union LC_TokenVal { + LC_BigInt i; + double f64; + LC_Intern ident; +}; + +struct LC_Token { + LC_TokenKind kind; + int line; + int column; + int len; + char *str; + LC_Lex *lex; + union { + LC_BigInt i; + double f64; + LC_Intern ident; + }; +}; + +struct LC_Lex { + char *at; + char *begin; + LC_Intern file; + int line; + int column; + LC_Token *tokens; + int token_count; + bool insert_semicolon; +}; + +struct LC_Parser { + LC_Token *at; + LC_Token *begin; + LC_Token *end; + LC_Lex *x; +}; + +struct LC_Resolver { + LC_Type *compo_context_type; + int compo_context_array_size; + LC_Type *expected_ret_type; + LC_AST *package; + DeclScope *active_scope; + LC_DeclStack locals; + LC_Map duplicate_map; // currently used for finding duplicates in compos + LC_ASTArray stmt_block_stack; +}; + +typedef struct LC_Printer LC_Printer; +struct LC_Printer { + LC_Arena *arena; + LC_StringList list; + int indent; + LC_Intern last_filename; + int last_line_num; + LC_ASTArray out_block_stack; +}; + +const int LC_OPF_Error = 1; +const int LC_OPF_UTConst = 2; +const int LC_OPF_LValue = 4; +const int LC_OPF_Const = 8; +const int LC_OPF_Returned = 16; + +// warning: I introduced a null compare using the values in the operand +// make sure to revisit that when modifying the struct +typedef struct { + int flags; + union { + LC_Decl *decl; + LC_TypeAndVal val; + struct { + LC_Type *type; + LC_Val v; + }; + }; +} LC_Operand; + +typedef enum { + LC_ARCH_Invalid, + LC_ARCH_X64, + LC_ARCH_X86, + LC_ARCH_Count, +} LC_ARCH; + +typedef enum { + LC_GEN_Invalid, + LC_GEN_C, + LC_GEN_Count, +} LC_GEN; + +typedef enum { + LC_OS_Invalid, + LC_OS_WINDOWS, + LC_OS_LINUX, + LC_OS_MAC, + LC_OS_Count, +} LC_OS; + +typedef struct { + LC_String path; + LC_String content; + int line; +} LoadedFile; + +typedef enum { + LC_OPResult_Error, + LC_OPResult_Ok, + LC_OPResult_Bool, +} LC_OPResult; + +typedef struct { + int left; + int right; +} LC_BindingPower; + +typedef enum { + LC_Binding_Prefix, + LC_Binding_Infix, + LC_Binding_Postfix, +} LC_Binding; + +typedef enum { + LC_CmpRes_LT, + LC_CmpRes_GT, + LC_CmpRes_EQ, +} LC_CmpRes; + +typedef struct LC_FileIter LC_FileIter; +struct LC_FileIter { + bool is_valid; + bool is_directory; + LC_String absolute_path; + LC_String relative_path; + LC_String filename; + + LC_String path; + LC_Arena *arena; + union { + struct LC_Win32_FileIter *w32; + void *dir; + }; +}; + +#define LC_LIST_KEYWORDS \ + X(for) \ + X(import) \ + X(if) \ + X(else) \ + X(return) \ + X(defer) \ + X(continue) \ + X(break) \ + X(default) \ + X(case) \ + X(typedef) \ + X(switch) \ + X(proc) \ + X(struct) \ + X(union) \ + X(addptr) \ + X(and) \ + X(or) \ + X(bit_and) \ + X(bit_or) \ + X(bit_xor) \ + X(not ) \ + X(true) \ + X(false) + +#define LC_LIST_INTERNS \ + X(foreign, true) \ + X(api, true) \ + X(weak, true) \ + X(c, true) \ + X(fallthrough, true) \ + X(packed, true) \ + X(not_init, true) \ + X(unused, true) \ + X(static_assert, true) \ + X(str, true) \ + X(thread_local, true) \ + X(dont_mangle, true) \ + X(build_if, true) \ + X(Any, false) \ + X(main, false) \ + X(debug_break, false) \ + X(sizeof, false) \ + X(alignof, false) \ + X(typeof, false) \ + X(lengthof, false) \ + X(offsetof, false) + +#define LC_LIST_TYPES \ + X(char, false) \ + X(uchar, true) \ + X(short, false) \ + X(ushort, true) \ + X(bool, false) \ + X(int, false) \ + X(uint, true) \ + X(long, false) \ + X(ulong, true) \ + X(llong, false) \ + X(ullong, true) \ + X(float, false) \ + X(double, false) + +struct LC_Lang { + LC_Arena *arena; + + LC_Arena *lex_arena; + + LC_Arena *ast_arena; + int ast_count; + + LC_Arena *decl_arena; + int decl_count; + + LC_Arena *type_arena; + int type_count; + + int errors; + + int typeids; + LC_Map type_map; + + LC_AST *builtin_package; + LC_Resolver resolver; + LC_Parser *parser; + + // Package registry + LC_AST *fpackage; + LC_AST *lpackage; + LC_Intern first_package; + LC_ASTRefList ordered_packages; + LC_StringList package_dirs; + + LC_Map interns; + LC_Map declared_notes; + LC_Map foreign_names; + LC_Map implicit_any; + unsigned unique_counter; + + LC_Intern first_keyword; + LC_Intern last_keyword; + +#define X(x) LC_Intern k##x; + LC_LIST_KEYWORDS +#undef X + +#define X(x, declare) LC_Intern i##x; + LC_LIST_INTERNS +#undef X + + LC_Type types[14]; // be careful when changing +#define X(TNAME, IS_UNSIGNED) LC_Type *t##TNAME; + LC_LIST_TYPES +#undef X + + // When adding new special pointer types make sure to + // also update LC_SetPointerSizeAndAlign so that it properly + // updates the types after LC_LangBegin + int pointer_size; + int pointer_align; + LC_Type *tvoid; + LC_Type *tpvoid; + LC_Type *tpchar; + + LC_Type ttstring; + LC_Type *tstring; + LC_Type *tuntypednil; + LC_Type *tuntypedbool; + LC_Type *tuntypedint; + LC_Type ttuntypedfloat; + LC_Type *tuntypedfloat; + LC_Type ttuntypedstring; + LC_Type *tuntypedstring; + LC_Type ttany; + LC_Type *tany; + + LC_Token NullToken; + LC_AST NullAST; + LC_Token BuiltinToken; + LC_Lex NullLEX; + + LC_Printer printer; + LC_Parser quick_parser; + + // @configurable + LC_ARCH arch; + LC_GEN gen; + LC_OS os; + + bool emit_line_directives; + bool breakpoint_on_error; + bool use_colored_terminal_output; + + bool (*on_decl_parsed)(bool discarded, LC_AST *n); // returning 'true' from here indicates that declaration should be discarded + void (*on_expr_parsed)(LC_AST *n); + void (*on_stmt_parsed)(LC_AST *n); + void (*on_typespec_parsed)(LC_AST *n); + void (*on_decl_type_resolved)(LC_Decl *decl); + void (*on_proc_body_resolved)(LC_Decl *decl); + void (*on_expr_resolved)(LC_AST *expr, LC_Operand *op); + void (*on_stmt_resolved)(LC_AST *n); + void (*before_call_args_resolved)(LC_AST *n, LC_Type *type); + void (*on_file_load)(LC_AST *package, LoadedFile *file); + void (*on_message)(LC_Token *pos, char *str, int len); // pos and x can be null + void (*on_fatal_error)(void); + void *user_data; +}; + +extern LC_THREAD_LOCAL LC_Lang *L; +extern LC_Operand LC_OPNull; + +// +// Main @api +// + +LC_FUNCTION LC_Lang *LC_LangAlloc(void); // This allocates memory for LC_Lang which can be used to register callbacks and set configurables +LC_FUNCTION void LC_LangBegin(LC_Lang *l); // Prepare for compilation: init types, init builtins, set architecture variables stuff like that +LC_FUNCTION void LC_LangEnd(LC_Lang *lang); // Deallocate language memory + +LC_FUNCTION void LC_RegisterPackageDir(char *dir); // Add a package search directory +LC_FUNCTION LC_ASTRefList LC_ResolvePackageByName(LC_Intern name); // Fully resolve a package and all it's dependences +LC_FUNCTION LC_String LC_GenerateUnityBuild(LC_ASTRefList packages); // Generate the C program and return as a string + +// Smaller passes for AST modification +LC_FUNCTION void LC_ParsePackagesUsingRegistry(LC_Intern name); // These 3 functions are equivalent to LC_ResolvePackageByName, +LC_FUNCTION void LC_OrderAndResolveTopLevelDecls(LC_Intern name); // you can use them to hook into the compilation process - you can modify the AST +LC_FUNCTION void LC_ResolveAllProcBodies(void); // before resolving or use resolved top declarations to generate some code. + // The Parse and Order functions can be called multiple times to accommodate this. + +// Extended pass / optimization +LC_FUNCTION void LC_FindUnusedLocalsAndRemoveUnusedGlobalDecls(void); // Extended pass that you can execute once you have resolved all packages + +// These three functions are used to implement LC_FindUnusedLocalsAndRemoveUnusedGlobalDecls +LC_FUNCTION LC_Map LC_CountDeclRefs(LC_Arena *arena); +LC_FUNCTION void LC_RemoveUnreferencedGlobalDecls(LC_Map *map_of_visits); +LC_FUNCTION void LC_ErrorOnUnreferencedLocals(LC_Map *map_of_visits); + +// Notes +LC_FUNCTION void LC_DeclareNote(LC_Intern intern); +LC_FUNCTION bool LC_IsNoteDeclared(LC_Intern intern); +LC_FUNCTION LC_AST *LC_HasNote(LC_AST *ast, LC_Intern i); + +// Quick parse functions +LC_FUNCTION LC_AST *LC_ParseStmtf(const char *str, ...); +LC_FUNCTION LC_AST *LC_ParseExprf(const char *str, ...); +LC_FUNCTION LC_AST *LC_ParseDeclf(const char *str, ...); + +// AST Walking and copy +LC_FUNCTION LC_AST *LC_CopyAST(LC_Arena *arena, LC_AST *n); // Deep copy the AST +LC_FUNCTION LC_ASTArray LC_FlattenAST(LC_Arena *arena, LC_AST *n); // This walks the passed down tree and generates a flat array of pointers, very nice to use for traversing AST +LC_FUNCTION void LC_WalkAST(LC_ASTWalker *ctx, LC_AST *n); +LC_FUNCTION LC_ASTWalker LC_GetDefaultWalker(LC_Arena *arena, LC_ASTWalkProc *proc); + +LC_FUNCTION void LC_ReserveAST(LC_ASTArray *arr, int size); +LC_FUNCTION void LC_PushAST(LC_ASTArray *arr, LC_AST *ast); +LC_FUNCTION void LC_PopAST(LC_ASTArray *arr); +LC_FUNCTION LC_AST *LC_GetLastAST(LC_ASTArray *arr); + +// Interning API +LC_FUNCTION LC_Intern LC_ILit(char *str); +LC_FUNCTION void LC_InternTokens(LC_Lex *x); + +LC_FUNCTION LC_Intern LC_InternStrLen(char *str, int len); +LC_FUNCTION LC_Intern LC_GetUniqueIntern(const char *name_for_debug); +LC_FUNCTION char *LC_GetUniqueName(const char *name_for_debug); + +// +// Package functions +// +LC_FUNCTION LC_Operand LC_ImportPackage(LC_AST *import, LC_AST *dst, LC_AST *src); +LC_FUNCTION LC_Intern LC_MakePackageNameFromPath(LC_String path); +LC_FUNCTION bool LC_PackageNameValid(LC_Intern name); +LC_FUNCTION bool LC_PackageNameDuplicate(LC_Intern name); +LC_FUNCTION void LC_AddPackageToList(LC_AST *n); +LC_FUNCTION LC_AST *LC_RegisterPackage(LC_String path); +LC_FUNCTION void LC_AddFileToPackage(LC_AST *pkg, LC_AST *f); +LC_FUNCTION LC_AST *LC_FindImportInRefList(LC_ASTRefList *arr, LC_Intern path); +LC_FUNCTION void LC_AddASTToRefList(LC_ASTRefList *refs, LC_AST *ast); +LC_FUNCTION LC_ASTRefList LC_GetPackageImports(LC_AST *package); +LC_FUNCTION LC_AST *LC_GetPackageByName(LC_Intern name); +LC_FUNCTION LC_StringList LC_ListFilesInPackage(LC_Arena *arena, LC_String path); +LC_FUNCTION LoadedFile LC_ReadFileHook(LC_AST *package, LC_String path); +LC_FUNCTION void LC_ParsePackage(LC_AST *n); +LC_FUNCTION void LC_AddOrderedPackageToRefList(LC_AST *n); +LC_FUNCTION LC_AST *LC_OrderPackagesAndBasicResolve(LC_AST *pos, LC_Intern name); +LC_FUNCTION void LC_AddSingleFilePackage(LC_Intern name, LC_String path); + +// +// Lexing functions +// +LC_FUNCTION LC_Lex *LC_LexStream(char *file, char *str, int line); +LC_FUNCTION LC_String LC_GetTokenLine(LC_Token *token); + +LC_FUNCTION void LC_LexingError(LC_Token *pos, const char *str, ...); +LC_FUNCTION bool LC_IsAssign(LC_TokenKind kind); +LC_FUNCTION bool LC_IsHexDigit(char c); +LC_FUNCTION bool LC_IsBinDigit(char c); +LC_FUNCTION uint64_t LC_MapCharToNumber(char c); +LC_FUNCTION uint64_t LC_GetEscapeCode(char c); +LC_FUNCTION LC_String LC_GetEscapeString(char c); +LC_FUNCTION void LC_LexAdvance(LC_Lex *x); +LC_FUNCTION void LC_EatWhitespace(LC_Lex *x); +LC_FUNCTION void LC_EatIdent(LC_Lex *x); +LC_FUNCTION void LC_SetTokenLen(LC_Lex *x, LC_Token *t); +LC_FUNCTION void LC_EatUntilIncluding(LC_Lex *x, char c); +LC_FUNCTION LC_BigInt LC_LexBigInt(char *string, int len, uint64_t base); +LC_FUNCTION void LC_LexNestedComments(LC_Lex *x, LC_Token *t); +LC_FUNCTION void LC_LexStringLiteral(LC_Lex *x, LC_Token *t, LC_TokenKind kind); +LC_FUNCTION void LC_LexUnicodeLiteral(LC_Lex *x, LC_Token *t); +LC_FUNCTION void LC_LexIntOrFloat(LC_Lex *x, LC_Token *t); +LC_FUNCTION void LC_LexCase2(LC_Lex *x, LC_Token *t, LC_TokenKind tk0, char c, LC_TokenKind tk1); +LC_FUNCTION void LC_LexCase3(LC_Lex *x, LC_Token *t, LC_TokenKind tk, char c0, LC_TokenKind tk0, char c1, LC_TokenKind tk1); +LC_FUNCTION void LC_LexCase4(LC_Lex *x, LC_Token *t, LC_TokenKind tk, char c0, LC_TokenKind tk0, char c1, LC_TokenKind tk1, char c2, LC_TokenKind tk2); +LC_FUNCTION void LC_LexNext(LC_Lex *x, LC_Token *t); + +// +// LC_Map API +// +LC_FUNCTION void LC_MapReserve(LC_Map *map, int size); +LC_FUNCTION int LC_NextPow2(int v); +LC_FUNCTION LC_MapEntry *LC_GetMapEntryEx(LC_Map *map, uint64_t key); +LC_FUNCTION bool LC_InsertWithoutReplace(LC_Map *map, void *key, void *value); +LC_FUNCTION LC_MapEntry *LC_InsertMapEntry(LC_Map *map, uint64_t key, uint64_t value); +LC_FUNCTION LC_MapEntry *LC_GetMapEntry(LC_Map *map, uint64_t key); +LC_FUNCTION void LC_MapInsert(LC_Map *map, LC_String keystr, void *value); +LC_FUNCTION void *LC_MapGet(LC_Map *map, LC_String keystr); +LC_FUNCTION void LC_MapInsertU64(LC_Map *map, uint64_t key, void *value); +LC_FUNCTION void *LC_MapGetU64(LC_Map *map, uint64_t key); +LC_FUNCTION void *LC_MapGetP(LC_Map *map, void *key); +LC_FUNCTION void LC_MapInsertP(LC_Map *map, void *key, void *value); +LC_FUNCTION void LC_MapClear(LC_Map *map); + +// +// LC_AST Creation +// +LC_FUNCTION LC_AST *LC_CreateAST(LC_Token *pos, LC_ASTKind kind); +LC_FUNCTION LC_AST *LC_CreateUnary(LC_Token *pos, LC_TokenKind op, LC_AST *expr); +LC_FUNCTION LC_AST *LC_CreateBinary(LC_Token *pos, LC_AST *left, LC_AST *right, LC_TokenKind op); +LC_FUNCTION LC_AST *LC_CreateIndex(LC_Token *pos, LC_AST *left, LC_AST *index); + +LC_FUNCTION bool LC_ContainsCallExpr(LC_AST *ast); +LC_FUNCTION void LC_SetASTPosOnAll(LC_AST *n, LC_Token *pos); +LC_FUNCTION bool LC_ContainsCBuiltin(LC_AST *n); + +// +// LC_Type functions +// +LC_FUNCTION void LC_SetPointerSizeAndAlign(int size, int align); +LC_FUNCTION LC_Type *LC_CreateType(LC_TypeKind kind); +LC_FUNCTION LC_Type *LC_CreateTypedef(LC_Decl *decl, LC_Type *base); +LC_FUNCTION LC_Type *LC_CreatePointerType(LC_Type *type); +LC_FUNCTION LC_Type *LC_CreateArrayType(LC_Type *type, int size); +LC_FUNCTION LC_Type *LC_CreateProcType(LC_TypeMemberList args, LC_Type *ret, bool has_vargs, bool has_vargs_any_promotion); +LC_FUNCTION LC_Type *LC_CreateIncompleteType(LC_Decl *decl); +LC_FUNCTION LC_Type *LC_CreateUntypedIntEx(LC_Type *base, LC_Decl *decl); +LC_FUNCTION LC_Type *LC_CreateUntypedInt(LC_Type *base); +LC_FUNCTION LC_TypeMember *LC_AddTypeToList(LC_TypeMemberList *list, LC_Intern name, LC_Type *type, LC_AST *ast); +LC_FUNCTION int LC_GetLevelsOfIndirection(LC_Type *type); +LC_FUNCTION bool LC_BigIntFits(LC_BigInt i, LC_Type *type); +LC_FUNCTION LC_Type *LC_StripPointer(LC_Type *type); + +// +// Parsing functions +// +LC_FUNCTION LC_AST *LC_ParseFile(LC_AST *package, char *filename, char *content, int line); +LC_FUNCTION LC_AST *LC_ParseTokens(LC_AST *package, LC_Lex *x); + +LC_FUNCTION LC_Parser LC_MakeParser(LC_Lex *x); +LC_FUNCTION LC_Parser *LC_MakeParserQuick(char *str); +LC_FUNCTION LC_Token *LC_Next(void); +LC_FUNCTION LC_Token *LC_Get(void); +LC_FUNCTION LC_Token *LC_GetI(int i); +LC_FUNCTION LC_Token *LC_Is(LC_TokenKind kind); +LC_FUNCTION LC_Token *LC_IsKeyword(LC_Intern intern); +LC_FUNCTION LC_Token *LC_Match(LC_TokenKind kind); +LC_FUNCTION LC_Token *LC_MatchKeyword(LC_Intern intern); +LC_FUNCTION LC_BindingPower LC_MakeBP(int left, int right); +LC_FUNCTION LC_BindingPower LC_GetBindingPower(LC_Binding binding, LC_TokenKind kind); +LC_FUNCTION LC_AST *LC_ParseExprEx(int min_bp); +LC_FUNCTION LC_AST *LC_ParseCompo(LC_Token *pos, LC_AST *left); +LC_FUNCTION LC_AST *LC_ParseExpr(void); +LC_FUNCTION LC_AST *LC_ParseProcType(LC_Token *pos); +LC_FUNCTION LC_AST *LC_ParseType(void); +LC_FUNCTION LC_AST *LC_ParseForStmt(LC_Token *pos); +LC_FUNCTION LC_AST *LC_ParseSwitchStmt(LC_Token *pos); +LC_FUNCTION LC_AST *LC_ParseStmt(bool check_semicolon); +LC_FUNCTION LC_AST *LC_ParseStmtBlock(int flags); +LC_FUNCTION LC_AST *LC_ParseProcDecl(LC_Token *name); +LC_FUNCTION LC_AST *LC_ParseStruct(LC_ASTKind kind, LC_Token *ident); +LC_FUNCTION LC_AST *LC_ParseTypedef(LC_Token *ident); +LC_FUNCTION LC_AST *LC_CreateNote(LC_Token *pos, LC_Intern ident); +LC_FUNCTION LC_AST *LC_ParseNote(void); +LC_FUNCTION LC_AST *LC_ParseNotes(void); +LC_FUNCTION bool LC_ResolveBuildIf(LC_AST *build_if); +LC_FUNCTION LC_AST *LC_ParseImport(void); +LC_FUNCTION LC_AST *LC_ParseDecl(LC_AST *file); +LC_FUNCTION bool LC_EatUntilNextValidDecl(void); +LC_FUNCTION bool LC_ParseHashBuildOn(LC_AST *n); +LC_FUNCTION LC_AST *LC_ParseFileEx(LC_AST *package); + +// +// Resolution functions +// +LC_FUNCTION void LC_AddDecl(LC_DeclStack *scope, LC_Decl *decl); +LC_FUNCTION void LC_InitDeclStack(LC_DeclStack *stack, int size); +LC_FUNCTION LC_DeclStack *LC_CreateDeclStack(int size); +LC_FUNCTION LC_Decl *LC_FindDeclOnStack(LC_DeclStack *scp, LC_Intern name); + +LC_FUNCTION DeclScope *LC_CreateScope(int size); +LC_FUNCTION LC_Decl *LC_CreateDecl(LC_DeclKind kind, LC_Intern name, LC_AST *n); +LC_FUNCTION LC_Operand LC_AddDeclToScope(DeclScope *scp, LC_Decl *decl); +LC_FUNCTION LC_Decl *LC_FindDeclInScope(DeclScope *scope, LC_Intern name); +LC_FUNCTION LC_Operand LC_ThereIsNoDecl(DeclScope *scp, LC_Decl *decl, bool check_locals); +LC_FUNCTION void LC_MarkDeclError(LC_Decl *decl); +LC_FUNCTION LC_Decl *LC_GetLocalOrGlobalDecl(LC_Intern name); +LC_FUNCTION LC_Operand LC_PutGlobalDecl(LC_Decl *decl); +LC_FUNCTION LC_Operand LC_CreateLocalDecl(LC_DeclKind kind, LC_Intern name, LC_AST *ast); +LC_FUNCTION LC_Decl *LC_AddConstIntDecl(char *key, int64_t value); +LC_FUNCTION LC_Decl *LC_GetBuiltin(LC_Intern name); +LC_FUNCTION void LC_AddBuiltinConstInt(char *key, int64_t value); + +LC_FUNCTION void LC_RegisterDeclsFromFile(LC_AST *file); +LC_FUNCTION void LC_ResolveDeclsFromFile(LC_AST *file); +LC_FUNCTION void LC_PackageDecls(LC_AST *package); +LC_FUNCTION void LC_ResolveProcBodies(LC_AST *package); +LC_FUNCTION void LC_ResolveIncompleteTypes(LC_AST *package); +LC_FUNCTION LC_Operand LC_ResolveNote(LC_AST *n, bool is_decl); +LC_FUNCTION LC_Operand LC_ResolveProcBody(LC_Decl *decl); +LC_FUNCTION LC_ResolvedCompoItem *LC_AddResolvedCallItem(LC_ResolvedCompo *list, LC_TypeMember *t, LC_AST *comp, LC_AST *expr); +LC_FUNCTION LC_Operand LC_ResolveCompoCall(LC_AST *n, LC_Type *type); +LC_FUNCTION LC_Operand LC_ResolveCompoAggregate(LC_AST *n, LC_Type *type); +LC_FUNCTION LC_ResolvedCompoArrayItem *LC_AddResolvedCompoArrayItem(LC_ResolvedArrayCompo *arr, int index, LC_AST *comp); +LC_FUNCTION LC_Operand LC_ResolveCompoArray(LC_AST *n, LC_Type *type); +LC_FUNCTION LC_Operand LC_ResolveTypeOrExpr(LC_AST *n); +LC_FUNCTION LC_Operand LC_ExpectBuiltinWithOneArg(LC_AST *n); +LC_FUNCTION LC_Operand LC_ResolveBuiltin(LC_AST *n); +LC_FUNCTION bool LC_TryTyping(LC_AST *n, LC_Operand op); +LC_FUNCTION bool LC_TryDefaultTyping(LC_AST *n, LC_Operand *o); +LC_FUNCTION LC_Operand LC_ResolveNameInScope(LC_AST *n, LC_Decl *parent_decl); +LC_FUNCTION LC_Operand LC_ResolveExpr(LC_AST *expr); +LC_FUNCTION LC_Operand LC_ResolveExprAndPushCompoContext(LC_AST *expr, LC_Type *type); +LC_FUNCTION LC_Operand LC_ResolveExprEx(LC_AST *n); +LC_FUNCTION LC_Operand LC_ResolveStmtBlock(LC_AST *n); +LC_FUNCTION LC_Operand LC_ResolveVarDecl(LC_Decl *decl); +LC_FUNCTION LC_Operand LC_MakeSureNoDeferBlock(LC_AST *n, char *str); +LC_FUNCTION LC_Operand LC_MakeSureInsideLoopBlock(LC_AST *n, char *str); +LC_FUNCTION LC_Operand LC_MatchLabeledBlock(LC_AST *n); +LC_FUNCTION LC_Operand LC_ResolveStmt(LC_AST *n); +LC_FUNCTION LC_Operand LC_ResolveConstDecl(LC_Decl *decl); +LC_FUNCTION LC_Operand LC_ResolveName(LC_AST *pos, LC_Intern intern); +LC_FUNCTION LC_Operand LC_ResolveConstInt(LC_AST *n, LC_Type *int_type, uint64_t *out_size); +LC_FUNCTION LC_Operand LC_ResolveType(LC_AST *n); +LC_FUNCTION LC_Operand LC_ResolveBinaryExpr(LC_AST *n, LC_Operand l, LC_Operand r); +LC_FUNCTION LC_Operand LC_ResolveTypeVargs(LC_AST *pos, LC_Operand v); +LC_FUNCTION LC_Operand LC_ResolveTypeCast(LC_AST *pos, LC_Operand t, LC_Operand v); +LC_FUNCTION LC_Operand LC_ResolveTypeVarDecl(LC_AST *pos, LC_Operand t, LC_Operand v); +LC_FUNCTION LC_Operand LC_ResolveTypeAggregate(LC_AST *pos, LC_Type *type); + +LC_FUNCTION LC_Operand LC_OPError(void); +LC_FUNCTION LC_Operand LC_OPConstType(LC_Type *type); +LC_FUNCTION LC_Operand LC_OPDecl(LC_Decl *decl); +LC_FUNCTION LC_Operand LC_OPType(LC_Type *type); +LC_FUNCTION LC_Operand LC_OPLValueAndType(LC_Type *type); +LC_FUNCTION LC_Operand LC_ConstCastFloat(LC_AST *pos, LC_Operand op); +LC_FUNCTION LC_Operand LC_ConstCastInt(LC_AST *pos, LC_Operand op); +LC_FUNCTION LC_Operand LC_OPInt(int64_t v); +LC_FUNCTION LC_Operand LC_OPIntT(LC_Type *type, int64_t v); +LC_FUNCTION LC_Operand LC_OPModDefaultUT(LC_Operand val); +LC_FUNCTION LC_Operand LC_OPModType(LC_Operand op, LC_Type *type); +LC_FUNCTION LC_Operand LC_OPModBool(LC_Operand op); +LC_FUNCTION LC_Operand LC_OPModBoolV(LC_Operand op, int v); +LC_FUNCTION LC_Operand LC_EvalBinary(LC_AST *pos, LC_Operand a, LC_TokenKind op, LC_Operand b); +LC_FUNCTION LC_Operand LC_EvalUnary(LC_AST *pos, LC_TokenKind op, LC_Operand a); +LC_FUNCTION LC_OPResult LC_IsBinaryExprValidForType(LC_TokenKind op, LC_Type *type); +LC_FUNCTION LC_OPResult LC_IsUnaryOpValidForType(LC_TokenKind op, LC_Type *type); +LC_FUNCTION LC_OPResult LC_IsAssignValidForType(LC_TokenKind op, LC_Type *type); + +// +// Error +// +LC_FUNCTION void LC_IgnoreMessage(LC_Token *pos, char *str, int len); +LC_FUNCTION void LC_SendErrorMessage(LC_Token *pos, LC_String s8); +LC_FUNCTION void LC_SendErrorMessagef(LC_Lex *x, LC_Token *pos, const char *str, ...); +LC_FUNCTION LC_AST *LC_ReportParseError(LC_Token *pos, const char *str, ...); +LC_FUNCTION LC_Operand LC_ReportASTError(LC_AST *n, const char *str, ...); +LC_FUNCTION LC_Operand LC_ReportASTErrorEx(LC_AST *n1, LC_AST *n2, const char *str, ...); +LC_FUNCTION void LC_HandleFatalError(void); + +#define LC_ASSERT(n, cond) \ + if (!(cond)) { \ + LC_ReportASTError(n, "internal compiler error: assert condition failed: %s, inside of %s", #cond, __FUNCTION__); \ + LC_HandleFatalError(); \ + } + +// +// Code generation and printing helpers +// +LC_FUNCTION LC_StringList *LC_BeginStringGen(LC_Arena *arena); +LC_FUNCTION LC_String LC_EndStringGen(LC_Arena *arena); + +// clang-format off +#define LC_Genf(...) LC_Addf(L->printer.arena, &L->printer.list, __VA_ARGS__) +#define LC_GenLinef(...) do { LC_Genf("\n"); LC_GenIndent(); LC_Genf(__VA_ARGS__); } while (0) +// clang-format on + +LC_FUNCTION void LC_GenIndent(void); +LC_FUNCTION void LC_GenLine(void); +LC_FUNCTION char *LC_Strf(const char *str, ...); +LC_FUNCTION char *LC_GenLCType(LC_Type *type); +LC_FUNCTION char *LC_GenLCTypeVal(LC_TypeAndVal v); +LC_FUNCTION char *LC_GenLCAggName(LC_Type *t); +LC_FUNCTION void LC_GenLCNode(LC_AST *n); + +// C code generation +LC_FUNCTION void LC_GenCHeader(LC_AST *package); +LC_FUNCTION void LC_GenCImpl(LC_AST *package); + +LC_FUNCTION void LC_GenCLineDirective(LC_AST *node); +LC_FUNCTION void LC_GenLastCLineDirective(void); +LC_FUNCTION void LC_GenCLineDirectiveNum(int num); + +LC_FUNCTION char *LC_GenCTypeParen(char *str, char c); +LC_FUNCTION char *LC_GenCType(LC_Type *type, char *str); +LC_FUNCTION LC_Intern LC_GetStringFromSingleArgNote(LC_AST *note); +LC_FUNCTION void LC_GenCCompound(LC_AST *n); +LC_FUNCTION void LC_GenCString(char *s, LC_Type *type); +LC_FUNCTION char *LC_GenCVal(LC_TypeAndVal v, LC_Type *type); +LC_FUNCTION void LC_GenCExpr(LC_AST *n); +LC_FUNCTION void LC_GenCNote(LC_AST *note); +LC_FUNCTION void LC_GenCVarExpr(LC_AST *n, bool is_declaration); +LC_FUNCTION void LC_GenCDefers(LC_AST *block); +LC_FUNCTION void LC_GenCDefersLoopBreak(LC_AST *n); +LC_FUNCTION void LC_GenCDefersReturn(LC_AST *n); +LC_FUNCTION void LC_GenCStmt2(LC_AST *n, int flags); +LC_FUNCTION void LC_GenCStmt(LC_AST *n); +LC_FUNCTION void LC_GenCExprParen(LC_AST *expr); +LC_FUNCTION void LC_GenCStmtBlock(LC_AST *n); +LC_FUNCTION void LC_GenCProcDecl(LC_Decl *decl); +LC_FUNCTION void LC_GenCAggForwardDecl(LC_Decl *decl); +LC_FUNCTION void LC_GenCTypeDecl(LC_Decl *decl); +LC_FUNCTION void LC_GenCVarFDecl(LC_Decl *decl); + +// +// Inline helpers +// +static inline bool LC_IsUTInt(LC_Type *x) { return x->kind == LC_TypeKind_UntypedInt; } +static inline bool LC_IsUTFloat(LC_Type *x) { return x->kind == LC_TypeKind_UntypedFloat; } +static inline bool LC_IsUTStr(LC_Type *x) { return x->kind == LC_TypeKind_UntypedString; } +static inline bool LC_IsUntyped(LC_Type *x) { return (x)->kind >= LC_TypeKind_UntypedInt && x->kind <= LC_TypeKind_UntypedString; } + +static inline bool LC_IsNum(LC_Type *x) { return x->kind >= LC_TypeKind_char && x->kind <= LC_TypeKind_double; } +static inline bool LC_IsInt(LC_Type *x) { return (x->kind >= LC_TypeKind_char && x->kind <= LC_TypeKind_ullong) || LC_IsUTInt(x); } +static inline bool LC_IsIntLike(LC_Type *x) { return LC_IsInt(x) || x->kind == LC_TypeKind_Pointer || x->kind == LC_TypeKind_Proc; } +static inline bool LC_IsFloat(LC_Type *x) { return ((x)->kind == LC_TypeKind_float || (x->kind == LC_TypeKind_double)) || LC_IsUTFloat(x); } +static inline bool LC_IsSmallerThenInt(LC_Type *x) { return x->kind < LC_TypeKind_int; } + +static inline bool LC_IsAggType(LC_Type *x) { return ((x)->kind == LC_TypeKind_Struct || (x)->kind == LC_TypeKind_Union); } +static inline bool LC_IsArray(LC_Type *x) { return (x)->kind == LC_TypeKind_Array; } +static inline bool LC_IsProc(LC_Type *x) { return (x)->kind == LC_TypeKind_Proc; } +static inline bool LC_IsVoidPtr(LC_Type *x) { return (x) == L->tpvoid; } +static inline bool LC_IsPtr(LC_Type *x) { return (x)->kind == LC_TypeKind_Pointer; } +static inline bool LC_IsPtrLike(LC_Type *x) { return (x)->kind == LC_TypeKind_Pointer || x->kind == LC_TypeKind_Proc; } +static inline bool LC_IsStr(LC_Type *x) { return x == L->tpchar || x == L->tstring; } + +static inline bool LC_IsDecl(LC_AST *x) { return (x->kind >= LC_ASTKind_FirstDecl && x->kind <= LC_ASTKind_LastDecl); } +static inline bool LC_IsStmt(LC_AST *x) { return (x->kind >= LC_ASTKind_FirstStmt && x->kind <= LC_ASTKind_LastStmt); } +static inline bool LC_IsExpr(LC_AST *x) { return (x->kind >= LC_ASTKind_FirstExpr && x->kind <= LC_ASTKind_LastExpr); } +static inline bool LC_IsType(LC_AST *x) { return (x->kind >= LC_ASTKind_FirstTypespec && x->kind <= LC_ASTKind_LastTypespec); } +static inline bool LC_IsAgg(LC_AST *x) { return (x->kind == LC_ASTKind_DeclStruct || x->kind == LC_ASTKind_DeclUnion); } + +// I tried removing this because I thought it's redundant +// but this reminded me that "Untyped bool" can appear from normal expressions: (a == b) +// This is required, maybe there is a way around it, not sure +static inline bool LC_IsUTConst(LC_Operand op) { return (op.flags & LC_OPF_UTConst) != 0; } +static inline bool LC_IsConst(LC_Operand op) { return (op.flags & LC_OPF_Const) != 0; } +static inline bool LC_IsLValue(LC_Operand op) { return (op.flags & LC_OPF_LValue) != 0; } +static inline bool LC_IsError(LC_Operand op) { return (op.flags & LC_OPF_Error) != 0; } + +static inline LC_Type *LC_GetBase(LC_Type *x) { return (x)->tbase; } + +// +// Stringifying functions +// +LC_FUNCTION const char *LC_OSToString(LC_OS os); +LC_FUNCTION const char *LC_GENToString(LC_GEN os); +LC_FUNCTION const char *LC_ARCHToString(LC_ARCH arch); +LC_FUNCTION const char *LC_ASTKindToString(LC_ASTKind kind); +LC_FUNCTION const char *LC_TypeKindToString(LC_TypeKind kind); +LC_FUNCTION const char *LC_DeclKindToString(LC_DeclKind decl_kind); +LC_FUNCTION const char *LC_TokenKindToString(LC_TokenKind token_kind); +LC_FUNCTION const char *LC_TokenKindToOperator(LC_TokenKind token_kind); + +// +// bigint functions +// +LC_FUNCTION LC_BigInt LC_Bigint_u64(uint64_t val); +LC_FUNCTION uint64_t *LC_Bigint_ptr(LC_BigInt *big_int); +LC_FUNCTION size_t LC_Bigint_bits_needed(LC_BigInt *big_int); +LC_FUNCTION void LC_Bigint_init_unsigned(LC_BigInt *big_int, uint64_t value); +LC_FUNCTION void LC_Bigint_init_signed(LC_BigInt *dest, int64_t value); +LC_FUNCTION void LC_Bigint_init_bigint(LC_BigInt *dest, LC_BigInt *src); +LC_FUNCTION void LC_Bigint_negate(LC_BigInt *dest, LC_BigInt *source); +LC_FUNCTION size_t LC_Bigint_clz(LC_BigInt *big_int, size_t bit_count); +LC_FUNCTION bool LC_Bigint_eql(LC_BigInt a, LC_BigInt b); +LC_FUNCTION bool LC_Bigint_fits_in_bits(LC_BigInt *big_int, size_t bit_count, bool is_signed); +LC_FUNCTION uint64_t LC_Bigint_as_unsigned(LC_BigInt *bigint); +LC_FUNCTION void LC_Bigint_add(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_add_wrap(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed); +LC_FUNCTION void LC_Bigint_sub(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_sub_wrap(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed); +LC_FUNCTION void LC_Bigint_mul(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_mul_wrap(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed); +LC_FUNCTION void LC_Bigint_unsigned_division(LC_BigInt *op1, LC_BigInt *op2, LC_BigInt *Quotient, LC_BigInt *Remainder); +LC_FUNCTION void LC_Bigint_div_trunc(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_div_floor(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_rem(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_mod(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_or(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_and(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_xor(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_shl(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_shl_int(LC_BigInt *dest, LC_BigInt *op1, uint64_t shift); +LC_FUNCTION void LC_Bigint_shl_trunc(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed); +LC_FUNCTION void LC_Bigint_shr(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_not(LC_BigInt *dest, LC_BigInt *op, size_t bit_count, bool is_signed); +LC_FUNCTION void LC_Bigint_truncate(LC_BigInt *dst, LC_BigInt *op, size_t bit_count, bool is_signed); +LC_FUNCTION LC_CmpRes LC_Bigint_cmp(LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION char *LC_Bigint_str(LC_BigInt *bigint, uint64_t base); +LC_FUNCTION int64_t LC_Bigint_as_signed(LC_BigInt *bigint); +LC_FUNCTION LC_CmpRes LC_Bigint_cmp_zero(LC_BigInt *op); +LC_FUNCTION double LC_Bigint_as_float(LC_BigInt *bigint); + +// +// Unicode API +// +struct LC_UTF32Result { + uint32_t out_str; + int advance; + int error; +}; + +struct LC_UTF8Result { + uint8_t out_str[4]; + int len; + int error; +}; + +struct LC_UTF16Result { + uint16_t out_str[2]; + int len; + int error; +}; + +LC_FUNCTION LC_UTF32Result LC_ConvertUTF16ToUTF32(uint16_t *c, int max_advance); +LC_FUNCTION LC_UTF8Result LC_ConvertUTF32ToUTF8(uint32_t codepoint); +LC_FUNCTION LC_UTF32Result LC_ConvertUTF8ToUTF32(char *c, int max_advance); +LC_FUNCTION LC_UTF16Result LC_ConvertUTF32ToUTF16(uint32_t codepoint); +LC_FUNCTION int64_t LC_CreateCharFromWidechar(char *buffer, int64_t buffer_size, wchar_t *in, int64_t inlen); +LC_FUNCTION int64_t LC_CreateWidecharFromChar(wchar_t *buffer, int64_t buffer_size, char *in, int64_t inlen); + +// +// Filesystem API +// +LC_FUNCTION bool LC_IsDir(LC_Arena *temp, LC_String path); +LC_FUNCTION LC_String LC_GetAbsolutePath(LC_Arena *arena, LC_String relative); +LC_FUNCTION bool LC_EnableTerminalColors(void); +LC_FUNCTION LC_String LC_ReadFile(LC_Arena *arena, LC_String path); + +LC_FUNCTION bool LC_IsValid(LC_FileIter it); +LC_FUNCTION void LC_Advance(LC_FileIter *it); +LC_FUNCTION LC_FileIter LC_IterateFiles(LC_Arena *scratch_arena, LC_String path); + +// +// Arena API +// +#define LC_PushSize(a, size) LC__PushSize(a, size) +#define LC_PushSizeNonZeroed(a, size) LC__PushSizeNonZeroed(a, size) + +#define LC_PushArrayNonZeroed(a, T, c) (T *)LC__PushSizeNonZeroed(a, sizeof(T) * (c)) +#define LC_PushStructNonZeroed(a, T) (T *)LC__PushSizeNonZeroed(a, sizeof(T)) +#define LC_PushStruct(a, T) (T *)LC__PushSize(a, sizeof(T)) +#define LC_PushArray(a, T, c) (T *)LC__PushSize(a, sizeof(T) * (c)) + +#define LC_Assertf(cond, ...) LC_ASSERT(NULL, cond) + +#ifndef LC_USE_CUSTOM_ARENA +LC_FUNCTION void LC_InitArenaEx(LC_Arena *a, size_t reserve); +LC_FUNCTION void LC_InitArena(LC_Arena *a); +LC_FUNCTION void LC_InitArenaFromBuffer(LC_Arena *arena, void *buffer, size_t size); +LC_FUNCTION LC_Arena *LC_BootstrapArena(void); +LC_FUNCTION LC_Arena LC_PushArena(LC_Arena *arena, size_t size); +LC_FUNCTION LC_Arena *LC_PushArenaP(LC_Arena *arena, size_t size); + +LC_FUNCTION void *LC__PushSizeNonZeroed(LC_Arena *a, size_t size); +LC_FUNCTION void *LC__PushSize(LC_Arena *arena, size_t size); +LC_FUNCTION LC_TempArena LC_BeginTemp(LC_Arena *arena); +LC_FUNCTION void LC_EndTemp(LC_TempArena checkpoint); + +LC_FUNCTION void LC_PopToPos(LC_Arena *arena, size_t pos); +LC_FUNCTION void LC_PopSize(LC_Arena *arena, size_t size); +LC_FUNCTION void LC_DeallocateArena(LC_Arena *arena); +LC_FUNCTION void LC_ResetArena(LC_Arena *arena); + +LC_FUNCTION LC_VMemory LC_VReserve(size_t size); +LC_FUNCTION bool LC_VCommit(LC_VMemory *m, size_t commit); +LC_FUNCTION void LC_VDeallocate(LC_VMemory *m); +LC_FUNCTION bool LC_VDecommitPos(LC_VMemory *m, size_t pos); +#endif // LC_USE_CUSTOM_ARENA + +LC_FUNCTION size_t LC_GetAlignOffset(size_t size, size_t align); +LC_FUNCTION size_t LC_AlignUp(size_t size, size_t align); +LC_FUNCTION size_t LC_AlignDown(size_t size, size_t align); + +#define LC_IS_POW2(x) (((x) & ((x)-1)) == 0) +#define LC_MIN(x, y) ((x) <= (y) ? (x) : (y)) +#define LC_MAX(x, y) ((x) >= (y) ? (x) : (y)) +#define LC_StrLenof(x) ((int64_t)((sizeof(x) / sizeof((x)[0])))) + +#define LC_CLAMP_TOP(x, max) ((x) >= (max) ? (max) : (x)) +#define LC_CLAMP_BOT(x, min) ((x) <= (min) ? (min) : (x)) +#define LC_CLAMP(x, min, max) ((x) >= (max) ? (max) : (x) <= (min) ? (min) \ + : (x)) +#define LC_KIB(x) ((x##ull) * 1024ull) +#define LC_MIB(x) (LC_KIB(x) * 1024ull) +#define LC_GIB(x) (LC_MIB(x) * 1024ull) +#define LC_TIB(x) (LC_GIB(x) * 1024ull) + +// +// String API +// + +typedef int LC_FindFlag; +enum { + LC_FindFlag_None = 0, + LC_FindFlag_IgnoreCase = 1, + LC_FindFlag_MatchFindLast = 2, +}; + +typedef int LC_SplitFlag; +enum { + LC_SplitFlag_None = 0, + LC_SplitFlag_IgnoreCase = 1, + LC_SplitFlag_SplitInclusive = 2, +}; + +static const bool LC_IgnoreCase = true; + +#if defined(__has_attribute) + #if __has_attribute(format) + #define LC__PrintfFormat(fmt, va) __attribute__((format(printf, fmt, va))) + #endif +#endif + +#ifndef LC__PrintfFormat + #define LC__PrintfFormat(fmt, va) +#endif + +#define LC_Lit(string) LC_MakeString((char *)string, sizeof(string) - 1) +#define LC_Expand(string) (int)(string).len, (string).str + +#define LC_FORMAT(allocator, str, result) \ + va_list args1; \ + va_start(args1, str); \ + LC_String result = LC_FormatV(allocator, str, args1); \ + va_end(args1) + +#ifdef __cplusplus + #define LC_IF_CPP(x) x +#else + #define LC_IF_CPP(x) +#endif + +LC_FUNCTION char LC_ToLowerCase(char a); +LC_FUNCTION char LC_ToUpperCase(char a); +LC_FUNCTION bool LC_IsWhitespace(char w); +LC_FUNCTION bool LC_IsAlphabetic(char a); +LC_FUNCTION bool LC_IsIdent(char a); +LC_FUNCTION bool LC_IsDigit(char a); +LC_FUNCTION bool LC_IsAlphanumeric(char a); + +LC_FUNCTION int64_t LC_StrLen(char *string); +LC_FUNCTION bool LC_AreEqual(LC_String a, LC_String b, unsigned ignore_case LC_IF_CPP(= false)); +LC_FUNCTION bool LC_EndsWith(LC_String a, LC_String end, unsigned ignore_case LC_IF_CPP(= false)); +LC_FUNCTION bool LC_StartsWith(LC_String a, LC_String start, unsigned ignore_case LC_IF_CPP(= false)); +LC_FUNCTION LC_String LC_MakeString(char *str, int64_t len); +LC_FUNCTION LC_String LC_CopyString(LC_Arena *allocator, LC_String string); +LC_FUNCTION LC_String LC_CopyChar(LC_Arena *allocator, char *s); +LC_FUNCTION LC_String LC_NormalizePath(LC_Arena *allocator, LC_String s); +LC_FUNCTION void LC_NormalizePathUnsafe(LC_String s); // make sure there is no way string is const etc. +LC_FUNCTION LC_String LC_Chop(LC_String string, int64_t len); +LC_FUNCTION LC_String LC_Skip(LC_String string, int64_t len); +LC_FUNCTION LC_String LC_GetPostfix(LC_String string, int64_t len); +LC_FUNCTION LC_String LC_GetPrefix(LC_String string, int64_t len); +LC_FUNCTION bool LC_Seek(LC_String string, LC_String find, LC_FindFlag flags LC_IF_CPP(= LC_FindFlag_None), int64_t *index_out LC_IF_CPP(= 0)); +LC_FUNCTION int64_t LC_Find(LC_String string, LC_String find, LC_FindFlag flags LC_IF_CPP(= LC_FindFlag_None)); +LC_FUNCTION LC_String LC_ChopLastSlash(LC_String s); +LC_FUNCTION LC_String LC_ChopLastPeriod(LC_String s); +LC_FUNCTION LC_String LC_SkipToLastSlash(LC_String s); +LC_FUNCTION LC_String LC_SkipToLastPeriod(LC_String s); +LC_FUNCTION LC_String LC_GetNameNoExt(LC_String s); +LC_FUNCTION LC_String LC_MakeFromChar(char *string); +LC_FUNCTION LC_String LC_MakeEmptyString(void); +LC_FUNCTION LC_StringList LC_MakeEmptyList(void); +LC_FUNCTION LC_String LC_FormatV(LC_Arena *allocator, const char *str, va_list args1); +LC_FUNCTION LC_String LC_Format(LC_Arena *allocator, const char *str, ...) LC__PrintfFormat(2, 3); + +LC_FUNCTION LC_StringList LC_Split(LC_Arena *allocator, LC_String string, LC_String find, LC_SplitFlag flags LC_IF_CPP(= LC_SplitFlag_None)); +LC_FUNCTION LC_String LC_MergeWithSeparator(LC_Arena *allocator, LC_StringList list, LC_String separator LC_IF_CPP(= LC_Lit(" "))); +LC_FUNCTION LC_String LC_MergeString(LC_Arena *allocator, LC_StringList list); + +LC_FUNCTION LC_StringNode *LC_CreateNode(LC_Arena *allocator, LC_String string); +LC_FUNCTION void LC_ReplaceNodeString(LC_StringList *list, LC_StringNode *node, LC_String new_string); +LC_FUNCTION void LC_AddExistingNode(LC_StringList *list, LC_StringNode *node); +LC_FUNCTION void LC_AddArray(LC_Arena *allocator, LC_StringList *list, char **array, int count); +LC_FUNCTION void LC_AddArrayWithPrefix(LC_Arena *allocator, LC_StringList *list, char *prefix, char **array, int count); +LC_FUNCTION LC_StringList LC_MakeList(LC_Arena *allocator, LC_String a); +LC_FUNCTION LC_StringList LC_CopyList(LC_Arena *allocator, LC_StringList a); +LC_FUNCTION LC_StringList LC_ConcatLists(LC_Arena *allocator, LC_StringList a, LC_StringList b); +LC_FUNCTION LC_StringNode *LC_AddNode(LC_Arena *allocator, LC_StringList *list, LC_String string); +LC_FUNCTION LC_StringNode *LC_Add(LC_Arena *allocator, LC_StringList *list, LC_String string); +LC_FUNCTION LC_String LC_Addf(LC_Arena *allocator, LC_StringList *list, const char *str, ...) LC__PrintfFormat(3, 4); + +LC_FUNCTION wchar_t *LC_ToWidechar(LC_Arena *allocator, LC_String string); + +// +// Linked list API +// +#define LC_SLLAddMod(f, l, n, next) \ + do { \ + (n)->next = 0; \ + if ((f) == 0) { \ + (f) = (l) = (n); \ + } else { \ + (l) = (l)->next = (n); \ + } \ + } while (0) +#define LC_AddSLL(f, l, n) LC_SLLAddMod(f, l, n, next) + +#define LC_SLLPopFirstMod(f, l, next) \ + do { \ + if ((f) == (l)) { \ + (f) = (l) = 0; \ + } else { \ + (f) = (f)->next; \ + } \ + } while (0) +#define LC_SLLPopFirst(f, l) LC_SLLPopFirstMod(f, l, next) + +#define LC_SLLStackAddMod(stack_base, new_stack_base, next) \ + do { \ + (new_stack_base)->next = (stack_base); \ + (stack_base) = (new_stack_base); \ + } while (0) + +#define LC_DLLAddMod(f, l, node, next, prev) \ + do { \ + if ((f) == 0) { \ + (f) = (l) = (node); \ + (node)->prev = 0; \ + (node)->next = 0; \ + } else { \ + (l)->next = (node); \ + (node)->prev = (l); \ + (node)->next = 0; \ + (l) = (node); \ + } \ + } while (0) +#define LC_DLLAdd(f, l, node) LC_DLLAddMod(f, l, node, next, prev) +#define LC_DLLAddFront(f, l, node) LC_DLLAddMod(l, f, node, prev, next) +#define LC_DLLRemoveMod(first, last, node, next, prev) \ + do { \ + if ((first) == (last)) { \ + (first) = (last) = 0; \ + } else if ((last) == (node)) { \ + (last) = (last)->prev; \ + (last)->next = 0; \ + } else if ((first) == (node)) { \ + (first) = (first)->next; \ + (first)->prev = 0; \ + } else { \ + (node)->prev->next = (node)->next; \ + (node)->next->prev = (node)->prev; \ + } \ + if (node) { \ + (node)->prev = 0; \ + (node)->next = 0; \ + } \ + } while (0) +#define LC_DLLRemove(first, last, node) LC_DLLRemoveMod(first, last, node, next, prev) + +#define LC_ASTFor(it, x) for (LC_AST *it = x; it; it = it->next) +#define LC_DeclFor(it, x) for (LC_Decl *it = x; it; it = it->next) +#define LC_TypeFor(it, x) for (LC_TypeMember *it = x; it; it = it->next) + +#if defined(__APPLE__) && defined(__MACH__) + #define LC_OPERATING_SYSTEM_MAC 1 + #define LC_OPERATING_SYSTEM_UNIX 1 +#elif defined(_WIN32) + #define LC_OPERATING_SYSTEM_WINDOWS 1 +#elif defined(__linux__) + #define LC_OPERATING_SYSTEM_UNIX 1 + #define LC_OPERATING_SYSTEM_LINUX 1 +#endif + +#ifndef LC_OPERATING_SYSTEM_MAC + #define LC_OPERATING_SYSTEM_MAC 0 +#endif + +#ifndef LC_OPERATING_SYSTEM_UNIX + #define LC_OPERATING_SYSTEM_UNIX 0 +#endif + +#ifndef LC_OPERATING_SYSTEM_WINDOWS + #define LC_OPERATING_SYSTEM_WINDOWS 0 +#endif + +#ifndef LC_OPERATING_SYSTEM_LINUX + #define LC_OPERATING_SYSTEM_LINUX 0 +#endif + +#endif +#ifdef LIB_COMPILER_IMPLEMENTATION + + +#if __clang__ + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wswitch" + #pragma clang diagnostic ignored "-Wwritable-strings" +#endif + +#ifndef LC_ParseFloat // @override + #include + #define LC_ParseFloat(str, len) strtod(str, NULL) +#endif + +#ifndef LC_Print // @override + #include + #define LC_Print(str, len) printf("%.*s", (int)len, str) +#endif + +#ifndef LC_Exit // @override + #include + #define LC_Exit(x) exit(x) +#endif + +#ifndef LC_MemoryZero // @override + #include + #define LC_MemoryZero(p, size) memset(p, 0, size) +#endif + +#ifndef LC_MemoryCopy // @override + #include + #define LC_MemoryCopy(dst, src, size) memcpy(dst, src, size); +#endif + +#ifndef LC_vsnprintf // @override + #include + #define LC_vsnprintf vsnprintf +#endif + +#ifdef _WIN32 + #ifndef NOMINMAX + #define NOMINMAX + #endif + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include +#endif + +LC_THREAD_LOCAL LC_Lang *L; + +LC_FUNCTION LC_UTF32Result LC_ConvertUTF16ToUTF32(uint16_t *c, int max_advance) { + LC_UTF32Result result; + LC_MemoryZero(&result, sizeof(result)); + if (max_advance >= 1) { + result.advance = 1; + result.out_str = c[0]; + if (c[0] >= 0xD800 && c[0] <= 0xDBFF && c[1] >= 0xDC00 && c[1] <= 0xDFFF) { + if (max_advance >= 2) { + result.out_str = 0x10000; + result.out_str += (uint32_t)(c[0] & 0x03FF) << 10u | (c[1] & 0x03FF); + result.advance = 2; + } else + result.error = 2; + } + } else { + result.error = 1; + } + return result; +} + +LC_FUNCTION LC_UTF8Result LC_ConvertUTF32ToUTF8(uint32_t codepoint) { + LC_UTF8Result result; + LC_MemoryZero(&result, sizeof(result)); + + if (codepoint <= 0x7F) { + result.len = 1; + result.out_str[0] = (char)codepoint; + } else if (codepoint <= 0x7FF) { + result.len = 2; + result.out_str[0] = 0xc0 | (0x1f & (codepoint >> 6)); + result.out_str[1] = 0x80 | (0x3f & codepoint); + } else if (codepoint <= 0xFFFF) { // 16 bit word + result.len = 3; + result.out_str[0] = 0xe0 | (0xf & (codepoint >> 12)); // 4 bits + result.out_str[1] = 0x80 | (0x3f & (codepoint >> 6)); // 6 bits + result.out_str[2] = 0x80 | (0x3f & codepoint); // 6 bits + } else if (codepoint <= 0x10FFFF) { // 21 bit word + result.len = 4; + result.out_str[0] = 0xf0 | (0x7 & (codepoint >> 18)); // 3 bits + result.out_str[1] = 0x80 | (0x3f & (codepoint >> 12)); // 6 bits + result.out_str[2] = 0x80 | (0x3f & (codepoint >> 6)); // 6 bits + result.out_str[3] = 0x80 | (0x3f & codepoint); // 6 bits + } else { + result.error = 1; + } + + return result; +} + +LC_FUNCTION LC_UTF32Result LC_ConvertUTF8ToUTF32(char *c, int max_advance) { + LC_UTF32Result result; + LC_MemoryZero(&result, sizeof(result)); + + if ((c[0] & 0x80) == 0) { // Check if leftmost zero of first byte is unset + if (max_advance >= 1) { + result.out_str = c[0]; + result.advance = 1; + } else result.error = 1; + } + + else if ((c[0] & 0xe0) == 0xc0) { + if ((c[1] & 0xc0) == 0x80) { // Continuation byte required + if (max_advance >= 2) { + result.out_str = (uint32_t)(c[0] & 0x1f) << 6u | (c[1] & 0x3f); + result.advance = 2; + } else result.error = 2; + } else result.error = 2; + } + + else if ((c[0] & 0xf0) == 0xe0) { + if ((c[1] & 0xc0) == 0x80 && (c[2] & 0xc0) == 0x80) { // Two continuation bytes required + if (max_advance >= 3) { + result.out_str = (uint32_t)(c[0] & 0xf) << 12u | (uint32_t)(c[1] & 0x3f) << 6u | (c[2] & 0x3f); + result.advance = 3; + } else result.error = 3; + } else result.error = 3; + } + + else if ((c[0] & 0xf8) == 0xf0) { + if ((c[1] & 0xc0) == 0x80 && (c[2] & 0xc0) == 0x80 && (c[3] & 0xc0) == 0x80) { // Three continuation bytes required + if (max_advance >= 4) { + result.out_str = (uint32_t)(c[0] & 0xf) << 18u | (uint32_t)(c[1] & 0x3f) << 12u | (uint32_t)(c[2] & 0x3f) << 6u | (uint32_t)(c[3] & 0x3f); + result.advance = 4; + } else result.error = 4; + } else result.error = 4; + } else result.error = 4; + + return result; +} + +LC_FUNCTION LC_UTF16Result LC_ConvertUTF32ToUTF16(uint32_t codepoint) { + LC_UTF16Result result; + LC_MemoryZero(&result, sizeof(result)); + if (codepoint < 0x10000) { + result.out_str[0] = (uint16_t)codepoint; + result.out_str[1] = 0; + result.len = 1; + } else if (codepoint <= 0x10FFFF) { + uint32_t code = (codepoint - 0x10000); + result.out_str[0] = (uint16_t)(0xD800 | (code >> 10)); + result.out_str[1] = (uint16_t)(0xDC00 | (code & 0x3FF)); + result.len = 2; + } else { + result.error = 1; + } + + return result; +} + +#define LC__HANDLE_DECODE_ERROR(question_mark) \ + { \ + if (outlen < buffer_size - 1) buffer[outlen++] = (question_mark); \ + break; \ + } + +LC_FUNCTION int64_t LC_CreateCharFromWidechar(char *buffer, int64_t buffer_size, wchar_t *in, int64_t inlen) { + int64_t outlen = 0; + for (int64_t i = 0; i < inlen && in[i];) { + LC_UTF32Result decode = LC_ConvertUTF16ToUTF32((uint16_t *)(in + i), (int)(inlen - i)); + if (!decode.error) { + i += decode.advance; + LC_UTF8Result encode = LC_ConvertUTF32ToUTF8(decode.out_str); + if (!encode.error) { + for (int64_t j = 0; j < encode.len; j++) { + if (outlen < buffer_size - 1) { + buffer[outlen++] = encode.out_str[j]; + } + } + } else LC__HANDLE_DECODE_ERROR('?'); + } else LC__HANDLE_DECODE_ERROR('?'); + } + + buffer[outlen] = 0; + return outlen; +} + +LC_FUNCTION int64_t LC_CreateWidecharFromChar(wchar_t *buffer, int64_t buffer_size, char *in, int64_t inlen) { + int64_t outlen = 0; + for (int64_t i = 0; i < inlen;) { + LC_UTF32Result decode = LC_ConvertUTF8ToUTF32(in + i, (int)(inlen - i)); + if (!decode.error) { + i += decode.advance; + LC_UTF16Result encode = LC_ConvertUTF32ToUTF16(decode.out_str); + if (!encode.error) { + for (int64_t j = 0; j < encode.len; j++) { + if (outlen < buffer_size - 1) { + buffer[outlen++] = encode.out_str[j]; + } + } + } else LC__HANDLE_DECODE_ERROR(0x003f); + } else LC__HANDLE_DECODE_ERROR(0x003f); + } + + buffer[outlen] = 0; + return outlen; +} + +#undef LC__HANDLE_DECODE_ERROR +LC_FUNCTION int64_t LC__ClampTop(int64_t val, int64_t max) { + if (val > max) val = max; + return val; +} + +LC_FUNCTION char LC_ToLowerCase(char a) { + if (a >= 'A' && a <= 'Z') a += 32; + return a; +} + +LC_FUNCTION char LC_ToUpperCase(char a) { + if (a >= 'a' && a <= 'z') a -= 32; + return a; +} + +LC_FUNCTION bool LC_IsWhitespace(char w) { + bool result = w == '\n' || w == ' ' || w == '\t' || w == '\v' || w == '\r'; + return result; +} + +LC_FUNCTION bool LC_IsAlphabetic(char a) { + bool result = (a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z'); + return result; +} + +LC_FUNCTION bool LC_IsIdent(char a) { + bool result = (a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z') || a == '_'; + return result; +} + +LC_FUNCTION bool LC_IsDigit(char a) { + bool result = a >= '0' && a <= '9'; + return result; +} + +LC_FUNCTION bool LC_IsAlphanumeric(char a) { + bool result = LC_IsDigit(a) || LC_IsAlphabetic(a); + return result; +} + +LC_FUNCTION bool LC_AreEqual(LC_String a, LC_String b, unsigned ignore_case) { + if (a.len != b.len) return false; + for (int64_t i = 0; i < a.len; i++) { + char A = a.str[i]; + char B = b.str[i]; + if (ignore_case) { + A = LC_ToLowerCase(A); + B = LC_ToLowerCase(B); + } + if (A != B) + return false; + } + return true; +} + +LC_FUNCTION bool LC_EndsWith(LC_String a, LC_String end, unsigned ignore_case) { + LC_String a_end = LC_GetPostfix(a, end.len); + bool result = LC_AreEqual(end, a_end, ignore_case); + return result; +} + +LC_FUNCTION bool LC_StartsWith(LC_String a, LC_String start, unsigned ignore_case) { + LC_String a_start = LC_GetPrefix(a, start.len); + bool result = LC_AreEqual(start, a_start, ignore_case); + return result; +} + +LC_FUNCTION LC_String LC_MakeString(char *str, int64_t len) { + LC_String result; + result.str = (char *)str; + result.len = len; + return result; +} + +LC_FUNCTION LC_String LC_CopyString(LC_Arena *allocator, LC_String string) { + char *copy = (char *)LC_PushSize(allocator, sizeof(char) * (string.len + 1)); + LC_MemoryCopy(copy, string.str, string.len); + copy[string.len] = 0; + LC_String result = LC_MakeString(copy, string.len); + return result; +} + +LC_FUNCTION LC_String LC_CopyChar(LC_Arena *allocator, char *s) { + int64_t len = LC_StrLen(s); + char *copy = (char *)LC_PushSize(allocator, sizeof(char) * (len + 1)); + LC_MemoryCopy(copy, s, len); + copy[len] = 0; + LC_String result = LC_MakeString(copy, len); + return result; +} + +LC_FUNCTION LC_String LC_NormalizePath(LC_Arena *allocator, LC_String s) { + LC_String copy = LC_CopyString(allocator, s); + for (int64_t i = 0; i < copy.len; i++) { + if (copy.str[i] == '\\') + copy.str[i] = '/'; + } + return copy; +} + +LC_FUNCTION void LC_NormalizePathUnsafe(LC_String s) { + for (int64_t i = 0; i < s.len; i++) { + if (s.str[i] == '\\') + s.str[i] = '/'; + } +} + +LC_FUNCTION LC_String LC_Chop(LC_String string, int64_t len) { + len = LC__ClampTop(len, string.len); + LC_String result = LC_MakeString(string.str, string.len - len); + return result; +} + +LC_FUNCTION LC_String LC_Skip(LC_String string, int64_t len) { + len = LC__ClampTop(len, string.len); + int64_t remain = string.len - len; + LC_String result = LC_MakeString(string.str + len, remain); + return result; +} + +LC_FUNCTION LC_String LC_GetPostfix(LC_String string, int64_t len) { + len = LC__ClampTop(len, string.len); + int64_t remain_len = string.len - len; + LC_String result = LC_MakeString(string.str + remain_len, len); + return result; +} + +LC_FUNCTION LC_String LC_GetPrefix(LC_String string, int64_t len) { + len = LC__ClampTop(len, string.len); + LC_String result = LC_MakeString(string.str, len); + return result; +} + +LC_FUNCTION LC_String LC_GetNameNoExt(LC_String s) { + return LC_SkipToLastSlash(LC_ChopLastPeriod(s)); +} + +LC_FUNCTION LC_String LC_Slice(LC_String string, int64_t first_index, int64_t one_past_last_index) { + if (one_past_last_index < 0) one_past_last_index = string.len + one_past_last_index + 1; + if (first_index < 0) first_index = string.len + first_index; + LC_ASSERT(NULL, first_index < one_past_last_index && "LC_Slice, first_index is bigger then one_past_last_index"); + LC_ASSERT(NULL, string.len > 0 && "Slicing string of length 0! Might be an error!"); + LC_String result = string; + if (string.len > 0) { + if (one_past_last_index > first_index) { + first_index = LC__ClampTop(first_index, string.len - 1); + one_past_last_index = LC__ClampTop(one_past_last_index, string.len); + result.str += first_index; + result.len = one_past_last_index - first_index; + } else { + result.len = 0; + } + } + return result; +} + +LC_FUNCTION bool LC_Seek(LC_String string, LC_String find, LC_FindFlag flags, int64_t *index_out) { + bool ignore_case = flags & LC_FindFlag_IgnoreCase ? true : false; + bool result = false; + if (flags & LC_FindFlag_MatchFindLast) { + for (int64_t i = string.len; i != 0; i--) { + int64_t index = i - 1; + LC_String substring = LC_Slice(string, index, index + find.len); + if (LC_AreEqual(substring, find, ignore_case)) { + if (index_out) + *index_out = index; + result = true; + break; + } + } + } else { + for (int64_t i = 0; i < string.len; i++) { + LC_String substring = LC_Slice(string, i, i + find.len); + if (LC_AreEqual(substring, find, ignore_case)) { + if (index_out) + *index_out = i; + result = true; + break; + } + } + } + + return result; +} + +LC_FUNCTION int64_t LC_Find(LC_String string, LC_String find, LC_FindFlag flag) { + int64_t result = -1; + LC_Seek(string, find, flag, &result); + return result; +} + +LC_FUNCTION LC_StringList LC_Split(LC_Arena *allocator, LC_String string, LC_String find, LC_SplitFlag flags) { + LC_StringList result = LC_MakeEmptyList(); + int64_t index = 0; + + LC_FindFlag find_flag = flags & LC_SplitFlag_IgnoreCase ? LC_FindFlag_IgnoreCase : LC_FindFlag_None; + while (LC_Seek(string, find, find_flag, &index)) { + LC_String before_match = LC_MakeString(string.str, index); + LC_AddNode(allocator, &result, before_match); + if (flags & LC_SplitFlag_SplitInclusive) { + LC_String match = LC_MakeString(string.str + index, find.len); + LC_AddNode(allocator, &result, match); + } + string = LC_Skip(string, index + find.len); + } + if (string.len) LC_AddNode(allocator, &result, string); + return result; +} + +LC_FUNCTION LC_String LC_MergeWithSeparator(LC_Arena *allocator, LC_StringList list, LC_String separator) { + if (list.node_count == 0) return LC_MakeEmptyString(); + if (list.char_count == 0) return LC_MakeEmptyString(); + + int64_t base_size = (list.char_count + 1); + int64_t sep_size = (list.node_count - 1) * separator.len; + int64_t size = base_size + sep_size; + char *buff = (char *)LC_PushSize(allocator, sizeof(char) * (size + 1)); + LC_String string = LC_MakeString(buff, 0); + for (LC_StringNode *it = list.first; it; it = it->next) { + LC_ASSERT(NULL, string.len + it->string.len <= size); + LC_MemoryCopy(string.str + string.len, it->string.str, it->string.len); + string.len += it->string.len; + if (it != list.last) { + LC_MemoryCopy(string.str + string.len, separator.str, separator.len); + string.len += separator.len; + } + } + LC_ASSERT(NULL, string.len == size - 1); + string.str[size] = 0; + return string; +} + +LC_FUNCTION LC_String LC_MergeString(LC_Arena *allocator, LC_StringList list) { + return LC_MergeWithSeparator(allocator, list, LC_Lit("")); +} + +LC_FUNCTION LC_String LC_ChopLastSlash(LC_String s) { + LC_String result = s; + LC_Seek(s, LC_Lit("/"), LC_FindFlag_MatchFindLast, &result.len); + return result; +} + +LC_FUNCTION LC_String LC_ChopLastPeriod(LC_String s) { + LC_String result = s; + LC_Seek(s, LC_Lit("."), LC_FindFlag_MatchFindLast, &result.len); + return result; +} + +LC_FUNCTION LC_String LC_SkipToLastSlash(LC_String s) { + int64_t pos; + LC_String result = s; + if (LC_Seek(s, LC_Lit("/"), LC_FindFlag_MatchFindLast, &pos)) { + result = LC_Skip(result, pos + 1); + } + return result; +} + +LC_FUNCTION LC_String LC_SkipToLastPeriod(LC_String s) { + int64_t pos; + LC_String result = s; + if (LC_Seek(s, LC_Lit("."), LC_FindFlag_MatchFindLast, &pos)) { + result = LC_Skip(result, pos + 1); + } + return result; +} + +LC_FUNCTION int64_t LC_StrLen(char *string) { + int64_t len = 0; + while (*string++ != 0) + len++; + return len; +} + +LC_FUNCTION LC_String LC_MakeFromChar(char *string) { + LC_String result; + result.str = (char *)string; + result.len = LC_StrLen(string); + return result; +} + +LC_FUNCTION LC_String LC_MakeEmptyString(void) { + return LC_MakeString(0, 0); +} + +LC_FUNCTION LC_StringList LC_MakeEmptyList(void) { + LC_StringList result; + result.first = 0; + result.last = 0; + result.char_count = 0; + result.node_count = 0; + return result; +} + +LC_FUNCTION LC_String LC_FormatV(LC_Arena *allocator, const char *str, va_list args1) { + va_list args2; + va_copy(args2, args1); + int64_t len = LC_vsnprintf(0, 0, str, args2); + va_end(args2); + + char *result = (char *)LC_PushSize(allocator, sizeof(char) * (len + 1)); + LC_vsnprintf(result, (int)(len + 1), str, args1); + LC_String res = LC_MakeString(result, len); + return res; +} + +LC_FUNCTION LC_String LC_Format(LC_Arena *allocator, const char *str, ...) { + LC_FORMAT(allocator, str, result); + return result; +} + +LC_FUNCTION LC_StringNode *LC_CreateNode(LC_Arena *allocator, LC_String string) { + LC_StringNode *result = (LC_StringNode *)LC_PushSize(allocator, sizeof(LC_StringNode)); + result->string = string; + result->next = 0; + return result; +} + +LC_FUNCTION void LC_ReplaceNodeString(LC_StringList *list, LC_StringNode *node, LC_String new_string) { + list->char_count -= node->string.len; + list->char_count += new_string.len; + node->string = new_string; +} + +LC_FUNCTION void LC_AddExistingNode(LC_StringList *list, LC_StringNode *node) { + if (list->first) { + list->last->next = node; + list->last = list->last->next; + } else { + list->first = list->last = node; + } + list->node_count += 1; + list->char_count += node->string.len; +} + +LC_FUNCTION void LC_AddArray(LC_Arena *allocator, LC_StringList *list, char **array, int count) { + for (int i = 0; i < count; i += 1) { + LC_String s = LC_MakeFromChar(array[i]); + LC_AddNode(allocator, list, s); + } +} + +LC_FUNCTION void LC_AddArrayWithPrefix(LC_Arena *allocator, LC_StringList *list, char *prefix, char **array, int count) { + for (int i = 0; i < count; i += 1) { + LC_Addf(allocator, list, "%s%s", prefix, array[i]); + } +} + +LC_FUNCTION LC_StringList LC_MakeList(LC_Arena *allocator, LC_String a) { + LC_StringList result = LC_MakeEmptyList(); + LC_AddNode(allocator, &result, a); + return result; +} + +LC_FUNCTION LC_StringList LC_CopyList(LC_Arena *allocator, LC_StringList a) { + LC_StringList result = LC_MakeEmptyList(); + for (LC_StringNode *it = a.first; it; it = it->next) LC_AddNode(allocator, &result, it->string); + return result; +} + +LC_FUNCTION LC_StringList LC_ConcatLists(LC_Arena *allocator, LC_StringList a, LC_StringList b) { + LC_StringList result = LC_MakeEmptyList(); + for (LC_StringNode *it = a.first; it; it = it->next) LC_AddNode(allocator, &result, it->string); + for (LC_StringNode *it = b.first; it; it = it->next) LC_AddNode(allocator, &result, it->string); + return result; +} + +LC_FUNCTION LC_StringNode *LC_AddNode(LC_Arena *allocator, LC_StringList *list, LC_String string) { + LC_StringNode *node = LC_CreateNode(allocator, string); + LC_AddExistingNode(list, node); + return node; +} + +LC_FUNCTION LC_StringNode *LC_Add(LC_Arena *allocator, LC_StringList *list, LC_String string) { + LC_String copy = LC_CopyString(allocator, string); + LC_StringNode *node = LC_CreateNode(allocator, copy); + LC_AddExistingNode(list, node); + return node; +} + +LC_FUNCTION LC_String LC_Addf(LC_Arena *allocator, LC_StringList *list, const char *str, ...) { + LC_FORMAT(allocator, str, result); + LC_AddNode(allocator, list, result); + return result; +} + +LC_FUNCTION LC_String16 LC_ToWidecharEx(LC_Arena *allocator, LC_String string) { + LC_ASSERT(NULL, sizeof(wchar_t) == 2); + wchar_t *buffer = (wchar_t *)LC_PushSize(allocator, sizeof(wchar_t) * (string.len + 1)); + int64_t size = LC_CreateWidecharFromChar(buffer, string.len + 1, string.str, string.len); + LC_String16 result = {buffer, size}; + return result; +} + +LC_FUNCTION wchar_t *LC_ToWidechar(LC_Arena *allocator, LC_String string) { + LC_String16 result = LC_ToWidecharEx(allocator, string); + return result.str; +} + +LC_FUNCTION LC_String LC_FromWidecharEx(LC_Arena *allocator, wchar_t *wstring, int64_t wsize) { + LC_ASSERT(NULL, sizeof(wchar_t) == 2); + + int64_t buffer_size = (wsize + 1) * 2; + char *buffer = (char *)LC_PushSize(allocator, buffer_size); + int64_t size = LC_CreateCharFromWidechar(buffer, buffer_size, wstring, wsize); + LC_String result = LC_MakeString(buffer, size); + + LC_ASSERT(NULL, size < buffer_size); + return result; +} + +LC_FUNCTION int64_t LC_WideLength(wchar_t *string) { + int64_t len = 0; + while (*string++ != 0) + len++; + return len; +} + +LC_FUNCTION LC_String LC_FromWidechar(LC_Arena *allocator, wchar_t *wstring) { + int64_t size = LC_WideLength(wstring); + LC_String result = LC_FromWidecharEx(allocator, wstring, size); + return result; +} + +LC_FUNCTION const char *LC_OSToString(LC_OS os) { + switch (os) { + case LC_OS_WINDOWS: return "OS_WINDOWS"; + case LC_OS_LINUX: return "OS_LINUX"; + case LC_OS_MAC: return "OS_MAC"; + default: return "UNKNOWN_OPERATING_SYSTEM"; + } +} + +LC_FUNCTION const char *LC_GENToString(LC_GEN os) { + switch (os) { + case LC_GEN_C: return "GEN_C"; + default: return "UNKNOWN_GENERATOR"; + } +} + +LC_FUNCTION const char *LC_ARCHToString(LC_ARCH arch) { + switch (arch) { + case LC_ARCH_X86: return "ARCH_X86"; + case LC_ARCH_X64: return "ARCH_X64"; + default: return "UNKNOWN_ARCHITECTURE"; + } +} + +LC_FUNCTION const char *LC_ASTKindToString(LC_ASTKind kind) { + static const char *strs[] = { + "ast null", + "ast error", + "ast note", + "ast note list", + "ast file", + "ast package", + "ast ignore", + "typespec procdure argument", + "typespec aggregate member", + "expr call item", + "expr compound item", + "expr note", + "stmt switch case", + "stmt switch default", + "stmt else if", + "stmt else", + "import", + "global note", + "decl proc", + "decl struct", + "decl union", + "decl var", + "decl const", + "decl typedef", + "typespec ident", + "typespec field", + "typespec pointer", + "typespec array", + "typespec proc", + "stmt block", + "stmt note", + "stmt return", + "stmt break", + "stmt continue", + "stmt defer", + "stmt for", + "stmt if", + "stmt switch", + "stmt assign", + "stmt expr", + "stmt var", + "stmt const", + "expr ident", + "expr string", + "expr int", + "expr float", + "expr bool", + "expr type", + "expr binary", + "expr unary", + "expr builtin", + "expr call", + "expr compound", + "expr cast", + "expr field", + "expr index", + "expr pointerindex", + "expr getvalueofpointer", + "expr getpointerofvalue", + }; + if (kind < 0 || kind >= LC_ASTKind_Count) { + return ""; + } + return strs[kind]; +} + +LC_FUNCTION const char *LC_TypeKindToString(LC_TypeKind kind) { + static const char *strs[] = { + "LC_TypeKind_char", + "LC_TypeKind_uchar", + "LC_TypeKind_short", + "LC_TypeKind_ushort", + "LC_TypeKind_bool", + "LC_TypeKind_int", + "LC_TypeKind_uint", + "LC_TypeKind_long", + "LC_TypeKind_ulong", + "LC_TypeKind_llong", + "LC_TypeKind_ullong", + "LC_TypeKind_float", + "LC_TypeKind_double", + "LC_TypeKind_void", + "LC_TypeKind_Struct", + "LC_TypeKind_Union", + "LC_TypeKind_Pointer", + "LC_TypeKind_Array", + "LC_TypeKind_Proc", + "LC_TypeKind_UntypedInt", + "LC_TypeKind_UntypedFloat", + "LC_TypeKind_UntypedString", + "LC_TypeKind_Incomplete", + "LC_TypeKind_Completing", + "LC_TypeKind_Error", + }; + if (kind < 0 || kind >= T_TotalCount) { + return ""; + } + return strs[kind]; +} + +LC_FUNCTION const char *LC_DeclKindToString(LC_DeclKind decl_kind) { + static const char *strs[] = { + "declaration of error kind", + "type declaration", + "const declaration", + "variable declaration", + "procedure declaration", + "import declaration", + }; + if (decl_kind < 0 || decl_kind >= LC_DeclKind_Count) { + return ""; + } + return strs[decl_kind]; +} + +LC_FUNCTION const char *LC_TokenKindToString(LC_TokenKind token_kind) { + static const char *strs[] = { + "end of file", + "token error", + "comment", + "doc comment", + "file doc comment", + "package doc comment", + "note '@'", + "hash '#'", + "identifier", + "keyword", + "string literal", + "raw string literal", + "integer literal", + "float literal", + "unicode literal", + "open paren '('", + "close paren ')'", + "open brace '{'", + "close brace '}'", + "open bracket '['", + "close bracket ']'", + "comma ','", + "question mark '?'", + "semicolon ';'", + "period '.'", + "three dots '...'", + "colon ':'", + "multiply '*'", + "divide '/'", + "modulo '%'", + "left shift '<<'", + "right shift '>>'", + "add '+'", + "subtract '-'", + "equals '=='", + "lesser then '<'", + "greater then '>'", + "lesser then or equal '<='", + "greater then or equal '>='", + "not equal '!='", + "bit and '&'", + "bit or '|'", + "bit xor '^'", + "and '&&'", + "or '||'", + "addptr keyword", + "negation '~'", + "exclamation '!'", + "assignment '='", + "assignment '/='", + "assignment '*='", + "assignment '%='", + "assignment '-='", + "assignment '+='", + "assignment '&='", + "assignment '|='", + "assignment '^='", + "assignment '<<='", + "assignment '>>='", + }; + + if (token_kind < 0 || token_kind >= LC_TokenKind_Count) { + return ""; + } + return strs[token_kind]; +} + +LC_FUNCTION const char *LC_TokenKindToOperator(LC_TokenKind token_kind) { + static const char *strs[] = { + "end of file", + "token error", + "comment", + "doc comment", + "file doc comment", + "package doc comment", + "@", + "#", + "identifier", + "keyword", + "string literal", + "raw string literal", + "integer literal", + "float literal", + "unicode literal", + "(", + ")", + "{", + "}", + "[", + "]", + ",", + "?", + ";", + ".", + "...", + ":", + "*", + "/", + "%", + "<<", + ">>", + "+", + "-", + "==", + "<", + ">", + "<=", + ">=", + "!=", + "&", + "|", + "^", + "&&", + "||", + "+", + "~", + "!", + "=", + "/=", + "*=", + "%=", + "-=", + "+=", + "&=", + "|=", + "^=", + "<<=", + ">>=", + }; + if (token_kind < 0 || token_kind >= LC_TokenKind_Count) { + return ""; + } + return strs[token_kind]; +} + +#if __cplusplus + #define LC_Alignof(...) alignof(__VA_ARGS__) +#else + #define LC_Alignof(...) _Alignof(__VA_ARGS__) +#endif + +#define LC_WRAP_AROUND_POWER_OF_2(x, pow2) (((x) & ((pow2)-1llu))) + +#if defined(_MSC_VER) + #define LC_DebugBreak() (L->breakpoint_on_error && IsDebuggerPresent() && (__debugbreak(), 0)) +#else + #define LC_DebugBreak() (L->breakpoint_on_error && (__builtin_trap(), 0)) +#endif +#define LC_FatalError() (L->breakpoint_on_error ? LC_DebugBreak() : (LC_Exit(1), 0)) + +LC_FUNCTION void LC_IgnoreMessage(LC_Token *pos, char *str, int len) { +} + +LC_FUNCTION void LC_SendErrorMessage(LC_Token *pos, LC_String s8) { + if (L->on_message) { + L->on_message(pos, s8.str, (int)s8.len); + } else { + if (pos) { + LC_String line = LC_GetTokenLine(pos); + LC_String fmt = LC_Format(L->arena, "%s(%d,%d): error: %.*s\n%.*s", (char *)pos->lex->file, pos->line, pos->column, LC_Expand(s8), LC_Expand(line)); + LC_Print(fmt.str, fmt.len); + } else { + LC_Print(s8.str, s8.len); + } + } + LC_DebugBreak(); +} + +LC_FUNCTION void LC_SendErrorMessagef(LC_Lex *x, LC_Token *pos, const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + LC_SendErrorMessage(pos, s8); +} + +LC_FUNCTION void LC_HandleFatalError(void) { + if (L->on_fatal_error) { + L->on_fatal_error(); + return; + } + LC_FatalError(); +} + +LC_FUNCTION void LC_MapReserve(LC_Map *map, int size) { + LC_Map old_map = *map; + + LC_ASSERT(NULL, LC_IS_POW2(size)); + map->len = 0; + map->cap = size; + LC_ASSERT(NULL, map->arena); + + map->entries = LC_PushArray(map->arena, LC_MapEntry, map->cap); + + if (old_map.entries) { + for (int i = 0; i < old_map.cap; i += 1) { + LC_MapEntry *it = old_map.entries + i; + if (it->key) LC_InsertMapEntry(map, it->key, it->value); + } + } +} + +// FNV HASH (1a?) +LC_FUNCTION uint64_t LC_HashBytes(void *data, uint64_t size) { + uint8_t *data8 = (uint8_t *)data; + uint64_t hash = (uint64_t)14695981039346656037ULL; + for (uint64_t i = 0; i < size; i++) { + hash = hash ^ (uint64_t)(data8[i]); + hash = hash * (uint64_t)1099511628211ULL; + } + return hash; +} + +LC_FUNCTION uint64_t LC_HashMix(uint64_t x, uint64_t y) { + x ^= y; + x *= 0xff51afd7ed558ccd; + x ^= x >> 32; + return x; +} + +LC_FUNCTION int LC_NextPow2(int v) { + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; +} + +LC_FUNCTION LC_MapEntry *LC_GetMapEntryEx(LC_Map *map, uint64_t key) { + LC_ASSERT(NULL, key); + if (map->len * 2 >= map->cap) { + LC_MapReserve(map, map->cap * 2); + } + + uint64_t hash = LC_HashBytes(&key, sizeof(key)); + if (hash == 0) hash += 1; + uint64_t index = LC_WRAP_AROUND_POWER_OF_2(hash, map->cap); + uint64_t i = index; + for (;;) { + LC_MapEntry *it = map->entries + i; + if (it->key == key || it->key == 0) { + return it; + } + + i = LC_WRAP_AROUND_POWER_OF_2(i + 1, map->cap); + if (i == index) return NULL; + } + LC_ASSERT(NULL, !"invalid codepath"); +} + +LC_FUNCTION bool LC_InsertWithoutReplace(LC_Map *map, void *key, void *value) { + LC_MapEntry *entry = LC_GetMapEntryEx(map, (uint64_t)key); + if (entry->key != 0) return false; + + map->len += 1; + entry->key = (uint64_t)key; + entry->value = (uint64_t)value; + return true; +} + +LC_FUNCTION LC_MapEntry *LC_InsertMapEntry(LC_Map *map, uint64_t key, uint64_t value) { + LC_MapEntry *entry = LC_GetMapEntryEx(map, key); + if (entry->key == key) { + entry->value = value; + } + if (entry->key == 0) { + entry->key = key; + entry->value = value; + map->len += 1; + } + return entry; +} + +LC_FUNCTION LC_MapEntry *LC_GetMapEntry(LC_Map *map, uint64_t key) { + LC_MapEntry *entry = LC_GetMapEntryEx(map, key); + if (entry && entry->key == key) { + return entry; + } + return NULL; +} + +LC_FUNCTION void LC_MapInsert(LC_Map *map, LC_String keystr, void *value) { + uint64_t key = LC_HashBytes(keystr.str, keystr.len); + LC_InsertMapEntry(map, key, (uint64_t)value); +} + +LC_FUNCTION void *LC_MapGet(LC_Map *map, LC_String keystr) { + uint64_t key = LC_HashBytes(keystr.str, keystr.len); + LC_MapEntry *r = LC_GetMapEntry(map, key); + return r ? (void *)r->value : 0; +} + +LC_FUNCTION void LC_MapInsertU64(LC_Map *map, uint64_t key, void *value) { + LC_InsertMapEntry(map, key, (uint64_t)value); +} + +LC_FUNCTION void *LC_MapGetU64(LC_Map *map, uint64_t key) { + LC_MapEntry *r = LC_GetMapEntry(map, key); + return r ? (void *)r->value : 0; +} + +LC_FUNCTION void *LC_MapGetP(LC_Map *map, void *key) { + return LC_MapGetU64(map, (uint64_t)key); +} + +LC_FUNCTION void LC_MapInsertP(LC_Map *map, void *key, void *value) { + LC_InsertMapEntry(map, (uint64_t)key, (uint64_t)value); +} + +LC_FUNCTION void LC_MapClear(LC_Map *map) { + if (map->len != 0) LC_MemoryZero(map->entries, map->cap * sizeof(LC_MapEntry)); + map->len = 0; +} + +LC_FUNCTION size_t LC_GetAlignOffset(size_t size, size_t align) { + size_t mask = align - 1; + size_t val = size & mask; + if (val) { + val = align - val; + } + return val; +} + +LC_FUNCTION size_t LC_AlignUp(size_t size, size_t align) { + size_t result = size + LC_GetAlignOffset(size, align); + return result; +} + +LC_FUNCTION size_t LC_AlignDown(size_t size, size_t align) { + size += 1; // Make sure when align is 8 doesn't get rounded down to 0 + size_t result = size - (align - LC_GetAlignOffset(size, align)); + return result; +} + +typedef struct { + int len; + char str[]; +} INTERN_Entry; + +LC_FUNCTION LC_Intern LC_InternStrLen(char *str, int len) { + LC_String key = LC_MakeString(str, len); + INTERN_Entry *entry = (INTERN_Entry *)LC_MapGet(&L->interns, key); + if (entry == NULL) { + LC_ASSERT(NULL, sizeof(INTERN_Entry) == sizeof(int)); + entry = (INTERN_Entry *)LC_PushSize(L->arena, sizeof(int) + sizeof(char) * (len + 1)); + entry->len = len; + LC_MemoryCopy(entry->str, str, len); + entry->str[len] = 0; + LC_MapInsert(&L->interns, key, entry); + } + + return (uintptr_t)entry->str; +} + +LC_FUNCTION LC_Intern LC_ILit(char *str) { + return LC_InternStrLen(str, (int)LC_StrLen(str)); +} + +LC_FUNCTION LC_Intern LC_GetUniqueIntern(const char *name_for_debug) { + LC_String name = LC_Format(L->arena, "U%u_%s", ++L->unique_counter, name_for_debug); + LC_Intern result = LC_InternStrLen(name.str, (int)name.len); + return result; +} + +LC_FUNCTION char *LC_GetUniqueName(const char *name_for_debug) { + LC_String name = LC_Format(L->arena, "U%u_%s", ++L->unique_counter, name_for_debug); + return name.str; +} + +LC_FUNCTION void LC_DeclareNote(LC_Intern intern) { + LC_MapInsertU64(&L->declared_notes, intern, (void *)intern); +} + +LC_FUNCTION bool LC_IsNoteDeclared(LC_Intern intern) { + void *p = LC_MapGetU64(&L->declared_notes, intern); + bool result = p != NULL; + return result; +} +LC_FUNCTION void LC_LexingError(LC_Token *pos, const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + LC_SendErrorMessage(pos, s8); + L->errors += 1; + pos->kind = LC_TokenKind_Error; +} + +#define LC_IF(cond, ...) \ + do { \ + if (cond) { \ + LC_LexingError(t, __VA_ARGS__); \ + return; \ + } \ + } while (0) + +LC_FUNCTION bool LC_IsAssign(LC_TokenKind kind) { + bool result = kind >= LC_TokenKind_Assign && kind <= LC_TokenKind_RightShiftAssign; + return result; +} + +LC_FUNCTION bool LC_IsHexDigit(char c) { + bool result = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + return result; +} + +LC_FUNCTION bool LC_IsBinDigit(char c) { + bool result = (c >= '0' && c <= '1'); + return result; +} + +LC_FUNCTION uint64_t LC_MapCharToNumber(char c) { + // clang-format off + switch (c) { + case '0': return 0; + case '1': return 1; + case '2': return 2; + case '3': return 3; + case '4': return 4; + case '5': return 5; + case '6': return 6; + case '7': return 7; + case '8': return 8; + case '9': return 9; + case 'a': case 'A': return 10; + case 'b': case 'B': return 11; + case 'c': case 'C': return 12; + case 'd': case 'D': return 13; + case 'e': case 'E': return 14; + case 'f': case 'F': return 15; + default: return 255; + } + // clang-format on +} + +LC_FUNCTION uint64_t LC_GetEscapeCode(char c) { + switch (c) { + case 'a': return '\a'; + case 'b': return '\b'; + case 'e': return 0x1B; + case 'f': return '\f'; + case 'n': return '\n'; + case 'r': return '\r'; + case 't': return '\t'; + case 'v': return '\v'; + case '\\': return '\\'; + case '\'': return '\''; + case '\"': return '\"'; + case '0': return '\0'; + default: return UINT64_MAX; + } +} + +LC_FUNCTION LC_String LC_GetEscapeString(char c) { + switch (c) { + case '\a': return LC_Lit("\\a"); + case '\b': return LC_Lit("\\b"); + case 0x1B: return LC_Lit("\\x1B"); + case '\f': return LC_Lit("\\f"); + case '\n': return LC_Lit("\\n"); + case '\r': return LC_Lit("\\r"); + case '\t': return LC_Lit("\\t"); + case '\v': return LC_Lit("\\v"); + case '\\': return LC_Lit("\\\\"); + case '\'': return LC_Lit("\\'"); + case '\"': return LC_Lit("\\\""); + case '\0': return LC_Lit("\\0"); + default: return LC_Lit(""); + } +} + +LC_FUNCTION void LC_LexAdvance(LC_Lex *x) { + if (x->at[0] == 0) { + return; + } else if (x->at[0] == '\n') { + x->line += 1; + x->column = 0; + } + x->column += 1; + x->at += 1; +} + +LC_FUNCTION void LC_EatWhitespace(LC_Lex *x) { + while (LC_IsWhitespace(x->at[0])) LC_LexAdvance(x); +} + +LC_FUNCTION void LC_EatIdent(LC_Lex *x) { + while (x->at[0] == '_' || LC_IsAlphanumeric(x->at[0])) LC_LexAdvance(x); +} + +LC_FUNCTION void LC_SetTokenLen(LC_Lex *x, LC_Token *t) { + t->len = (int)(x->at - t->str); + LC_ASSERT(NULL, t->len < 2000000000); +} + +LC_FUNCTION void LC_EatUntilIncluding(LC_Lex *x, char c) { + while (x->at[0] != 0 && x->at[0] != c) LC_LexAdvance(x); + LC_LexAdvance(x); +} + +// @todo: add temporary allocation + copy at end to perm +LC_FUNCTION LC_BigInt LC_LexBigInt(char *string, int len, uint64_t base) { + LC_ASSERT(NULL, base >= 2 && base <= 16); + LC_BigInt m = LC_Bigint_u64(1); + LC_BigInt base_mul = LC_Bigint_u64(base); + LC_BigInt result = LC_Bigint_u64(0); + + LC_BigInt tmp = {0}; + for (int i = len - 1; i >= 0; --i) { + uint64_t u = LC_MapCharToNumber(string[i]); + LC_ASSERT(NULL, u < base); + LC_BigInt val = LC_Bigint_u64(u); + LC_Bigint_mul(&tmp, &val, &m); + LC_BigInt new_val = tmp; + LC_Bigint_add(&tmp, &result, &new_val); + result = tmp; + LC_Bigint_mul(&tmp, &m, &base_mul); + m = tmp; + } + + return result; +} + +LC_FUNCTION void LC_LexNestedComments(LC_Lex *x, LC_Token *t) { + t->kind = LC_TokenKind_Comment; + LC_LexAdvance(x); + + if (x->at[0] == '*') { + LC_LexAdvance(x); + t->kind = LC_TokenKind_DocComment; + + if (x->at[0] == ' ' && x->at[1] == 'f' && x->at[2] == 'i' && x->at[3] == 'l' && x->at[4] == 'e') { + t->kind = LC_TokenKind_FileDocComment; + } + + if (x->at[0] == ' ' && x->at[1] == 'p' && x->at[2] == 'a' && x->at[3] == 'c' && x->at[4] == 'k' && x->at[5] == 'a' && x->at[6] == 'g' && x->at[7] == 'e') { + t->kind = LC_TokenKind_PackageDocComment; + } + } + + int counter = 0; + for (;;) { + if (x->at[0] == '*' && x->at[1] == '/') { + if (counter <= 0) break; + counter -= 1; + } else if (x->at[0] == '/' && x->at[1] == '*') { + counter += 1; + LC_LexAdvance(x); + } + LC_IF(x->at[0] == 0, "Unclosed block comment"); + LC_LexAdvance(x); + } + t->str += 2; + LC_SetTokenLen(x, t); + LC_LexAdvance(x); + LC_LexAdvance(x); +} + +LC_FUNCTION void LC_LexStringLiteral(LC_Lex *x, LC_Token *t, LC_TokenKind kind) { + t->kind = kind; + if (kind == LC_TokenKind_RawString) { + LC_EatUntilIncluding(x, '`'); + } else if (kind == LC_TokenKind_String) { + for (;;) { + LC_IF(x->at[0] == '\n', "got a new line while parsing a '\"' string literal"); + LC_IF(x->at[0] == 0, "reached end of file during string lexing"); + if (x->at[0] == '"') break; + if (x->at[0] == '\\' && x->at[1] == '"') LC_LexAdvance(x); + LC_LexAdvance(x); + } + LC_LexAdvance(x); + } else { + LC_IF(1, "internal compiler error: unhandled case in %s", __FUNCTION__); + } + + LC_SetTokenLen(x, t); + t->len -= 2; + t->str += 1; +} + +LC_FUNCTION void LC_LexUnicodeLiteral(LC_Lex *x, LC_Token *t) { + t->kind = LC_TokenKind_Unicode; + LC_UTF32Result decode = LC_ConvertUTF8ToUTF32(x->at, 4); + LC_IF(decode.error, "invalid utf8 sequence"); + + uint8_t c[8] = {0}; + for (int i = 0; i < decode.advance; i += 1) { + c[i] = x->at[0]; + LC_LexAdvance(x); + } + uint64_t result = *(uint64_t *)&c[0]; + + if (result == '\\') { + LC_ASSERT(NULL, decode.advance == 1); + result = LC_GetEscapeCode(x->at[0]); + LC_IF(result == UINT64_MAX, "invalid escape code"); + LC_LexAdvance(x); + } + LC_IF(x->at[0] != '\'', "unclosed unicode literal"); + + LC_Bigint_init_signed(&t->i, result); + LC_LexAdvance(x); + LC_SetTokenLen(x, t); + t->str += 1; + t->len -= 2; + + LC_IF(t->len == 0, "empty unicode literal"); +} + +LC_FUNCTION void LC_LexIntOrFloat(LC_Lex *x, LC_Token *t) { + t->kind = LC_TokenKind_Int; + for (;;) { + if (x->at[0] == '.') { + LC_IF(t->kind == LC_TokenKind_Float, "failed to parse a floating point number, invalid format, found multiple '.'"); + if (t->kind == LC_TokenKind_Int) t->kind = LC_TokenKind_Float; + } else if (!LC_IsDigit(x->at[0])) break; + LC_LexAdvance(x); + } + + LC_SetTokenLen(x, t); + if (t->kind == LC_TokenKind_Int) { + t->i = LC_LexBigInt(t->str, t->len, 10); + } else if (t->kind == LC_TokenKind_Float) { + t->f64 = LC_ParseFloat(t->str, t->len); + } else { + LC_IF(1, "internal compiler error: unhandled case in %s", __FUNCTION__); + } +} + +LC_FUNCTION void LC_LexCase2(LC_Lex *x, LC_Token *t, LC_TokenKind tk0, char c, LC_TokenKind tk1) { + t->kind = tk0; + if (x->at[0] == c) { + LC_LexAdvance(x); + t->kind = tk1; + } +} + +LC_FUNCTION void LC_LexCase3(LC_Lex *x, LC_Token *t, LC_TokenKind tk, char c0, LC_TokenKind tk0, char c1, LC_TokenKind tk1) { + t->kind = tk; + if (x->at[0] == c0) { + t->kind = tk0; + LC_LexAdvance(x); + } else if (x->at[0] == c1) { + t->kind = tk1; + LC_LexAdvance(x); + } +} + +LC_FUNCTION void LC_LexCase4(LC_Lex *x, LC_Token *t, LC_TokenKind tk, char c0, LC_TokenKind tk0, char c1, LC_TokenKind tk1, char c2, LC_TokenKind tk2) { + t->kind = tk; + if (x->at[0] == c0) { + t->kind = tk0; + LC_LexAdvance(x); + } else if (x->at[0] == c1) { + LC_LexAdvance(x); + LC_LexCase2(x, t, tk1, c2, tk2); + } +} + +LC_FUNCTION void LC_LexNext(LC_Lex *x, LC_Token *t) { + LC_EatWhitespace(x); + LC_MemoryZero(t, sizeof(LC_Token)); + t->str = x->at; + t->line = x->line + 1; + t->column = x->column; + t->lex = x; + char *c = x->at; + LC_LexAdvance(x); + + switch (c[0]) { + case 0: t->kind = LC_TokenKind_EOF; break; + case '(': t->kind = LC_TokenKind_OpenParen; break; + case ')': t->kind = LC_TokenKind_CloseParen; break; + case '{': t->kind = LC_TokenKind_OpenBrace; break; + case '}': t->kind = LC_TokenKind_CloseBrace; break; + case '[': t->kind = LC_TokenKind_OpenBracket; break; + case ']': t->kind = LC_TokenKind_CloseBracket; break; + case ',': t->kind = LC_TokenKind_Comma; break; + case ':': t->kind = LC_TokenKind_Colon; break; + case ';': t->kind = LC_TokenKind_Semicolon; break; + case '~': t->kind = LC_TokenKind_Neg; break; + case '#': t->kind = LC_TokenKind_Hash; break; + case '@': t->kind = LC_TokenKind_Note; break; + case '\'': LC_LexUnicodeLiteral(x, t); break; + case '"': LC_LexStringLiteral(x, t, LC_TokenKind_String); break; + case '`': LC_LexStringLiteral(x, t, LC_TokenKind_RawString); break; + case '=': LC_LexCase2(x, t, LC_TokenKind_Assign, '=', LC_TokenKind_Equals); break; + case '!': LC_LexCase2(x, t, LC_TokenKind_Not, '=', LC_TokenKind_NotEquals); break; + case '*': LC_LexCase2(x, t, LC_TokenKind_Mul, '=', LC_TokenKind_MulAssign); break; + case '%': LC_LexCase2(x, t, LC_TokenKind_Mod, '=', LC_TokenKind_ModAssign); break; + case '+': LC_LexCase2(x, t, LC_TokenKind_Add, '=', LC_TokenKind_AddAssign); break; + case '-': LC_LexCase2(x, t, LC_TokenKind_Sub, '=', LC_TokenKind_SubAssign); break; + case '^': LC_LexCase2(x, t, LC_TokenKind_BitXor, '=', LC_TokenKind_BitXorAssign); break; + case '&': LC_LexCase3(x, t, LC_TokenKind_BitAnd, '=', LC_TokenKind_BitAndAssign, '&', LC_TokenKind_And); break; + case '|': LC_LexCase3(x, t, LC_TokenKind_BitOr, '=', LC_TokenKind_BitOrAssign, '|', LC_TokenKind_Or); break; + case '>': LC_LexCase4(x, t, LC_TokenKind_GreaterThen, '=', LC_TokenKind_GreaterThenEq, '>', LC_TokenKind_RightShift, '=', LC_TokenKind_RightShiftAssign); break; + case '<': LC_LexCase4(x, t, LC_TokenKind_LesserThen, '=', LC_TokenKind_LesserThenEq, '<', LC_TokenKind_LeftShift, '=', LC_TokenKind_LeftShiftAssign); break; + case '.': { + t->kind = LC_TokenKind_Dot; + if (x->at[0] == '.' && x->at[1] == '.') { + t->kind = LC_TokenKind_ThreeDots; + LC_LexAdvance(x); + LC_LexAdvance(x); + } + } break; + + case '0': { + if (x->at[0] == 'x') { + t->kind = LC_TokenKind_Int; + LC_LexAdvance(x); + while (LC_IsHexDigit(x->at[0])) LC_LexAdvance(x); + LC_SetTokenLen(x, t); + LC_IF(t->len < 3, "invalid hex number"); + t->i = LC_LexBigInt(t->str + 2, t->len - 2, 16); + break; + } + if (x->at[0] == 'b') { + t->kind = LC_TokenKind_Int; + LC_LexAdvance(x); + while (LC_IsBinDigit(x->at[0])) LC_LexAdvance(x); + LC_SetTokenLen(x, t); + LC_IF(t->len < 3, "invalid binary number"); + t->i = LC_LexBigInt(t->str + 2, t->len - 2, 2); + break; + } + } // @fallthrough + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': { + LC_LexIntOrFloat(x, t); + } break; + + case 'A': + case 'a': + case 'B': + case 'b': + case 'C': + case 'c': + case 'D': + case 'd': + case 'E': + case 'e': + case 'F': + case 'f': + case 'G': + case 'g': + case 'H': + case 'h': + case 'I': + case 'i': + case 'J': + case 'j': + case 'K': + case 'k': + case 'L': + case 'l': + case 'M': + case 'm': + case 'N': + case 'n': + case 'O': + case 'o': + case 'P': + case 'p': + case 'Q': + case 'q': + case 'R': + case 'r': + case 'S': + case 's': + case 'T': + case 't': + case 'U': + case 'u': + case 'V': + case 'v': + case 'W': + case 'w': + case 'X': + case 'x': + case 'Y': + case 'y': + case 'Z': + case 'z': + case '_': { + t->kind = LC_TokenKind_Ident; + LC_EatIdent(x); + } break; + + case '/': { + t->kind = LC_TokenKind_Div; + if (x->at[0] == '=') { + t->kind = LC_TokenKind_DivAssign; + LC_LexAdvance(x); + } else if (x->at[0] == '/') { + t->kind = LC_TokenKind_Comment; + LC_LexAdvance(x); + while (x->at[0] != '\n' && x->at[0] != 0) LC_LexAdvance(x); + LC_SetTokenLen(x, t); + } else if (x->at[0] == '*') { + LC_LexNestedComments(x, t); + } + } break; + + default: LC_IF(1, "invalid character"); + } + if (t->len == 0 && t->kind != LC_TokenKind_String && t->kind != LC_TokenKind_RawString) LC_SetTokenLen(x, t); + if (t->kind == LC_TokenKind_Comment) LC_LexNext(x, t); +} + +LC_FUNCTION LC_Lex *LC_LexStream(char *file, char *str, int line) { + LC_Lex *x = LC_PushStruct(L->lex_arena, LC_Lex); + x->begin = str; + x->at = str; + x->file = LC_ILit(file); + x->line = line; + + for (;;) { + LC_Token *t = LC_PushStruct(L->lex_arena, LC_Token); + if (!x->tokens) x->tokens = t; + x->token_count += 1; + + LC_LexNext(x, t); + if (t->kind == LC_TokenKind_EOF) break; + } + + return x; +} + +LC_FUNCTION LC_String LC_GetTokenLine(LC_Token *token) { + LC_Lex *x = token->lex; + LC_String content = LC_MakeFromChar(x->begin); + LC_StringList lines = LC_Split(L->arena, content, LC_Lit("\n"), 0); + + LC_String l[3] = {LC_MakeEmptyString()}; + + int line = 1; + for (LC_StringNode *it = lines.first; it; it = it->next) { + LC_String sline = it->string; + if (token->line - 1 == line) { + l[0] = LC_Format(L->arena, "> %.*s\n", LC_Expand(sline)); + } + if (token->line + 1 == line) { + l[2] = LC_Format(L->arena, "> %.*s\n", LC_Expand(sline)); + break; + } + if (token->line == line) { + int begin = (int)(token->str - sline.str); + LC_String left = LC_GetPrefix(sline, begin); + LC_String past_left = LC_Skip(sline, begin); + LC_String mid = LC_GetPrefix(past_left, token->len); + LC_String right = LC_Skip(past_left, token->len); + + char *green = "\033[32m"; + char *reset = "\033[0m"; + if (!L->use_colored_terminal_output) { + green = ">>>>"; + reset = "<<<<"; + } + l[1] = LC_Format(L->arena, "> %.*s%s%.*s%s%.*s\n", LC_Expand(left), green, LC_Expand(mid), reset, LC_Expand(right)); + } + line += 1; + } + + LC_String result = LC_Format(L->arena, "%.*s%.*s%.*s", LC_Expand(l[0]), LC_Expand(l[1]), LC_Expand(l[2])); + return result; +} + +LC_FUNCTION void LC_InternTokens(LC_Lex *x) { + // @todo: add scratch, we can dump the LC_PushArray strings + for (int i = 0; i < x->token_count; i += 1) { + LC_Token *t = x->tokens + i; + if (t->kind == LC_TokenKind_String) { + int string_len = 0; + char *string = LC_PushArray(L->arena, char, t->len); + for (int i = 0; i < t->len; i += 1) { + char c0 = t->str[i]; + char c1 = t->str[i + 1]; + if (i + 1 >= t->len) c1 = 0; + + if (c0 == '\\') { + uint64_t code = LC_GetEscapeCode(c1); + if (code == UINT64_MAX) { + LC_LexingError(t, "invalid escape code in string '%c%c'", c0, c1); + break; + } + + c0 = (char)code; + i += 1; + } + + string[string_len++] = c0; + } + t->ident = LC_InternStrLen(string, string_len); + } + if (t->kind == LC_TokenKind_Note || t->kind == LC_TokenKind_Ident || t->kind == LC_TokenKind_RawString) { + t->ident = LC_InternStrLen(t->str, t->len); + } + if (t->kind == LC_TokenKind_Ident) { + bool is_keyword = t->ident >= L->first_keyword && t->ident <= L->last_keyword; + if (is_keyword) { + t->kind = LC_TokenKind_Keyword; + if (L->kaddptr == t->ident) t->kind = LC_TokenKind_AddPtr; + } + } + } +} + +#undef LC_IF + +/* +The bigint code was written by Christoffer Lerno, he is the programmer +behind C3. He allowed me to use this code without any restrictions. Great guy! +You can check out C3 compiler: https://github.com/c3lang/c3c +He also writes very helpful blogs about compilers: https://c3.handmade.network/blog +*/ + +#ifndef malloc_arena + #define malloc_arena(size) LC_PushSize(L->arena, size) +#endif +#define ALLOC_DIGITS(_digits) ((_digits) ? (uint64_t *)malloc_arena(sizeof(uint64_t) * (_digits)) : NULL) + +LC_FUNCTION uint32_t LC_u32_min(uint32_t a, uint32_t b) { + return a < b ? a : b; +} + +LC_FUNCTION size_t LC_size_max(size_t a, size_t b) { + return a > b ? a : b; +} + +LC_FUNCTION unsigned LC_unsigned_max(unsigned a, unsigned b) { + return a > b ? a : b; +} + +LC_FUNCTION uint64_t *LC_Bigint_ptr(LC_BigInt *big_int) { + return big_int->digit_count == 1 ? &big_int->digit : big_int->digits; +} + +LC_FUNCTION LC_BigInt LC_Bigint_u64(uint64_t val) { + LC_BigInt result = {0}; + LC_Bigint_init_unsigned(&result, val); + return result; +} + +LC_FUNCTION void LC_normalize(LC_BigInt *big_int) { + uint64_t *digits = LC_Bigint_ptr(big_int); + unsigned last_non_zero = UINT32_MAX; + for (unsigned i = 0; i < big_int->digit_count; i++) { + if (digits[i] != 0) { + last_non_zero = i; + } + } + if (last_non_zero == UINT32_MAX) { + big_int->is_negative = false; + big_int->digit_count = 0; + return; + } + big_int->digit_count = last_non_zero + 1; + if (!last_non_zero) { + big_int->digit = digits[0]; + } +} + +LC_FUNCTION char LC_digit_to_char(uint8_t digit, bool upper) { + if (digit <= 9) { + return (char)(digit + '0'); + } + if (digit <= 35) { + return (char)(digit + (upper ? 'A' : 'a') - 10); + } + LC_ASSERT(NULL, !"Can't reach"); + return 0; +} + +LC_FUNCTION bool LC_bit_at_index(LC_BigInt *big_int, size_t index) { + size_t digit_index = index / 64; + if (digit_index >= big_int->digit_count) { + return false; + } + size_t digit_bit_index = index % 64; + uint64_t *digits = LC_Bigint_ptr(big_int); + uint64_t digit = digits[digit_index]; + return ((digit >> digit_bit_index) & 0x1U) == 0x1U; +} + +LC_FUNCTION size_t LC_Bigint_bits_needed(LC_BigInt *big_int) { + size_t full_bits = big_int->digit_count * 64; + size_t leading_zero_count = LC_Bigint_clz(big_int, full_bits); + size_t bits_needed = full_bits - leading_zero_count; + return bits_needed + big_int->is_negative; +} + +LC_FUNCTION void LC_Bigint_init_unsigned(LC_BigInt *big_int, uint64_t value) { + if (value == 0) { + big_int->digit_count = 0; + big_int->is_negative = false; + return; + } + big_int->digit_count = 1; + big_int->digit = value; + big_int->is_negative = false; +} + +LC_FUNCTION void LC_Bigint_init_signed(LC_BigInt *dest, int64_t value) { + if (value >= 0) { + LC_Bigint_init_unsigned(dest, (uint64_t)value); + return; + } + dest->is_negative = true; + dest->digit_count = 1; + dest->digit = ((uint64_t)(-(value + 1))) + 1; +} + +LC_FUNCTION void LC_Bigint_init_bigint(LC_BigInt *dest, LC_BigInt *src) { + if (src->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + if (src->digit_count == 1) { + dest->digit_count = 1; + dest->digit = src->digit; + dest->is_negative = src->is_negative; + return; + } + dest->is_negative = src->is_negative; + dest->digit_count = src->digit_count; + dest->digits = ALLOC_DIGITS(dest->digit_count); + LC_MemoryCopy(dest->digits, src->digits, sizeof(uint64_t) * dest->digit_count); +} + +LC_FUNCTION void LC_Bigint_negate(LC_BigInt *dest, LC_BigInt *source) { + LC_Bigint_init_bigint(dest, source); + dest->is_negative = !dest->is_negative; + LC_normalize(dest); +} + +LC_FUNCTION void LC_to_twos_complement(LC_BigInt *dest, LC_BigInt *source, size_t bit_count) { + if (bit_count == 0 || source->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + if (source->is_negative) { + LC_BigInt negated = {0}; + LC_Bigint_negate(&negated, source); + + LC_BigInt inverted = {0}; + LC_Bigint_not(&inverted, &negated, bit_count, false); + + LC_BigInt one = {0}; + LC_Bigint_init_unsigned(&one, 1); + + LC_Bigint_add(dest, &inverted, &one); + return; + } + + dest->is_negative = false; + uint64_t *source_digits = LC_Bigint_ptr(source); + if (source->digit_count == 1) { + dest->digit = source_digits[0]; + if (bit_count < 64) { + dest->digit &= (1ULL << bit_count) - 1; + } + dest->digit_count = 1; + LC_normalize(dest); + return; + } + unsigned digits_to_copy = (unsigned int)(bit_count / 64); + unsigned leftover_bits = (unsigned int)(bit_count % 64); + dest->digit_count = digits_to_copy + ((leftover_bits == 0) ? 0 : 1); + if (dest->digit_count == 1 && leftover_bits == 0) { + dest->digit = source_digits[0]; + if (dest->digit == 0) dest->digit_count = 0; + return; + } + dest->digits = (uint64_t *)malloc_arena(dest->digit_count * sizeof(uint64_t)); + for (size_t i = 0; i < digits_to_copy; i += 1) { + uint64_t digit = (i < source->digit_count) ? source_digits[i] : 0; + dest->digits[i] = digit; + } + if (leftover_bits != 0) { + uint64_t digit = (digits_to_copy < source->digit_count) ? source_digits[digits_to_copy] : 0; + dest->digits[digits_to_copy] = digit & ((1ULL << leftover_bits) - 1); + } + LC_normalize(dest); +} + +LC_FUNCTION size_t LC_Bigint_clz(LC_BigInt *big_int, size_t bit_count) { + if (big_int->is_negative || bit_count == 0) { + return 0; + } + if (big_int->digit_count == 0) { + return bit_count; + } + size_t count = 0; + for (size_t i = bit_count - 1;;) { + if (LC_bit_at_index(big_int, i)) { + return count; + } + count++; + if (i == 0) break; + i--; + } + return count; +} + +LC_FUNCTION bool LC_Bigint_eql(LC_BigInt a, LC_BigInt b) { + return LC_Bigint_cmp(&a, &b) == LC_CmpRes_EQ; +} + +LC_FUNCTION void LC_from_twos_complement(LC_BigInt *dest, LC_BigInt *src, size_t bit_count, bool is_signed) { + LC_ASSERT(NULL, !src->is_negative); + + if (bit_count == 0 || src->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + + if (is_signed && LC_bit_at_index(src, bit_count - 1)) { + LC_BigInt negative_one = {0}; + LC_Bigint_init_signed(&negative_one, -1); + + LC_BigInt minus_one = {0}; + LC_Bigint_add(&minus_one, src, &negative_one); + + LC_BigInt inverted = {0}; + LC_Bigint_not(&inverted, &minus_one, bit_count, false); + + LC_Bigint_negate(dest, &inverted); + return; + } + + LC_Bigint_init_bigint(dest, src); +} + +void LC_Bigint_init_data(LC_BigInt *dest, uint64_t *digits, unsigned int digit_count, bool is_negative) { + if (digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + + if (digit_count == 1) { + dest->digit_count = 1; + dest->digit = digits[0]; + dest->is_negative = is_negative; + LC_normalize(dest); + return; + } + + dest->digit_count = digit_count; + dest->is_negative = is_negative; + dest->digits = ALLOC_DIGITS(digit_count); + LC_MemoryCopy(dest->digits, digits, sizeof(uint64_t) * digit_count); + + LC_normalize(dest); +} + +LC_FUNCTION bool LC_Bigint_fits_in_bits(LC_BigInt *big_int, size_t bit_count, bool is_signed) { + LC_ASSERT(NULL, big_int->digit_count != 1 || big_int->digit != 0); + if (bit_count == 0) { + return LC_Bigint_cmp_zero(big_int) == LC_CmpRes_EQ; + } + if (big_int->digit_count == 0) { + return true; + } + + if (!is_signed) { + size_t full_bits = big_int->digit_count * 64; + size_t leading_zero_count = LC_Bigint_clz(big_int, full_bits); + return bit_count >= full_bits - leading_zero_count; + } + + LC_BigInt one = {0}; + LC_Bigint_init_unsigned(&one, 1); + + LC_BigInt shl_amt = {0}; + LC_Bigint_init_unsigned(&shl_amt, bit_count - 1); + + LC_BigInt max_value_plus_one = {0}; + LC_Bigint_shl(&max_value_plus_one, &one, &shl_amt); + + LC_BigInt max_value = {0}; + LC_Bigint_sub(&max_value, &max_value_plus_one, &one); + + LC_BigInt min_value = {0}; + LC_Bigint_negate(&min_value, &max_value_plus_one); + + LC_CmpRes min_cmp = LC_Bigint_cmp(big_int, &min_value); + LC_CmpRes max_cmp = LC_Bigint_cmp(big_int, &max_value); + + return (min_cmp == LC_CmpRes_GT || min_cmp == LC_CmpRes_EQ) && (max_cmp == LC_CmpRes_LT || max_cmp == LC_CmpRes_EQ); +} + +LC_FUNCTION uint64_t LC_Bigint_as_unsigned(LC_BigInt *bigint) { + LC_ASSERT(NULL, !bigint->is_negative); + if (bigint->digit_count == 0) { + return 0; + } + if (bigint->digit_count != 1) { + LC_ASSERT(NULL, !"Bigint exceeds u64"); + } + return bigint->digit; +} + +#if defined(_MSC_VER) + +LC_FUNCTION bool LC_add_u64_overflow(uint64_t op1, uint64_t op2, uint64_t *result) { + *result = op1 + op2; + return *result < op1 || *result < op2; +} + +LC_FUNCTION bool LC_sub_u64_overflow(uint64_t op1, uint64_t op2, uint64_t *result) { + *result = op1 - op2; + return *result > op1; +} + +LC_FUNCTION bool LC_mul_u64_overflow(uint64_t op1, uint64_t op2, uint64_t *result) { + *result = op1 * op2; + + if (op1 == 0 || op2 == 0) return false; + if (op1 > UINT64_MAX / op2) return true; + if (op2 > UINT64_MAX / op1) return true; + return false; +} + +#else + +LC_FUNCTION bool LC_add_u64_overflow(uint64_t op1, uint64_t op2, uint64_t *result) { + return __builtin_uaddll_overflow((unsigned long long)op1, (unsigned long long)op2, + (unsigned long long *)result); +} + +LC_FUNCTION bool LC_sub_u64_overflow(uint64_t op1, uint64_t op2, uint64_t *result) { + return __builtin_usubll_overflow((unsigned long long)op1, (unsigned long long)op2, + (unsigned long long *)result); +} + +LC_FUNCTION bool LC_mul_u64_overflow(uint64_t op1, uint64_t op2, uint64_t *result) { + return __builtin_umulll_overflow((unsigned long long)op1, (unsigned long long)op2, + (unsigned long long *)result); +} + +#endif + +LC_FUNCTION void LC_Bigint_add(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->digit_count == 0) { + LC_Bigint_init_bigint(dest, op2); + return; + } + if (op2->digit_count == 0) { + LC_Bigint_init_bigint(dest, op1); + return; + } + if (op1->is_negative == op2->is_negative) { + dest->is_negative = op1->is_negative; + + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + uint64_t overflow = LC_add_u64_overflow(op1_digits[0], op2_digits[0], &dest->digit); + if (overflow == 0 && op1->digit_count == 1 && op2->digit_count == 1) { + dest->digit_count = 1; + LC_normalize(dest); + return; + } + unsigned i = 1; + uint64_t first_digit = dest->digit; + dest->digits = ALLOC_DIGITS(LC_unsigned_max(op1->digit_count, op2->digit_count) + 1); + dest->digits[0] = first_digit; + + for (;;) { + bool found_digit = false; + uint64_t x = (uint64_t)overflow; + overflow = 0; + + if (i < op1->digit_count) { + found_digit = true; + uint64_t digit = op1_digits[i]; + overflow += LC_add_u64_overflow(x, digit, &x); + } + + if (i < op2->digit_count) { + found_digit = true; + uint64_t digit = op2_digits[i]; + overflow += LC_add_u64_overflow(x, digit, &x); + } + + dest->digits[i] = x; + i += 1; + + if (!found_digit) { + dest->digit_count = i; + LC_normalize(dest); + return; + } + } + } + LC_BigInt *op_pos; + LC_BigInt *op_neg; + if (op1->is_negative) { + op_neg = op1; + op_pos = op2; + } else { + op_pos = op1; + op_neg = op2; + } + + LC_BigInt op_neg_abs = {0}; + LC_Bigint_negate(&op_neg_abs, op_neg); + LC_BigInt *bigger_op; + LC_BigInt *smaller_op; + switch (LC_Bigint_cmp(op_pos, &op_neg_abs)) { + case LC_CmpRes_EQ: + LC_Bigint_init_unsigned(dest, 0); + return; + case LC_CmpRes_LT: + bigger_op = &op_neg_abs; + smaller_op = op_pos; + dest->is_negative = true; + break; + case LC_CmpRes_GT: + bigger_op = op_pos; + smaller_op = &op_neg_abs; + dest->is_negative = false; + break; + default: + LC_ASSERT(NULL, !"UNREACHABLE"); + } + uint64_t *bigger_op_digits = LC_Bigint_ptr(bigger_op); + uint64_t *smaller_op_digits = LC_Bigint_ptr(smaller_op); + uint64_t overflow = (uint64_t)LC_sub_u64_overflow(bigger_op_digits[0], smaller_op_digits[0], &dest->digit); + if (overflow == 0 && bigger_op->digit_count == 1 && smaller_op->digit_count == 1) { + dest->digit_count = 1; + LC_normalize(dest); + return; + } + uint64_t first_digit = dest->digit; + dest->digits = ALLOC_DIGITS(bigger_op->digit_count); + dest->digits[0] = first_digit; + unsigned i = 1; + + for (;;) { + bool found_digit = false; + uint64_t x = bigger_op_digits[i]; + uint64_t prev_overflow = overflow; + overflow = 0; + + if (i < smaller_op->digit_count) { + found_digit = true; + uint64_t digit = smaller_op_digits[i]; + overflow += LC_sub_u64_overflow(x, digit, &x); + } + if (LC_sub_u64_overflow(x, prev_overflow, &x)) { + found_digit = true; + overflow += 1; + } + dest->digits[i] = x; + i += 1; + + if (!found_digit || i >= bigger_op->digit_count) { + break; + } + } + LC_ASSERT(NULL, overflow == 0); + dest->digit_count = i; + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_add_wrap(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed) { + LC_BigInt unwrapped = {0}; + LC_Bigint_add(&unwrapped, op1, op2); + LC_Bigint_truncate(dest, &unwrapped, bit_count, is_signed); +} + +LC_FUNCTION void LC_Bigint_sub(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + LC_BigInt op2_negated = {0}; + LC_Bigint_negate(&op2_negated, op2); + LC_Bigint_add(dest, op1, &op2_negated); + return; +} + +LC_FUNCTION void LC_Bigint_sub_wrap(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed) { + LC_BigInt op2_negated = {0}; + LC_Bigint_negate(&op2_negated, op2); + LC_Bigint_add_wrap(dest, op1, &op2_negated, bit_count, is_signed); + return; +} + +LC_FUNCTION void mul_overflow(uint64_t op1, uint64_t op2, uint64_t *lo, uint64_t *hi) { + uint64_t u1 = (op1 & 0xffffffff); + uint64_t v1 = (op2 & 0xffffffff); + uint64_t t = (u1 * v1); + uint64_t w3 = (t & 0xffffffff); + uint64_t k = (t >> 32); + + op1 >>= 32; + t = (op1 * v1) + k; + k = (t & 0xffffffff); + uint64_t w1 = (t >> 32); + + op2 >>= 32; + t = (u1 * op2) + k; + k = (t >> 32); + + *hi = (op1 * op2) + w1 + k; + *lo = (t << 32) + w3; +} + +LC_FUNCTION void LC_mul_scalar(LC_BigInt *dest, LC_BigInt *op, uint64_t scalar) { + LC_Bigint_init_unsigned(dest, 0); + + LC_BigInt bi_64; + LC_Bigint_init_unsigned(&bi_64, 64); + + uint64_t *op_digits = LC_Bigint_ptr(op); + size_t i = op->digit_count - 1; + + while (1) { + LC_BigInt shifted; + LC_Bigint_shl(&shifted, dest, &bi_64); + + uint64_t result_scalar; + uint64_t carry_scalar; + mul_overflow(scalar, op_digits[i], &result_scalar, &carry_scalar); + + LC_BigInt result; + LC_Bigint_init_unsigned(&result, result_scalar); + + LC_BigInt carry; + LC_Bigint_init_unsigned(&carry, carry_scalar); + + LC_BigInt carry_shifted; + LC_Bigint_shl(&carry_shifted, &carry, &bi_64); + + LC_BigInt tmp; + LC_Bigint_add(&tmp, &shifted, &carry_shifted); + + LC_Bigint_add(dest, &tmp, &result); + + if (i == 0) { + break; + } + i -= 1; + } +} + +LC_FUNCTION void LC_Bigint_mul(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->digit_count == 0 || op2->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + + uint64_t carry; + mul_overflow(op1_digits[0], op2_digits[0], &dest->digit, &carry); + if (carry == 0 && op1->digit_count == 1 && op2->digit_count == 1) { + dest->is_negative = (op1->is_negative != op2->is_negative); + dest->digit_count = 1; + LC_normalize(dest); + return; + } + + LC_Bigint_init_unsigned(dest, 0); + + LC_BigInt bi_64; + LC_Bigint_init_unsigned(&bi_64, 64); + + size_t i = op2->digit_count - 1; + for (;;) { + LC_BigInt shifted; + LC_Bigint_shl(&shifted, dest, &bi_64); + + LC_BigInt scalar_result; + LC_mul_scalar(&scalar_result, op1, op2_digits[i]); + + LC_Bigint_add(dest, &scalar_result, &shifted); + + if (i == 0) { + break; + } + i -= 1; + } + + dest->is_negative = (op1->is_negative != op2->is_negative); + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_mul_wrap(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed) { + LC_BigInt unwrapped = {0}; + LC_Bigint_mul(&unwrapped, op1, op2); + LC_Bigint_truncate(dest, &unwrapped, bit_count, is_signed); +} + +LC_FUNCTION unsigned LC_count_leading_zeros(uint32_t val) { + if (val == 0) return 32; + +#if _MSC_VER + unsigned long Index; + _BitScanReverse(&Index, val); + return Index ^ 31; +#else + return __builtin_clz(val); +#endif +} + +// Make a 64-bit integer from a high / low pair of 32-bit integers. +LC_FUNCTION uint64_t LC_make_64(uint32_t hi, uint32_t lo) { + return (((uint64_t)hi) << 32) | ((uint64_t)lo); +} + +// Return the high 32 bits of a 64 bit value. +LC_FUNCTION uint32_t LC_hi_32(uint64_t value) { + return (uint32_t)(value >> 32); +} + +// Return the low 32 bits of a 64 bit value. +LC_FUNCTION uint32_t LC_lo_32(uint64_t val) { + return (uint32_t)val; +} + +// Implementation of Knuth's Algorithm D (Division of nonnegative integers) +// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The +// variables here have the same names as in the algorithm. Comments explain +// the algorithm and any deviation from it. +LC_FUNCTION void LC_knuth_div(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t *r, unsigned m, unsigned n) { + LC_ASSERT(NULL, u && "Must provide dividend"); + LC_ASSERT(NULL, v && "Must provide divisor"); + LC_ASSERT(NULL, q && "Must provide quotient"); + LC_ASSERT(NULL, u != v && u != q && v != q && "Must use different memory"); + LC_ASSERT(NULL, n > 1 && "n must be > 1"); + + // b denotes the base of the number system. In our case b is 2^32. + uint64_t b = ((uint64_t)1) << 32; + + // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of + // u and v by d. Note that we have taken Knuth's advice here to use a power + // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of + // 2 allows us to shift instead of multiply and it is easy to determine the + // shift amount from the leading zeros. We are basically normalizing the u + // and v so that its high bits are shifted to the top of v's range without + // overflow. Note that this can require an extra word in u so that u must + // be of length m+n+1. + unsigned shift = LC_count_leading_zeros(v[n - 1]); + uint32_t v_carry = 0; + uint32_t u_carry = 0; + if (shift) { + for (unsigned i = 0; i < m + n; ++i) { + uint32_t u_tmp = u[i] >> (32 - shift); + u[i] = (u[i] << shift) | u_carry; + u_carry = u_tmp; + } + for (unsigned i = 0; i < n; ++i) { + uint32_t v_tmp = v[i] >> (32 - shift); + v[i] = (v[i] << shift) | v_carry; + v_carry = v_tmp; + } + } + u[m + n] = u_carry; + + // D2. [Initialize j.] Set j to m. This is the loop counter over the places. + int j = (int)m; + do { + // D3. [Calculate q'.]. + // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q') + // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r') + // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease + // qp by 1, increase rp by v[n-1], and repeat this test if rp < b. The test + // on v[n-2] determines at high speed most of the cases in which the trial + // value qp is one too large, and it eliminates all cases where qp is two + // too large. + uint64_t dividend = LC_make_64(u[j + n], u[j + n - 1]); + uint64_t qp = dividend / v[n - 1]; + uint64_t rp = dividend % v[n - 1]; + if (qp == b || qp * v[n - 2] > b * rp + u[j + n - 2]) { + qp--; + rp += v[n - 1]; + if (rp < b && (qp == b || qp * v[n - 2] > b * rp + u[j + n - 2])) { + qp--; + } + } + + // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with + // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation + // consists of a simple multiplication by a one-place number, combined with + // a subtraction. + // The digits (u[j+n]...u[j]) should be kept positive; if the result of + // this step is actually negative, (u[j+n]...u[j]) should be left as the + // true value plus b**(n+1), namely as the b's complement of + // the true value, and a "borrow" to the left should be remembered. + int64_t borrow = 0; + for (unsigned i = 0; i < n; ++i) { + uint64_t p = ((uint64_t)qp) * ((uint64_t)(v[i])); + int64_t subres = ((int64_t)(u[j + i])) - borrow - LC_lo_32(p); + u[j + i] = LC_lo_32((uint64_t)subres); + borrow = LC_hi_32(p) - LC_hi_32((uint64_t)subres); + } + bool is_neg = u[j + n] < borrow; + u[j + n] -= LC_lo_32((uint64_t)borrow); + + // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was + // negative, go to step D6; otherwise go on to step D7. + q[j] = LC_lo_32(qp); + if (is_neg) { + // D6. [Add back]. The probability that this step is necessary is very + // small, on the order of only 2/b. Make sure that test data accounts for + // this possibility. Decrease q[j] by 1 + q[j]--; + // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]). + // A carry will occur to the left of u[j+n], and it should be ignored + // since it cancels with the borrow that occurred in D4. + bool carry = false; + for (unsigned i = 0; i < n; i++) { + uint32_t limit = LC_u32_min(u[j + i], v[i]); + u[j + i] += v[i] + carry; + carry = u[j + i] < limit || (carry && u[j + i] == limit); + } + u[j + n] += carry; + } + + // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3. + } while (--j >= 0); + + // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired + // remainder may be obtained by dividing u[...] by d. If r is non-null we + // compute the remainder (urem uses this). + if (r) { + // The value d is expressed by the "shift" value above since we avoided + // multiplication by d by using a shift left. So, all we have to do is + // shift right here. + if (shift) { + uint32_t carry = 0; + for (int i = (int)n - 1; i >= 0; i--) { + r[i] = (u[i] >> shift) | carry; + carry = u[i] << (32 - shift); + } + } else { + for (int i = (int)n - 1; i >= 0; i--) { + r[i] = u[i]; + } + } + } +} + +LC_FUNCTION void LC_Bigint_unsigned_division(LC_BigInt *op1, LC_BigInt *op2, LC_BigInt *Quotient, LC_BigInt *Remainder) { + LC_CmpRes cmp = LC_Bigint_cmp(op1, op2); + if (cmp == LC_CmpRes_LT) { + if (!Quotient) { + LC_Bigint_init_unsigned(Quotient, 0); + } + if (!Remainder) { + LC_Bigint_init_bigint(Remainder, op1); + } + return; + } + if (cmp == LC_CmpRes_EQ) { + if (!Quotient) { + LC_Bigint_init_unsigned(Quotient, 1); + } + if (!Remainder) { + LC_Bigint_init_unsigned(Remainder, 0); + } + return; + } + + uint64_t *lhs = LC_Bigint_ptr(op1); + uint64_t *rhs = LC_Bigint_ptr(op2); + unsigned lhsWords = op1->digit_count; + unsigned rhsWords = op2->digit_count; + + // First, compose the values into an array of 32-bit words instead of + // 64-bit words. This is a necessity of both the "short division" algorithm + // and the Knuth "classical algorithm" which requires there to be native + // operations for +, -, and * on an m bit value with an m*2 bit result. We + // can't use 64-bit operands here because we don't have native results of + // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't + // work on large-endian machines. + unsigned n = rhsWords * 2; + unsigned m = (lhsWords * 2) - n; + + // Allocate space for the temporary values we need either on the stack, if + // it will fit, or on the heap if it won't. + uint32_t space[128]; + uint32_t *U = NULL; + uint32_t *V = NULL; + uint32_t *Q = NULL; + uint32_t *R = NULL; + if ((Remainder ? 4 : 3) * n + 2 * m + 1 <= 128) { + U = &space[0]; + V = &space[m + n + 1]; + Q = &space[(m + n + 1) + n]; + if (Remainder) { + R = &space[(m + n + 1) + n + (m + n)]; + } + } else { + U = (uint32_t *)malloc_arena(sizeof(uint32_t) * (m + n + 1)); + V = (uint32_t *)malloc_arena(sizeof(uint32_t) * n); + Q = (uint32_t *)malloc_arena(sizeof(uint32_t) * (m + n)); + if (Remainder) { + R = (uint32_t *)malloc_arena(sizeof(uint32_t) * n); + } + } + + // Initialize the dividend + LC_MemoryZero(U, (m + n + 1) * sizeof(uint32_t)); + for (unsigned i = 0; i < lhsWords; ++i) { + uint64_t tmp = lhs[i]; + U[i * 2] = LC_lo_32(tmp); + U[i * 2 + 1] = LC_hi_32(tmp); + } + U[m + n] = 0; // this extra word is for "spill" in the Knuth algorithm. + + // Initialize the divisor + LC_MemoryZero(V, (n) * sizeof(uint32_t)); + for (unsigned i = 0; i < rhsWords; ++i) { + uint64_t tmp = rhs[i]; + V[i * 2] = LC_lo_32(tmp); + V[i * 2 + 1] = LC_hi_32(tmp); + } + + // initialize the quotient and remainder + LC_MemoryZero(Q, (m + n) * sizeof(uint32_t)); + if (Remainder) LC_MemoryZero(R, n * sizeof(uint32_t)); + + // Now, adjust m and n for the Knuth division. n is the number of words in + // the divisor. m is the number of words by which the dividend exceeds the + // divisor (i.e. m+n is the length of the dividend). These sizes must not + // contain any zero words or the Knuth algorithm fails. + for (unsigned i = n; i > 0 && V[i - 1] == 0; i--) { + n--; + m++; + } + for (unsigned i = m + n; i > 0 && U[i - 1] == 0; i--) { + m--; + } + + // If we're left with only a single word for the divisor, Knuth doesn't work + // so we implement the short division algorithm here. This is much simpler + // and faster because we are certain that we can divide a 64-bit quantity + // by a 32-bit quantity at hardware speed and short division is simply a + // series of such operations. This is just like doing short division but we + // are using base 2^32 instead of base 10. + LC_ASSERT(NULL, n != 0 && "Divide by zero?"); + if (n == 1) { + uint32_t divisor = V[0]; + uint32_t rem = 0; + for (int i = (int)m; i >= 0; i--) { + uint64_t partial_dividend = LC_make_64(rem, U[i]); + if (partial_dividend == 0) { + Q[i] = 0; + rem = 0; + } else if (partial_dividend < divisor) { + Q[i] = 0; + rem = LC_lo_32(partial_dividend); + } else if (partial_dividend == divisor) { + Q[i] = 1; + rem = 0; + } else { + Q[i] = LC_lo_32(partial_dividend / divisor); + rem = LC_lo_32(partial_dividend - (Q[i] * divisor)); + } + } + if (R) { + R[0] = rem; + } + } else { + // Now we're ready to invoke the Knuth classical divide algorithm. In this + // case n > 1. + LC_knuth_div(U, V, Q, R, m, n); + } + + // If the caller wants the quotient + if (Quotient) { + Quotient->is_negative = false; + Quotient->digit_count = lhsWords; + if (lhsWords == 1) { + Quotient->digit = LC_make_64(Q[1], Q[0]); + } else { + Quotient->digits = ALLOC_DIGITS(lhsWords); + for (size_t i = 0; i < lhsWords; i += 1) { + Quotient->digits[i] = LC_make_64(Q[i * 2 + 1], Q[i * 2]); + } + } + } + + // If the caller wants the remainder + if (Remainder) { + Remainder->is_negative = false; + Remainder->digit_count = rhsWords; + if (rhsWords == 1) { + Remainder->digit = LC_make_64(R[1], R[0]); + } else { + Remainder->digits = ALLOC_DIGITS(rhsWords); + for (size_t i = 0; i < rhsWords; i += 1) { + Remainder->digits[i] = LC_make_64(R[i * 2 + 1], R[i * 2]); + } + } + } +} + +LC_FUNCTION void LC_Bigint_div_trunc(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + LC_ASSERT(NULL, op2->digit_count != 0); // division by zero + if (op1->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + if (op1->digit_count == 1 && op2->digit_count == 1) { + dest->digit = op1_digits[0] / op2_digits[0]; + dest->digit_count = 1; + dest->is_negative = op1->is_negative != op2->is_negative; + LC_normalize(dest); + return; + } + if (op2->digit_count == 1 && op2_digits[0] == 1) { + // X / 1 == X + LC_Bigint_init_bigint(dest, op1); + dest->is_negative = op1->is_negative != op2->is_negative; + LC_normalize(dest); + return; + } + + LC_BigInt *op1_positive; + LC_BigInt op1_positive_data; + if (op1->is_negative) { + LC_Bigint_negate(&op1_positive_data, op1); + op1_positive = &op1_positive_data; + } else { + op1_positive = op1; + } + + LC_BigInt *op2_positive; + LC_BigInt op2_positive_data; + if (op2->is_negative) { + LC_Bigint_negate(&op2_positive_data, op2); + op2_positive = &op2_positive_data; + } else { + op2_positive = op2; + } + + LC_Bigint_unsigned_division(op1_positive, op2_positive, dest, NULL); + dest->is_negative = op1->is_negative != op2->is_negative; + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_div_floor(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->is_negative != op2->is_negative) { + LC_Bigint_div_trunc(dest, op1, op2); + LC_BigInt mult_again = {0}; + LC_Bigint_mul(&mult_again, dest, op2); + mult_again.is_negative = op1->is_negative; + if (LC_Bigint_cmp(&mult_again, op1) != LC_CmpRes_EQ) { + LC_BigInt tmp = {0}; + LC_Bigint_init_bigint(&tmp, dest); + LC_BigInt neg_one = {0}; + LC_Bigint_init_signed(&neg_one, -1); + LC_Bigint_add(dest, &tmp, &neg_one); + } + LC_normalize(dest); + } else { + LC_Bigint_div_trunc(dest, op1, op2); + } +} + +LC_FUNCTION void LC_Bigint_rem(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + LC_ASSERT(NULL, op2->digit_count != 0); // division by zero + if (op1->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + + if (op1->digit_count == 1 && op2->digit_count == 1) { + dest->digit = op1_digits[0] % op2_digits[0]; + dest->digit_count = 1; + dest->is_negative = op1->is_negative; + LC_normalize(dest); + return; + } + if (op2->digit_count == 2 && op2_digits[0] == 0 && op2_digits[1] == 1) { + // special case this divisor + LC_Bigint_init_unsigned(dest, op1_digits[0]); + dest->is_negative = op1->is_negative; + LC_normalize(dest); + return; + } + + if (op2->digit_count == 1 && op2_digits[0] == 1) { + // X % 1 == 0 + LC_Bigint_init_unsigned(dest, 0); + return; + } + + LC_BigInt *op1_positive; + LC_BigInt op1_positive_data; + if (op1->is_negative) { + LC_Bigint_negate(&op1_positive_data, op1); + op1_positive = &op1_positive_data; + } else { + op1_positive = op1; + } + + LC_BigInt *op2_positive; + LC_BigInt op2_positive_data; + if (op2->is_negative) { + LC_Bigint_negate(&op2_positive_data, op2); + op2_positive = &op2_positive_data; + } else { + op2_positive = op2; + } + + LC_Bigint_unsigned_division(op1_positive, op2_positive, NULL, dest); + dest->is_negative = op1->is_negative; + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_mod(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->is_negative) { + LC_BigInt first_rem; + LC_Bigint_rem(&first_rem, op1, op2); + first_rem.is_negative = !op2->is_negative; + LC_BigInt op2_minus_rem; + LC_Bigint_add(&op2_minus_rem, op2, &first_rem); + LC_Bigint_rem(dest, &op2_minus_rem, op2); + dest->is_negative = false; + } else { + LC_Bigint_rem(dest, op1, op2); + dest->is_negative = false; + } +} + +LC_FUNCTION void LC_Bigint_or(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->digit_count == 0) { + LC_Bigint_init_bigint(dest, op2); + return; + } + if (op2->digit_count == 0) { + LC_Bigint_init_bigint(dest, op1); + return; + } + if (op1->is_negative || op2->is_negative) { + size_t big_bit_count = LC_size_max(LC_Bigint_bits_needed(op1), LC_Bigint_bits_needed(op2)); + + LC_BigInt twos_comp_op1 = {0}; + LC_to_twos_complement(&twos_comp_op1, op1, big_bit_count); + + LC_BigInt twos_comp_op2 = {0}; + LC_to_twos_complement(&twos_comp_op2, op2, big_bit_count); + + LC_BigInt twos_comp_dest = {0}; + LC_Bigint_or(&twos_comp_dest, &twos_comp_op1, &twos_comp_op2); + + LC_from_twos_complement(dest, &twos_comp_dest, big_bit_count, true); + } else { + dest->is_negative = false; + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + if (op1->digit_count == 1 && op2->digit_count == 1) { + dest->digit_count = 1; + dest->digit = op1_digits[0] | op2_digits[0]; + LC_normalize(dest); + return; + } + dest->digit_count = LC_unsigned_max(op1->digit_count, op2->digit_count); + dest->digits = ALLOC_DIGITS(dest->digit_count); + for (size_t i = 0; i < dest->digit_count; i += 1) { + uint64_t digit = 0; + if (i < op1->digit_count) { + digit |= op1_digits[i]; + } + if (i < op2->digit_count) { + digit |= op2_digits[i]; + } + dest->digits[i] = digit; + } + LC_normalize(dest); + } +} + +LC_FUNCTION void LC_Bigint_and(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->digit_count == 0 || op2->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + if (op1->is_negative || op2->is_negative) { + size_t big_bit_count = LC_size_max(LC_Bigint_bits_needed(op1), LC_Bigint_bits_needed(op2)); + + LC_BigInt twos_comp_op1 = {0}; + LC_to_twos_complement(&twos_comp_op1, op1, big_bit_count); + + LC_BigInt twos_comp_op2 = {0}; + LC_to_twos_complement(&twos_comp_op2, op2, big_bit_count); + + LC_BigInt twos_comp_dest = {0}; + LC_Bigint_and(&twos_comp_dest, &twos_comp_op1, &twos_comp_op2); + + LC_from_twos_complement(dest, &twos_comp_dest, big_bit_count, true); + } else { + dest->is_negative = false; + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + if (op1->digit_count == 1 && op2->digit_count == 1) { + dest->digit_count = 1; + dest->digit = op1_digits[0] & op2_digits[0]; + LC_normalize(dest); + return; + } + + dest->digit_count = LC_unsigned_max(op1->digit_count, op2->digit_count); + dest->digits = ALLOC_DIGITS(dest->digit_count); + + size_t i = 0; + for (; i < op1->digit_count && i < op2->digit_count; i += 1) { + dest->digits[i] = op1_digits[i] & op2_digits[i]; + } + for (; i < dest->digit_count; i += 1) { + dest->digits[i] = 0; + } + LC_normalize(dest); + } +} + +LC_FUNCTION void LC_Bigint_xor(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->digit_count == 0) { + LC_Bigint_init_bigint(dest, op2); + return; + } + if (op2->digit_count == 0) { + LC_Bigint_init_bigint(dest, op1); + return; + } + if (op1->is_negative || op2->is_negative) { + size_t big_bit_count = LC_size_max(LC_Bigint_bits_needed(op1), LC_Bigint_bits_needed(op2)); + + LC_BigInt twos_comp_op1 = {0}; + LC_to_twos_complement(&twos_comp_op1, op1, big_bit_count); + + LC_BigInt twos_comp_op2 = {0}; + LC_to_twos_complement(&twos_comp_op2, op2, big_bit_count); + + LC_BigInt twos_comp_dest = {0}; + LC_Bigint_xor(&twos_comp_dest, &twos_comp_op1, &twos_comp_op2); + + LC_from_twos_complement(dest, &twos_comp_dest, big_bit_count, true); + } else { + dest->is_negative = false; + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + + LC_ASSERT(NULL, op1->digit_count > 0 && op2->digit_count > 0); + if (op1->digit_count == 1 && op2->digit_count == 1) { + dest->digit_count = 1; + dest->digit = op1_digits[0] ^ op2_digits[0]; + LC_normalize(dest); + return; + } + dest->digit_count = LC_unsigned_max(op1->digit_count, op2->digit_count); + dest->digits = ALLOC_DIGITS(dest->digit_count); + size_t i = 0; + for (; i < op1->digit_count && i < op2->digit_count; i += 1) { + dest->digits[i] = op1_digits[i] ^ op2_digits[i]; + } + for (; i < dest->digit_count; i += 1) { + if (i < op1->digit_count) { + dest->digits[i] = op1_digits[i]; + } else if (i < op2->digit_count) { + dest->digits[i] = op2_digits[i]; + } else { + LC_ASSERT(NULL, !"Unreachable"); + } + } + LC_normalize(dest); + } +} + +LC_FUNCTION void LC_Bigint_shl(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + LC_ASSERT(NULL, !op2->is_negative); + + if (op2->digit_count == 0) { + return; + } + if (op2->digit_count != 1) { + LC_ASSERT(NULL, !"Unsupported: shift left by amount greater than 64 bit integer"); + } + LC_Bigint_shl_int(dest, op1, LC_Bigint_as_unsigned(op2)); +} + +LC_FUNCTION void LC_Bigint_shl_int(LC_BigInt *dest, LC_BigInt *op1, uint64_t shift) { + if (shift == 0) { + LC_Bigint_init_bigint(dest, op1); + return; + } + + if (op1->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + + uint64_t *op1_digits = LC_Bigint_ptr(op1); + + if (op1->digit_count == 1 && shift < 64) { + dest->digit = op1_digits[0] << shift; + if (dest->digit > op1_digits[0]) { + dest->digit_count = 1; + dest->is_negative = op1->is_negative; + return; + } + } + + uint64_t digit_shift_count = shift / 64; + uint64_t leftover_shift_count = shift % 64; + + dest->digits = ALLOC_DIGITS(op1->digit_count + digit_shift_count + 1); + dest->digit_count = (unsigned)digit_shift_count; + uint64_t carry = 0; + for (size_t i = 0; i < op1->digit_count; i += 1) { + uint64_t digit = op1_digits[i]; + dest->digits[dest->digit_count] = carry | (digit << leftover_shift_count); + dest->digit_count++; + if (leftover_shift_count > 0) { + carry = digit >> (64 - leftover_shift_count); + } else { + carry = 0; + } + } + dest->digits[dest->digit_count] = carry; + dest->digit_count += 1; + dest->is_negative = op1->is_negative; + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_shl_trunc(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed) { + LC_BigInt unwrapped = {0}; + LC_Bigint_shl(&unwrapped, op1, op2); + LC_Bigint_truncate(dest, &unwrapped, bit_count, is_signed); +} + +LC_FUNCTION void LC_Bigint_shr(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + LC_ASSERT(NULL, !op2->is_negative); + + if (op1->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + + if (op2->digit_count == 0) { + LC_Bigint_init_bigint(dest, op1); + return; + } + + if (op2->digit_count != 1) { + LC_ASSERT(NULL, !"Unsupported: shift right by amount greater than 64 bit integer"); + } + + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t shift_amt = LC_Bigint_as_unsigned(op2); + + if (op1->digit_count == 1) { + dest->digit = shift_amt < 64 ? op1_digits[0] >> shift_amt : 0; + dest->digit_count = 1; + dest->is_negative = op1->is_negative; + LC_normalize(dest); + return; + } + + uint64_t digit_shift_count = shift_amt / 64; + uint64_t leftover_shift_count = shift_amt % 64; + + if (digit_shift_count >= op1->digit_count) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + + dest->digit_count = (unsigned)(op1->digit_count - digit_shift_count); + uint64_t *digits; + if (dest->digit_count == 1) { + digits = &dest->digit; + } else { + digits = ALLOC_DIGITS(dest->digit_count); + dest->digits = digits; + } + + uint64_t carry = 0; + for (size_t op_digit_index = op1->digit_count - 1;;) { + uint64_t digit = op1_digits[op_digit_index]; + size_t dest_digit_index = op_digit_index - digit_shift_count; + digits[dest_digit_index] = carry | (digit >> leftover_shift_count); + carry = digit << (64 - leftover_shift_count); + + if (dest_digit_index == 0) break; + op_digit_index -= 1; + } + dest->is_negative = op1->is_negative; + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_not(LC_BigInt *dest, LC_BigInt *op, size_t bit_count, bool is_signed) { + if (bit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + + if (is_signed) { + LC_BigInt twos_comp = {0}; + LC_to_twos_complement(&twos_comp, op, bit_count); + + LC_BigInt inverted = {0}; + LC_Bigint_not(&inverted, &twos_comp, bit_count, false); + + LC_from_twos_complement(dest, &inverted, bit_count, true); + return; + } + + LC_ASSERT(NULL, !op->is_negative); + + dest->is_negative = false; + uint64_t *op_digits = LC_Bigint_ptr(op); + if (bit_count <= 64) { + dest->digit_count = 1; + if (op->digit_count == 0) { + if (bit_count == 64) { + dest->digit = UINT64_MAX; + } else { + dest->digit = (1ULL << bit_count) - 1; + } + } else if (op->digit_count == 1) { + dest->digit = ~op_digits[0]; + if (bit_count != 64) { + uint64_t + mask = (1ULL << bit_count) - 1; + dest->digit &= mask; + } + } + LC_normalize(dest); + return; + } + dest->digit_count = (unsigned int)((bit_count + 63) / 64); + LC_ASSERT(NULL, dest->digit_count >= op->digit_count); + dest->digits = ALLOC_DIGITS(dest->digit_count); + size_t i = 0; + for (; i < op->digit_count; i += 1) { + dest->digits[i] = ~op_digits[i]; + } + for (; i < dest->digit_count; i += 1) { + dest->digits[i] = 0xffffffffffffffffULL; + } + size_t digit_index = dest->digit_count - 1; + size_t digit_bit_index = bit_count % 64; + if (digit_bit_index != 0) { + uint64_t + mask = (1ULL << digit_bit_index) - 1; + dest->digits[digit_index] &= mask; + } + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_truncate(LC_BigInt *dst, LC_BigInt *op, size_t bit_count, bool is_signed) { + LC_BigInt twos_comp; + LC_to_twos_complement(&twos_comp, op, bit_count); + LC_from_twos_complement(dst, &twos_comp, bit_count, is_signed); +} + +LC_FUNCTION LC_CmpRes LC_Bigint_cmp(LC_BigInt *op1, LC_BigInt *op2) { + if (op1->is_negative && !op2->is_negative) return LC_CmpRes_LT; + if (!op1->is_negative && op2->is_negative) return LC_CmpRes_GT; + if (op1->digit_count > op2->digit_count) return op1->is_negative ? LC_CmpRes_LT : LC_CmpRes_GT; + if (op2->digit_count > op1->digit_count) return op1->is_negative ? LC_CmpRes_GT : LC_CmpRes_LT; + if (op1->digit_count == 0) return LC_CmpRes_EQ; + + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + for (unsigned i = op1->digit_count - 1;; i--) { + uint64_t op1_digit = op1_digits[i]; + uint64_t op2_digit = op2_digits[i]; + + if (op1_digit > op2_digit) { + return op1->is_negative ? LC_CmpRes_LT : LC_CmpRes_GT; + } + if (op1_digit < op2_digit) { + return op1->is_negative ? LC_CmpRes_GT : LC_CmpRes_LT; + } + if (i == 0) { + return LC_CmpRes_EQ; + } + } +} + +LC_FUNCTION char *LC_Bigint_str(LC_BigInt *bigint, uint64_t base) { + LC_StringList out = {0}; + if (bigint->digit_count == 0) { + return "0"; + } + if (bigint->is_negative) { + LC_Addf(L->arena, &out, "-"); + } + if (bigint->digit_count == 1 && base == 10) { + LC_Addf(L->arena, &out, "%llu", (unsigned long long)bigint->digit); + } else { + size_t len = bigint->digit_count * 64; + char *start = (char *)malloc_arena(len); + char *buf = start; + + LC_BigInt digit_bi = {0}; + LC_BigInt a1 = {0}; + LC_BigInt a2 = {0}; + LC_BigInt base_bi = {0}; + LC_BigInt *a = &a1; + LC_BigInt *other_a = &a2; + + LC_Bigint_init_bigint(a, bigint); + LC_Bigint_init_unsigned(&base_bi, base); + + for (;;) { + LC_Bigint_rem(&digit_bi, a, &base_bi); + uint8_t digit = (uint8_t)LC_Bigint_as_unsigned(&digit_bi); + *(buf++) = LC_digit_to_char(digit, false); + LC_Bigint_div_trunc(other_a, a, &base_bi); + { + LC_BigInt *tmp = a; + a = other_a; + other_a = tmp; + } + if (LC_Bigint_cmp_zero(a) == LC_CmpRes_EQ) { + break; + } + } + + // reverse + + for (char *ptr = buf - 1; ptr >= start; ptr--) { + LC_Addf(L->arena, &out, "%c", *ptr); + } + } + LC_String s = LC_MergeString(L->arena, out); + return s.str; +} + +LC_FUNCTION int64_t LC_Bigint_as_signed(LC_BigInt *bigint) { + if (bigint->digit_count == 0) return 0; + if (bigint->digit_count != 1) { + LC_ASSERT(NULL, !"LC_BigInt larger than i64"); + } + + if (bigint->is_negative) { + // TODO this code path is untested + if (bigint->digit <= 9223372036854775808ULL) { + return (-((int64_t)(bigint->digit - 1))) - 1; + } + LC_ASSERT(NULL, !"LC_BigInt does not fit in i64"); + } + return (int64_t)bigint->digit; +} + +LC_FUNCTION LC_CmpRes LC_Bigint_cmp_zero(LC_BigInt *op) { + if (op->digit_count == 0) { + return LC_CmpRes_EQ; + } + return op->is_negative ? LC_CmpRes_LT : LC_CmpRes_GT; +} + +LC_FUNCTION double LC_Bigint_as_float(LC_BigInt *bigint) { + if (LC_Bigint_fits_in_bits(bigint, 64, bigint->is_negative)) { + return bigint->is_negative ? (double)LC_Bigint_as_signed(bigint) : (double)LC_Bigint_as_unsigned(bigint); + } + LC_BigInt div; + uint64_t mult = 0x100000000000ULL; + double mul = 1; + LC_Bigint_init_unsigned(&div, mult); + LC_BigInt current; + LC_Bigint_init_bigint(¤t, bigint); + double f = 0; + do { + LC_BigInt temp; + LC_Bigint_mod(&temp, ¤t, &div); + f += LC_Bigint_as_signed(&temp) * mul; + mul *= mult; + LC_Bigint_div_trunc(&temp, ¤t, &div); + current = temp; + } while (current.digit_count > 0); + return f; +} +LC_Operand LC_OPNull; + +LC_FUNCTION LC_Operand LC_OPError(void) { + LC_Operand result = {LC_OPF_Error}; + return result; +} + +LC_FUNCTION LC_Operand LC_OPConstType(LC_Type *type) { + LC_Operand result = {LC_OPF_UTConst | LC_OPF_Const}; + result.type = type; + return result; +} + +LC_FUNCTION LC_Operand LC_OPDecl(LC_Decl *decl) { + LC_Operand result = {0}; + result.decl = decl; + return result; +} + +LC_FUNCTION LC_Operand LC_OPType(LC_Type *type) { + LC_Operand result = {0}; + result.type = type; + return result; +} + +LC_FUNCTION LC_Operand LC_OPLValueAndType(LC_Type *type) { + LC_Operand result = LC_OPType(type); + result.flags = LC_OPF_LValue; + return result; +} + +LC_FUNCTION LC_Operand LC_ReportASTError(LC_AST *n, const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + LC_SendErrorMessage(n ? n->pos : NULL, s8); + L->errors += 1; + return LC_OPError(); +} + +LC_FUNCTION LC_Operand LC_ReportASTErrorEx(LC_AST *n1, LC_AST *n2, const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + LC_SendErrorMessage(n1->pos, s8); + LC_SendErrorMessage(n2->pos, s8); + L->errors += 1; + return LC_OPError(); +} + +LC_FUNCTION LC_Operand LC_ConstCastFloat(LC_AST *pos, LC_Operand op) { + LC_ASSERT(pos, LC_IsUTConst(op)); + LC_ASSERT(pos, LC_IsUntyped(op.type)); + if (LC_IsUTInt(op.type)) op.val.d = LC_Bigint_as_float(&op.val.i); + if (LC_IsUTStr(op.type)) return LC_ReportASTError(pos, "Trying to convert '%s' to float", LC_GenLCType(op.type)); + op.type = L->tuntypedfloat; + return op; +} + +LC_FUNCTION LC_Operand LC_ConstCastInt(LC_AST *pos, LC_Operand op) { + LC_ASSERT(pos, LC_IsUTConst(op)); + LC_ASSERT(pos, LC_IsUntyped(op.type)); + if (LC_IsUTFloat(op.type)) { + double v = op.val.d; // add rounding? + LC_Bigint_init_signed(&op.val.i, (int64_t)v); + } + if (LC_IsUTStr(op.type)) return LC_ReportASTError(pos, "Trying to convert %s to int", LC_GenLCType(op.type)); + op.type = L->tuntypedint; + return op; +} + +LC_FUNCTION LC_Operand LC_OPInt(int64_t v) { + LC_Operand op = {0}; + op.type = L->tuntypedint; + op.flags |= LC_OPF_UTConst | LC_OPF_Const; + LC_Bigint_init_signed(&op.v.i, v); + return op; +} + +LC_FUNCTION LC_Operand LC_OPIntT(LC_Type *type, int64_t v) { + LC_ASSERT(NULL, LC_IsInt(type)); + LC_Operand op = LC_OPInt(v); + op.type = type; + return op; +} + +LC_FUNCTION LC_Operand LC_OPModDefaultUT(LC_Operand val) { + if (LC_IsUntyped(val.type)) { + val.type = val.type->tbase; + } + return val; +} + +LC_FUNCTION LC_Operand LC_OPModType(LC_Operand op, LC_Type *type) { + if (LC_IsUTConst(op)) { + if (LC_IsUTInt(op.type) && LC_IsFloat(type)) { + op = LC_ConstCastFloat(NULL, op); + } + } + op.type = type; + return op; +} + +LC_FUNCTION LC_Operand LC_OPModBool(LC_Operand op) { + op.type = L->tuntypedbool; + return op; +} + +LC_FUNCTION LC_Operand LC_OPModBoolV(LC_Operand op, int v) { + op.type = L->tuntypedbool; + LC_Bigint_init_signed(&op.v.i, v); + return op; +} + +LC_FUNCTION LC_Operand LC_EvalBinary(LC_AST *pos, LC_Operand a, LC_TokenKind op, LC_Operand b) { + LC_ASSERT(pos, LC_IsUTConst(a)); + LC_ASSERT(pos, LC_IsUTConst(b)); + LC_ASSERT(pos, LC_IsUntyped(a.type)); + LC_ASSERT(pos, LC_IsUntyped(b.type)); + LC_ASSERT(pos, a.type->kind == b.type->kind); + + LC_Operand c = LC_OPConstType(a.type); + if (LC_IsUTStr(a.type)) { + return LC_ReportASTError(pos, "invalid operand %s for binary expr of type untyped string", LC_TokenKindToString(op)); + } + if (LC_IsUTFloat(a.type)) { + switch (op) { + case LC_TokenKind_Add: c.v.d = a.v.d + b.v.d; break; + case LC_TokenKind_Sub: c.v.d = a.v.d - b.v.d; break; + case LC_TokenKind_Mul: c.v.d = a.v.d * b.v.d; break; + case LC_TokenKind_Div: { + if (b.v.d == 0.0) return LC_ReportASTError(pos, "division by 0"); + c.v.d = a.v.d / b.v.d; + } break; + case LC_TokenKind_LesserThenEq: c = LC_OPModBoolV(c, a.v.d <= b.v.d); break; + case LC_TokenKind_GreaterThenEq: c = LC_OPModBoolV(c, a.v.d >= b.v.d); break; + case LC_TokenKind_GreaterThen: c = LC_OPModBoolV(c, a.v.d > b.v.d); break; + case LC_TokenKind_LesserThen: c = LC_OPModBoolV(c, a.v.d < b.v.d); break; + case LC_TokenKind_Equals: c = LC_OPModBoolV(c, a.v.d == b.v.d); break; + case LC_TokenKind_NotEquals: c = LC_OPModBoolV(c, a.v.d != b.v.d); break; + default: return LC_ReportASTError(pos, "invalid operand %s for binary expr of type untyped float", LC_TokenKindToString(op)); + } + } + if (LC_IsUTInt(a.type)) { + switch (op) { + case LC_TokenKind_BitXor: LC_Bigint_xor(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_BitAnd: LC_Bigint_and(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_BitOr: LC_Bigint_or(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_Add: LC_Bigint_add(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_Sub: LC_Bigint_sub(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_Mul: LC_Bigint_mul(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_Div: { + if (b.v.i.digit_count == 0) return LC_ReportASTError(pos, "division by zero in constant expression"); + LC_Bigint_div_floor(&c.v.i, &a.v.i, &b.v.i); + } break; + case LC_TokenKind_Mod: { + if (b.v.i.digit_count == 0) return LC_ReportASTError(pos, "modulo by zero in constant expression"); + LC_Bigint_mod(&c.v.i, &a.v.i, &b.v.i); + } break; + case LC_TokenKind_LeftShift: LC_Bigint_shl(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_RightShift: LC_Bigint_shr(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_And: { + int left = LC_Bigint_cmp_zero(&a.v.i) != LC_CmpRes_EQ; + int right = LC_Bigint_cmp_zero(&b.v.i) != LC_CmpRes_EQ; + c = LC_OPModBoolV(c, left && right); + } break; + case LC_TokenKind_Or: { + int left = LC_Bigint_cmp_zero(&a.v.i) != LC_CmpRes_EQ; + int right = LC_Bigint_cmp_zero(&b.v.i) != LC_CmpRes_EQ; + c = LC_OPModBoolV(c, left || right); + } break; + default: { + LC_CmpRes cmp = LC_Bigint_cmp(&a.v.i, &b.v.i); + switch (op) { + case LC_TokenKind_LesserThenEq: c = LC_OPModBoolV(c, (cmp == LC_CmpRes_LT) || (cmp == LC_CmpRes_EQ)); break; + case LC_TokenKind_GreaterThenEq: c = LC_OPModBoolV(c, (cmp == LC_CmpRes_GT) || (cmp == LC_CmpRes_EQ)); break; + case LC_TokenKind_GreaterThen: c = LC_OPModBoolV(c, cmp == LC_CmpRes_GT); break; + case LC_TokenKind_LesserThen: c = LC_OPModBoolV(c, cmp == LC_CmpRes_LT); break; + case LC_TokenKind_Equals: c = LC_OPModBoolV(c, cmp == LC_CmpRes_EQ); break; + case LC_TokenKind_NotEquals: c = LC_OPModBoolV(c, cmp != LC_CmpRes_EQ); break; + default: return LC_ReportASTError(pos, "invalid operand %s for binary expr of type untyped int", LC_TokenKindToString(op)); + } + } + } + } + + return c; +} + +LC_FUNCTION LC_Operand LC_EvalUnary(LC_AST *pos, LC_TokenKind op, LC_Operand a) { + LC_ASSERT(pos, LC_IsUTConst(a)); + LC_ASSERT(pos, LC_IsUntyped(a.type)); + LC_Operand c = a; + + if (LC_IsUTStr(a.type)) { + return LC_ReportASTError(pos, "invalid operand %s for unary expr of type untyped string", LC_TokenKindToString(op)); + } + if (LC_IsUTFloat(a.type)) { + switch (op) { + case LC_TokenKind_Sub: c.v.d = -a.v.d; break; + case LC_TokenKind_Add: c.v.d = +a.v.d; break; + default: return LC_ReportASTError(pos, "invalid operand %s for unary expr of type untyped float", LC_TokenKindToString(op)); + } + } + if (LC_IsUTInt(a.type)) { + switch (op) { + case LC_TokenKind_Not: c = LC_OPModBoolV(c, LC_Bigint_cmp_zero(&a.v.i) == LC_CmpRes_EQ); break; + case LC_TokenKind_Sub: LC_Bigint_negate(&c.v.i, &a.v.i); break; + case LC_TokenKind_Add: c = a; break; + case LC_TokenKind_Neg: LC_Bigint_not(&c.v.i, &a.v.i, a.type->tbase->size * 8, !a.type->tbase->is_unsigned); break; + default: return LC_ReportASTError(pos, "invalid operand %s for unary expr of type untyped int", LC_TokenKindToString(op)); + } + } + + return c; +} + +LC_FUNCTION bool LC_BigIntFits(LC_BigInt i, LC_Type *type) { + LC_ASSERT(NULL, LC_IsInt(type)); + if (!LC_Bigint_fits_in_bits(&i, type->size * 8, !type->is_unsigned)) { + return false; + } + return true; +} + +LC_FUNCTION LC_OPResult LC_IsBinaryExprValidForType(LC_TokenKind op, LC_Type *type) { + if (LC_IsFloat(type)) { + switch (op) { + case LC_TokenKind_Add: return LC_OPResult_Ok; break; + case LC_TokenKind_Sub: return LC_OPResult_Ok; break; + case LC_TokenKind_Mul: return LC_OPResult_Ok; break; + case LC_TokenKind_Div: return LC_OPResult_Ok; break; + case LC_TokenKind_LesserThenEq: return LC_OPResult_Bool; break; + case LC_TokenKind_GreaterThenEq: return LC_OPResult_Bool; break; + case LC_TokenKind_GreaterThen: return LC_OPResult_Bool; break; + case LC_TokenKind_LesserThen: return LC_OPResult_Bool; break; + case LC_TokenKind_Equals: return LC_OPResult_Bool; break; + case LC_TokenKind_NotEquals: return LC_OPResult_Bool; break; + default: return LC_OPResult_Error; + } + } + if (LC_IsInt(type)) { + switch (op) { + case LC_TokenKind_BitXor: return LC_OPResult_Ok; break; + case LC_TokenKind_BitAnd: return LC_OPResult_Ok; break; + case LC_TokenKind_BitOr: return LC_OPResult_Ok; break; + case LC_TokenKind_Add: return LC_OPResult_Ok; break; + case LC_TokenKind_Sub: return LC_OPResult_Ok; break; + case LC_TokenKind_Mul: return LC_OPResult_Ok; break; + case LC_TokenKind_Div: return LC_OPResult_Ok; break; + case LC_TokenKind_Mod: return LC_OPResult_Ok; break; + case LC_TokenKind_LeftShift: return LC_OPResult_Ok; break; + case LC_TokenKind_RightShift: return LC_OPResult_Ok; break; + case LC_TokenKind_And: return LC_OPResult_Bool; break; + case LC_TokenKind_Or: return LC_OPResult_Bool; break; + case LC_TokenKind_LesserThenEq: return LC_OPResult_Bool; break; + case LC_TokenKind_GreaterThenEq: return LC_OPResult_Bool; break; + case LC_TokenKind_GreaterThen: return LC_OPResult_Bool; break; + case LC_TokenKind_LesserThen: return LC_OPResult_Bool; break; + case LC_TokenKind_Equals: return LC_OPResult_Bool; break; + case LC_TokenKind_NotEquals: return LC_OPResult_Bool; break; + default: return LC_OPResult_Error; + } + } + if (LC_IsPtrLike(type)) { + switch (op) { + case LC_TokenKind_And: return LC_OPResult_Bool; break; + case LC_TokenKind_Or: return LC_OPResult_Bool; break; + case LC_TokenKind_LesserThenEq: return LC_OPResult_Bool; break; + case LC_TokenKind_GreaterThenEq: return LC_OPResult_Bool; break; + case LC_TokenKind_GreaterThen: return LC_OPResult_Bool; break; + case LC_TokenKind_LesserThen: return LC_OPResult_Bool; break; + case LC_TokenKind_Equals: return LC_OPResult_Bool; break; + case LC_TokenKind_NotEquals: return LC_OPResult_Bool; break; + default: return LC_OPResult_Error; + } + } + + return LC_OPResult_Error; +} + +LC_FUNCTION LC_OPResult LC_IsUnaryOpValidForType(LC_TokenKind op, LC_Type *type) { + if (LC_IsFloat(type)) { + if (op == LC_TokenKind_Sub) return LC_OPResult_Ok; + if (op == LC_TokenKind_Add) return LC_OPResult_Ok; + } + if (LC_IsInt(type)) { + if (op == LC_TokenKind_Not) return LC_OPResult_Bool; + if (op == LC_TokenKind_Sub) return LC_OPResult_Ok; + if (op == LC_TokenKind_Add) return LC_OPResult_Ok; + if (op == LC_TokenKind_Neg) return LC_OPResult_Ok; + } + if (LC_IsPtrLike(type)) { + if (op == LC_TokenKind_Not) return LC_OPResult_Bool; + } + return LC_OPResult_Error; +} + +LC_FUNCTION LC_OPResult LC_IsAssignValidForType(LC_TokenKind op, LC_Type *type) { + if (op == LC_TokenKind_Assign) return LC_OPResult_Ok; + if (LC_IsInt(type)) { + switch (op) { + case LC_TokenKind_DivAssign: return LC_OPResult_Ok; + case LC_TokenKind_MulAssign: return LC_OPResult_Ok; + case LC_TokenKind_ModAssign: return LC_OPResult_Ok; + case LC_TokenKind_SubAssign: return LC_OPResult_Ok; + case LC_TokenKind_AddAssign: return LC_OPResult_Ok; + case LC_TokenKind_BitAndAssign: return LC_OPResult_Ok; + case LC_TokenKind_BitOrAssign: return LC_OPResult_Ok; + case LC_TokenKind_BitXorAssign: return LC_OPResult_Ok; + case LC_TokenKind_LeftShiftAssign: return LC_OPResult_Ok; + case LC_TokenKind_RightShiftAssign: return LC_OPResult_Ok; + default: return LC_OPResult_Error; + } + } + if (LC_IsFloat(type)) { + switch (op) { + case LC_TokenKind_DivAssign: return LC_OPResult_Ok; + case LC_TokenKind_MulAssign: return LC_OPResult_Ok; + case LC_TokenKind_SubAssign: return LC_OPResult_Ok; + case LC_TokenKind_AddAssign: return LC_OPResult_Ok; + default: return LC_OPResult_Error; + } + } + return LC_OPResult_Error; +} + +LC_FUNCTION int LC_GetLevelsOfIndirection(LC_Type *type) { + if (type->kind == LC_TypeKind_Pointer) return LC_GetLevelsOfIndirection(type->tbase) + 1; + if (type->kind == LC_TypeKind_Array) return LC_GetLevelsOfIndirection(type->tbase) + 1; + return 0; +} + +LC_FUNCTION LC_AST *LC_CreateAST(LC_Token *pos, LC_ASTKind kind) { + LC_AST *n = LC_PushStruct(L->ast_arena, LC_AST); + n->id = ++L->ast_count; + n->kind = kind; + n->pos = pos; + if (L->parser == &L->quick_parser) n->pos = &L->BuiltinToken; + return n; +} + +LC_FUNCTION LC_AST *LC_CreateUnary(LC_Token *pos, LC_TokenKind op, LC_AST *expr) { + LC_AST *r = LC_CreateAST(pos, LC_ASTKind_ExprUnary); + r->eunary.op = op; + r->eunary.expr = expr; + return r; +} + +LC_FUNCTION LC_AST *LC_CreateBinary(LC_Token *pos, LC_AST *left, LC_AST *right, LC_TokenKind op) { + LC_AST *r = LC_CreateAST(pos, LC_ASTKind_ExprBinary); + r->ebinary.op = op; + r->ebinary.left = left; + r->ebinary.right = right; + return r; +} + +LC_FUNCTION LC_AST *LC_CreateIndex(LC_Token *pos, LC_AST *left, LC_AST *index) { + LC_AST *r = LC_CreateAST(pos, LC_ASTKind_ExprIndex); + r->eindex.index = index; + r->eindex.base = left; + return r; +} + +LC_FUNCTION void LC_SetPointerSizeAndAlign(int size, int align) { + L->pointer_align = align; + L->pointer_size = size; + if (L->tpvoid) { + L->tpvoid->size = size; + L->tpvoid->align = align; + } + if (L->tpchar) { + L->tpchar->size = size; + L->tpchar->align = align; + } +} + +LC_FUNCTION LC_Type *LC_CreateType(LC_TypeKind kind) { + LC_Type *r = LC_PushStruct(L->type_arena, LC_Type); + L->type_count += 1; + r->kind = kind; + r->id = ++L->typeids; + if (r->kind == LC_TypeKind_Proc || r->kind == LC_TypeKind_Pointer) { + r->size = L->pointer_size; + r->align = L->pointer_align; + r->is_unsigned = true; + } + return r; +} + +LC_FUNCTION LC_Type *LC_CreateTypedef(LC_Decl *decl, LC_Type *base) { + LC_Type *n = LC_CreateType(base->kind); + *n = *base; + decl->typedef_renamed_type_decl = base->decl; + n->decl = decl; + return n; +} + +LC_FUNCTION LC_Type *LC_CreatePointerType(LC_Type *type) { + uint64_t key = (uint64_t)type; + LC_Type *entry = (LC_Type *)LC_MapGetU64(&L->type_map, key); + if (entry) { + return entry; + } + LC_Type *n = LC_CreateType(LC_TypeKind_Pointer); + n->tbase = type; + LC_MapInsertU64(&L->type_map, key, n); + return n; +} + +LC_FUNCTION LC_Type *LC_CreateArrayType(LC_Type *type, int size) { + uint64_t size_key = LC_HashBytes(&size, sizeof(size)); + uint64_t type_key = LC_HashBytes(type, sizeof(*type)); + uint64_t key = LC_HashMix(size_key, type_key); + LC_Type *entry = (LC_Type *)LC_MapGetU64(&L->type_map, key); + if (entry) { + return entry; + } + LC_Type *n = LC_CreateType(LC_TypeKind_Array); + n->tbase = type; + n->tarray.size = size; + n->size = type->size * size; + n->align = type->align; + LC_MapInsertU64(&L->type_map, key, n); + return n; +} + +LC_FUNCTION LC_Type *LC_CreateProcType(LC_TypeMemberList args, LC_Type *ret, bool has_vargs, bool has_vargs_any_promotion) { + LC_ASSERT(NULL, ret); + uint64_t key = LC_HashBytes(ret, sizeof(*ret)); + key = LC_HashMix(key, LC_HashBytes(&has_vargs, sizeof(has_vargs))); + key = LC_HashMix(key, LC_HashBytes(&has_vargs_any_promotion, sizeof(has_vargs_any_promotion))); + int procarg_count = 0; + LC_TypeFor(it, args.first) { + key = LC_HashMix(LC_HashBytes(it->type, sizeof(it->type[0])), key); + key = LC_HashMix(LC_HashBytes((char *)it->name, LC_StrLen((char *)it->name)), key); + if (it->default_value_expr) { + key = LC_HashMix(LC_HashBytes(&it->default_value_expr, sizeof(LC_AST *)), key); + } + procarg_count += 1; + } + LC_Type *n = (LC_Type *)LC_MapGetU64(&L->type_map, key); + if (n) return n; + + n = LC_CreateType(LC_TypeKind_Proc); + n->tproc.args = args; + n->tproc.vargs = has_vargs; + n->tproc.vargs_any_promotion = has_vargs_any_promotion; + n->tproc.ret = ret; + LC_MapInsertU64(&L->type_map, key, n); + return n; +} + +LC_FUNCTION LC_Type *LC_CreateIncompleteType(LC_Decl *decl) { + LC_Type *n = LC_CreateType(LC_TypeKind_Incomplete); + n->decl = decl; + return n; +} + +LC_FUNCTION LC_Type *LC_CreateUntypedIntEx(LC_Type *base, LC_Decl *decl) { + uint64_t hash_base = LC_HashBytes(base, sizeof(*base)); + uint64_t untyped_int = LC_TypeKind_UntypedInt; + uint64_t key = LC_HashMix(hash_base, untyped_int); + LC_Type *n = (LC_Type *)LC_MapGetU64(&L->type_map, key); + if (n) return n; + + n = LC_CreateType(LC_TypeKind_UntypedInt); + n->tbase = base; + n->decl = decl; + return n; +} + +LC_FUNCTION LC_Type *LC_CreateUntypedInt(LC_Type *base) { + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Type, LC_ILit("UntypedInt"), &L->NullAST); + LC_Type *n = LC_CreateUntypedIntEx(base, decl); + return n; +} + +LC_FUNCTION LC_TypeMember *LC_AddTypeToList(LC_TypeMemberList *list, LC_Intern name, LC_Type *type, LC_AST *ast) { + LC_TypeFor(it, list->first) { + if (name == it->name) { + return NULL; + } + } + + LC_TypeMember *r = LC_PushStruct(L->arena, LC_TypeMember); + r->name = name; + r->type = type; + r->ast = ast; + LC_DLLAdd(list->first, list->last, r); + list->count += 1; + return r; +} + +LC_FUNCTION LC_Type *LC_StripPointer(LC_Type *type) { + if (type->kind == LC_TypeKind_Pointer) { + return type->tbase; + } + return type; +} + +LC_FUNCTION void LC_ReserveAST(LC_ASTArray *stack, int size) { + if (size > stack->cap) { + LC_AST **new_stack = LC_PushArray(stack->arena, LC_AST *, size); + + LC_MemoryCopy(new_stack, stack->data, stack->len * sizeof(LC_AST *)); + stack->data = new_stack; + stack->cap = size; + } +} + +LC_FUNCTION void LC_PushAST(LC_ASTArray *stack, LC_AST *ast) { + LC_ASSERT(NULL, stack->len <= stack->cap); + LC_ASSERT(NULL, stack->arena); + if (stack->len == stack->cap) { + int new_cap = stack->cap < 16 ? 16 : stack->cap * 2; + LC_AST **new_stack = LC_PushArray(stack->arena, LC_AST *, new_cap); + + LC_MemoryCopy(new_stack, stack->data, stack->len * sizeof(LC_AST *)); + stack->data = new_stack; + stack->cap = new_cap; + } + stack->data[stack->len++] = ast; +} + +LC_FUNCTION void LC_PopAST(LC_ASTArray *stack) { + LC_ASSERT(NULL, stack->arena); + LC_ASSERT(NULL, stack->len > 0); + stack->len -= 1; +} + +LC_FUNCTION LC_AST *LC_GetLastAST(LC_ASTArray *arr) { + LC_ASSERT(NULL, arr->len > 0); + LC_AST *result = arr->data[arr->len - 1]; + return result; +} + +LC_FUNCTION void LC_WalkAST(LC_ASTWalker *ctx, LC_AST *n) { + if (!ctx->depth_first) { + ctx->proc(ctx, n); + } + + if (ctx->dont_recurse) { + ctx->dont_recurse = false; + return; + } + + LC_PushAST(&ctx->stack, n); + switch (n->kind) { + case LC_ASTKind_TypespecIdent: + case LC_ASTKind_ExprIdent: + case LC_ASTKind_ExprString: + case LC_ASTKind_ExprInt: + case LC_ASTKind_ExprFloat: + case LC_ASTKind_GlobImport: + case LC_ASTKind_ExprBool: + case LC_ASTKind_StmtBreak: + case LC_ASTKind_StmtContinue: break; + + case LC_ASTKind_Package: { + LC_ASTFor(it, n->apackage.ffile) LC_WalkAST(ctx, it); + + ctx->inside_discarded += 1; + if (ctx->visit_discarded) LC_ASTFor(it, n->apackage.fdiscarded) LC_WalkAST(ctx, it); + ctx->inside_discarded -= 1; + } break; + + case LC_ASTKind_File: { + LC_ASTFor(it, n->afile.fimport) LC_WalkAST(ctx, it); + LC_ASTFor(it, n->afile.fdecl) { + if (ctx->visit_notes == false && it->kind == LC_ASTKind_DeclNote) continue; + LC_WalkAST(ctx, it); + } + + ctx->inside_discarded += 1; + if (ctx->visit_discarded) LC_ASTFor(it, n->afile.fdiscarded) LC_WalkAST(ctx, it); + ctx->inside_discarded -= 1; + } break; + + case LC_ASTKind_DeclProc: { + LC_WalkAST(ctx, n->dproc.type); + if (n->dproc.body) LC_WalkAST(ctx, n->dproc.body); + } break; + case LC_ASTKind_NoteList: { + if (ctx->visit_notes) LC_ASTFor(it, n->anote_list.first) LC_WalkAST(ctx, it); + } break; + case LC_ASTKind_TypespecProcArg: { + LC_WalkAST(ctx, n->tproc_arg.type); + if (n->tproc_arg.expr) LC_WalkAST(ctx, n->tproc_arg.expr); + } break; + case LC_ASTKind_TypespecAggMem: { + LC_WalkAST(ctx, n->tproc_arg.type); + } break; + + case LC_ASTKind_ExprNote: { + ctx->inside_note += 1; + if (ctx->visit_notes) LC_WalkAST(ctx, n->enote.expr); + ctx->inside_note -= 1; + } break; + + case LC_ASTKind_StmtSwitch: { + LC_WalkAST(ctx, n->sswitch.expr); + LC_ASTFor(it, n->sswitch.first) LC_WalkAST(ctx, it); + } break; + + case LC_ASTKind_StmtSwitchCase: { + LC_ASTFor(it, n->scase.first) LC_WalkAST(ctx, it); + LC_WalkAST(ctx, n->scase.body); + } break; + case LC_ASTKind_StmtSwitchDefault: { + LC_ASTFor(it, n->scase.first) LC_WalkAST(ctx, it); + LC_WalkAST(ctx, n->scase.body); + } break; + + case LC_ASTKind_StmtIf: { + LC_WalkAST(ctx, n->sif.expr); + LC_WalkAST(ctx, n->sif.body); + LC_ASTFor(it, n->sif.first) LC_WalkAST(ctx, it); + } break; + case LC_ASTKind_StmtElse: + case LC_ASTKind_StmtElseIf: { + if (n->sif.expr) LC_WalkAST(ctx, n->sif.expr); + LC_WalkAST(ctx, n->sif.body); + } break; + + case LC_ASTKind_DeclNote: { + ctx->inside_note += 1; + if (ctx->visit_notes) LC_WalkAST(ctx, n->dnote.expr); + ctx->inside_note -= 1; + } break; + case LC_ASTKind_DeclUnion: + case LC_ASTKind_DeclStruct: { + LC_ASTFor(it, n->dagg.first) LC_WalkAST(ctx, it); + } break; + + case LC_ASTKind_DeclVar: { + if (n->dvar.type) LC_WalkAST(ctx, n->dvar.type); + if (n->dvar.expr) LC_WalkAST(ctx, n->dvar.expr); + } break; + case LC_ASTKind_DeclConst: { + if (n->dconst.expr) LC_WalkAST(ctx, n->dconst.expr); + } break; + case LC_ASTKind_DeclTypedef: { + LC_WalkAST(ctx, n->dtypedef.type); + } break; + case LC_ASTKind_TypespecField: { + LC_WalkAST(ctx, n->efield.left); + } break; + + case LC_ASTKind_TypespecPointer: { + LC_WalkAST(ctx, n->tpointer.base); + } break; + case LC_ASTKind_TypespecArray: { + LC_WalkAST(ctx, n->tarray.base); + if (n->tarray.index) LC_WalkAST(ctx, n->tarray.index); + } break; + case LC_ASTKind_TypespecProc: { + LC_ASTFor(it, n->tproc.first) LC_WalkAST(ctx, it); + if (n->tproc.ret) LC_WalkAST(ctx, n->tproc.ret); + } break; + case LC_ASTKind_StmtBlock: { + LC_ASTFor(it, n->sblock.first) LC_WalkAST(ctx, it); + // hmm should we inline defers or maybe remove them from + // the stmt list? + // LC_ASTFor(it, n->sblock.first_defer) LC_WalkAST(ctx, it); + } break; + + case LC_ASTKind_StmtNote: { + ctx->inside_note += 1; + if (ctx->visit_notes) LC_WalkAST(ctx, n->snote.expr); + ctx->inside_note -= 1; + } break; + case LC_ASTKind_StmtReturn: { + if (n->sreturn.expr) LC_WalkAST(ctx, n->sreturn.expr); + } break; + + case LC_ASTKind_StmtDefer: { + LC_WalkAST(ctx, n->sdefer.body); + } break; + case LC_ASTKind_StmtFor: { + if (n->sfor.init) LC_WalkAST(ctx, n->sfor.init); + if (n->sfor.cond) LC_WalkAST(ctx, n->sfor.cond); + if (n->sfor.inc) LC_WalkAST(ctx, n->sfor.inc); + LC_WalkAST(ctx, n->sfor.body); + } break; + + case LC_ASTKind_StmtAssign: { + LC_WalkAST(ctx, n->sassign.left); + LC_WalkAST(ctx, n->sassign.right); + } break; + case LC_ASTKind_StmtExpr: { + LC_WalkAST(ctx, n->sexpr.expr); + } break; + case LC_ASTKind_StmtVar: { + if (n->svar.type) LC_WalkAST(ctx, n->svar.type); + if (n->svar.expr) LC_WalkAST(ctx, n->svar.expr); + } break; + case LC_ASTKind_StmtConst: { + LC_WalkAST(ctx, n->sconst.expr); + } break; + + case LC_ASTKind_ExprType: { + LC_WalkAST(ctx, n->etype.type); + } break; + case LC_ASTKind_ExprAddPtr: + case LC_ASTKind_ExprBinary: { + LC_WalkAST(ctx, n->ebinary.left); + LC_WalkAST(ctx, n->ebinary.right); + } break; + case LC_ASTKind_ExprGetPointerOfValue: + case LC_ASTKind_ExprGetValueOfPointer: + case LC_ASTKind_ExprUnary: { + LC_WalkAST(ctx, n->eunary.expr); + } break; + case LC_ASTKind_ExprCompoundItem: + case LC_ASTKind_ExprCallItem: { + if (n->ecompo_item.index) LC_WalkAST(ctx, n->ecompo_item.index); + LC_WalkAST(ctx, n->ecompo_item.expr); + } break; + case LC_ASTKind_Note: { + ctx->inside_note += 1; + if (n->ecompo.name) LC_WalkAST(ctx, n->ecompo.name); + LC_ASTFor(it, n->ecompo.first) LC_WalkAST(ctx, it); + ctx->inside_note -= 1; + } break; + case LC_ASTKind_ExprBuiltin: { + ctx->inside_builtin += 1; + if (n->ecompo.name) LC_WalkAST(ctx, n->ecompo.name); + LC_ASTFor(it, n->ecompo.first) LC_WalkAST(ctx, it); + ctx->inside_builtin -= 1; + } break; + case LC_ASTKind_ExprCall: + case LC_ASTKind_ExprCompound: { + if (n->ecompo.name) LC_WalkAST(ctx, n->ecompo.name); + LC_ASTFor(it, n->ecompo.first) LC_WalkAST(ctx, it); + } break; + case LC_ASTKind_ExprCast: { + LC_WalkAST(ctx, n->ecast.type); + LC_WalkAST(ctx, n->ecast.expr); + } break; + case LC_ASTKind_ExprField: { + LC_WalkAST(ctx, n->efield.left); + } break; + case LC_ASTKind_ExprIndex: { + LC_WalkAST(ctx, n->eindex.index); + LC_WalkAST(ctx, n->eindex.base); + } break; + + case LC_ASTKind_Ignore: + case LC_ASTKind_Error: + default: LC_ReportASTError(n, "internal compiler error: got invalid ast kind during ast walk: %s", LC_ASTKindToString(n->kind)); + } + + if (ctx->visit_notes && n->notes) { + LC_WalkAST(ctx, n->notes); + } + LC_PopAST(&ctx->stack); + + if (ctx->depth_first) { + ctx->proc(ctx, n); + } +} + +LC_FUNCTION LC_ASTWalker LC_GetDefaultWalker(LC_Arena *arena, LC_ASTWalkProc *proc) { + LC_ASTWalker result = {0}; + result.stack.arena = arena; + result.proc = proc; + result.depth_first = true; + return result; +} + +LC_FUNCTION void WalkAndFlattenAST(LC_ASTWalker *ctx, LC_AST *n) { + LC_ASTArray *array = (LC_ASTArray *)ctx->user_data; + LC_PushAST(array, n); +} + +LC_FUNCTION LC_ASTArray LC_FlattenAST(LC_Arena *arena, LC_AST *n) { + LC_ASTArray array = {arena}; + LC_ASTWalker walker = LC_GetDefaultWalker(arena, WalkAndFlattenAST); + walker.user_data = (void *)&array; + LC_WalkAST(&walker, n); + return array; +} + +LC_FUNCTION void WalkToFindSizeofLike(LC_ASTWalker *w, LC_AST *n) { + if (n->kind == LC_ASTKind_ExprBuiltin) { + LC_ASSERT(n, n->ecompo.name->kind == LC_ASTKind_ExprIdent); + if (n->ecompo.name->eident.name == L->isizeof || n->ecompo.name->eident.name == L->ialignof || n->ecompo.name->eident.name == L->ioffsetof) { + ((bool *)w->user_data)[0] = true; + } + } +} + +LC_FUNCTION bool LC_ContainsCBuiltin(LC_AST *n) { + LC_TempArena checkpoint = LC_BeginTemp(L->arena); + bool found = false; + { + LC_ASTWalker walker = LC_GetDefaultWalker(L->arena, WalkToFindSizeofLike); + walker.depth_first = false; + walker.user_data = (void *)&found; + LC_WalkAST(&walker, n); + } + LC_EndTemp(checkpoint); + return found; +} + +LC_FUNCTION void SetASTPosOnAll_Walk(LC_ASTWalker *ctx, LC_AST *n) { + n->pos = (LC_Token *)ctx->user_data; +} + +LC_FUNCTION void LC_SetASTPosOnAll(LC_AST *n, LC_Token *pos) { + LC_TempArena check = LC_BeginTemp(L->arena); + LC_ASTWalker walker = LC_GetDefaultWalker(L->arena, SetASTPosOnAll_Walk); + walker.user_data = (void *)pos; + LC_WalkAST(&walker, n); + LC_EndTemp(check); +} +LC_FUNCTION LC_AST *LC_CopyAST(LC_Arena *arena, LC_AST *n) { + if (n == NULL) return NULL; + + LC_AST *result = LC_PushStruct(arena, LC_AST); + result->kind = n->kind; + result->id = ++L->ast_count; + result->notes = LC_CopyAST(arena, n->notes); + result->pos = n->pos; + + switch (n->kind) { + case LC_ASTKind_File: { + result->afile.x = n->afile.x; + + LC_ASTFor(it, n->afile.fimport) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->afile.fimport, result->afile.limport, it_copy); + } + LC_ASTFor(it, n->afile.fdecl) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->afile.fdecl, result->afile.ldecl, it_copy); + } + LC_ASTFor(it, n->afile.fdiscarded) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->afile.fdiscarded, result->afile.ldiscarded, it_copy); + } + + result->afile.build_if = n->afile.build_if; + } break; + + case LC_ASTKind_DeclProc: { + result->dbase.name = n->dbase.name; + result->dproc.body = LC_CopyAST(arena, n->dproc.body); + result->dproc.type = LC_CopyAST(arena, n->dproc.type); + } break; + + case LC_ASTKind_NoteList: { + LC_ASTFor(it, n->anote_list.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->anote_list.first, result->anote_list.last, it_copy); + } + } break; + + case LC_ASTKind_TypespecAggMem: + case LC_ASTKind_TypespecProcArg: { + result->tproc_arg.name = n->tproc_arg.name; + result->tproc_arg.type = LC_CopyAST(arena, n->tproc_arg.type); + result->tproc_arg.expr = LC_CopyAST(arena, n->tproc_arg.expr); + } break; + + case LC_ASTKind_ExprNote: { + result->enote.expr = LC_CopyAST(arena, n->enote.expr); + } break; + + case LC_ASTKind_StmtSwitch: { + LC_ASTFor(it, n->sswitch.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->sswitch.first, result->sswitch.last, it_copy); + } + result->sswitch.total_switch_case_count = n->sswitch.total_switch_case_count; + result->sswitch.expr = LC_CopyAST(arena, n->sswitch.expr); + } break; + + case LC_ASTKind_StmtSwitchCase: { + LC_ASTFor(it, n->scase.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->scase.first, result->scase.last, it_copy); + } + result->scase.body = LC_CopyAST(arena, n->scase.body); + } break; + + case LC_ASTKind_StmtSwitchDefault: { + LC_ASTFor(it, n->scase.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->scase.first, result->scase.last, it_copy); + } + result->scase.body = LC_CopyAST(arena, n->scase.body); + } break; + + case LC_ASTKind_StmtIf: { + LC_ASTFor(it, n->sif.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->sswitch.first, result->sswitch.last, it_copy); + } + result->sif.expr = LC_CopyAST(arena, n->sif.expr); + result->sif.body = LC_CopyAST(arena, n->sif.body); + } break; + + case LC_ASTKind_StmtElse: + case LC_ASTKind_StmtElseIf: { + result->sif.expr = LC_CopyAST(arena, n->sif.expr); + result->sif.body = LC_CopyAST(arena, n->sif.body); + } break; + + case LC_ASTKind_GlobImport: { + result->gimport.name = n->gimport.name; + result->gimport.path = n->gimport.path; + } break; + + case LC_ASTKind_DeclNote: { + result->dnote.expr = LC_CopyAST(arena, n->dnote.expr); + } break; + + case LC_ASTKind_DeclUnion: + case LC_ASTKind_DeclStruct: { + result->dbase.name = n->dbase.name; + LC_ASTFor(it, n->dagg.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->dagg.first, result->dagg.last, it_copy); + } + } break; + + case LC_ASTKind_DeclVar: { + result->dbase.name = n->dbase.name; + result->dvar.type = LC_CopyAST(arena, n->dvar.type); + result->dvar.expr = LC_CopyAST(arena, n->dvar.expr); + } break; + + case LC_ASTKind_DeclConst: { + result->dbase.name = n->dbase.name; + result->dconst.expr = LC_CopyAST(arena, n->dconst.expr); + } break; + + case LC_ASTKind_DeclTypedef: { + result->dbase.name = n->dbase.name; + result->dtypedef.type = LC_CopyAST(arena, n->dtypedef.type); + } break; + + case LC_ASTKind_ExprField: + case LC_ASTKind_TypespecField: { + result->efield.left = LC_CopyAST(arena, n->efield.left); + result->efield.right = n->efield.right; + } break; + + case LC_ASTKind_TypespecIdent: { + result->eident.name = n->eident.name; + } break; + + case LC_ASTKind_TypespecPointer: { + result->tpointer.base = LC_CopyAST(arena, n->tpointer.base); + } break; + + case LC_ASTKind_TypespecArray: { + result->tarray.base = LC_CopyAST(arena, n->tarray.base); + result->tarray.index = LC_CopyAST(arena, n->tarray.index); + } break; + + case LC_ASTKind_TypespecProc: { + LC_ASTFor(it, n->tproc.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->tproc.first, result->tproc.last, it_copy); + } + result->tproc.ret = LC_CopyAST(arena, n->tproc.ret); + result->tproc.vargs = n->tproc.vargs; + } break; + + case LC_ASTKind_StmtBlock: { + LC_ASTFor(it, n->sblock.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->sblock.first, result->sblock.last, it_copy); + + if (it_copy->kind == LC_ASTKind_StmtDefer) { + LC_SLLStackAddMod(result->sblock.first_defer, it_copy, sdefer.next); + } + } + if (n->sblock.first_defer) { + LC_ASSERT(result, result->sblock.first_defer); + } + result->sblock.kind = n->sblock.kind; + result->sblock.name = n->sblock.name; + } break; + + case LC_ASTKind_StmtNote: { + result->snote.expr = LC_CopyAST(arena, n->snote.expr); + } break; + + case LC_ASTKind_StmtReturn: { + result->sreturn.expr = LC_CopyAST(arena, n->sreturn.expr); + } break; + + case LC_ASTKind_StmtBreak: { + result->sbreak.name = n->sbreak.name; + } break; + + case LC_ASTKind_StmtContinue: { + result->scontinue.name = n->scontinue.name; + } break; + + case LC_ASTKind_StmtDefer: { + result->sdefer.body = LC_CopyAST(arena, n->sdefer.body); + } break; + + case LC_ASTKind_StmtFor: { + result->sfor.init = LC_CopyAST(arena, n->sfor.init); + result->sfor.cond = LC_CopyAST(arena, n->sfor.cond); + result->sfor.inc = LC_CopyAST(arena, n->sfor.inc); + result->sfor.body = LC_CopyAST(arena, n->sfor.body); + } break; + + case LC_ASTKind_StmtAssign: { + result->sassign.op = n->sassign.op; + result->sassign.left = LC_CopyAST(arena, n->sassign.left); + result->sassign.right = LC_CopyAST(arena, n->sassign.right); + } break; + + case LC_ASTKind_StmtExpr: { + result->sexpr.expr = LC_CopyAST(arena, n->sexpr.expr); + } break; + + case LC_ASTKind_StmtVar: { + result->svar.type = LC_CopyAST(arena, n->svar.type); + result->svar.expr = LC_CopyAST(arena, n->svar.expr); + result->svar.name = n->svar.name; + } break; + + case LC_ASTKind_StmtConst: { + result->sconst.expr = LC_CopyAST(arena, n->sconst.expr); + result->sconst.name = n->sconst.name; + } break; + + case LC_ASTKind_ExprIdent: { + result->eident.name = n->eident.name; + } break; + + case LC_ASTKind_ExprBool: + case LC_ASTKind_ExprFloat: + case LC_ASTKind_ExprInt: + case LC_ASTKind_ExprString: { + result->eatom = n->eatom; + } break; + + case LC_ASTKind_ExprType: { + result->etype.type = LC_CopyAST(arena, n->etype.type); + } break; + + case LC_ASTKind_ExprAddPtr: + case LC_ASTKind_ExprBinary: { + result->ebinary.op = n->ebinary.op; + result->ebinary.left = LC_CopyAST(arena, n->ebinary.left); + result->ebinary.right = LC_CopyAST(arena, n->ebinary.right); + } break; + + case LC_ASTKind_ExprGetPointerOfValue: + case LC_ASTKind_ExprGetValueOfPointer: + case LC_ASTKind_ExprUnary: { + result->eunary.op = n->eunary.op; + result->eunary.expr = LC_CopyAST(arena, n->eunary.expr); + } break; + + case LC_ASTKind_ExprCompoundItem: + case LC_ASTKind_ExprCallItem: { + result->ecompo_item.name = n->ecompo_item.name; + result->ecompo_item.index = LC_CopyAST(arena, n->ecompo_item.index); + result->ecompo_item.expr = LC_CopyAST(arena, n->ecompo_item.expr); + } break; + + case LC_ASTKind_ExprBuiltin: + case LC_ASTKind_Note: + case LC_ASTKind_ExprCall: + case LC_ASTKind_ExprCompound: { + LC_ASTFor(it, n->ecompo.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->ecompo.first, result->ecompo.last, it_copy); + } + + result->ecompo.size = n->ecompo.size; + result->ecompo.name = LC_CopyAST(arena, n->ecompo.name); + } break; + + case LC_ASTKind_ExprCast: { + result->ecast.type = LC_CopyAST(arena, n->ecast.type); + result->ecast.expr = LC_CopyAST(arena, n->ecast.expr); + } break; + + case LC_ASTKind_ExprIndex: { + result->eindex.index = LC_CopyAST(arena, n->eindex.index); + result->eindex.base = LC_CopyAST(arena, n->eindex.base); + } break; + + default: LC_ReportASTError(n, "internal compiler error: failed to LC_CopyAST, got invalid ast kind: %s", LC_ASTKindToString(n->kind)); + } + + return result; +} + +// clang-format off +#define LC_PUSH_COMP_ARRAY_SIZE(SIZE) int PREV_SIZE = L->resolver.compo_context_array_size; L->resolver.compo_context_array_size = SIZE; +#define LC_POP_COMP_ARRAY_SIZE() L->resolver.compo_context_array_size = PREV_SIZE +#define LC_PUSH_SCOPE(SCOPE) DeclScope *PREV_SCOPE = L->resolver.active_scope; L->resolver.active_scope = SCOPE +#define LC_POP_SCOPE() L->resolver.active_scope = PREV_SCOPE +#define LC_PUSH_LOCAL_SCOPE() int LOCAL_LEN = L->resolver.locals.len +#define LC_POP_LOCAL_SCOPE() L->resolver.locals.len = LOCAL_LEN +#define LC_PUSH_PACKAGE(PKG) LC_AST *PREV_PKG = L->resolver.package; L->resolver.package = PKG; LC_PUSH_SCOPE(PKG->apackage.scope) +#define LC_POP_PACKAGE() L->resolver.package = PREV_PKG; LC_POP_SCOPE() +#define LC_PROP_ERROR(OP, n, ...) OP = __VA_ARGS__; if (LC_IsError(OP)) { n->kind = LC_ASTKind_Error; return OP; } +#define LC_DECL_PROP_ERROR(OP, ...) OP = __VA_ARGS__; if (LC_IsError(OP)) { LC_MarkDeclError(decl); return OP; } + +#define LC_IF(COND, N, ...) if (COND) { LC_Operand R_ = LC_ReportASTError(N, __VA_ARGS__); N->kind = LC_ASTKind_Error; return R_; } +#define LC_DECL_IF(COND, ...) if (COND) { LC_MarkDeclError(decl); return LC_ReportASTError(__VA_ARGS__); } +#define LC_TYPE_IF(COND, ...) if (COND) { LC_MarkDeclError(decl); type->kind = LC_TypeKind_Error; return LC_ReportASTError(__VA_ARGS__); } +// clang-format on + +LC_FUNCTION void LC_AddDecl(LC_DeclStack *scope, LC_Decl *decl) { + if (scope->len + 1 > scope->cap) { + LC_ASSERT(NULL, scope->cap); + int new_cap = scope->cap * 2; + LC_Decl **new_stack = LC_PushArray(L->arena, LC_Decl *, new_cap); + LC_MemoryCopy(new_stack, scope->stack, scope->len * sizeof(LC_Decl *)); + scope->stack = new_stack; + scope->cap = new_cap; + } + scope->stack[scope->len++] = decl; +} + +LC_FUNCTION void LC_InitDeclStack(LC_DeclStack *stack, int size) { + stack->stack = LC_PushArray(L->arena, LC_Decl *, size); + stack->cap = size; +} + +LC_FUNCTION LC_DeclStack *LC_CreateDeclStack(int size) { + LC_DeclStack *stack = LC_PushStruct(L->arena, LC_DeclStack); + LC_InitDeclStack(stack, size); + return stack; +} + +LC_FUNCTION LC_Decl *LC_FindDeclOnStack(LC_DeclStack *scp, LC_Intern name) { + for (int i = 0; i < scp->len; i += 1) { + LC_Decl *it = scp->stack[i]; + if (it->name == name) { + return it; + } + } + return NULL; +} + +LC_FUNCTION void LC_MarkDeclError(LC_Decl *decl) { + if (decl) { + decl->kind = LC_DeclKind_Error; + decl->state = LC_DeclState_Error; + if (decl->ast) decl->ast->kind = LC_ASTKind_Error; + } +} + +LC_FUNCTION LC_Decl *LC_CreateDecl(LC_DeclKind kind, LC_Intern name, LC_AST *n) { + LC_Decl *decl = LC_PushStruct(L->decl_arena, LC_Decl); + L->decl_count += 1; + + decl->name = name; + decl->kind = kind; + decl->ast = n; + decl->package = L->resolver.package; + LC_ASSERT(n, decl->package); + + LC_AST *note = LC_HasNote(n, L->iforeign); + if (note) { + decl->is_foreign = true; + if (note->anote.first) { + if (note->anote.size != 1) LC_ReportASTError(note, "invalid format of @foreign(...), more then 1 argument"); + LC_AST *expr = note->anote.first->ecompo_item.expr; + if (expr->kind == LC_ASTKind_ExprIdent) decl->foreign_name = expr->eident.name; + if (expr->kind != LC_ASTKind_ExprIdent) LC_ReportASTError(note, "invalid format of @foreign(...), expected identifier"); + } + } + if (!decl->foreign_name) decl->foreign_name = decl->name; + return decl; +} + +LC_FUNCTION LC_Operand LC_ThereIsNoDecl(DeclScope *scp, LC_Decl *decl, bool check_locals) { + LC_Decl *r = (LC_Decl *)LC_MapGetU64(scp, decl->name); + if (check_locals && !r) { + r = LC_FindDeclOnStack(&L->resolver.locals, decl->name); + } + if (r) { + LC_MarkDeclError(r); + LC_MarkDeclError(decl); + return LC_ReportASTErrorEx(decl->ast, r->ast, "there are 2 decls with the same name '%s'", decl->name); + } + return LC_OPNull; +} + +LC_FUNCTION LC_Operand LC_AddDeclToScope(DeclScope *scp, LC_Decl *decl) { + LC_Operand LC_DECL_PROP_ERROR(op, LC_ThereIsNoDecl(scp, decl, false)); + LC_MapInsertU64(scp, decl->name, decl); + return LC_OPDecl(decl); +} + +LC_FUNCTION DeclScope *LC_CreateScope(int size) { + DeclScope *scope = LC_PushStruct(L->arena, DeclScope); + scope->arena = L->arena; + LC_MapReserve(scope, size); + return scope; +} + +LC_FUNCTION LC_Decl *LC_FindDeclInScope(DeclScope *scope, LC_Intern name) { + LC_Decl *decl = (LC_Decl *)LC_MapGetU64(scope, name); + return decl; +} + +LC_FUNCTION LC_Decl *LC_GetLocalOrGlobalDecl(LC_Intern name) { + LC_Decl *decl = LC_FindDeclInScope(L->resolver.active_scope, name); + if (!decl && L->resolver.package->apackage.scope == L->resolver.active_scope) { + decl = LC_FindDeclOnStack(&L->resolver.locals, name); + } + return decl; +} + +LC_FUNCTION LC_Operand LC_PutGlobalDecl(LC_Decl *decl) { + LC_Operand LC_DECL_PROP_ERROR(op, LC_AddDeclToScope(L->resolver.package->apackage.scope, decl)); + + // :Mangle global scope name + if (!decl->is_foreign && decl->package != L->builtin_package) { + bool mangle = true; + if (LC_HasNote(decl->ast, L->idont_mangle)) mangle = false; + if (LC_HasNote(decl->ast, L->iapi)) mangle = false; + if (decl->name == L->imain) { + if (L->first_package) { + if (L->first_package == decl->package->apackage.name) { + mangle = false; + } + } else mangle = false; + } + if (mangle) { + LC_String name = LC_Format(L->arena, "lc_%s_%s", (char *)decl->package->apackage.name, (char *)decl->name); + decl->foreign_name = LC_InternStrLen(name.str, (int)name.len); + } + } + + LC_Decl *conflict = (LC_Decl *)LC_MapGetU64(&L->foreign_names, decl->foreign_name); + if (conflict && !decl->is_foreign) { + LC_ReportASTErrorEx(decl->ast, conflict->ast, "found two global declarations with the same foreign name: %s", decl->foreign_name); + } else { + LC_MapInsertU64(&L->foreign_names, decl->foreign_name, decl); + } + + return op; +} + +LC_FUNCTION LC_Operand LC_CreateLocalDecl(LC_DeclKind kind, LC_Intern name, LC_AST *ast) { + LC_Decl *decl = LC_CreateDecl(kind, name, ast); + decl->state = LC_DeclState_Resolving; + LC_Operand LC_DECL_PROP_ERROR(operr0, LC_ThereIsNoDecl(L->resolver.package->apackage.scope, decl, true)); + LC_AddDecl(&L->resolver.locals, decl); + return LC_OPDecl(decl); +} + +LC_FUNCTION LC_Decl *LC_AddConstIntDecl(char *key, int64_t value) { + LC_Intern intern = LC_ILit(key); + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Const, intern, &L->NullAST); + decl->state = LC_DeclState_Resolved; + decl->type = L->tuntypedint; + LC_Bigint_init_signed(&decl->v.i, value); + LC_AddDeclToScope(L->resolver.package->apackage.scope, decl); + return decl; +} + +LC_FUNCTION LC_Decl *LC_GetBuiltin(LC_Intern name) { + LC_Decl *decl = (LC_Decl *)LC_MapGetU64(L->builtin_package->apackage.scope, name); + return decl; +} + +LC_FUNCTION void LC_AddBuiltinConstInt(char *key, int64_t value) { + LC_PUSH_PACKAGE(L->builtin_package); + LC_AddConstIntDecl(key, value); + LC_POP_PACKAGE(); +} + +LC_FUNCTION LC_AST *LC_HasNote(LC_AST *ast, LC_Intern i) { + if (ast && ast->notes) { + LC_ASTFor(it, ast->notes->anote_list.first) { + LC_ASSERT(it, "internal compiler error: note is not an identifier"); + if (it->anote.name->eident.name == i) { + return it; + } + } + } + return NULL; +} + +LC_FUNCTION void LC_RegisterDeclsFromFile(LC_AST *file) { + LC_ASTFor(n, file->afile.fdecl) { + if (n->dbase.resolved_decl) continue; + if (n->kind == LC_ASTKind_DeclNote) continue; + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Type, n->dbase.name, n); + switch (n->kind) { + case LC_ASTKind_DeclStruct: + case LC_ASTKind_DeclUnion: + decl->type = LC_CreateIncompleteType(decl); + decl->state = LC_DeclState_Resolved; + decl->kind = LC_DeclKind_Type; + break; + case LC_ASTKind_DeclTypedef: decl->kind = LC_DeclKind_Type; break; + case LC_ASTKind_DeclProc: decl->kind = LC_DeclKind_Proc; break; + case LC_ASTKind_DeclConst: decl->kind = LC_DeclKind_Const; break; + case LC_ASTKind_DeclVar: decl->kind = LC_DeclKind_Var; break; + default: LC_ReportASTError(n, "internal compiler error: got unhandled ast declaration kind in %s", __FUNCTION__); + } + LC_PutGlobalDecl(decl); + n->dbase.resolved_decl = decl; + } +} + +LC_FUNCTION void LC_ResolveDeclsFromFile(LC_AST *file) { + LC_ASTFor(n, file->afile.fdecl) { + if (n->kind == LC_ASTKind_DeclNote) { + LC_ResolveNote(n, false); + } else { + LC_ResolveName(n, n->dbase.name); + } + } +} + +LC_FUNCTION void LC_PackageDecls(LC_AST *package) { + LC_PUSH_PACKAGE(package); + + // Register top level declarations + LC_ASTFor(file, package->apackage.ffile) { + LC_ASTFor(import, file->afile.fimport) { + if (import->gimport.resolved == false) LC_ReportASTError(import, "internal compiler error: unresolved import got into typechecking stage"); + } + LC_RegisterDeclsFromFile(file); + } + + // Resolve declarations by name + LC_ASTFor(file, package->apackage.ffile) { + LC_ResolveDeclsFromFile(file); + } + + LC_POP_PACKAGE(); +} + +LC_FUNCTION void LC_ResolveProcBodies(LC_AST *package) { + LC_PUSH_PACKAGE(package); + + LC_ASTFor(file, package->apackage.ffile) { + LC_ASTFor(n, file->afile.fdecl) { + if (n->kind == LC_ASTKind_DeclNote) continue; + + LC_Decl *decl = n->dbase.resolved_decl; + if (decl->kind == LC_DeclKind_Proc) { + LC_Operand op = LC_ResolveProcBody(decl); + if (LC_IsError(op)) LC_MarkDeclError(decl); + } + } + } + + LC_POP_PACKAGE(); +} + +LC_FUNCTION void LC_ResolveIncompleteTypes(LC_AST *package) { + LC_PUSH_PACKAGE(package); + + LC_ASTFor(file, package->apackage.ffile) { + LC_ASTFor(n, file->afile.fdecl) { + if (n->kind == LC_ASTKind_DeclNote) continue; + + LC_Decl *decl = n->dbase.resolved_decl; + if (decl->kind == LC_DeclKind_Type) { + LC_ResolveTypeAggregate(decl->ast, decl->type); + } + } + } + + LC_POP_PACKAGE(); +} + +LC_FUNCTION LC_Operand LC_ResolveNote(LC_AST *n, bool is_decl) { + LC_AST *note = n->dnote.expr; + if (n->kind == LC_ASTKind_ExprNote) note = n->enote.expr; + else if (n->kind == LC_ASTKind_StmtNote) note = n->snote.expr; + else { + LC_ASSERT(n, n->kind == LC_ASTKind_DeclNote); + if (n->dnote.processed) return LC_OPNull; + } + + if (note->ecompo.name->eident.name == L->istatic_assert) { + LC_IF(is_decl, note, "#static_assert cant be used as variable initializer"); + LC_Operand LC_PROP_ERROR(op, n, LC_ExpectBuiltinWithOneArg(note)); + LC_IF(!LC_IsUTConst(op) || !LC_IsUTInt(op.type), n, "static assert requires constant untyped integer value"); + int val = (int)LC_Bigint_as_signed(&op.val.i); + LC_IF(!val, note, "#static_assert failed !"); + n->dnote.processed = true; + } + + return LC_OPNull; +} + +void SetConstVal(LC_AST *n, LC_TypeAndVal val) { + LC_ASSERT(n, LC_IsUntyped(val.type)); + n->const_val = val; +} + +LC_FUNCTION LC_Operand LC_ResolveProcBody(LC_Decl *decl) { + if (decl->state == LC_DeclState_Error) return LC_OPError(); + if (decl->state == LC_DeclState_ResolvedBody) return LC_OPNull; + LC_ASSERT(decl->ast, decl->state == LC_DeclState_Resolved); + + LC_AST *n = decl->ast; + if (n->dproc.body == NULL) return LC_OPNull; + L->resolver.locals.len = 0; + LC_ASTFor(it, n->dproc.type->tproc.first) { + if (it->kind == LC_ASTKind_Error) { + LC_MarkDeclError(decl); + return LC_OPError(); + } + LC_ASSERT(it, it->type); + LC_Operand LC_DECL_PROP_ERROR(op, LC_CreateLocalDecl(LC_DeclKind_Var, it->tproc_arg.name, it)); + op.decl->type = it->type; + op.decl->state = LC_DeclState_Resolved; + it->tproc_arg.resolved_decl = op.decl; + } + + int errors_before = L->errors; + LC_ASSERT(n, decl->type->tproc.ret); + L->resolver.expected_ret_type = decl->type->tproc.ret; + LC_Operand LC_DECL_PROP_ERROR(op, LC_ResolveStmtBlock(n->dproc.body)); + L->resolver.locals.len = 0; + + if (errors_before == L->errors && decl->type->tproc.ret != L->tvoid && !(op.flags & LC_OPF_Returned)) { + LC_ReportASTError(n, "you can get through this procedure without hitting a return stmt, add a return to cover all control paths"); + } + decl->state = LC_DeclState_ResolvedBody; + if (L->on_proc_body_resolved) L->on_proc_body_resolved(decl); + return LC_OPNull; +} + +LC_FUNCTION LC_ResolvedCompoItem *LC_AddResolvedCallItem(LC_ResolvedCompo *list, LC_TypeMember *t, LC_AST *comp, LC_AST *expr) { + LC_AST *duplicate1 = (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, list); + if (t && !duplicate1) { + for (LC_ResolvedCompoItem *it = list->first; it; it = it->next) { + if (t == it->t) { + LC_MapInsertP(&L->resolver.duplicate_map, list, comp); + LC_MapInsertP(&L->resolver.duplicate_map, comp, it->comp); // duplicate2 + break; + } + } + } + LC_ResolvedCompoItem *match = LC_PushStruct(L->arena, LC_ResolvedCompoItem); + list->count += 1; + match->t = t; + match->expr = expr; + match->comp = comp; + LC_AddSLL(list->first, list->last, match); + return match; +} + +LC_FUNCTION LC_Operand LC_ResolveCompoCall(LC_AST *n, LC_Type *type) { + LC_ASSERT(n, type->kind == LC_TypeKind_Proc); + LC_IF(type->tproc.vargs && type->tagg.mems.count > n->ecompo.size, n, "calling procedure with invalid argument count, expected at least %d args, got %d, the procedure type is: %s", type->tagg.mems.count, n->ecompo.size, LC_GenLCType(type)); + + bool named_field_appeared = false; + LC_ASTFor(it, n->ecompo.first) { + LC_IF(type->tproc.vargs && it->ecompo_item.name, it, "variadic procedures cannot have named arguments"); + LC_IF(it->ecompo_item.index, it, "index inside a call is not allowed"); + LC_IF(named_field_appeared && it->ecompo_item.name == 0, it, "mixing named and positional arguments is illegal"); + if (it->ecompo_item.name) named_field_appeared = true; + } + + LC_ResolvedCompo *matches = LC_PushStruct(L->arena, LC_ResolvedCompo); + LC_TypeMember *type_it = type->tproc.args.first; + LC_AST *npos_it = n->ecompo.first; + + // greedy match unnamed arguments + for (; type_it; type_it = type_it->next, npos_it = npos_it->next) { + if (npos_it == NULL || npos_it->ecompo_item.name) break; + LC_AddResolvedCallItem(matches, type_it, npos_it, npos_it->ecompo_item.expr); + } + + // greedy match variadic arguments + if (type->tproc.vargs) { + for (; npos_it; npos_it = npos_it->next) { + LC_ResolvedCompoItem *m = LC_AddResolvedCallItem(matches, NULL, npos_it, npos_it->ecompo_item.expr); + m->varg = true; + } + } + + // for every required proc type argument we seek a named argument + // in either default proc values or passed in call arguments + for (; type_it; type_it = type_it->next) { + LC_ASTFor(n_it, npos_it) { + if (type_it->name == n_it->ecompo_item.name) { + LC_AddResolvedCallItem(matches, type_it, n_it, n_it->ecompo_item.expr); + goto end_of_outer_loop; + } + } + + if (type_it->default_value_expr) { + LC_ResolvedCompoItem *m = LC_AddResolvedCallItem(matches, type_it, NULL, type_it->default_value_expr); + m->defaultarg = true; + } + end_of_outer_loop:; + } + + // make sure we matched every item in call + LC_ASTFor(n_it, n->ecompo.first) { + LC_AST *expr = n_it->ecompo_item.expr; + bool included = false; + for (LC_ResolvedCompoItem *it = matches->first; it; it = it->next) { + if (it->expr == expr) { + included = true; + break; + } + } + + LC_IF(!included, expr, "unknown argument to a procedure call, couldn't match it with any of the declared arguments, the procedure type is: %s", LC_GenLCType(type)); + } + + LC_IF(!type->tproc.vargs && matches->count != type->tproc.args.count, n, "invalid argument count passed in to procedure call, expected: %d, matched: %d, the procedure type is: %s", type->tproc.args.count, matches->count, LC_GenLCType(type)); + + // error on duplicates + LC_AST *duplicate1 = (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, matches); + LC_AST *duplicate2 = duplicate1 ? (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, duplicate1) : NULL; + LC_MapClear(&L->resolver.duplicate_map); + if (duplicate1) { + LC_Operand err = LC_ReportASTErrorEx(duplicate1, duplicate2, "two call items match the same procedure argument"); + n->kind = LC_ASTKind_Error; + return err; + } + + // resolve + for (LC_ResolvedCompoItem *it = matches->first; it; it = it->next) { + if (it->varg) { + if (type->tproc.vargs_any_promotion) { + LC_Operand LC_PROP_ERROR(opexpr, it->expr, LC_ResolveExprAndPushCompoContext(it->expr, L->tany)); + LC_TryTyping(it->expr, LC_OPType(L->tany)); + } else { + LC_Operand LC_PROP_ERROR(opexpr, it->expr, LC_ResolveExpr(it->expr)); + LC_Operand LC_PROP_ERROR(op, it->expr, LC_ResolveTypeVargs(it->expr, opexpr)); + LC_TryTyping(it->expr, op); + } + continue; + } + if (it->defaultarg) { + continue; + } + LC_Operand LC_PROP_ERROR(opexpr, it->expr, LC_ResolveExprAndPushCompoContext(it->expr, it->t->type)); + LC_Operand LC_PROP_ERROR(op, it->expr, LC_ResolveTypeVarDecl(it->expr, LC_OPType(it->t->type), opexpr)); + LC_TryTyping(it->expr, op); + } + + n->ecompo.resolved_items = matches; + LC_Operand result = LC_OPLValueAndType(type->tproc.ret); + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveCompoAggregate(LC_AST *n, LC_Type *type) { + LC_ASSERT(n, type->kind == LC_TypeKind_Union || type->kind == LC_TypeKind_Struct); + LC_IF(n->ecompo.size > 1 && type->kind == LC_TypeKind_Union, n, "too many union initializers, expected 1 or 0 got %d", n->ecompo.size); + LC_IF(n->ecompo.size > type->tagg.mems.count, n, "too many struct initializers, expected less then %d got instead %d", type->tagg.mems.count, n->ecompo.size); + + bool named_field_appeared = false; + LC_ASTFor(it, n->ecompo.first) { + LC_IF(type->kind == LC_TypeKind_Union && it->ecompo_item.name == 0, it, "unions can only be initialized using named arguments"); + LC_IF(named_field_appeared && it->ecompo_item.name == 0, it, "mixing named and positional arguments is illegal"); + LC_IF(it->ecompo_item.index, it, "index specifier in non array compound is illegal"); + if (it->ecompo_item.name) named_field_appeared = true; + } + + LC_ResolvedCompo *matches = LC_PushStruct(L->arena, LC_ResolvedCompo); + LC_TypeMember *type_it = type->tagg.mems.first; + LC_AST *npos_it = n->ecompo.first; + + // greedy match unnamed arguments + for (; type_it; type_it = type_it->next, npos_it = npos_it->next) { + if (npos_it == NULL || npos_it->ecompo_item.name) break; + LC_AddResolvedCallItem(matches, type_it, npos_it, npos_it->ecompo_item.expr); + } + + // match named arguments + for (; npos_it; npos_it = npos_it->next) { + bool found = false; + LC_TypeFor(type_it, type->tagg.mems.first) { + if (type_it->name == npos_it->ecompo_item.name) { + LC_AddResolvedCallItem(matches, type_it, npos_it, npos_it->ecompo_item.expr); + found = true; + break; + } + } + + LC_IF(!found, npos_it, "no matching declaration with name '%s' in type '%s'", npos_it->ecompo_item.name, LC_GenLCType(type)); + } + + // error on duplicates + LC_AST *duplicate1 = (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, matches); + LC_AST *duplicate2 = duplicate1 ? (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, duplicate1) : NULL; + if (duplicate1) { + LC_Operand err = LC_ReportASTErrorEx(duplicate1, duplicate2, "two compound items match the same struct variable"); + n->kind = LC_ASTKind_Error; + return err; + } + + // resolve + LC_Operand result = LC_OPLValueAndType(type); + result.flags |= LC_OPF_Const; + for (LC_ResolvedCompoItem *it = matches->first; it; it = it->next) { + LC_Operand LC_PROP_ERROR(opexpr, it->expr, LC_ResolveExprAndPushCompoContext(it->expr, it->t->type)); + LC_Operand LC_PROP_ERROR(op, it->expr, LC_ResolveTypeVarDecl(it->expr, LC_OPType(it->t->type), opexpr)); + LC_TryTyping(it->expr, op); + + if (!(opexpr.flags & LC_OPF_Const)) result.flags &= ~LC_OPF_Const; + } + + n->ecompo.resolved_items = matches; + return result; +} + +LC_FUNCTION LC_ResolvedCompoArrayItem *LC_AddResolvedCompoArrayItem(LC_ResolvedArrayCompo *arr, int index, LC_AST *comp) { + LC_AST *duplicate1 = (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, arr); + if (!duplicate1) { + for (LC_ResolvedCompoArrayItem *it = arr->first; it; it = it->next) { + if (index == it->index) { + LC_MapInsertP(&L->resolver.duplicate_map, arr, comp); + LC_MapInsertP(&L->resolver.duplicate_map, comp, it->comp); + break; + } + } + } + LC_ResolvedCompoArrayItem *result = LC_PushStruct(L->arena, LC_ResolvedCompoArrayItem); + result->index = index; + result->comp = comp; + arr->count += 1; + LC_AddSLL(arr->first, arr->last, result); + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveCompoArray(LC_AST *n, LC_Type *type) { + LC_ASSERT(n, type->kind == LC_TypeKind_Array); + LC_IF(n->ecompo.size > type->tarray.size, n, "too many array intializers, array is of size '%d', got '%d'", type->tarray.size, n->ecompo.size); + + bool index_appeared = false; + LC_ASTFor(it, n->ecompo.first) { + LC_IF(index_appeared && it->ecompo_item.index == NULL, it, "mixing indexed and positional arguments is illegal"); + LC_IF(it->ecompo_item.name, it, "named arguments are invalid in array compound literal"); + if (it->ecompo_item.index) index_appeared = true; + } + + LC_ResolvedArrayCompo *matches = LC_PushStruct(L->arena, LC_ResolvedArrayCompo); + LC_AST *npos_it = n->ecompo.first; + int index = 0; + + // greedy match unnamed arguments + for (; npos_it; npos_it = npos_it->next) { + if (npos_it->ecompo_item.index) break; + LC_ASSERT(n, index < type->tarray.size); + LC_AddResolvedCompoArrayItem(matches, index++, npos_it); + } + + // match indexed arguments + for (; npos_it; npos_it = npos_it->next) { + uint64_t val = 0; + LC_Operand LC_PROP_ERROR(op, npos_it, LC_ResolveConstInt(npos_it->ecompo_item.index, L->tint, &val)); + LC_IF(val > type->tarray.size, npos_it, "array index out of bounds, array is of size %d", type->tarray.size); + LC_AddResolvedCompoArrayItem(matches, (int)val, npos_it); + } + + // error on duplicates + LC_AST *duplicate1 = (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, matches); + LC_AST *duplicate2 = duplicate1 ? (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, duplicate1) : NULL; + if (duplicate1) { + LC_Operand err = LC_ReportASTErrorEx(duplicate1, duplicate2, "two items in compound array literal match the same index"); + n->kind = LC_ASTKind_Error; + return err; + } + + // resolve + LC_Operand result = LC_OPLValueAndType(type); + result.flags |= LC_OPF_Const; + for (LC_ResolvedCompoArrayItem *it = matches->first; it; it = it->next) { + LC_AST *expr = it->comp->ecompo_item.expr; + LC_Operand LC_PROP_ERROR(opexpr, expr, LC_ResolveExprAndPushCompoContext(expr, type->tbase)); + LC_Operand LC_PROP_ERROR(op, expr, LC_ResolveTypeVarDecl(expr, LC_OPType(type->tbase), opexpr)); + LC_TryTyping(expr, op); + + if (!(opexpr.flags & LC_OPF_Const)) result.flags &= ~LC_OPF_Const; + } + + n->ecompo.resolved_array_items = matches; + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveTypeOrExpr(LC_AST *n) { + if (n->kind == LC_ASTKind_ExprType) { + LC_Operand LC_PROP_ERROR(result, n, LC_ResolveType(n->etype.type)); + n->type = result.type; + return result; + } else { + LC_Operand LC_PROP_ERROR(result, n, LC_ResolveExpr(n)); + return result; + } +} + +LC_FUNCTION LC_Operand LC_ExpectBuiltinWithOneArg(LC_AST *n) { + LC_IF(n->ecompo.size != 1, n, "expected 1 argument to builtin procedure, got: %d", n->ecompo.size); + LC_IF(n->ecompo.first->ecompo_item.name, n, "named arguments in this builtin procedure are illegal"); + LC_AST *expr = n->ecompo.first->ecompo_item.expr; + LC_Operand LC_PROP_ERROR(op, expr, LC_ResolveTypeOrExpr(expr)); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, op.type)); + expr->type = op.type; + return op; +} + +LC_FUNCTION LC_Operand LC_ResolveBuiltin(LC_AST *n) { + LC_Operand result = {0}; + if (n->ecompo.name == 0 || n->ecompo.name->kind != LC_ASTKind_ExprIdent) return result; + LC_Intern ident = n->ecompo.name->eident.name; + + if (ident == L->ilengthof) { + LC_Operand LC_PROP_ERROR(op, n, LC_ExpectBuiltinWithOneArg(n)); + if (LC_IsArray(op.type)) { + result = LC_OPInt(op.type->tarray.size); + } else if (LC_IsUTStr(op.type)) { + int64_t length = LC_StrLen((char *)op.v.name); + result = LC_OPInt(length); + } else LC_IF(1, n, "expected array or constant string type, got instead '%s'", LC_GenLCType(op.type)); + n->kind = LC_ASTKind_ExprBuiltin; + } else if (ident == L->isizeof) { + LC_Operand LC_PROP_ERROR(op, n, LC_ExpectBuiltinWithOneArg(n)); + LC_IF(LC_IsUntyped(op.type), n, "cannot get sizeof a value that is untyped: '%s'", LC_GenLCType(op.type)); + result = LC_OPInt(op.type->size); + n->kind = LC_ASTKind_ExprBuiltin; + } else if (ident == L->ialignof) { + LC_Operand LC_PROP_ERROR(op, n, LC_ExpectBuiltinWithOneArg(n)); + LC_IF(LC_IsUntyped(op.type), n, "cannot get alignof a value that is untyped: '%s'", LC_GenLCType(op.type)); + + LC_AST *expr = n->ecompo.first->ecompo_item.expr; + LC_IF(expr->kind != LC_ASTKind_ExprType, expr, "argument should be a type, instead it's '%s'", LC_ASTKindToString(expr->kind)); + + result = LC_OPInt(op.type->align); + n->kind = LC_ASTKind_ExprBuiltin; + } else if (ident == L->itypeof) { + LC_Operand LC_PROP_ERROR(op, n, LC_ExpectBuiltinWithOneArg(n)); + LC_IF(LC_IsUntyped(op.type), n, "cannot get typeof a value that is untyped: '%s'", LC_GenLCType(op.type)); + result = LC_OPInt(op.type->id); + n->kind = LC_ASTKind_ExprBuiltin; + } else if (ident == L->ioffsetof) { + LC_IF(n->ecompo.size != 2, n, "expected 2 arguments to builtin procedure 'offsetof', got: %d", n->ecompo.size); + LC_AST *a1 = n->ecompo.first; + LC_AST *a2 = a1->next; + LC_IF(a1->ecompo_item.name, a1, "named arguments in this builtin procedure are illegal"); + LC_IF(a2->ecompo_item.name, a2, "named arguments in this builtin procedure are illegal"); + LC_AST *a1e = a1->ecompo_item.expr; + LC_AST *a2e = a2->ecompo_item.expr; + LC_IF(a1e->kind != LC_ASTKind_ExprType, a1e, "first argument should be a type, instead it's '%s'", LC_ASTKindToString(a1e->kind)); + LC_Operand LC_PROP_ERROR(optype, a1e, LC_ResolveType(a1e->etype.type)); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(a1e, optype.type)); + LC_IF(!LC_IsAggType(optype.type), a1e, "expected aggregate type in first parameter of 'offsetof', instead got '%s'", LC_GenLCType(optype.type)); + LC_IF(a2e->kind != LC_ASTKind_ExprIdent, a2e, "expected identifier as second parameter to 'offsetof', instead got '%s'", LC_ASTKindToString(a2e->kind)); + a1e->type = optype.type; + + LC_Type *type = optype.type; + LC_TypeMember *found_type = NULL; + LC_TypeFor(it, type->tagg.mems.first) { + if (it->name == a2e->eident.name) { + found_type = it; + break; + } + } + + LC_ASSERT(n, type->decl); + LC_IF(!found_type, n, "field '%s' not found in '%s'", a2e->eident.name, type->decl->name); + result = LC_OPInt(found_type->offset); + n->kind = LC_ASTKind_ExprBuiltin; + } + + if (LC_IsUTConst(result)) { + n->const_val = result.val; + } + + return result; +} + +LC_FUNCTION bool LC_TryTyping(LC_AST *n, LC_Operand op) { + LC_ASSERT(n, n->type); + + if (LC_IsUntyped(n->type)) { + if (LC_IsUTInt(n->type) && LC_IsFloat(op.type)) { + LC_Operand in = {LC_OPF_UTConst | LC_OPF_Const}; + in.val = n->const_val; + LC_Operand op = LC_ConstCastFloat(NULL, in); + SetConstVal(n, op.val); + } + if (L->tany == op.type) op = LC_OPModDefaultUT(LC_OPType(n->type)); + n->type = op.type; + + // Bounds check + if (n->const_val.type && LC_IsUTInt(n->const_val.type)) { + if (LC_IsInt(n->type) && !LC_BigIntFits(n->const_val.i, n->type)) { + const char *val = LC_Bigint_str(&n->const_val.i, 10); + LC_ReportASTError(n, "value '%s', doesn't fit into type '%s'", val, LC_GenLCType(n->type)); + } + } + } + + // I think it returns true to do this: (a, b) + return true; +} + +LC_FUNCTION bool LC_TryDefaultTyping(LC_AST *n, LC_Operand *o) { + LC_ASSERT(n, n->type); + if (LC_IsUntyped(n->type)) { + n->type = n->type->tbase; + if (o) o->type = n->type; + } + return true; +} + +LC_FUNCTION LC_Operand LC_ResolveNameInScope(LC_AST *n, LC_Decl *parent_decl) { + LC_ASSERT(n, n->kind == LC_ASTKind_ExprField || n->kind == LC_ASTKind_TypespecField); + LC_PUSH_SCOPE(parent_decl->scope); + LC_Operand op = LC_ResolveName(n, n->efield.right); + LC_POP_SCOPE(); + if (LC_IsError(op)) { + n->kind = LC_ASTKind_Error; + return op; + } + + LC_ASSERT(n, op.decl); + n->efield.resolved_decl = op.decl; + n->efield.parent_decl = parent_decl; + + LC_ASSERT(n, op.decl->kind != LC_DeclKind_Import); + return op; +} + +LC_FUNCTION LC_Operand LC_ResolveExpr(LC_AST *expr) { + return LC_ResolveExprAndPushCompoContext(expr, NULL); +} + +LC_FUNCTION LC_Operand LC_ResolveExprAndPushCompoContext(LC_AST *expr, LC_Type *type) { + LC_Type *save = L->resolver.compo_context_type; + L->resolver.compo_context_type = type; + LC_Operand LC_PROP_ERROR(result, expr, LC_ResolveExprEx(expr)); + L->resolver.compo_context_type = save; + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveExprEx(LC_AST *n) { + LC_Operand result = {0}; + LC_ASSERT(n, LC_IsExpr(n)); + + switch (n->kind) { + case LC_ASTKind_ExprFloat: { + result.flags = LC_OPF_UTConst | LC_OPF_Const; + result.val.d = n->eatom.d; + result.val.type = L->tuntypedfloat; + SetConstVal(n, result.val); + } break; + case LC_ASTKind_ExprInt: { + result.flags = LC_OPF_UTConst | LC_OPF_Const; + result.val.i = n->eatom.i; + result.val.type = L->tuntypedint; + SetConstVal(n, result.val); + } break; + case LC_ASTKind_ExprBool: { + result.flags = LC_OPF_UTConst | LC_OPF_Const; + result.val.i = n->eatom.i; + result.val.type = L->tuntypedbool; + SetConstVal(n, result.val); + } break; + case LC_ASTKind_ExprString: { + result.flags = LC_OPF_LValue | LC_OPF_UTConst | LC_OPF_Const; + result.val.name = n->eatom.name; + result.val.type = L->tuntypedstring; + SetConstVal(n, result.val); + } break; + case LC_ASTKind_ExprType: { + return LC_ReportASTError(n, "cannot use type as value"); + } break; + + case LC_ASTKind_ExprIdent: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveName(n, n->eident.name)); + LC_IF(op.decl->kind == LC_DeclKind_Type, n, "declaration is type, unexpected inside expression"); + LC_IF(op.decl->kind == LC_DeclKind_Import, n, "declaration is import, unexpected usage"); + + n->eident.resolved_decl = op.decl; + result.val = op.decl->val; + if (op.decl->kind == LC_DeclKind_Const) { + result.flags |= LC_OPF_UTConst | LC_OPF_Const; + SetConstVal(n, result.val); + } else { + result.flags |= LC_OPF_LValue | LC_OPF_Const; + } + } break; + + case LC_ASTKind_ExprCast: { + LC_Operand LC_PROP_ERROR(optype, n, LC_ResolveType(n->ecast.type)); + LC_Operand LC_PROP_ERROR(opexpr, n, LC_ResolveExpr(n->ecast.expr)); + // :ConstantFold + // the idea is that this will convert the literal into corresponding + // type. In c :uint(32) will become 32u. This way we can avoid doing + // typed arithmetic and let the backend handle it. + if (LC_IsUTConst(opexpr) && (LC_IsNum(optype.type) || LC_IsStr(optype.type))) { + if (LC_IsFloat(optype.type)) { + LC_PROP_ERROR(opexpr, n, LC_ConstCastFloat(n, opexpr)); + SetConstVal(n, opexpr.val); + } else if (LC_IsInt(optype.type)) { + LC_PROP_ERROR(opexpr, n, LC_ConstCastInt(n, opexpr)); + SetConstVal(n, opexpr.val); + } else if (LC_IsStr(optype.type)) { + LC_IF(!LC_IsUTStr(opexpr.type), n, "cannot cast constant expression of type '%s' to '%s'", LC_GenLCType(opexpr.type), LC_GenLCType(optype.type)); + SetConstVal(n, opexpr.val); + } else LC_IF(1, n, "cannot cast constant expression of type '%s' to '%s'", LC_GenLCType(opexpr.type), LC_GenLCType(optype.type)); + result.type = optype.type; + } else { + LC_PROP_ERROR(result, n, LC_ResolveTypeCast(n, optype, opexpr)); + LC_TryTyping(n->ecast.expr, result); + } + result.flags |= (opexpr.flags & LC_OPF_Const); + } break; + + case LC_ASTKind_ExprUnary: { + LC_PROP_ERROR(result, n, LC_ResolveExpr(n->eunary.expr)); + + if (LC_IsUTConst(result)) { + LC_PROP_ERROR(result, n, LC_EvalUnary(n, n->eunary.op, result)); + SetConstVal(n, result.val); + } else { + LC_OPResult r = LC_IsUnaryOpValidForType(n->eunary.op, result.type); + LC_IF(r == LC_OPResult_Error, n, "invalid unary operation for type '%s'", LC_GenLCType(result.type)); + if (r == LC_OPResult_Bool) result = LC_OPModBool(result); + } + } break; + + case LC_ASTKind_ExprBinary: { + LC_Operand LC_PROP_ERROR(left, n, LC_ResolveExpr(n->ebinary.left)); + LC_Operand LC_PROP_ERROR(right, n, LC_ResolveExpr(n->ebinary.right)); + LC_PROP_ERROR(result, n, LC_ResolveBinaryExpr(n, left, right)); + } break; + + case LC_ASTKind_ExprAddPtr: { + LC_Operand LC_PROP_ERROR(left, n, LC_ResolveExpr(n->ebinary.left)); + LC_Operand LC_PROP_ERROR(right, n, LC_ResolveExpr(n->ebinary.right)); + LC_IF(!LC_IsInt(right.type), n, "trying to addptr non integer value of type '%s'", LC_GenLCType(left.type)); + if (LC_IsUTStr(left.type)) LC_TryDefaultTyping(n->ebinary.left, &left); + LC_IF(!LC_IsPtr(left.type) && !LC_IsArray(left.type), n, "left type is required to be a pointer or array, instead got '%s'", LC_GenLCType(left.type)); + result = left; + if (!LC_IsUTConst(right)) result.flags &= ~LC_OPF_Const; + if (LC_IsArray(result.type)) result.type = LC_CreatePointerType(result.type->tbase); + LC_TryTyping(n->ebinary.right, result); + } break; + + case LC_ASTKind_ExprIndex: { + LC_Operand LC_PROP_ERROR(opindex, n, LC_ResolveExpr(n->eindex.index)); + LC_Operand LC_PROP_ERROR(opexpr, n, LC_ResolveExpr(n->eindex.base)); + LC_IF(!LC_IsInt(opindex.type), n, "indexing with non integer value of type '%s'", LC_GenLCType(opindex.type)); + if (LC_IsUTStr(opexpr.type)) LC_TryDefaultTyping(n->eindex.base, &opexpr); + LC_IF(!LC_IsPtr(opexpr.type) && !LC_IsArray(opexpr.type), n, "trying to index non indexable type '%s'", LC_GenLCType(opexpr.type)); + LC_IF(LC_IsVoidPtr(opexpr.type), n, "void is non indexable"); + LC_TryDefaultTyping(n->eindex.index, &opindex); + result.type = LC_GetBase(opexpr.type); + result.flags |= LC_OPF_LValue; + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, result.type)); + } break; + + case LC_ASTKind_ExprGetPointerOfValue: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveExpr(n->eunary.expr)); + LC_IF(!LC_IsLValue(op), n, "trying to access address of a temporal object"); + result.type = LC_CreatePointerType(op.type); + result.flags |= (op.flags & LC_OPF_Const); + } break; + + case LC_ASTKind_ExprGetValueOfPointer: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveExpr(n->eunary.expr)); + LC_IF(!LC_IsPtr(op.type), n, "trying to get value of non pointer type: '%s'", LC_GenLCType(op.type)); + result.type = LC_GetBase(op.type); + result.flags |= LC_OPF_LValue; + result.flags &= ~LC_OPF_Const; + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, result.type)); + } break; + + case LC_ASTKind_ExprField: { + bool first_part_executed = false; + + LC_Operand op = {0}; + if (n->efield.left->kind == LC_ASTKind_ExprIdent) { + LC_AST *nf = n->efield.left; + LC_Operand LC_PROP_ERROR(op_name, nf, LC_ResolveName(nf, nf->eident.name)); + + // LC_Match (Package.) and fold (Package.Other) into just (Other) + if (op_name.decl->kind == LC_DeclKind_Import) { + first_part_executed = true; + nf->eident.resolved_decl = op_name.decl; + nf->type = L->tvoid; + + LC_PROP_ERROR(op, n, LC_ResolveNameInScope(n, op_name.decl)); + } + } + + if (!first_part_executed) { + LC_ASTKind left_kind = n->efield.left->kind; + LC_PROP_ERROR(op, n, LC_ResolveExpr(n->efield.left)); + + LC_Type *type = LC_StripPointer(op.type); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, type)); + LC_IF(!LC_IsAggType(type), n->efield.left, "invalid operation, expected aggregate type, '%s' is not an aggregate", LC_GenLCType(type)); + LC_PROP_ERROR(op, n, LC_ResolveNameInScope(n, type->decl)); + LC_ASSERT(n, op.decl->kind == LC_DeclKind_Var); + result.flags |= LC_OPF_LValue | LC_OPF_Const; + } + result.val = op.decl->val; + } break; + + case LC_ASTKind_ExprCall: { + LC_ASSERT(n, n->ecompo.name); + LC_PROP_ERROR(result, n, LC_ResolveBuiltin(n)); + if (!result.type) { + LC_Operand LC_PROP_ERROR(left, n, LC_ResolveExpr(n->ecompo.name)); + LC_IF(!LC_IsProc(left.type), n, "trying to call value of invalid type '%s', not a procedure", LC_GenLCType(left.type)); + if (L->before_call_args_resolved) L->before_call_args_resolved(n, left.type); + LC_PROP_ERROR(result, n, LC_ResolveCompoCall(n, left.type)); + } + } break; + + case LC_ASTKind_ExprCompound: { + LC_Type *type = NULL; + if (n->ecompo.name) { + LC_PUSH_COMP_ARRAY_SIZE(n->ecompo.size); + LC_Operand LC_PROP_ERROR(left, n, LC_ResolveTypeOrExpr(n->ecompo.name)); + type = left.type; + LC_POP_COMP_ARRAY_SIZE(); + } + if (!n->ecompo.name) type = L->resolver.compo_context_type; + LC_IF(!type, n, "failed to deduce type of compound expression"); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, type)); + + if (LC_IsAggType(type)) { + LC_PROP_ERROR(result, n, LC_ResolveCompoAggregate(n, type)); + } else if (LC_IsArray(type)) { + LC_PROP_ERROR(result, n, LC_ResolveCompoArray(n, type)); + } else { + LC_IF(1, n, "compound of type '%s' is illegal, expected array, struct or union type", LC_GenLCType(type)); + } + } break; + + default: LC_IF(1, n, "internal compiler error: unhandled expression kind '%s'", LC_ASTKindToString(n->kind)); + } + + n->type = result.type; + if (n->type != L->tany && L->resolver.compo_context_type == L->tany) { + LC_MapInsertP(&L->implicit_any, n, (void *)(intptr_t)1); + result.flags &= ~LC_OPF_Const; + } + + if (L->on_expr_resolved) L->on_expr_resolved(n, &result); + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveStmtBlock(LC_AST *n) { + LC_ASSERT(n, n->kind == LC_ASTKind_StmtBlock); + + LC_PUSH_LOCAL_SCOPE(); + LC_PushAST(&L->resolver.stmt_block_stack, n); + + LC_Operand result = {0}; + for (LC_AST *it = n->sblock.first; it; it = it->next) { + LC_Operand op = LC_ResolveStmt(it); + + // We don't want to whine about non returned procedures if we spotted any errors + // inside of it. + if (LC_IsError(op) || (op.flags & LC_OPF_Returned)) result.flags |= LC_OPF_Returned; + } + + LC_PopAST(&L->resolver.stmt_block_stack); + LC_POP_LOCAL_SCOPE(); + + if (L->on_stmt_resolved) L->on_stmt_resolved(n); + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveVarDecl(LC_Decl *decl) { + LC_ASSERT(decl->ast, decl->kind == LC_DeclKind_Var); + LC_Operand result = {0}; + result.flags |= LC_OPF_Const; + + LC_AST *n = decl->ast; + LC_Operand optype = {0}; + LC_Operand opexpr = {0}; + + LC_AST *expr = n->dvar.expr; + LC_AST *type = n->dvar.type; + if (n->kind == LC_ASTKind_StmtVar) { + expr = n->svar.expr; + type = n->svar.type; + } else { + LC_ASSERT(n, n->kind == LC_ASTKind_DeclVar); + } + + // special case := #c(``) + if (expr && expr->kind == LC_ASTKind_ExprNote) { + LC_Operand LC_PROP_ERROR(opnote, expr, LC_ResolveNote(expr, true)); + LC_IF(type == NULL, n, "invalid usage of unknown type, need to add type annotation"); + LC_DECL_PROP_ERROR(optype, LC_ResolveType(type)); + decl->type = optype.type; + } else { + if (type) { + if (expr && expr->kind == LC_ASTKind_ExprCompound) { + LC_PUSH_COMP_ARRAY_SIZE(expr->ecompo.size); + LC_DECL_PROP_ERROR(optype, LC_ResolveType(type)); + LC_POP_COMP_ARRAY_SIZE(); + } else { + LC_DECL_PROP_ERROR(optype, LC_ResolveType(type)); + } + } + if (expr) { + LC_DECL_PROP_ERROR(opexpr, LC_ResolveExprAndPushCompoContext(expr, optype.type)); + if (!(opexpr.flags & LC_OPF_Const)) result.flags &= ~LC_OPF_Const; + } + + LC_Operand LC_DECL_PROP_ERROR(opcast, LC_ResolveTypeVarDecl(n, optype, opexpr)); + if (expr) LC_TryTyping(expr, opcast); + decl->val = opcast.val; + } + + LC_ASSERT(n, decl->type); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, decl->type)); + result.type = decl->type; + return result; +} + +LC_FUNCTION LC_Operand LC_MakeSureNoDeferBlock(LC_AST *n, char *str) { + for (int i = L->resolver.stmt_block_stack.len - 1; i >= 0; i -= 1) { + LC_AST *it = L->resolver.stmt_block_stack.data[i]; + if (it->kind == LC_ASTKind_Error) return LC_OPError(); + LC_ASSERT(it, it->kind == LC_ASTKind_StmtBlock); + LC_IF(it->sblock.kind == SBLK_Defer, n, str); + } + return LC_OPNull; +} + +LC_FUNCTION LC_Operand LC_MakeSureInsideLoopBlock(LC_AST *n, char *str) { + bool loop_found = false; + for (int i = L->resolver.stmt_block_stack.len - 1; i >= 0; i -= 1) { + LC_AST *it = L->resolver.stmt_block_stack.data[i]; + if (it->kind == LC_ASTKind_Error) return LC_OPError(); + LC_ASSERT(it, it->kind == LC_ASTKind_StmtBlock); + if (it->sblock.kind == SBLK_Loop) { + loop_found = true; + break; + } + } + LC_IF(!loop_found, n, str); + return LC_OPNull; +} + +LC_FUNCTION LC_Operand LC_MatchLabeledBlock(LC_AST *n) { + if (n->sbreak.name) { + bool found = false; + for (int i = L->resolver.stmt_block_stack.len - 1; i >= 0; i -= 1) { + LC_AST *it = L->resolver.stmt_block_stack.data[i]; + if (it->kind == LC_ASTKind_Error) return LC_OPError(); + if (it->sblock.name == n->sbreak.name) { + found = true; + break; + } + } + LC_IF(!found, n, "no label with name '%s'", n->sbreak.name); + } + return LC_OPNull; +} + +LC_FUNCTION void WalkToFindCall(LC_ASTWalker *w, LC_AST *n) { + if (n->kind == LC_ASTKind_ExprCall || n->kind == LC_ASTKind_ExprBuiltin) ((bool *)w->user_data)[0] = true; +} + +LC_FUNCTION bool LC_ContainsCallExpr(LC_AST *ast) { + LC_TempArena checkpoint = LC_BeginTemp(L->arena); + bool found_call = false; + { + LC_ASTWalker walker = LC_GetDefaultWalker(L->arena, WalkToFindCall); + walker.depth_first = false; + walker.user_data = (void *)&found_call; + LC_WalkAST(&walker, ast); + } + LC_EndTemp(checkpoint); + return found_call; +} + +LC_FUNCTION LC_Operand LC_ResolveStmt(LC_AST *n) { + LC_ASSERT(n, LC_IsStmt(n)); + + LC_Operand result = {0}; + switch (n->kind) { + case LC_ASTKind_StmtVar: { + LC_Operand LC_PROP_ERROR(opdecl, n, LC_CreateLocalDecl(LC_DeclKind_Var, n->svar.name, n)); + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveVarDecl(opdecl.decl)); + opdecl.decl->state = LC_DeclState_Resolved; + n->svar.resolved_decl = opdecl.decl; + n->type = op.type; + } break; + + case LC_ASTKind_StmtConst: { + LC_Operand LC_PROP_ERROR(opdecl, n, LC_CreateLocalDecl(LC_DeclKind_Const, n->sconst.name, n)); + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveConstDecl(opdecl.decl)); + opdecl.decl->state = LC_DeclState_Resolved; + n->type = op.type; + } break; + + case LC_ASTKind_StmtAssign: { + LC_Operand LC_PROP_ERROR(left, n, LC_ResolveExpr(n->sassign.left)); + LC_IF(!LC_IsLValue(left), n, "assigning value to a temporal object (lvalue)"); + LC_Type *type = left.type; + + LC_OPResult valid = LC_IsAssignValidForType(n->sassign.op, type); + LC_IF(valid == LC_OPResult_Error, n, "invalid assignment operation '%s' for type '%s'", LC_TokenKindToString(n->sassign.op), LC_GenLCType(type)); + + LC_Operand LC_PROP_ERROR(right, n, LC_ResolveExprAndPushCompoContext(n->sassign.right, type)); + LC_PROP_ERROR(result, n, LC_ResolveTypeVarDecl(n, left, right)); + LC_TryTyping(n->sassign.left, result); + LC_TryTyping(n->sassign.right, result); + n->type = result.type; + } break; + + case LC_ASTKind_StmtExpr: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveExpr(n->sexpr.expr)); + LC_TryDefaultTyping(n->sexpr.expr, &op); + n->type = op.type; + bool contains_call = LC_ContainsCallExpr(n->sexpr.expr); + LC_AST *note = LC_HasNote(n, L->iunused); + LC_IF(!note && !contains_call, n, "very likely a bug, expression statement doesn't contain any calls so it doesn't do anything"); + } break; + + case LC_ASTKind_StmtReturn: { + LC_PROP_ERROR(result, n, LC_MakeSureNoDeferBlock(n, "returning from defer block is illegal")); + LC_Operand op = LC_OPType(L->tvoid); + if (n->sreturn.expr) { + LC_PROP_ERROR(op, n, LC_ResolveExprAndPushCompoContext(n->sreturn.expr, L->resolver.expected_ret_type)); + } + + if (!(op.type == L->resolver.expected_ret_type && op.type == L->tvoid)) { + LC_PROP_ERROR(op, n, LC_ResolveTypeVarDecl(n, LC_OPType(L->resolver.expected_ret_type), op)); + if (n->sreturn.expr) LC_TryTyping(n->sreturn.expr, op); + } + result.flags |= LC_OPF_Returned; + } break; + + case LC_ASTKind_StmtNote: LC_PROP_ERROR(result, n, LC_ResolveNote(n, false)); break; + case LC_ASTKind_StmtContinue: + LC_PROP_ERROR(result, n, LC_MakeSureNoDeferBlock(n, "continue inside of defer is illegal")); + LC_PROP_ERROR(result, n, LC_MakeSureInsideLoopBlock(n, "continue outside of a for loop is illegal")); + case LC_ASTKind_StmtBreak: { + LC_PROP_ERROR(result, n, LC_MakeSureNoDeferBlock(n, "break inside of defer is illegal")); + LC_PROP_ERROR(result, n, LC_MakeSureInsideLoopBlock(n, "break outside of a for loop is illegal")); + LC_PROP_ERROR(result, n, LC_MatchLabeledBlock(n)); + } break; + + case LC_ASTKind_StmtDefer: { + LC_PROP_ERROR(result, n, LC_MakeSureNoDeferBlock(n, "defer inside of defer is illegal")); + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveStmtBlock(n->sdefer.body)); + LC_AST *parent_block = LC_GetLastAST(&L->resolver.stmt_block_stack); + LC_ASSERT(n, parent_block->kind == LC_ASTKind_StmtBlock); + LC_SLLStackAddMod(parent_block->sblock.first_defer, n, sdefer.next); + } break; + + case LC_ASTKind_StmtSwitch: { + LC_Operand LC_PROP_ERROR(opfirst, n, LC_ResolveExpr(n->sswitch.expr)); + LC_IF(!LC_IsInt(opfirst.type), n, "invalid type in switch condition '%s', it should be an integer", LC_GenLCType(opfirst.type)); + LC_TryDefaultTyping(n->sswitch.expr, &opfirst); + + bool all_returned = true; + bool has_default = n->sswitch.last && n->sswitch.last->kind == LC_ASTKind_StmtSwitchDefault; + + LC_Operand *ops = LC_PushArray(L->arena, LC_Operand, n->sswitch.total_switch_case_count); + int opi = 0; + LC_ASTFor(case_it, n->sswitch.first) { + if (case_it->kind == LC_ASTKind_StmtSwitchCase) { + LC_ASTFor(case_expr_it, case_it->scase.first) { + LC_Operand LC_PROP_ERROR(opcase, n, LC_ResolveExpr(case_expr_it)); + LC_IF(!LC_IsUTConst(opcase), case_expr_it, "expected an untyped constant"); + ops[opi++] = opcase; + + LC_Operand LC_PROP_ERROR(o, n, LC_ResolveTypeVarDecl(case_expr_it, opfirst, opcase)); + LC_TryTyping(case_expr_it, o); + } + } + LC_Operand LC_PROP_ERROR(opbody, case_it, LC_ResolveStmtBlock(case_it->scase.body)); + if (!(opbody.flags & LC_OPF_Returned)) all_returned = false; + } + LC_ASSERT(n, opi == n->sswitch.total_switch_case_count); + + for (int i = 0; i < opi; i += 1) { + LC_Operand a = ops[i]; + for (int j = 0; j < opi; j += 1) { + if (i == j) continue; + LC_Operand b = ops[j]; + + // bounds check error is thrown in LC_ResolveTypeVarDecl + if (LC_BigIntFits(a.v.i, opfirst.type) && LC_BigIntFits(b.v.i, opfirst.type)) { + uint64_t au = LC_Bigint_as_unsigned(&a.v.i); + uint64_t bu = LC_Bigint_as_unsigned(&b.v.i); + LC_IF(au == bu, n, "duplicate fields, with value: %llu, in a switch statement", au); + } + } + } + + if (all_returned && has_default) result.flags |= LC_OPF_Returned; + } break; + + case LC_ASTKind_StmtFor: { + LC_StmtFor *sfor = &n->sfor; + LC_PUSH_LOCAL_SCOPE(); + + if (sfor->init) { + LC_Operand opinit = LC_ResolveStmt(sfor->init); + if (LC_IsError(opinit)) { + n->kind = LC_ASTKind_Error; + LC_POP_LOCAL_SCOPE(); + return opinit; + } + + LC_TryDefaultTyping(sfor->init, &opinit); + } + if (sfor->cond) { + LC_Operand opcond = LC_ResolveExpr(sfor->cond); + if (LC_IsError(opcond)) { + n->kind = LC_ASTKind_Error; + LC_POP_LOCAL_SCOPE(); + return opcond; + } + + LC_TryDefaultTyping(sfor->cond, &opcond); + if (!LC_IsIntLike(opcond.type)) { + n->kind = LC_ASTKind_Error; + LC_POP_LOCAL_SCOPE(); + return LC_ReportASTError(n, "invalid type in for condition '%s', it should be an integer or pointer", LC_GenLCType(opcond.type)); + } + } + if (sfor->inc) { + LC_Operand opinc = LC_ResolveStmt(sfor->inc); + if (LC_IsError(opinc)) { + n->kind = LC_ASTKind_Error; + LC_POP_LOCAL_SCOPE(); + return opinc; + } + } + result = LC_ResolveStmtBlock(sfor->body); + if (LC_IsError(result)) { + n->kind = LC_ASTKind_Error; + LC_POP_LOCAL_SCOPE(); + return result; + } + + LC_POP_LOCAL_SCOPE(); + } break; + + case LC_ASTKind_StmtBlock: { + // we don't handle errors here explicitly + LC_Operand op = LC_ResolveStmtBlock(n); + if (op.flags & LC_OPF_Returned) result.flags |= LC_OPF_Returned; + } break; + + case LC_ASTKind_StmtIf: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveExpr(n->sif.expr)); + LC_TryDefaultTyping(n->sif.expr, &op); + LC_IF(!LC_IsIntLike(op.type), n, "invalid type in if clause expression %s it should be an integer or pointer", LC_GenLCType(op.type)); + + bool all_returned = true; + bool has_else = n->sif.last && n->sif.last->kind == LC_ASTKind_StmtElse; + + LC_Operand LC_PROP_ERROR(opbody, n, LC_ResolveStmtBlock(n->sif.body)); + if (!(opbody.flags & LC_OPF_Returned)) all_returned = false; + + LC_ASTFor(it, n->sif.first) { + if (it->kind == LC_ASTKind_StmtElseIf) { + LC_Operand LC_PROP_ERROR(op, it, LC_ResolveExpr(it->sif.expr)); + LC_TryDefaultTyping(it->sif.expr, &op); + LC_IF(!LC_IsIntLike(op.type), n, "invalid type in if clause expression %s it should be an integer or pointer", LC_GenLCType(op.type)); + } + LC_Operand LC_PROP_ERROR(opbody, it, LC_ResolveStmtBlock(it->sif.body)); + if (!(opbody.flags & LC_OPF_Returned)) all_returned = false; + } + + if (all_returned && has_else) result.flags |= LC_OPF_Returned; + } break; + default: LC_IF(1, n, "internal compiler error: unhandled statement kind '%s'", LC_ASTKindToString(n->kind)); + } + + if (L->on_stmt_resolved) L->on_stmt_resolved(n); + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveConstDecl(LC_Decl *decl) { + LC_ASSERT(decl->ast, decl->kind == LC_DeclKind_Const); + LC_AST *n = decl->ast; + LC_AST *expr = n->dconst.expr; + if (n->kind == LC_ASTKind_StmtConst) { + expr = n->sconst.expr; + } else { + LC_ASSERT(n, n->kind == LC_ASTKind_DeclConst); + } + + LC_Operand LC_DECL_PROP_ERROR(opexpr, LC_ResolveExpr(expr)); + LC_DECL_IF(!LC_IsUTConst(opexpr), n, "expected an untyped constant"); + LC_DECL_IF(!LC_IsUntyped(opexpr.type), n, "type of constant expression is not a simple type"); + decl->val = opexpr.val; + return opexpr; +} + +LC_FUNCTION LC_Operand LC_ResolveName(LC_AST *pos, LC_Intern intern) { + LC_Decl *decl = LC_GetLocalOrGlobalDecl(intern); + LC_DECL_IF(!decl, pos, "undeclared identifier '%s'", intern); + LC_DECL_IF(decl->state == LC_DeclState_Resolving, pos, "cyclic dependency %s", intern); + if (decl->state == LC_DeclState_Error) return LC_OPError(); + if (decl->state == LC_DeclState_Resolved || decl->state == LC_DeclState_ResolvedBody) return LC_OPDecl(decl); + LC_ASSERT(pos, decl->state == LC_DeclState_Unresolved); + decl->state = LC_DeclState_Resolving; + + LC_AST *n = decl->ast; + switch (decl->kind) { + case LC_DeclKind_Const: { + LC_Operand LC_DECL_PROP_ERROR(op, LC_ResolveConstDecl(decl)); + } break; + case LC_DeclKind_Var: { + LC_Operand LC_DECL_PROP_ERROR(op, LC_ResolveVarDecl(decl)); + LC_DECL_IF(!(op.flags & LC_OPF_Const), n, "non constant global declarations are illegal"); + } break; + case LC_DeclKind_Proc: { + LC_Operand LC_DECL_PROP_ERROR(optype, LC_ResolveType(n->dproc.type)); + decl->type = optype.type; + decl->type->decl = decl; + } break; + case LC_DeclKind_Import: { + LC_ASSERT(n, decl->scope); + } break; + case LC_DeclKind_Type: { + LC_ASSERT(n, n->kind == LC_ASTKind_DeclTypedef); + LC_Operand LC_DECL_PROP_ERROR(op, LC_ResolveType(n->dtypedef.type)); + decl->val = op.val; + + // I have decided that aggregates cannot be hard typedefed. + // It brings issues to LC_ResolveTypeAggregate and is not needed, what's needed + // is typedef on numbers and pointers that create distinct new + // types. I have never had a use for typedefing a struct to make + // it more typesafe etc. + LC_AST *is_weak = LC_HasNote(n, L->iweak); + bool is_agg = op.type->decl && LC_IsAgg(op.type->decl->ast); + if (!is_weak && !is_agg) decl->type = LC_CreateTypedef(decl, decl->type); + LC_DECL_IF(is_weak && is_agg, n, "@weak doesn't work on aggregate types"); + } break; + default: LC_DECL_IF(1, n, "internal compiler error: unhandled LC_DeclKind: '%s'", LC_DeclKindToString(decl->kind)) + } + decl->state = LC_DeclState_Resolved; + + if (L->on_decl_type_resolved) L->on_decl_type_resolved(decl); + LC_AST *pkg = decl->package; + LC_DLLAdd(pkg->apackage.first_ordered, pkg->apackage.last_ordered, decl); + return LC_OPDecl(decl); +} + +LC_FUNCTION LC_Operand LC_ResolveConstInt(LC_AST *n, LC_Type *int_type, uint64_t *out_size) { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveExpr(n)); + LC_IF(!LC_IsUTConst(op), n, "expected a constant untyped int"); + LC_IF(!LC_IsUTInt(op.type), n, "expected untyped int constant instead: '%s'", LC_GenLCType(op.type)); + LC_IF(!LC_BigIntFits(op.val.i, int_type), n, "constant value: '%s', doesn't fit in type '%s'", LC_GenLCTypeVal(op.val), LC_GenLCType(int_type)); + if (out_size) *out_size = LC_Bigint_as_unsigned(&op.val.i); + LC_TryTyping(n, LC_OPType(int_type)); + return op; +} + +LC_FUNCTION LC_Operand LC_ResolveType(LC_AST *n) { + LC_ASSERT(n, LC_IsType(n)); + LC_Operand result = {0}; + + switch (n->kind) { + case LC_ASTKind_TypespecField: { + LC_ASSERT(n, n->efield.left->kind == LC_ASTKind_TypespecIdent); + LC_Operand LC_PROP_ERROR(l, n, LC_ResolveName(n, n->efield.left->eident.name)); + LC_IF(l.decl->kind != LC_DeclKind_Import, n, "only accessing '.' imports in type definitions is valid, you are trying to access: '%s'", LC_DeclKindToString(l.decl->kind)); + n->efield.left->eident.resolved_decl = l.decl; + n->efield.left->type = L->tvoid; + + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveNameInScope(n, l.decl)); + LC_IF(op.decl->kind != LC_DeclKind_Type, n, "expected reference to type, instead it's: '%s'", LC_DeclKindToString(op.decl->kind)); + result.type = op.decl->type; + } break; + + case LC_ASTKind_TypespecIdent: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveName(n, n->eident.name)); + LC_IF(op.decl->kind != LC_DeclKind_Type, n, "identifier is not a type"); + result.type = op.decl->type; + n->eident.resolved_decl = op.decl; + } break; + + case LC_ASTKind_TypespecPointer: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveType(n->tpointer.base)); + result.type = LC_CreatePointerType(op.type); + } break; + + case LC_ASTKind_TypespecArray: { + LC_Operand LC_PROP_ERROR(opbase, n, LC_ResolveType(n->tarray.base)); + uint64_t size = L->resolver.compo_context_array_size; + if (n->tarray.index) { + LC_Operand LC_PROP_ERROR(opindex, n, LC_ResolveConstInt(n->tarray.index, L->tint, &size)); + } + LC_IF(size == 0, n, "failed to deduce array size"); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, opbase.type)); + + result.type = LC_CreateArrayType(opbase.type, (int)size); + } break; + + case LC_ASTKind_TypespecProc: { + LC_Type *ret = L->tvoid; + if (n->tproc.ret) { + LC_Operand LC_PROP_ERROR(op, n->tproc.ret, LC_ResolveType(n->tproc.ret)); + ret = op.type; + } + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, ret)); + LC_TypeMemberList typelist = {0}; + LC_ASTFor(it, n->tproc.first) { + LC_Operand LC_PROP_ERROR(op, it, LC_ResolveType(it->tproc_arg.type)); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(it, op.type)); + + LC_AST *expr = it->tproc_arg.expr; + if (expr) { + LC_Operand LC_PROP_ERROR(opexpr, expr, LC_ResolveExprAndPushCompoContext(expr, op.type)); + LC_Operand LC_PROP_ERROR(opfin, expr, LC_ResolveTypeVarDecl(expr, op, opexpr)); + LC_TryTyping(expr, opfin); + } + + LC_TypeMember *mem = LC_AddTypeToList(&typelist, it->tproc_arg.name, op.type, it); + LC_IF(!mem, it, "duplicate proc argument '%s'", it->tproc_arg.name); + mem->default_value_expr = expr; + it->type = op.type; + } + + LC_TypeFor(i, typelist.first) { + LC_TypeFor(j, typelist.first) { + LC_IF(i != j && i->name == j->name, i->ast, "procedure has 2 arguments with the same name"); + } + } + result.type = LC_CreateProcType(typelist, ret, n->tproc.vargs, n->tproc.vargs_any_promotion); + } break; + + default: LC_IF(1, n, "internal compiler error: unhandled kind in LC_ResolveType '%s'", LC_ASTKindToString(n->kind)); + } + + n->type = result.type; + LC_ASSERT(n, result.type); + return result; +} + +// clang-format off +// NA - Not applicable +// LC_RPS - OK if right side int of pointer size +// LC_LPS +// LC_TEQ - OK if types equal +// LC_RO0 - OK if right value is int equal nil +// LT - Left untyped to typed +// RT +// LF - Left to float +// RF +// LC_SR - String +enum { LC_INT, LC_FLOAT, LC_UT_INT, LC_UT_FLOAT, LC_UT_STR, LC_PTR, LC_VOID_PTR, LC_PROC, LC_AGG, LC_ARRAY, LC_ANY, LC_VOID, LC_TYPE_COUNT }; +typedef enum { LC_NO, LC_OK, LC_LPS, LC_RPS, LC_TEQ, LC_NA, LC_RO0, LC_LT, LC_RT, LC_LF, LC_RF, LC_SR } LC_TypeRule; + +LC_TypeRule CastingRules[LC_TYPE_COUNT][LC_TYPE_COUNT] = { +//\/:tgt( src)> LC_INT , LC_FLOAT , LC_UT_INT , LC_UT_FLOAT , LC_UT_STR , LC_PTR , LC_VOID_PTR , LC_PROC , LC_AGG , LC_ARRAY +/*[LC_INT] = */{LC_OK , LC_OK , LC_OK , LC_OK , LC_NO , LC_LPS , LC_LPS , LC_NO , LC_NO , LC_NO} , +/*[LC_FLOAT] = */{LC_OK , LC_OK , LC_OK , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO} , +/*[LC_UT_INT] = */{LC_NA , LC_NA , LC_NA , LC_NA , LC_NO , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA} , +/*[LC_UT_FLOAT] = */{LC_NA , LC_NA , LC_NA , LC_NA , LC_NO , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA} , +/*[LC_UT_STR] = */{LC_NA , LC_NA , LC_NA , LC_NA , LC_NO , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA} , +/*[LC_PTR] = */{LC_RPS , LC_NO , LC_OK , LC_NO , LC_SR , LC_OK , LC_OK , LC_OK , LC_NO , LC_NO} , +/*[LC_VOID_PTR] = */{LC_RPS , LC_NO , LC_OK , LC_NO , LC_OK , LC_OK , LC_OK , LC_OK , LC_NO , LC_NO} , +/*[LC_PROC] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_OK , LC_OK , LC_OK , LC_NO , LC_NO} , +/*[LC_AGG] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_SR , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO} , +/*[LC_ARRAY] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO} , +}; + +LC_TypeRule AssignRules[LC_TYPE_COUNT][LC_TYPE_COUNT] = { +//\/l r> LC_INT , LC_FLOAT , LC_UT_INT , LC_UT_FLOAT , LC_UT_STR , LC_PTR , LC_VOID_PTR , LC_PROC , LC_AGG , LC_ARRAY , LC_ANY +/*[LC_INT] = */{LC_TEQ , LC_NO , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO} , +/*[LC_FLOAT] = */{LC_NO , LC_TEQ , LC_OK , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO} , +/*[LC_UT_INT] = */{LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NO} , +/*[LC_UT_FLOAT] = */{LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NO} , +/*[LC_UT_STR] = */{LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NO , LC_NA , LC_NA , LC_NA , LC_NA , LC_NO} , +/*[LC_PTR] = */{LC_NO , LC_NO , LC_RO0 , LC_NO , LC_SR , LC_TEQ , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO} , +/*[LC_VOID_PTR] = */{LC_NO , LC_NO , LC_RO0 , LC_NO , LC_OK , LC_OK , LC_OK , LC_OK , LC_NO , LC_NO , LC_NO} , +/*[LC_PROC] = */{LC_NO , LC_NO , LC_RO0 , LC_NO , LC_NO , LC_NO , LC_OK , LC_TEQ , LC_NO , LC_NO , LC_NO} , +/*[LC_AGG] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_SR , LC_NO , LC_NO , LC_NO , LC_TEQ , LC_NO , LC_TEQ} , +/*[LC_ARRAY] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_TEQ , LC_NO} , +/*[LC_ANY] = */{LC_OK , LC_OK , LC_OK , LC_OK , LC_OK , LC_OK , LC_NO , LC_OK , LC_OK , LC_OK , LC_OK} , +}; + +LC_TypeRule BinaryRules[LC_TYPE_COUNT][LC_TYPE_COUNT] = { +//\/l r> LC_INT , LC_FLOAT , LC_UT_INT , LC_UT_FLOAT , LC_UT_STR , LC_PTR , LC_VOID_PTR , LC_PROC , LC_AGG , LC_ARRAY +/*[LC_INT] = */{LC_TEQ , LC_NO , LC_RT , LC_NO , LC_NO , LC_NO , LC_OK , LC_OK , LC_NO , LC_NO , } , +/*[LC_FLOAT] = */{LC_NO , LC_TEQ , LC_RT , LC_RT , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , } , +/*[LC_UT_INT] = */{LC_LT , LC_LT , LC_OK , LC_LF , LC_NO , LC_OK , LC_OK , LC_OK , LC_NO , LC_NO , } , +/*[LC_UT_FLOAT]= */{LC_NO , LC_LT , LC_RF , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , } , +/*[LC_UT_STR] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , } , +/*[LC_PTR] = */{LC_OK , LC_NO , LC_OK , LC_NO , LC_NO , LC_OK , LC_OK , LC_NO , LC_NO , LC_NO , } , +/*[LC_VOID_PTR]= */{LC_OK , LC_NO , LC_OK , LC_NO , LC_NO , LC_OK , LC_OK , LC_NO , LC_NO , LC_NO , } , +/*[LC_PROC] = */{LC_OK , LC_NO , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , } , +/*[LC_AGG] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , } , +/*[LC_ARRAY] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , } , +}; +// clang-format on + +int GetTypeCategory(LC_Type *x) { + if (x->kind >= LC_TypeKind_char && x->kind <= LC_TypeKind_ullong) return LC_INT; + if ((x->kind == LC_TypeKind_float) || (x->kind == LC_TypeKind_double)) return LC_FLOAT; + if (x->kind == LC_TypeKind_UntypedInt) return LC_UT_INT; + if (x->kind == LC_TypeKind_UntypedFloat) return LC_UT_FLOAT; + if (x->kind == LC_TypeKind_UntypedString) return LC_UT_STR; + if (x == L->tpvoid) return LC_VOID_PTR; + if (x == L->tany) return LC_ANY; + if (x->kind == LC_TypeKind_Pointer) return LC_PTR; + if (x->kind == LC_TypeKind_Proc) return LC_PROC; + if (LC_IsAggType(x)) return LC_AGG; + if (LC_IsArray(x)) return LC_ARRAY; + return LC_VOID; +} + +LC_FUNCTION LC_Operand LC_ResolveBinaryExpr(LC_AST *n, LC_Operand l, LC_Operand r) { + bool isconst = LC_IsConst(l) && LC_IsConst(r); + + LC_TypeRule rule = BinaryRules[GetTypeCategory(l.type)][GetTypeCategory(r.type)]; + LC_IF(rule == LC_NO, n, "cannot perform binary operation, types don't qualify for it, left: '%s' right: '%s'", LC_GenLCType(l.type), LC_GenLCType(r.type)); + LC_IF(rule == LC_TEQ && l.type != r.type, n, "cannot perform binary operation, types are incompatible, left: '%s' right: '%s'", LC_GenLCType(l.type), LC_GenLCType(r.type)); + if (rule == LC_LT) l = LC_OPModType(l, r.type); + if (rule == LC_RT) r = LC_OPModType(r, l.type); + if (rule == LC_LF) l = LC_ConstCastFloat(n, l); + if (rule == LC_RF) r = LC_ConstCastFloat(n, r); + LC_ASSERT(n, rule == LC_LT || rule == LC_RT || rule == LC_LF || rule == LC_RF || rule == LC_OK || rule == LC_TEQ); + + // WARNING: if we allow for more then boolean operations on pointers then + // we need to fix the propagated type here, we are counting on it getting + // modified to bool. + LC_Operand op = LC_OPType(l.type); + if (isconst) op.flags |= LC_OPF_Const; + if (LC_IsUTConst(l) && LC_IsUTConst(r)) { + LC_PROP_ERROR(op, n, LC_EvalBinary(n, l, n->ebinary.op, r)); + SetConstVal(n, op.val); + } else { + LC_OPResult r = LC_IsBinaryExprValidForType(n->ebinary.op, op.type); + LC_IF(r == LC_OPResult_Error, n, "invalid binary operation for type '%s'", LC_GenLCType(op.type)); + (LC_TryTyping(n->ebinary.left, op), LC_TryTyping(n->ebinary.right, op)); + if (r == LC_OPResult_Bool) op = LC_OPModBool(op); + } + + return op; +} + +LC_FUNCTION LC_Operand LC_ResolveTypeVargs(LC_AST *pos, LC_Operand v) { + if (LC_IsUntyped(v.type)) v = LC_OPModDefaultUT(v); // untyped => typed + if (LC_IsSmallerThenInt(v.type)) v = LC_OPModType(v, L->tint); // c int promotion + if (v.type == L->tfloat) v = LC_OPModType(v, L->tdouble); // c int promotion + return v; +} + +LC_FUNCTION LC_Operand LC_ResolveTypeCast(LC_AST *pos, LC_Operand t, LC_Operand v) { + LC_TypeRule rule = CastingRules[GetTypeCategory(t.type)][GetTypeCategory(v.type)]; + LC_IF(rule == LC_NO, pos, "cannot cast, types are incompatible, left: '%s' right: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_RPS && v.type->size != L->tpvoid->size, pos, "cannot cast, integer type on right is not big enough to hold a pointer, left: '%s' right: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_LPS && t.type->size != L->tpvoid->size, pos, "cannot cast, integer type on left is not big enough to hold a pointer, left: '%s' right: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_SR && !LC_IsStr(t.type), pos, "cannot cast untyped string to non string type: '%s'", LC_GenLCType(t.type)); + LC_ASSERT(pos, rule == LC_LPS || rule == LC_RPS || rule == LC_OK); + + LC_Operand op = LC_OPType(t.type); + op.flags = (v.flags & LC_OPF_LValue) | (v.flags & LC_OPF_Const); + return op; +} + +LC_FUNCTION LC_Operand LC_ResolveTypeVarDecl(LC_AST *pos, LC_Operand t, LC_Operand v) { + t.v = v.v; + LC_IF(t.type && t.type->kind == LC_TypeKind_void, pos, "cannot create a variable of type void"); + LC_IF(v.type && v.type->kind == LC_TypeKind_void, pos, "cannot assign void expression to a variable"); + if (v.type && t.type) { + LC_TypeRule rule = AssignRules[GetTypeCategory(t.type)][GetTypeCategory(v.type)]; + LC_IF(rule == LC_NO, pos, "cannot assign, types are incompatible, variable type: '%s' expression type: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_RPS && v.type->size != L->tpvoid->size, pos, "cannot assign, integer type of expression is not big enough to hold a pointer, left: '%s' right: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_LPS && t.type->size != L->tpvoid->size, pos, "cannot assign, integer type of variable is not big enough to hold a pointer, left: '%s' right: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_TEQ && t.type != v.type, pos, "cannot assign, types require explicit cast, variable type: '%s' expression type: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_RO0 && v.type != L->tuntypednil, pos, "cannot assign, can assign only const integer equal to 0, variable type: '%s' expression type: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_SR && !LC_IsStr(t.type), pos, "cannot assign untyped string to non string type: '%s'", LC_GenLCType(t.type)); + LC_ASSERT(pos, rule == LC_LPS || rule == LC_RPS || rule == LC_OK || rule == LC_TEQ || rule == LC_RO0 || rule == LC_SR); + return t; + } + + if (v.type) return LC_OPModDefaultUT(v); // NULL := untyped => default + if (t.type) return t; // T := NULL => T + return LC_ReportASTError(pos, "internal compiler error: failed to resolve type of variable, both type and expression are null"); +} + +LC_FUNCTION LC_Operand LC_ResolveTypeAggregate(LC_AST *pos, LC_Type *type) { + LC_Decl *decl = type->decl; + if (type->kind == LC_TypeKind_Error) return LC_OPError(); + LC_TYPE_IF(type->kind == LC_TypeKind_Completing, pos, "cyclic dependency in type '%s'", type->decl->name); + if (type->kind != LC_TypeKind_Incomplete) return LC_OPNull; + LC_PUSH_SCOPE(L->resolver.package->apackage.scope); + + LC_AST *n = decl->ast; + LC_ASSERT(n, decl); + LC_ASSERT(n, n->kind == LC_ASTKind_DeclStruct || n->kind == LC_ASTKind_DeclUnion); + int decl_stack_size = 0; + + type->kind = LC_TypeKind_Completing; + LC_ASTFor(it, n->dagg.first) { + LC_Intern name = it->tagg_mem.name; + + LC_Operand op = LC_ResolveType(it->tagg_mem.type); + if (LC_IsError(op)) { + LC_MarkDeclError(decl); + type->kind = LC_TypeKind_Error; + continue; // handle error after we go through all fields + } + + LC_Operand opc = LC_ResolveTypeAggregate(it, op.type); + if (LC_IsError(opc)) { + LC_MarkDeclError(decl); + type->kind = LC_TypeKind_Error; + continue; // handle error after we go through all fields + } + + LC_TypeMember *mem = LC_AddTypeToList(&type->tagg.mems, name, op.type, it); + LC_TYPE_IF(mem == NULL, it, "duplicate field '%s' in aggregate type '%s'", name, decl->name); + } + if (type->kind == LC_TypeKind_Error) { + return LC_OPError(); + } + LC_TYPE_IF(type->tagg.mems.count == 0, n, "aggregate type '%s' has no fields", decl->name); + decl_stack_size += type->tagg.mems.count; + + LC_AST *packed = LC_HasNote(n, L->ipacked); + if (n->kind == LC_ASTKind_DeclStruct) { + type->kind = LC_TypeKind_Struct; + int field_sizes = 0; + LC_TypeFor(it, type->tagg.mems.first) { + int mem_align = packed ? 1 : it->type->align; + LC_ASSERT(n, LC_IS_POW2(mem_align)); + type->size = (int)LC_AlignUp(type->size, mem_align); + it->offset = type->size; + field_sizes += it->type->size; + type->align = LC_MAX(type->align, mem_align); + type->size = it->type->size + (int)LC_AlignUp(type->size, mem_align); + } + type->size = (int)LC_AlignUp(type->size, type->align); + type->padding = type->size - field_sizes; + } + + if (n->kind == LC_ASTKind_DeclUnion) { + type->kind = LC_TypeKind_Union; + if (packed) LC_ReportASTError(packed, "@packed on union is invalid"); + LC_TypeFor(it, type->tagg.mems.first) { + LC_ASSERT(n, LC_IS_POW2(it->type->align)); + type->size = LC_MAX(type->size, it->type->size); + type->align = LC_MAX(type->align, it->type->align); + } + type->size = (int)LC_AlignUp(type->size, type->align); + } + + int map_size = LC_NextPow2(decl_stack_size * 2 + 1); + decl->scope = LC_CreateScope(map_size); + + LC_TypeFor(it, type->tagg.mems.first) { + LC_Decl *d = LC_CreateDecl(LC_DeclKind_Var, it->name, it->ast); + d->state = LC_DeclState_Resolved; + d->type = it->type; + d->type_member = it; + LC_AddDeclToScope(decl->scope, d); + } + + LC_ASSERT(n, decl->scope->cap == map_size); + + if (L->on_decl_type_resolved) L->on_decl_type_resolved(decl); + LC_AST *pkg = decl->package; + LC_DLLAdd(pkg->apackage.first_ordered, pkg->apackage.last_ordered, decl); + LC_POP_SCOPE(); + return LC_OPNull; +} + +#undef LC_IF +#undef LC_DECL_IF +#undef LC_PROP_ERROR +#undef LC_DECL_PROP_ERROR +const int ParseStmtBlock_AllowSingleStmt = 1; + +LC_FUNCTION LC_Parser LC_MakeParser(LC_Lex *x) { + LC_Parser p = {0}; + p.at = x->tokens; + p.begin = x->tokens; + p.end = x->tokens + x->token_count; + p.x = x; + return p; +} + +LC_FUNCTION LC_Parser *LC_MakeParserQuick(char *str) { + LC_Lex *x = LC_LexStream("quick_lex", str, 0); + LC_InternTokens(x); + + L->quick_parser = LC_MakeParser(x); + L->parser = &L->quick_parser; + return L->parser; +} + +LC_FUNCTION LC_AST *LC_ReportParseError(LC_Token *pos, const char *str, ...) { + LC_FORMAT(L->arena, str, n); + LC_SendErrorMessage(pos, n); + L->errors += 1; + LC_AST *r = LC_CreateAST(pos, LC_ASTKind_Error); + return r; +} + +LC_FUNCTION LC_Token *LC_Next(void) { + if (L->parser->at < L->parser->end) { + LC_Token *result = L->parser->at; + L->parser->at += 1; + return result; + } + return &L->NullToken; +} + +LC_FUNCTION LC_Token *LC_Get(void) { + if (L->parser->at < L->parser->end) { + return L->parser->at; + } + return &L->NullToken; +} + +LC_FUNCTION LC_Token *LC_GetI(int i) { + LC_Token *result = L->parser->at + i; + if (result >= L->parser->begin && result < L->parser->end) { + return result; + } + return &L->NullToken; +} + +LC_FUNCTION LC_Token *LC_Is(LC_TokenKind kind) { + LC_Token *t = LC_Get(); + if (t->kind == kind) { + return t; + } + return 0; +} + +LC_FUNCTION LC_Token *LC_IsKeyword(LC_Intern intern) { + LC_Token *t = LC_Get(); + if (t->kind == LC_TokenKind_Keyword && t->ident == intern) { + return t; + } + return 0; +} + +LC_FUNCTION LC_Token *LC_Match(LC_TokenKind kind) { + LC_Token *t = LC_Get(); + if (t->kind == kind) { + LC_Next(); + return t; + } + return 0; +} + +LC_FUNCTION LC_Token *LC_MatchKeyword(LC_Intern intern) { + LC_Token *t = LC_Get(); + if (t->kind == LC_TokenKind_Keyword && t->ident == intern) { + LC_Next(); + return t; + } + return 0; +} + +#define LC_EXPECT(token, KIND, context) \ + LC_Token *token = LC_Match(KIND); \ + if (!token) { \ + LC_Token *t = LC_Get(); \ + return LC_ReportParseError(t, "expected %s got instead %s, this happened while parsing: %s", LC_TokenKindToString(KIND), LC_TokenKindToString(t->kind), context); \ + } + +#define LC_PROP_ERROR(expr, ...) \ + expr = __VA_ARGS__; \ + do { \ + if (expr->kind == LC_ASTKind_Error) { \ + return expr; \ + } \ + } while (0) + +// Pratt expression parser +// Based on this really good article: https://matklad.github.io/2020/04/13/simple-but-powerful-pratt-parsing.html +// clang-format off +LC_FUNCTION LC_BindingPower LC_MakeBP(int left, int right) { + LC_BindingPower result = {left, right}; + return result; +} + +LC_FUNCTION LC_BindingPower LC_GetBindingPower(LC_Binding binding, LC_TokenKind kind) { + if (binding == LC_Binding_Prefix) goto Prefix; + if (binding == LC_Binding_Infix) goto Infix; + if (binding == LC_Binding_Postfix) goto Postfix; + LC_ASSERT(NULL, !"invalid codepath"); + +Prefix: + switch (kind) { + case LC_TokenKind_OpenBracket: return LC_MakeBP(-2, 22); + case LC_TokenKind_Mul: case LC_TokenKind_BitAnd: case LC_TokenKind_Keyword: case LC_TokenKind_OpenParen: + case LC_TokenKind_Sub: case LC_TokenKind_Add: case LC_TokenKind_Neg: case LC_TokenKind_Not: case LC_TokenKind_OpenBrace: return LC_MakeBP(-2, 20); + default: return LC_MakeBP(-1, -1); + } +Infix: + switch (kind) { + case LC_TokenKind_Or: return LC_MakeBP(9, 10); + case LC_TokenKind_And: return LC_MakeBP(11, 12); + case LC_TokenKind_Equals: case LC_TokenKind_NotEquals: case LC_TokenKind_GreaterThen: + case LC_TokenKind_GreaterThenEq: case LC_TokenKind_LesserThen: case LC_TokenKind_LesserThenEq: return LC_MakeBP(13, 14); + case LC_TokenKind_Sub: case LC_TokenKind_Add: case LC_TokenKind_BitOr: case LC_TokenKind_BitXor: return LC_MakeBP(15, 16); + case LC_TokenKind_RightShift: case LC_TokenKind_LeftShift: case LC_TokenKind_BitAnd: + case LC_TokenKind_Mul: case LC_TokenKind_Div: case LC_TokenKind_Mod: return LC_MakeBP(17, 18); + default: return LC_MakeBP(0, 0); + } +Postfix: + switch (kind) { + case LC_TokenKind_Dot: case LC_TokenKind_OpenBracket: case LC_TokenKind_OpenParen: return LC_MakeBP(21, -2); + default: return LC_MakeBP(-1, -1); + } +} + +LC_FUNCTION LC_AST *LC_ParseExprEx(int min_bp) { + LC_AST *left = NULL; + LC_Token *prev = LC_GetI(-1); + LC_Token *t = LC_Next(); + LC_BindingPower prefixbp = LC_GetBindingPower(LC_Binding_Prefix, t->kind); + + // parse prefix expression + switch (t->kind) { + case LC_TokenKind_RawString: + case LC_TokenKind_String: { left = LC_CreateAST(t, LC_ASTKind_ExprString); left->eatom.name = t->ident; } break; + case LC_TokenKind_Ident: { left = LC_CreateAST(t, LC_ASTKind_ExprIdent); left->eident.name = t->ident; } break; + case LC_TokenKind_Int: { left = LC_CreateAST(t, LC_ASTKind_ExprInt); left->eatom.i = t->i; } break; + case LC_TokenKind_Float: { left = LC_CreateAST(t, LC_ASTKind_ExprFloat); left->eatom.d = t->f64; } break; + case LC_TokenKind_Unicode: { left = LC_CreateAST(t, LC_ASTKind_ExprInt); left->eatom.i = t->i; } break; + + case LC_TokenKind_Keyword: { + if (t->ident == L->kfalse) { + left = LC_CreateAST(t, LC_ASTKind_ExprBool); + LC_Bigint_init_signed(&left->eatom.i, false); + } else if (t->ident == L->ktrue) { + left = LC_CreateAST(t, LC_ASTKind_ExprBool); + LC_Bigint_init_signed(&left->eatom.i, true); + } else { + return LC_ReportParseError(t, "got unexpected keyword '%s' while parsing expression", t->ident); + } + } break; + + case LC_TokenKind_AddPtr: { + LC_EXPECT(open_paren, LC_TokenKind_OpenParen, "addptr"); + LC_AST *LC_PROP_ERROR(ptr, LC_ParseExprEx(0)); + LC_EXPECT(comma, LC_TokenKind_Comma, "addptr"); + LC_AST *LC_PROP_ERROR(offset, LC_ParseExprEx(0)); + LC_EXPECT(close_paren, LC_TokenKind_CloseParen, "addptr"); + left = LC_CreateBinary(t, ptr, offset, LC_TokenKind_EOF); + left->kind = LC_ASTKind_ExprAddPtr; + } break; + + case LC_TokenKind_Colon: { + left = LC_CreateAST(t, LC_ASTKind_ExprType); + LC_PROP_ERROR(left->etype.type, LC_ParseType()); + + LC_Token *open = LC_Get(); + if (LC_Match(LC_TokenKind_OpenBrace)) { + left = LC_ParseCompo(open, left); + if (left->kind == LC_ASTKind_Error) { + L->parser->at = t; + return left; + } + } else if (LC_Match(LC_TokenKind_OpenParen)) { + LC_AST *type = left; + left = LC_CreateAST(open, LC_ASTKind_ExprCast); + left->ecast.type = type->etype.type; + type->kind = LC_ASTKind_Ignore; + + LC_PROP_ERROR(left->ecast.expr, LC_ParseExpr()); + LC_EXPECT(close_paren, LC_TokenKind_CloseParen, "cast expression"); + } + } break; + + case LC_TokenKind_OpenBrace: { + left = LC_ParseCompo(t, left); + if (left->kind == LC_ASTKind_Error) { + L->parser->at = prev; + return left; + } + } break; + + case LC_TokenKind_Not: case LC_TokenKind_Neg: case LC_TokenKind_Add: case LC_TokenKind_Sub: { + LC_AST *LC_PROP_ERROR(expr, LC_ParseExprEx(prefixbp.right)); + left = LC_CreateUnary(t, t->kind, expr); + } break; + + case LC_TokenKind_BitAnd: { + LC_AST *LC_PROP_ERROR(expr, LC_ParseExprEx(prefixbp.right)); + left = LC_CreateUnary(t, t->kind, expr); + left->kind = LC_ASTKind_ExprGetPointerOfValue; + } break; + + case LC_TokenKind_Mul: { + LC_AST *LC_PROP_ERROR(expr, LC_ParseExprEx(prefixbp.right)); + left = LC_CreateUnary(t, t->kind, expr); + left->kind = LC_ASTKind_ExprGetValueOfPointer; + } break; + + case LC_TokenKind_OpenParen: { + LC_AST *LC_PROP_ERROR(expr, LC_ParseExprEx(0)); + left = expr; + LC_EXPECT(_c, LC_TokenKind_CloseParen, "expression"); + } break; + + default: return LC_ReportParseError(prev, "got invalid token: %s, while parsing expression", LC_TokenKindToString(t->kind)); + } + + for (;;) { + t = LC_Get(); + + // lets say [+] is left:1, right:2 and we parse 2+3+4 + // We pass min_bp of 2 to the next recursion + // in recursion we check if left(1) > min_bp(2) + // it's not so we don't recurse - we break + // We do the for loop instead + + LC_BindingPower postfix_bp = LC_GetBindingPower(LC_Binding_Postfix, t->kind); + LC_BindingPower infix_bp = LC_GetBindingPower(LC_Binding_Infix, t->kind); + + // parse postfix expression + if (postfix_bp.left > min_bp) { + LC_Next(); + switch (t->kind) { + case LC_TokenKind_OpenBracket: { + LC_AST *LC_PROP_ERROR(index, LC_ParseExprEx(0)); + LC_EXPECT(close_bracket, LC_TokenKind_CloseBracket, "index expression"); + left = LC_CreateIndex(t, left, index); + } break; + case LC_TokenKind_OpenParen: { + LC_PROP_ERROR(left, LC_ParseCompo(t, left)); + } break; + case LC_TokenKind_Dot: { + LC_EXPECT(ident, LC_TokenKind_Ident, "field access expression"); + LC_AST *field = LC_CreateAST(t, LC_ASTKind_ExprField); + field->efield.left = left; + field->efield.right = ident->ident; + left = field; + } break; + default: {} + } + } + + // parse infix expression + else if (infix_bp.left > min_bp) { + t = LC_Next(); + LC_AST *LC_PROP_ERROR(right, LC_ParseExprEx(infix_bp.right)); + left = LC_CreateBinary(t, left, right, t->kind); + } + + else break; + } + + if (L->on_expr_parsed) L->on_expr_parsed(left); + return left; +} +// clang-format on + +LC_FUNCTION LC_AST *LC_ParseCompo(LC_Token *pos, LC_AST *left) { + if (pos->kind != LC_TokenKind_OpenBrace && pos->kind != LC_TokenKind_OpenParen) { + return LC_ReportParseError(pos, "internal compiler error: expected open brace or open paren in %s", __FUNCTION__); + } + + LC_ASTKind kind = pos->kind == LC_TokenKind_OpenBrace ? LC_ASTKind_ExprCompound : LC_ASTKind_ExprCall; + LC_TokenKind close_kind = pos->kind == LC_TokenKind_OpenBrace ? LC_TokenKind_CloseBrace : LC_TokenKind_CloseParen; + LC_ASTKind item_kind = pos->kind == LC_TokenKind_OpenBrace ? LC_ASTKind_ExprCompoundItem : LC_ASTKind_ExprCallItem; + + LC_AST *n = LC_CreateAST(pos, kind); + n->ecompo.name = left; + + while (!LC_Is(close_kind)) { + LC_Token *vpos = LC_Get(); + LC_AST *v = LC_CreateAST(vpos, item_kind); + + if (LC_Match(LC_TokenKind_OpenBracket)) { + if (kind == LC_ASTKind_ExprCall) return LC_ReportParseError(vpos, "procedure calls cant have indexed arguments"); + LC_PROP_ERROR(v->ecompo_item.index, LC_ParseExpr()); + LC_EXPECT(close_bracket, LC_TokenKind_CloseBracket, "compo expression"); + LC_EXPECT(assign, LC_TokenKind_Assign, "compo expression"); + LC_PROP_ERROR(v->ecompo_item.expr, LC_ParseExpr()); + } else { + LC_PROP_ERROR(v->ecompo_item.expr, LC_ParseExpr()); + if (LC_Match(LC_TokenKind_Assign)) { + LC_AST *e = v->ecompo_item.expr; + if (e->kind != LC_ASTKind_ExprIdent) return LC_ReportParseError(LC_GetI(-1), "named argument is required to be an identifier"); + LC_PROP_ERROR(v->ecompo_item.expr, LC_ParseExpr()); + v->ecompo_item.name = e->eident.name; + e->kind = LC_ASTKind_Ignore; // :FreeAST + } + } + + n->ecompo.size += 1; + LC_DLLAdd(n->ecompo.first, n->ecompo.last, v); + if (!LC_Match(LC_TokenKind_Comma)) break; + } + LC_EXPECT(close_token, close_kind, "compo expression"); + return n; +} + +LC_FUNCTION LC_AST *LC_ParseExpr(void) { + return LC_ParseExprEx(0); +} + +LC_FUNCTION LC_AST *LC_ParseProcType(LC_Token *pos) { + LC_AST *n = LC_CreateAST(pos, LC_ASTKind_TypespecProc); + LC_EXPECT(open_paren, LC_TokenKind_OpenParen, "procedure typespec"); + if (!LC_Match(LC_TokenKind_CloseParen)) { + for (;;) { + if (LC_Match(LC_TokenKind_ThreeDots)) { + n->tproc.vargs = true; + + LC_Token *any = LC_Get(); + if (any->kind == LC_TokenKind_Ident && any->ident == L->iAny) { + n->tproc.vargs_any_promotion = true; + LC_Next(); + } + break; + } + LC_EXPECT(ident, LC_TokenKind_Ident, "procedure typespec argument list"); + LC_AST *v = LC_CreateAST(ident, LC_ASTKind_TypespecProcArg); + v->tproc_arg.name = ident->ident; + + LC_EXPECT(colon, LC_TokenKind_Colon, "procedure typespec argument list"); + LC_PROP_ERROR(v->tproc_arg.type, LC_ParseType()); + + if (LC_Match(LC_TokenKind_Assign)) { + LC_PROP_ERROR(v->tproc_arg.expr, LC_ParseExpr()); + } + + v->notes = LC_ParseNotes(); + LC_DLLAdd(n->tproc.first, n->tproc.last, v); + + if (!LC_Match(LC_TokenKind_Comma)) break; + } + LC_EXPECT(close_paren, LC_TokenKind_CloseParen, "procedure typespec argument list"); + } + if (LC_Match(LC_TokenKind_Colon)) { + LC_PROP_ERROR(n->tproc.ret, LC_ParseType()); + } + return n; +} + +LC_FUNCTION LC_AST *LC_ParseType(void) { + LC_AST *n = NULL; + LC_Token *t = LC_Next(); + if (t->kind == LC_TokenKind_Ident) { + n = LC_CreateAST(t, LC_ASTKind_TypespecIdent); + n->eident.name = t->ident; + LC_Token *dot = LC_Match(LC_TokenKind_Dot); + if (dot) { + LC_AST *field = LC_CreateAST(t, LC_ASTKind_TypespecField); + field->efield.left = n; + LC_EXPECT(ident, LC_TokenKind_Ident, "field access typespec"); + field->efield.right = ident->ident; + return field; + } + } else if (t->kind == LC_TokenKind_Mul) { + n = LC_CreateAST(t, LC_ASTKind_TypespecPointer); + LC_PROP_ERROR(n->tpointer.base, LC_ParseType()); + } else if (t->kind == LC_TokenKind_OpenBracket) { + n = LC_CreateAST(t, LC_ASTKind_TypespecArray); + if (!LC_Match(LC_TokenKind_CloseBracket)) { + LC_PROP_ERROR(n->tarray.index, LC_ParseExpr()); + LC_EXPECT(close_bracket, LC_TokenKind_CloseBracket, "array typespec"); + } + LC_PROP_ERROR(n->tarray.base, LC_ParseType()); + } else if (t->kind == LC_TokenKind_Keyword && t->ident == L->kproc) { + LC_PROP_ERROR(n, LC_ParseProcType(t)); + } else { + return LC_ReportParseError(t, "failed to parse typespec, invalid token %s", LC_TokenKindToString(t->kind)); + } + + if (L->on_typespec_parsed) L->on_typespec_parsed(n); + return n; +} + +LC_FUNCTION LC_AST *LC_ParseForStmt(LC_Token *pos) { + LC_AST *n = LC_CreateAST(pos, LC_ASTKind_StmtFor); + + if (LC_Get()->kind != LC_TokenKind_OpenBrace) { + if (!LC_Is(LC_TokenKind_Semicolon)) { + LC_PROP_ERROR(n->sfor.init, LC_ParseStmt(false)); + if (n->sfor.init->kind == LC_ASTKind_StmtExpr) { + n->sfor.cond = n->sfor.init->sexpr.expr; + n->sfor.init->kind = LC_ASTKind_Ignore; // :FreeAST + n->sfor.init = NULL; + goto skip_to_last; + } else if (n->sfor.init->kind != LC_ASTKind_StmtVar && n->sfor.init->kind != LC_ASTKind_StmtAssign) { + return LC_ReportParseError(n->sfor.init->pos, "invalid for loop syntax, expected variable intializer or assignment"); + } + } + + if (LC_Match(LC_TokenKind_Semicolon) && !LC_Is(LC_TokenKind_Semicolon)) { + LC_PROP_ERROR(n->sfor.cond, LC_ParseExpr()); + } + + skip_to_last:; + if (LC_Match(LC_TokenKind_Semicolon)) { + LC_PROP_ERROR(n->sfor.inc, LC_ParseStmt(false)); + if (n->sfor.inc->kind != LC_ASTKind_StmtAssign && n->sfor.inc->kind != LC_ASTKind_StmtExpr) { + return LC_ReportParseError(n->sfor.inc->pos, "invalid for loop syntax, expected assignment or expression"); + } + } + } + + LC_PROP_ERROR(n->sfor.body, LC_ParseStmtBlock(ParseStmtBlock_AllowSingleStmt)); + n->sfor.body->sblock.kind = SBLK_Loop; + return n; +} + +LC_FUNCTION LC_AST *LC_ParseSwitchStmt(LC_Token *pos) { + LC_AST *n = LC_CreateAST(pos, LC_ASTKind_StmtSwitch); + LC_PROP_ERROR(n->sswitch.expr, LC_ParseExpr()); + LC_EXPECT(open_brace, LC_TokenKind_OpenBrace, "switch statement"); + for (;;) { + LC_Token *pos = LC_Get(); + if (LC_MatchKeyword(L->kcase)) { + LC_AST *v = LC_CreateAST(pos, LC_ASTKind_StmtSwitchCase); + do { + LC_AST *LC_PROP_ERROR(expr, LC_ParseExpr()); + LC_DLLAdd(v->scase.first, v->scase.last, expr); + n->sswitch.total_switch_case_count += 1; + } while (LC_Match(LC_TokenKind_Comma)); + LC_EXPECT(colon, LC_TokenKind_Colon, "switch statement case"); + LC_PROP_ERROR(v->scase.body, LC_ParseStmtBlock(ParseStmtBlock_AllowSingleStmt)); + v->notes = LC_ParseNotes(); + LC_DLLAdd(n->sswitch.first, n->sswitch.last, v); + } else if (LC_MatchKeyword(L->kdefault)) { + LC_EXPECT(colon, LC_TokenKind_Colon, "switch statement default case"); + LC_AST *v = LC_CreateAST(pos, LC_ASTKind_StmtSwitchDefault); + LC_PROP_ERROR(v->scase.body, LC_ParseStmtBlock(ParseStmtBlock_AllowSingleStmt)); + LC_EXPECT(close_brace, LC_TokenKind_CloseBrace, "switch statement default case"); + v->notes = LC_ParseNotes(); + LC_DLLAdd(n->sswitch.first, n->sswitch.last, v); + break; + } else { + return LC_ReportParseError(LC_Get(), "invalid token while parsing switch statement"); + } + + if (LC_Match(LC_TokenKind_EOF)) return LC_ReportParseError(pos, "Unclosed '}' switch stmt, reached end of file"); + if (LC_Match(LC_TokenKind_CloseBrace)) break; + } + return n; +} + +LC_FUNCTION LC_AST *LC_ParseStmt(bool check_semicolon) { + LC_AST *n = 0; + LC_Token *pos = LC_Get(); + LC_Token *pos1 = LC_GetI(1); + if (LC_MatchKeyword(L->kreturn)) { + n = LC_CreateAST(pos, LC_ASTKind_StmtReturn); + if (LC_Get()->kind != LC_TokenKind_Semicolon) { + LC_PROP_ERROR(n->sreturn.expr, LC_ParseExpr()); + } + } + + else if (LC_MatchKeyword(L->kbreak)) { + n = LC_CreateAST(pos, LC_ASTKind_StmtBreak); + LC_Token *ident = LC_Match(LC_TokenKind_Ident); + if (ident) n->sbreak.name = ident->ident; + } + + else if (LC_MatchKeyword(L->kcontinue)) { + n = LC_CreateAST(pos, LC_ASTKind_StmtContinue); + LC_Token *ident = LC_Match(LC_TokenKind_Ident); + if (ident) n->scontinue.name = ident->ident; + } + + else if (LC_MatchKeyword(L->kdefer)) { + check_semicolon = false; + n = LC_CreateAST(pos, LC_ASTKind_StmtDefer); + LC_PROP_ERROR(n->sdefer.body, LC_ParseStmtBlock(ParseStmtBlock_AllowSingleStmt)); + n->sdefer.body->sblock.kind = SBLK_Defer; + } + + else if (LC_MatchKeyword(L->kfor)) { + LC_PROP_ERROR(n, LC_ParseForStmt(pos)); + check_semicolon = false; + } + + else if (LC_MatchKeyword(L->kswitch)) { + LC_PROP_ERROR(n, LC_ParseSwitchStmt(pos)); + check_semicolon = false; + } + + else if (LC_MatchKeyword(L->kif)) { + n = LC_CreateAST(pos, LC_ASTKind_StmtIf); + LC_PROP_ERROR(n->sif.expr, LC_ParseExpr()); + LC_PROP_ERROR(n->sif.body, LC_ParseStmtBlock(ParseStmtBlock_AllowSingleStmt)); + for (;;) { + if (!LC_MatchKeyword(L->kelse)) break; + + LC_AST *v = LC_CreateAST(LC_GetI(-1), LC_ASTKind_StmtElse); + if (LC_MatchKeyword(L->kif)) { + v->kind = LC_ASTKind_StmtElseIf; + LC_PROP_ERROR(v->sif.expr, LC_ParseExpr()); + } + LC_PROP_ERROR(v->sif.body, LC_ParseStmtBlock(ParseStmtBlock_AllowSingleStmt)); + LC_DLLAdd(n->sif.first, n->sif.last, v); + } + check_semicolon = false; + } + + else if (LC_Match(LC_TokenKind_Hash)) { // #c(``); + n = LC_CreateAST(LC_Get(), LC_ASTKind_StmtNote); + LC_PROP_ERROR(n->snote.expr, LC_ParseNote()); + } else if (pos->kind == LC_TokenKind_OpenBrace) { // { block } + n = LC_ParseStmtBlock(0); + check_semicolon = false; + } + + else if (pos->kind == LC_TokenKind_Ident && pos1->kind == LC_TokenKind_Colon) { // Name: ... + LC_Next(); + LC_Next(); + + if (LC_MatchKeyword(L->kfor)) { + LC_PROP_ERROR(n, LC_ParseForStmt(LC_GetI(-1))); + n->sfor.body->sblock.name = pos->ident; + check_semicolon = false; + } else { + n = LC_CreateAST(pos, LC_ASTKind_StmtVar); + LC_Intern name = pos->ident; + if (LC_Match(LC_TokenKind_Assign)) { + LC_PROP_ERROR(n->svar.expr, LC_ParseExpr()); + n->svar.name = name; + } else if (LC_Match(LC_TokenKind_Colon)) { + n->kind = LC_ASTKind_StmtConst; + LC_PROP_ERROR(n->sconst.expr, LC_ParseExpr()); + n->sconst.name = name; + } else { + n->svar.name = name; + LC_PROP_ERROR(n->svar.type, LC_ParseType()); + if (LC_Match(LC_TokenKind_Assign)) { + if (LC_Match(LC_TokenKind_Hash)) { + LC_AST *note = LC_CreateAST(LC_Get(), LC_ASTKind_ExprNote); + LC_PROP_ERROR(note->enote.expr, LC_ParseNote()); + n->svar.expr = note; + } else { + LC_PROP_ERROR(n->svar.expr, LC_ParseExpr()); + } + } + } + } + } else { + n = LC_CreateAST(pos, LC_ASTKind_StmtExpr); + LC_PROP_ERROR(n->sexpr.expr, LC_ParseExpr()); + + LC_Token *t = LC_Get(); + if (LC_IsAssign(t->kind)) { + LC_Next(); + LC_AST *left = n->sexpr.expr; + + n->kind = LC_ASTKind_StmtAssign; + LC_PROP_ERROR(n->sassign.right, LC_ParseExpr()); + n->sassign.left = left; + n->sassign.op = t->kind; + } + } + + if (check_semicolon) { + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "statement lacks a semicolon at the end"); + } + + n->notes = LC_ParseNotes(); + return n; +} + +LC_FUNCTION LC_AST *LC_ParseStmtBlock(int flags) { + LC_AST *n = LC_CreateAST(LC_Get(), LC_ASTKind_StmtBlock); + + bool single_stmt = false; + if (flags & ParseStmtBlock_AllowSingleStmt) { + if (!LC_Is(LC_TokenKind_OpenBrace)) { + LC_AST *LC_PROP_ERROR(v, LC_ParseStmt(true)); + LC_DLLAdd(n->sblock.first, n->sblock.last, v); + single_stmt = true; + } + } + + if (!single_stmt) { + LC_EXPECT(open_brace, LC_TokenKind_OpenBrace, "statement block"); + if (!LC_Match(LC_TokenKind_CloseBrace)) { + for (;;) { + LC_AST *v = LC_ParseStmt(true); + + // Eat until next statement in case of error + if (v->kind == LC_ASTKind_Error) { + for (;;) { + if (LC_Is(LC_TokenKind_EOF) || LC_Is(LC_TokenKind_OpenBrace) || LC_Match(LC_TokenKind_CloseBrace)) return v; + if (LC_Match(LC_TokenKind_Semicolon)) break; + LC_Next(); + } + } + + if (L->on_stmt_parsed) L->on_stmt_parsed(v); + LC_DLLAdd(n->sblock.first, n->sblock.last, v); + if (LC_Match(LC_TokenKind_EOF)) return LC_ReportParseError(open_brace, "Unclosed '}' stmt list, reached end of file"); + if (LC_Match(LC_TokenKind_CloseBrace)) break; + } + } + } + + if (L->on_stmt_parsed) L->on_stmt_parsed(n); + return n; +} + +LC_FUNCTION LC_AST *LC_ParseProcDecl(LC_Token *name) { + LC_AST *n = LC_CreateAST(name, LC_ASTKind_DeclProc); + n->dbase.name = name->ident; + LC_PROP_ERROR(n->dproc.type, LC_ParseProcType(name)); + + LC_Token *ob = LC_Get(); + if (ob->kind == LC_TokenKind_OpenBrace) { + // Here I added additional error handling which slows down compilation a bit. + // We can for sure deduce where procs end and where they begin because of the syntaxes + // nature - so to avoid any error spills from one procedure to another and I + // seek for the last brace of procedure and set 'end' on parser to 1 after that token. + LC_Token *cb = ob; + LC_Token *last_open_brace = ob; + int pair_counter = 0; + + // Seek for the last '}' close brace of procedure + for (;;) { + LC_Token *d = LC_GetI(3); + if (LC_GetI(0)->kind == LC_TokenKind_Ident && LC_GetI(1)->kind == LC_TokenKind_Colon && LC_GetI(2)->kind == LC_TokenKind_Colon && d->kind == LC_TokenKind_Keyword) { + if (d->ident == L->kproc || d->ident == L->kstruct || d->ident == L->kunion || d->ident == L->ktypedef) { + break; + } + } + + LC_Token *token = LC_Next(); + if (token == &L->NullToken) break; + if (token->kind == LC_TokenKind_OpenBrace) pair_counter += 1; + if (token->kind == LC_TokenKind_OpenBrace) last_open_brace = token; + if (token->kind == LC_TokenKind_CloseBrace) pair_counter -= 1; + if (token->kind == LC_TokenKind_CloseBrace) cb = token; + } + if (pair_counter != 0) return LC_ReportParseError(last_open_brace, "unclosed open brace '{' inside this procedure"); + L->parser->at = ob; + + // Set the parsing boundary to one after the last close brace + LC_Token *save_end = L->parser->end; + L->parser->end = cb + 1; + n->dproc.body = LC_ParseStmtBlock(0); + L->parser->end = save_end; + if (n->dproc.body->kind == LC_ASTKind_Error) return n->dproc.body; + + n->dproc.body->sblock.kind = SBLK_Proc; + } else { + LC_EXPECT(semicolon, LC_TokenKind_Semicolon, "procedure declaration"); + } + + return n; +} + +LC_FUNCTION LC_AST *LC_ParseStruct(LC_ASTKind kind, LC_Token *ident) { + LC_AST *n = LC_CreateAST(ident, kind); + n->dbase.name = ident->ident; + LC_EXPECT(open_brace, LC_TokenKind_OpenBrace, "struct declaration"); + for (;;) { + LC_AST *v = LC_CreateAST(ident, LC_ASTKind_TypespecAggMem); + LC_EXPECT(ident, LC_TokenKind_Ident, "struct member"); + v->tagg_mem.name = ident->ident; + LC_EXPECT(colon, LC_TokenKind_Colon, "struct member"); + LC_PROP_ERROR(v->tagg_mem.type, LC_ParseType()); + LC_EXPECT(semicolon, LC_TokenKind_Semicolon, "struct member"); + + v->notes = LC_ParseNotes(); + LC_DLLAdd(n->dagg.first, n->dagg.last, v); + if (LC_Match(LC_TokenKind_EOF)) return LC_ReportParseError(ident, "Unclosed '}' struct, reached end of file"); + if (LC_Match(LC_TokenKind_CloseBrace)) break; + } + + return n; +} + +LC_FUNCTION LC_AST *LC_ParseTypedef(LC_Token *ident) { + LC_AST *n = LC_CreateAST(ident, LC_ASTKind_DeclTypedef); + n->dbase.name = ident->ident; + LC_PROP_ERROR(n->dtypedef.type, LC_ParseType()); + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "expected semicolon ';' after typedef declaration, got instead %s", LC_TokenKindToString(LC_GetI(-1)->kind)); + return n; +} + +LC_FUNCTION LC_AST *LC_CreateNote(LC_Token *pos, LC_Intern ident) { + LC_AST *n = LC_CreateAST(pos, LC_ASTKind_Note); + + LC_AST *astident = LC_CreateAST(pos, LC_ASTKind_ExprIdent); + astident->eident.name = ident; + n->ecompo.name = astident; + + return n; +} + +LC_FUNCTION LC_AST *LC_ParseNote(void) { + LC_AST *n = NULL; + + // syntactic sugar + // #`stuff` => #c(`stuff`) + LC_Token *str_token = LC_Match(LC_TokenKind_RawString); + if (str_token) { + n = LC_CreateNote(str_token, L->ic); + + // Add CallItem + { + LC_AST *astcallitem = LC_CreateAST(str_token, LC_ASTKind_ExprCallItem); + astcallitem->ecompo_item.expr = LC_CreateAST(str_token, LC_ASTKind_ExprString); + astcallitem->ecompo_item.expr->eatom.name = str_token->ident; + LC_DLLAdd(n->ecompo.first, n->ecompo.last, astcallitem); + } + } else { + + LC_EXPECT(ident, LC_TokenKind_Ident, "note"); + if (!LC_IsNoteDeclared(ident->ident)) { + LC_ReportParseError(ident, "unregistered note name: '%s'", ident->ident); + } + + LC_AST *astident = LC_CreateAST(ident, LC_ASTKind_ExprIdent); + astident->eident.name = ident->ident; + + LC_Token *open_paren = LC_Match(LC_TokenKind_OpenParen); + if (open_paren) { + n = LC_ParseCompo(open_paren, astident); + } else { + n = LC_CreateAST(ident, LC_ASTKind_Note); + } + n->ecompo.name = astident; + n->kind = LC_ASTKind_Note; + } + return n; +} + +LC_FUNCTION LC_AST *LC_ParseNotes(void) { + LC_Token *pos = LC_Get(); + LC_AST *first = 0; + LC_AST *last = 0; + for (;;) { + LC_Token *t = LC_Match(LC_TokenKind_Note); + if (!t) break; + LC_AST *n = LC_ParseNote(); + if (n->kind == LC_ASTKind_Error) continue; + LC_DLLAdd(first, last, n); + } + + if (first) { + LC_AST *n = LC_CreateAST(pos, LC_ASTKind_NoteList); + n->anote_list.first = first; + n->anote_list.last = last; + return n; + } + return 0; +} + +LC_FUNCTION bool LC_ResolveBuildIf(LC_AST *build_if) { + LC_ExprCompo *note = &build_if->anote; + if (note->size != 1) { + LC_ReportParseError(LC_GetI(-1), "invalid argument count for #build_if directive, expected 1, got %d", note->size); + return true; + } + + LC_ExprCompoItem *item = ¬e->first->ecompo_item; + if (item->index != NULL || item->name != 0) { + LC_ReportParseError(LC_GetI(-1), "invalid syntax, #build_if shouldn't have a named or indexed first argument"); + return true; + } + + LC_PUSH_PACKAGE(L->builtin_package); + LC_Operand op = LC_ResolveExpr(item->expr); + LC_POP_PACKAGE(); + if (!LC_IsUTConst(op)) { + LC_ReportParseError(LC_GetI(-1), "expected #build_if to have an untyped constant expcession"); + return true; + } + if (!LC_IsUTInt(op.type)) { + LC_ReportParseError(LC_GetI(-1), "expected #build_if to have expression of type untyped int"); + return true; + } + + int64_t result = LC_Bigint_as_signed(&op.v.i); + return (bool)result; +} + +LC_FUNCTION LC_AST *LC_ParseDecl(LC_AST *file) { + LC_AST *n = 0; + LC_Token *doc_comment = LC_Match(LC_TokenKind_DocComment); + LC_Token *ident = LC_Get(); + + if (LC_Match(LC_TokenKind_Ident)) { + if (LC_Match(LC_TokenKind_Colon)) { + if (LC_Match(LC_TokenKind_Colon)) { + if (LC_MatchKeyword(L->kproc)) { + LC_PROP_ERROR(n, LC_ParseProcDecl(ident)); + } else if (LC_MatchKeyword(L->kstruct)) { + LC_PROP_ERROR(n, LC_ParseStruct(LC_ASTKind_DeclStruct, ident)); + } else if (LC_MatchKeyword(L->kunion)) { + LC_PROP_ERROR(n, LC_ParseStruct(LC_ASTKind_DeclUnion, ident)); + } else if (LC_MatchKeyword(L->ktypedef)) { + LC_PROP_ERROR(n, LC_ParseTypedef(ident)); + } else { + n = LC_CreateAST(ident, LC_ASTKind_DeclConst); + n->dbase.name = ident->ident; + if (LC_Match(LC_TokenKind_BitXor)) { + LC_AST *last_decl = file->afile.ldecl; + if (!last_decl || last_decl->kind != LC_ASTKind_DeclConst) return LC_ReportParseError(LC_GetI(-1), "invalid usage, there is no constant declaration preceding '^', this operator implies - PREV_CONST + 1"); + LC_AST *left = LC_CreateAST(n->pos, LC_ASTKind_ExprIdent); + left->eident.name = last_decl->dbase.name; + LC_AST *right = LC_CreateAST(n->pos, LC_ASTKind_ExprInt); + right->eatom.i = LC_Bigint_u64(1); + + n->dconst.expr = LC_CreateBinary(n->pos, left, right, LC_TokenKind_Add); + } else if (LC_Match(LC_TokenKind_LeftShift)) { + LC_AST *last_decl = file->afile.ldecl; + if (!last_decl || last_decl->kind != LC_ASTKind_DeclConst) return LC_ReportParseError(LC_GetI(-1), "invalid usage, there is no constant declaration preceding '^', this operator implies - PREV_CONST << 1"); + LC_AST *left = LC_CreateAST(n->pos, LC_ASTKind_ExprIdent); + left->eident.name = last_decl->dbase.name; + LC_AST *right = LC_CreateAST(n->pos, LC_ASTKind_ExprInt); + right->eatom.i = LC_Bigint_u64(1); + + n->dconst.expr = LC_CreateBinary(n->pos, left, right, LC_TokenKind_LeftShift); + } else { + LC_PROP_ERROR(n->dconst.expr, LC_ParseExpr()); + } + + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "expected ';' semicolon"); + } + } else if (LC_Match(LC_TokenKind_Assign)) { + n = LC_CreateAST(ident, LC_ASTKind_DeclVar); + LC_PROP_ERROR(n->dvar.expr, LC_ParseExpr()); + n->dbase.name = ident->ident; + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "expected ';' semicolon"); + } else { + n = LC_CreateAST(ident, LC_ASTKind_DeclVar); + n->dbase.name = ident->ident; + + LC_PROP_ERROR(n->dvar.type, LC_ParseType()); + if (LC_Match(LC_TokenKind_Assign)) { + if (LC_Match(LC_TokenKind_Hash)) { + LC_AST *note = LC_CreateAST(LC_Get(), LC_ASTKind_ExprNote); + LC_PROP_ERROR(note->enote.expr, LC_ParseNote()); + n->dvar.expr = note; + } else { + LC_PROP_ERROR(n->dvar.expr, LC_ParseExpr()); + } + } + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "expected ';' semicolon"); + } + } else return LC_ReportParseError(ident, "got unexpected token: %s, while parsing declaration", LC_TokenKindToString(ident->kind)); + } else if (LC_Match(LC_TokenKind_Hash)) { + n = LC_CreateAST(ident, LC_ASTKind_DeclNote); + LC_PROP_ERROR(n->dnote.expr, LC_ParseNote()); + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "expected ';' semicolon"); + } else if (LC_MatchKeyword(L->kimport)) { + return LC_ReportParseError(LC_Get(), "imports can only appear at the top level"); + } else if (ident->kind == LC_TokenKind_EOF) return NULL; + else return LC_ReportParseError(ident, "got unexpected token: %s, while parsing declaration", LC_TokenKindToString(ident->kind)); + + LC_AST *notes = LC_ParseNotes(); + if (n) { + n->notes = notes; + n->dbase.doc_comment = doc_comment; + } + return n; +} + +LC_FUNCTION bool LC_EatUntilNextValidDecl(void) { + for (;;) { + LC_Token *a = LC_GetI(0); + if (a->kind == LC_TokenKind_Keyword && a->ident == L->kimport) { + return true; + } + + LC_Token *d = LC_GetI(3); + if (a->kind == LC_TokenKind_Ident && LC_GetI(1)->kind == LC_TokenKind_Colon && LC_GetI(2)->kind == LC_TokenKind_Colon && d->kind == LC_TokenKind_Keyword) { + if (d->ident == L->kproc || d->ident == L->kstruct || d->ident == L->kunion || d->ident == L->ktypedef) { + return false; + } + } + + LC_Token *token = LC_Next(); + if (token == &L->NullToken) { + return false; + } + } +} + +LC_FUNCTION bool LC_ParseHashBuildOn(LC_AST *n) { + LC_Token *t0 = LC_GetI(0); + LC_Token *t1 = LC_GetI(1); + if (t0->kind == LC_TokenKind_Hash && t1->kind == LC_TokenKind_Ident && t1->ident == L->ibuild_if) { + LC_Next(); + + LC_AST *build_if = LC_CreateAST(t1, LC_ASTKind_DeclNote); + build_if->dnote.expr = LC_ParseNote(); + if (build_if->dnote.expr->kind == LC_ASTKind_Error) { + LC_EatUntilNextValidDecl(); + return true; + } + + if (!LC_Match(LC_TokenKind_Semicolon)) { + LC_ReportParseError(LC_GetI(-1), "expected ';' semicolon"); + LC_EatUntilNextValidDecl(); + return true; + } + + LC_AST *note_list = LC_CreateAST(t0, LC_ASTKind_NoteList); + LC_DLLAdd(note_list->anote_list.first, note_list->anote_list.last, build_if); + n->notes = note_list; + + return LC_ResolveBuildIf(build_if->dnote.expr); + } + return true; +} + +LC_FUNCTION LC_AST *LC_ParseImport(void) { + LC_AST *n = NULL; + LC_Token *import = LC_MatchKeyword(L->kimport); + if (import) { + n = LC_CreateAST(import, LC_ASTKind_GlobImport); + + LC_Token *ident = LC_Match(LC_TokenKind_Ident); + if (ident) n->gimport.name = ident->ident; + + LC_Token *path = LC_Match(LC_TokenKind_String); + if (!path) return LC_ReportParseError(LC_GetI(-1), "expected string after an import, instead got %s", LC_TokenKindToString(LC_Get()->kind)); + + n->gimport.path = path->ident; + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "expected ';' semicolon"); + } + return n; +} + +LC_FUNCTION void LC_AddFileToPackage(LC_AST *pkg, LC_AST *f) { + f->afile.package = pkg; + LC_DLLAdd(pkg->apackage.ffile, pkg->apackage.lfile, f); +} + +LC_FUNCTION LC_AST *LC_ParseFileEx(LC_AST *package) { + LC_Token *package_doc_comment = LC_Match(LC_TokenKind_PackageDocComment); + + LC_AST *n = LC_CreateAST(LC_Get(), LC_ASTKind_File); + n->afile.x = L->parser->x; + n->afile.doc_comment = LC_Match(LC_TokenKind_FileDocComment); + n->afile.build_if = LC_ParseHashBuildOn(n); + + // Parse imports + while (!LC_Is(LC_TokenKind_EOF)) { + LC_AST *import = LC_ParseImport(); + if (!import) break; + + if (import->kind == LC_ASTKind_Error) { + bool is_import = LC_EatUntilNextValidDecl(); + if (!is_import) break; + } else { + LC_DLLAdd(n->afile.fimport, n->afile.limport, import); + } + } + + // Parse top level decls + while (!LC_Is(LC_TokenKind_EOF)) { + LC_AST *decl = LC_ParseDecl(n); + if (!decl) continue; + + if (decl->kind == LC_ASTKind_Error) { + LC_EatUntilNextValidDecl(); + } else { + bool skip = false; + + LC_AST *build_if = LC_HasNote(decl, L->ibuild_if); + if (build_if) { + skip = !LC_ResolveBuildIf(build_if); + } + + if (L->on_decl_parsed) { + skip = L->on_decl_parsed(skip, decl); + } + + if (skip) { + LC_DLLAdd(n->afile.fdiscarded, n->afile.ldiscarded, decl); + } else { + LC_DLLAdd(n->afile.fdecl, n->afile.ldecl, decl); + } + } + } + + if (package) { + if (package->apackage.doc_comment) LC_ReportParseError(package_doc_comment, "there are more then 1 package doc comments in %s package", (char *)package->apackage.name); + package->apackage.doc_comment = package_doc_comment; + + if (n->afile.build_if) { + LC_AddFileToPackage(package, n); + } else { + LC_DLLAdd(package->apackage.fdiscarded, package->apackage.ldiscarded, n); + n->afile.package = package; + } + } + + return n; +} + +LC_FUNCTION LC_AST *LC_ParseTokens(LC_AST *package, LC_Lex *x) { + LC_Parser p = LC_MakeParser(x); + L->parser = &p; + LC_AST *file = LC_ParseFileEx(package); + return L->errors ? NULL : file; +} + +LC_FUNCTION LC_AST *LC_ParseFile(LC_AST *package, char *filename, char *content, int line) { + if (content == NULL) { + LC_SendErrorMessagef(NULL, NULL, "internal compiler error: file passed to %s is null", __FUNCTION__); + return NULL; + } + if (filename == NULL) { + LC_SendErrorMessagef(NULL, NULL, "internal compiler error: filename passed to %s is null", __FUNCTION__); + return NULL; + } + + LC_Lex *x = LC_LexStream(filename, content, line); + if (L->errors) return NULL; + LC_InternTokens(x); + + LC_AST *file = LC_ParseTokens(package, x); + if (!file) return NULL; + return file; +} + +LC_FUNCTION LC_AST *LC_ParseStmtf(const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + + LC_Parser *old = L->parser; + LC_Parser *p = LC_MakeParserQuick(s8.str); + LC_AST *result = LC_ParseStmt(false); + L->parser = old; + + return result; +} + +LC_FUNCTION LC_AST *LC_ParseExprf(const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + + LC_Parser *old = L->parser; + LC_Parser *p = LC_MakeParserQuick(s8.str); + LC_AST *result = LC_ParseExpr(); + L->parser = old; + + return result; +} + +LC_FUNCTION LC_AST *LC_ParseDeclf(const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + + LC_Parser *old = L->parser; + LC_Parser *p = LC_MakeParserQuick(s8.str); + LC_AST *result = LC_ParseDecl(&L->NullAST); + L->parser = old; + + return result; +} + +#undef LC_EXPECT +#undef LC_PROP_ERROR +LC_FUNCTION LC_StringList *LC_BeginStringGen(LC_Arena *arena) { + L->printer.list = LC_MakeEmptyList(); + L->printer.arena = arena; + L->printer.last_filename = 0; + L->printer.last_line_num = 0; + L->printer.indent = 0; + return &L->printer.list; +} + +LC_FUNCTION LC_String LC_EndStringGen(LC_Arena *arena) { + LC_String result = LC_MergeString(arena, L->printer.list); + return result; +} + +LC_FUNCTION void LC_GenIndent(void) { + LC_String s = LC_Lit(" "); + for (int i = 0; i < L->printer.indent; i++) { + LC_AddNode(L->printer.arena, &L->printer.list, s); + } +} + +LC_FUNCTION char *LC_Strf(const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + return s8.str; +} + +LC_FUNCTION void LC_GenLine(void) { + LC_Genf("\n"); + LC_GenIndent(); +} + +LC_FUNCTION char *LC_GenLCType(LC_Type *type) { + LC_StringList out = {0}; + for (LC_Type *it = type; it;) { + if (it->kind == LC_TypeKind_Pointer) { + LC_Addf(L->arena, &out, "*"); + it = it->tptr.base; + } else if (it->kind == LC_TypeKind_Array) { + LC_Addf(L->arena, &out, "[%d]", it->tarray.size); + it = it->tarray.base; + } else if (it->kind == LC_TypeKind_Proc) { + LC_Addf(L->arena, &out, "proc("); + LC_TypeFor(mem, it->tproc.args.first) { + LC_Addf(L->arena, &out, "%s: %s", (char *)mem->name, LC_GenLCType(mem->type)); + if (mem->default_value_expr) LC_Addf(L->arena, &out, "/*has default value*/"); + if (mem->next) LC_Addf(L->arena, &out, ", "); + } + if (it->tproc.vargs) LC_Addf(L->arena, &out, ".."); + LC_Addf(L->arena, &out, ")"); + if (it->tproc.ret->kind != LC_TypeKind_void) LC_Addf(L->arena, &out, ": %s", LC_GenLCType(it->tproc.ret)); + break; + } else if (it->decl) { + LC_Decl *decl = it->decl; + LC_ASSERT(decl->ast, decl); + LC_Addf(L->arena, &out, "%s", (char *)decl->name); + break; + } else { + LC_SendErrorMessagef(NULL, NULL, "internal compiler error: unhandled type kind in %s", __FUNCTION__); + } + } + LC_String s = LC_MergeString(L->arena, out); + return s.str; +} + +LC_FUNCTION char *LC_GenLCTypeVal(LC_TypeAndVal v) { + if (LC_IsInt(v.type) || LC_IsPtr(v.type) || LC_IsProc(v.type)) { + return LC_Bigint_str(&v.i, 10); + } + if (LC_IsFloat(v.type)) { + LC_String s = LC_Format(L->arena, "%f", v.d); + return s.str; + } + LC_ASSERT(NULL, !"invalid codepath"); + return ""; +} + +LC_FUNCTION char *LC_GenLCAggName(LC_Type *t) { + if (t->kind == LC_TypeKind_Struct) return "struct"; + if (t->kind == LC_TypeKind_Union) return "union"; + return NULL; +} + +LC_FUNCTION void LC_GenLCNode(LC_AST *n) { + switch (n->kind) { + case LC_ASTKind_Package: { + LC_ASTFor(it, n->apackage.ffile) { + LC_GenLCNode(it); + } + } break; + + case LC_ASTKind_File: { + LC_ASTFor(it, n->afile.fimport) { + LC_GenLCNode(it); + } + + LC_ASTFor(it, n->afile.fdecl) { + LC_GenLCNode(it); + } + // @todo: we need to do something with notes so we can generate them in order! + + } break; + + case LC_ASTKind_GlobImport: { + LC_GenLinef("import %s \"%s\";", (char *)n->gimport.name, (char *)n->gimport.path); + } break; + + case LC_ASTKind_DeclProc: { + LC_GenLinef("%s :: ", (char *)n->dbase.name); + LC_GenLCNode(n->dproc.type); + if (n->dproc.body) { + LC_Genf(" "); + LC_GenLCNode(n->dproc.body); + } else { + LC_Genf(";"); + } + } break; + + case LC_ASTKind_DeclUnion: + case LC_ASTKind_DeclStruct: { + const char *agg = n->kind == LC_ASTKind_DeclUnion ? "union" : "struct"; + LC_GenLinef("%s :: %s {", (char *)n->dbase.name, agg); + L->printer.indent += 1; + LC_ASTFor(it, n->dagg.first) { + LC_GenLine(); + LC_GenLCNode(it); + LC_Genf(";"); + } + L->printer.indent -= 1; + LC_GenLinef("}"); + } break; + + case LC_ASTKind_TypespecAggMem: { + LC_Genf("%s: ", (char *)n->tagg_mem.name); + LC_GenLCNode(n->tagg_mem.type); + } break; + + case LC_ASTKind_DeclVar: { + LC_GenLinef("%s ", (char *)n->dbase.name); + if (n->dvar.type) { + LC_Genf(": "); + LC_GenLCNode(n->dvar.type); + if (n->dvar.expr) { + LC_Genf("= "); + LC_GenLCNode(n->dvar.expr); + } + } else { + LC_Genf(":= "); + LC_GenLCNode(n->dvar.expr); + } + LC_Genf(";"); + } break; + + case LC_ASTKind_DeclConst: { + LC_GenLinef("%s :: ", (char *)n->dbase.name); + LC_GenLCNode(n->dconst.expr); + LC_Genf(";"); + } break; + + case LC_ASTKind_DeclTypedef: { + LC_GenLinef("%s :: typedef ", (char *)n->dbase.name); + LC_GenLCNode(n->dtypedef.type); + LC_Genf(";"); + } break; + + case LC_ASTKind_ExprIdent: + case LC_ASTKind_TypespecIdent: { + LC_Genf("%s", (char *)n->eident.name); + } break; + + case LC_ASTKind_ExprField: + case LC_ASTKind_TypespecField: { + LC_GenLCNode(n->efield.left); + LC_Genf(".%s", (char *)n->efield.right); + } break; + + case LC_ASTKind_TypespecPointer: { + LC_Genf("*"); + LC_GenLCNode(n->tpointer.base); + } break; + + case LC_ASTKind_TypespecArray: { + LC_Genf("["); + if (n->tarray.index) LC_GenLCNode(n->tarray.index); + LC_Genf("]"); + LC_GenLCNode(n->tpointer.base); + } break; + + case LC_ASTKind_TypespecProc: { + LC_Genf("proc("); + LC_ASTFor(it, n->tproc.first) { + LC_GenLCNode(it); + if (it != n->tproc.last) LC_Genf(", "); + } + if (n->tproc.vargs) { + LC_Genf(", ..."); + if (n->tproc.vargs_any_promotion) LC_Genf("Any"); + } + LC_Genf(")"); + if (n->tproc.ret) { + LC_Genf(": "); + LC_GenLCNode(n->tproc.ret); + } + } break; + + case LC_ASTKind_TypespecProcArg: { + LC_Genf("%s: ", (char *)n->tproc_arg.name); + LC_GenLCNode(n->tproc_arg.type); + if (n->tproc_arg.expr) { + LC_Genf(" = "); + LC_GenLCNode(n->tproc_arg.expr); + } + } break; + + case LC_ASTKind_StmtBlock: { + if (n->sblock.name && n->sblock.kind != SBLK_Loop) LC_Genf("%s: ", (char *)n->sblock.name); + LC_Genf("{"); + L->printer.indent += 1; + LC_ASTFor(it, n->sblock.first) { + LC_GenLine(); + LC_GenLCNode(it); + if (it->kind != LC_ASTKind_StmtBlock && it->kind != LC_ASTKind_StmtDefer && it->kind != LC_ASTKind_StmtFor && it->kind != LC_ASTKind_StmtIf && it->kind != LC_ASTKind_StmtSwitch) LC_Genf(";"); + } + L->printer.indent -= 1; + LC_GenLinef("}"); + } break; + + case LC_ASTKind_StmtReturn: { + LC_Genf("return"); + if (n->sreturn.expr) { + LC_Genf(" "); + LC_GenLCNode(n->sreturn.expr); + } + } break; + + case LC_ASTKind_StmtBreak: { + LC_Genf("break"); + if (n->sbreak.name) LC_Genf(" %s", (char *)n->sbreak.name); + } break; + + case LC_ASTKind_StmtContinue: { + LC_Genf("continue"); + if (n->scontinue.name) LC_Genf(" %s", (char *)n->scontinue.name); + } break; + + case LC_ASTKind_StmtDefer: { + LC_Genf("defer "); + LC_GenLCNode(n->sdefer.body); + } break; + + case LC_ASTKind_StmtFor: { + LC_StmtBlock *sblock = &n->sfor.body->sblock; + if (sblock->name && sblock->kind == SBLK_Loop) { + LC_Genf("%s: ", (char *)sblock->name); + } + + LC_Genf("for "); + if (n->sfor.init) { + LC_GenLCNode(n->sfor.init); + if (n->sfor.cond) LC_Genf("; "); + } + + if (n->sfor.cond) { + LC_GenLCNode(n->sfor.cond); + if (n->sfor.inc) { + LC_Genf("; "); + LC_GenLCNode(n->sfor.inc); + } + } + + LC_Genf(" "); + LC_GenLCNode(n->sfor.body); + } break; + + case LC_ASTKind_StmtElseIf: + LC_Genf("else "); + case LC_ASTKind_StmtIf: { + LC_Genf("if "); + LC_GenLCNode(n->sif.expr); + LC_GenLCNode(n->sif.body); + LC_ASTFor(it, n->sif.first) { + LC_GenLCNode(it); + } + } break; + + case LC_ASTKind_StmtElse: { + LC_Genf("else "); + LC_GenLCNode(n->sif.body); + } break; + + case LC_ASTKind_StmtSwitch: { + LC_Genf("switch "); + LC_GenLCNode(n->sswitch.expr); + LC_Genf("{"); + L->printer.indent += 1; + LC_ASTFor(it, n->sswitch.first) { + LC_GenLine(); + LC_GenLCNode(it); + } + L->printer.indent -= 1; + LC_Genf("}"); + } break; + + case LC_ASTKind_StmtSwitchCase: { + LC_Genf("case "); + LC_ASTFor(it, n->scase.first) { + LC_GenLCNode(it); + if (it != n->scase.last) LC_Genf(", "); + } + LC_Genf(": "); + LC_GenLCNode(n->scase.body); + } break; + case LC_ASTKind_StmtSwitchDefault: { + LC_Genf("default: "); + LC_GenLCNode(n->scase.body); + } break; + + case LC_ASTKind_StmtAssign: { + LC_GenLCNode(n->sassign.left); + LC_Genf(" %s ", LC_TokenKindToOperator(n->sassign.op)); + LC_GenLCNode(n->sassign.right); + } break; + + case LC_ASTKind_StmtExpr: { + LC_GenLCNode(n->sexpr.expr); + } break; + + case LC_ASTKind_StmtVar: { + LC_Genf("%s", (char *)n->svar.name); + if (n->svar.type) { + LC_Genf(": "); + LC_GenLCNode(n->svar.type); + if (n->svar.expr) { + LC_Genf(" = "); + LC_GenLCNode(n->svar.expr); + } + } else { + LC_Genf(" := "); + LC_GenLCNode(n->svar.expr); + } + } break; + + case LC_ASTKind_StmtConst: { + LC_GenLinef("%s :: ", (char *)n->sconst.name); + LC_GenLCNode(n->sconst.expr); + } break; + + case LC_ASTKind_ExprString: { + LC_Genf("`%s`", (char *)n->eatom.name); + } break; + + case LC_ASTKind_ExprInt: { + LC_Genf("%s", LC_Bigint_str(&n->eatom.i, 10)); + } break; + + case LC_ASTKind_ExprFloat: { + LC_Genf("%f", n->eatom.d); + } break; + + case LC_ASTKind_ExprBool: { + int64_t value = LC_Bigint_as_unsigned(&n->eatom.i); + if (value) { + LC_Genf("true"); + } else { + LC_Genf("false"); + } + } break; + + case LC_ASTKind_ExprType: { + LC_Genf(":"); + LC_GenLCNode(n->etype.type); + } break; + + case LC_ASTKind_ExprBinary: { + LC_Genf("("); + LC_GenLCNode(n->ebinary.left); + LC_Genf("%s", LC_TokenKindToOperator(n->ebinary.op)); + LC_GenLCNode(n->ebinary.right); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprUnary: { + LC_Genf("%s(", LC_TokenKindToOperator(n->eunary.op)); + LC_GenLCNode(n->eunary.expr); + LC_Genf(")"); + } break; + + case LC_ASTKind_StmtNote: { + LC_Genf("#"); + LC_GenLCNode(n->snote.expr); + } break; + + case LC_ASTKind_ExprNote: { + LC_Genf("#"); + LC_GenLCNode(n->enote.expr); + } break; + + case LC_ASTKind_DeclNote: { + LC_GenLinef("#"); + LC_GenLCNode(n->dnote.expr); + LC_Genf(";"); + } break; + + case LC_ASTKind_Note: + case LC_ASTKind_ExprBuiltin: + case LC_ASTKind_ExprCall: { + LC_GenLCNode(n->ecompo.name); + LC_Genf("("); + LC_ASTFor(it, n->ecompo.first) { + LC_GenLCNode(it); + if (it != n->ecompo.last) LC_Genf(", "); + } + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprCompoundItem: + case LC_ASTKind_ExprCallItem: { + if (n->ecompo_item.name) { + LC_Genf("%s = ", (char *)n->ecompo_item.name); + } + if (n->ecompo_item.index) { + LC_Genf("["); + LC_GenLCNode(n->ecompo_item.index); + LC_Genf("] = "); + } + LC_GenLCNode(n->ecompo_item.expr); + } break; + + case LC_ASTKind_ExprCompound: { + if (n->ecompo.name) LC_GenLCNode(n->ecompo.name); + LC_Genf("{"); + LC_ASTFor(it, n->ecompo.first) { + LC_GenLCNode(it); + if (it != n->ecompo.last) LC_Genf(", "); + } + LC_Genf("}"); + } break; + + case LC_ASTKind_ExprCast: { + LC_Genf(":"); + LC_GenLCNode(n->ecast.type); + LC_Genf("("); + LC_GenLCNode(n->ecast.expr); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprIndex: { + LC_Genf("("); + LC_GenLCNode(n->eindex.base); + LC_Genf("["); + LC_GenLCNode(n->eindex.index); + LC_Genf("]"); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprAddPtr: { + LC_Genf("addptr("); + LC_GenLCNode(n->ebinary.left); + LC_Genf(", "); + LC_GenLCNode(n->ebinary.right); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprGetValueOfPointer: { + LC_Genf("*("); + LC_GenLCNode(n->eunary.expr); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprGetPointerOfValue: { + LC_Genf("&("); + LC_GenLCNode(n->eunary.expr); + LC_Genf(")"); + } break; + + default: LC_ReportASTError(n, "internal compiler error: unhandled ast kind in %s", __FUNCTION__); + } +} + +const bool LC_GenCInternalGenerateSizeofs = true; + +LC_FUNCTION void LC_GenCLineDirective(LC_AST *node) { + if (L->emit_line_directives) { + L->printer.last_line_num = node->pos->line; + LC_GenLinef("#line %d", L->printer.last_line_num); + LC_Intern file = node->pos->lex->file; + if (file != L->printer.last_filename) { + L->printer.last_filename = file; + LC_Genf(" \"%s\"", (char *)L->printer.last_filename); + } + } +} + +LC_FUNCTION void LC_GenLastCLineDirective(void) { + if (L->emit_line_directives) { + LC_Genf("#line %d", L->printer.last_line_num); + } +} + +LC_FUNCTION void LC_GenCLineDirectiveNum(int num) { + if (L->emit_line_directives) { + LC_Genf("#line %d", num); + } +} + +LC_FUNCTION char *LC_GenCTypeParen(char *str, char c) { + return c && c != '[' ? LC_Strf("(%s)", str) : str; +} + +LC_FUNCTION char *LC_GenCType(LC_Type *type, char *str) { + switch (type->kind) { + case LC_TypeKind_Pointer: { + return LC_GenCType(type->tptr.base, LC_GenCTypeParen(LC_Strf("*%s", str), *str)); + } break; + case LC_TypeKind_Array: { + if (type->tarray.size == 0) { + return LC_GenCType(type->tarray.base, LC_GenCTypeParen(LC_Strf("%s[]", str), *str)); + } else { + return LC_GenCType(type->tarray.base, LC_GenCTypeParen(LC_Strf("%s[%d]", str, type->tarray.size), *str)); + } + + } break; + case LC_TypeKind_Proc: { + LC_StringList out = {0}; + LC_Addf(L->arena, &out, "(*%s)", str); + LC_Addf(L->arena, &out, "("); + if (type->tagg.mems.count == 0) { + LC_Addf(L->arena, &out, "void"); + } else { + int i = 0; + for (LC_TypeMember *it = type->tproc.args.first; it; it = it->next) { + LC_Addf(L->arena, &out, "%s%s", i == 0 ? "" : ", ", LC_GenCType(it->type, "")); + i += 1; + } + } + if (type->tproc.vargs) { + LC_Addf(L->arena, &out, ", ..."); + } + LC_Addf(L->arena, &out, ")"); + char *front = LC_MergeString(L->arena, out).str; + char *result = LC_GenCType(type->tproc.ret, front); + return result; + } break; + default: return LC_Strf("%s%s%s", type->decl->foreign_name, str[0] ? " " : "", str); + } +} + +LC_FUNCTION LC_Intern LC_GetStringFromSingleArgNote(LC_AST *note) { + LC_ASSERT(note, note->kind == LC_ASTKind_Note); + LC_ASSERT(note, note->ecompo.first == note->ecompo.last); + LC_AST *arg = note->ecompo.first; + LC_ASSERT(note, arg->kind == LC_ASTKind_ExprCallItem); + LC_AST *str = arg->ecompo_item.expr; + LC_ASSERT(note, str->kind == LC_ASTKind_ExprString); + return str->eatom.name; +} + +LC_FUNCTION void LC_GenCCompound(LC_AST *n) { + LC_Type *type = n->type; + if (LC_IsAggType(type)) { + LC_ResolvedCompo *rd = n->ecompo.resolved_items; + LC_Genf("{"); + if (rd->first == NULL) LC_Genf("0"); + for (LC_ResolvedCompoItem *it = rd->first; it; it = it->next) { + LC_Genf(".%s = ", (char *)it->t->name); + LC_GenCExpr(it->expr); + if (it->next) LC_Genf(", "); + } + LC_Genf("}"); + } else if (LC_IsArray(type)) { + LC_ResolvedArrayCompo *rd = n->ecompo.resolved_array_items; + LC_Genf("{"); + for (LC_ResolvedCompoArrayItem *it = rd->first; it; it = it->next) { + LC_Genf("[%d] = ", it->index); + LC_GenCExpr(it->comp->ecompo_item.expr); + if (it->next) LC_Genf(", "); + } + LC_Genf("}"); + } else { + LC_ReportASTError(n, "internal compiler error: got unhandled case in %s", __FUNCTION__); + } +} + +LC_THREAD_LOCAL bool GC_SpecialCase_GlobalScopeStringDecl; + +LC_FUNCTION void LC_GenCString(char *s, LC_Type *type) { + if (type == L->tstring) { + if (!GC_SpecialCase_GlobalScopeStringDecl) LC_Genf("(LC_String)"); + LC_Genf("{ "); + } + LC_Genf("\""); + for (int i = 0; s[i]; i += 1) { + LC_String escape = LC_GetEscapeString(s[i]); + if (escape.len) { + LC_Genf("%.*s", LC_Expand(escape)); + } else { + LC_Genf("%c", s[i]); + } + } + LC_Genf("\""); + if (type == L->tstring) LC_Genf(", %d }", (int)LC_StrLen(s)); +} + +LC_FUNCTION char *LC_GenCVal(LC_TypeAndVal v, LC_Type *type) { + char *str = LC_GenLCTypeVal(v); + switch (type->kind) { + case LC_TypeKind_uchar: + case LC_TypeKind_ushort: + case LC_TypeKind_uint: str = LC_Strf("%su", str); break; + case LC_TypeKind_ulong: str = LC_Strf("%sul", str); break; + case LC_TypeKind_Pointer: + case LC_TypeKind_Proc: + case LC_TypeKind_ullong: str = LC_Strf("%sull", str); break; + case LC_TypeKind_long: str = LC_Strf("%sull", str); break; + case LC_TypeKind_llong: str = LC_Strf("%sull", str); break; + case LC_TypeKind_float: str = LC_Strf("%sf", str); break; + case LC_TypeKind_UntypedFloat: str = LC_Strf(" /*utfloat*/%s", str); break; + case LC_TypeKind_UntypedInt: str = LC_Strf(" /*utint*/%sull", str); break; + default: { + } + } + if (LC_IsUTInt(v.type) && !LC_IsUntyped(type) && type->size < 4) { + str = LC_Strf("(%s)%s", LC_GenCType(type, ""), str); + } + return str; +} + +LC_FUNCTION void LC_GenCExpr(LC_AST *n) { + LC_ASSERT(n, LC_IsExpr(n)); + intptr_t is_any = (intptr_t)LC_MapGetP(&L->implicit_any, n); + if (is_any) LC_Genf("(LC_Any){%d, (%s[]){", n->type->id, LC_GenCType(n->type, "")); + + if (n->const_val.type) { + bool contains_sizeof_like = LC_GenCInternalGenerateSizeofs ? LC_ContainsCBuiltin(n) : false; + if (!contains_sizeof_like) { + if (LC_IsUTStr(n->const_val.type)) { + LC_GenCString((char *)n->const_val.name, n->type); + } else { + char *val = LC_GenCVal(n->const_val, n->type); + LC_Genf("%s", val); + } + if (is_any) LC_Genf("}}"); + return; + } + } + + LC_Type *type = n->type; + switch (n->kind) { + case LC_ASTKind_ExprIdent: { + LC_Genf("%s", (char *)n->eident.resolved_decl->foreign_name); + } break; + + case LC_ASTKind_ExprCast: { + LC_Genf("("); + LC_Genf("(%s)", LC_GenCType(type, "")); + LC_Genf("("); + LC_GenCExpr(n->ecast.expr); + LC_Genf(")"); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprUnary: { + LC_Genf("%s(", LC_TokenKindToOperator(n->eunary.op)); + LC_GenCExpr(n->eunary.expr); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprAddPtr: { + LC_Genf("("); + LC_GenCExpr(n->ebinary.left); + LC_Genf("+"); + LC_GenCExpr(n->ebinary.right); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprBinary: { + LC_Genf("("); + LC_GenCExpr(n->ebinary.left); + LC_Genf("%s", LC_TokenKindToOperator(n->ebinary.op)); + LC_GenCExpr(n->ebinary.right); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprIndex: { + LC_Genf("("); + LC_GenCExpr(n->eindex.base); + LC_Genf("["); + LC_GenCExpr(n->eindex.index); + LC_Genf("]"); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprGetValueOfPointer: { + LC_Genf("(*("); + LC_GenCExpr(n->eunary.expr); + LC_Genf("))"); + } break; + + case LC_ASTKind_ExprGetPointerOfValue: { + LC_Genf("(&("); + LC_GenCExpr(n->eunary.expr); + LC_Genf("))"); + } break; + + case LC_ASTKind_ExprField: { + if (n->efield.parent_decl->kind != LC_DeclKind_Import) { + LC_Type *left_type = n->efield.left->type; + LC_GenCExpr(n->efield.left); + if (LC_IsPtr(left_type)) LC_Genf("->"); + else LC_Genf("."); + LC_Genf("%s", (char *)n->efield.right); + } else { + LC_Genf("%s", (char *)n->efield.resolved_decl->foreign_name); + } + } break; + + case LC_ASTKind_ExprCall: { + LC_ResolvedCompo *rd = n->ecompo.resolved_items; + LC_GenCExpr(n->ecompo.name); + LC_Genf("("); + for (LC_ResolvedCompoItem *it = rd->first; it; it = it->next) { + LC_GenCExpr(it->expr); + if (it->next) LC_Genf(", "); + } + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprCompound: { + LC_Genf("(%s)", LC_GenCType(type, "")); + LC_GenCCompound(n); + } break; + + case LC_ASTKind_ExprBuiltin: { + LC_ASSERT(n, n->ecompo.name->kind == LC_ASTKind_ExprIdent); + if (n->ecompo.name->eident.name == L->isizeof) { + LC_Genf("sizeof("); + LC_AST *expr = n->ecompo.first->ecompo_item.expr; + if (expr->kind == LC_ASTKind_ExprType) { + LC_Genf("%s", LC_GenCType(expr->type, "")); + } else { + LC_GenCExpr(expr); + } + LC_Genf(")"); + } else if (n->ecompo.name->eident.name == L->ialignof) { + LC_Genf("LC_Alignof("); + LC_AST *expr = n->ecompo.first->ecompo_item.expr; + if (expr->kind == LC_ASTKind_ExprType) { + LC_Genf("%s", LC_GenCType(expr->type, "")); + } else { + LC_GenCExpr(expr); + } + LC_Genf(")"); + } else if (n->ecompo.name->eident.name == L->ioffsetof) { + LC_AST *i1 = n->ecompo.first->ecompo_item.expr; + LC_AST *i2 = n->ecompo.first->next->ecompo_item.expr; + LC_Genf("offsetof(%s, %s)", LC_GenCType(i1->type, ""), (char *)i2->eident.name); + } else { + LC_ReportASTError(n, "internal compiler error: got unhandled case in %s / LC_ASTKind_ExprBuiltin", __FUNCTION__); + } + } break; + + default: LC_ReportASTError(n, "internal compiler error: got unhandled case in %s", __FUNCTION__); + } + + if (is_any) LC_Genf("}}"); +} + +const int GC_Stmt_OmitSemicolonAndNewLine = 1; + +LC_FUNCTION void LC_GenCNote(LC_AST *note) { + if (note->ecompo.name->eident.name == L->ic) { + LC_Genf("%s", (char *)LC_GetStringFromSingleArgNote(note)); + } +} + +LC_FUNCTION void LC_GenCVarExpr(LC_AST *n, bool is_declaration) { + if (LC_HasNote(n, L->inot_init)) return; + + LC_AST *e = n->dvar.expr; + if (n->kind == LC_ASTKind_StmtVar) e = n->svar.expr; + if (e) { + LC_Genf(" = "); + if (e->kind == LC_ASTKind_ExprNote) { + LC_GenCNote(e->enote.expr); + } else if (is_declaration && e->kind == LC_ASTKind_ExprCompound) { + LC_GenCCompound(e); + } else { + LC_GenCExpr(e); + } + } else { + LC_Genf(" = {0}"); + } +} + +LC_FUNCTION void LC_GenCDefers(LC_AST *block) { + LC_AST *first = block->sblock.first_defer; + if (first == NULL) return; + + int save = L->printer.last_line_num; + LC_GenLine(); + LC_GenLastCLineDirective(); + + LC_GenLinef("/*defer*/"); + for (LC_AST *it = first; it; it = it->sdefer.next) { + LC_GenCStmtBlock(it->sdefer.body); + } + + L->printer.last_line_num = save + 1; + LC_GenLine(); + LC_GenLastCLineDirective(); +} + +LC_FUNCTION void LC_GenCDefersLoopBreak(LC_AST *n) { + LC_ASSERT(n, n->kind == LC_ASTKind_StmtBreak || n->kind == LC_ASTKind_StmtContinue); + LC_AST *it = NULL; + for (int i = L->printer.out_block_stack.len - 1; i >= 0; i -= 1) { + it = L->printer.out_block_stack.data[i]; + LC_GenCDefers(it); + LC_ASSERT(it, it->sblock.kind != SBLK_Proc); + if (it->sblock.kind == SBLK_Loop) { + if (!n->sbreak.name) break; + if (n->sbreak.name && it->sblock.name == n->sbreak.name) break; + } + } + LC_ASSERT(it, it->sblock.kind == SBLK_Loop); +} + +LC_FUNCTION void LC_GenCDefersReturn(LC_AST *n) { + LC_ASSERT(n, n->kind == LC_ASTKind_StmtReturn); + LC_AST *it = NULL; + for (int i = L->printer.out_block_stack.len - 1; i >= 0; i -= 1) { + it = L->printer.out_block_stack.data[i]; + LC_GenCDefers(it); + if (it->sblock.kind == SBLK_Proc) { + break; + } + } + LC_ASSERT(it, it); + LC_ASSERT(it, it->sblock.kind == SBLK_Proc); +} + +LC_FUNCTION void LC_GenCStmt2(LC_AST *n, int flags) { + LC_ASSERT(n, LC_IsStmt(n)); + bool semicolon = !(flags & GC_Stmt_OmitSemicolonAndNewLine); + + if (semicolon) { + LC_GenLine(); + } + + switch (n->kind) { + case LC_ASTKind_StmtVar: { + LC_Type *type = n->type; + LC_Genf("%s", LC_GenCType(type, (char *)n->svar.name)); + LC_GenCVarExpr(n, true); + } break; + case LC_ASTKind_StmtExpr: LC_GenCExpr(n->sexpr.expr); break; + + case LC_ASTKind_StmtAssign: { + // Assigning to array doesn't work in C so we need to handle that + // specific compo case here. :CompoArray + if (LC_IsArray(n->type) && n->sassign.right->kind == LC_ASTKind_ExprCompound) { + LC_ASSERT(n, n->sassign.op == LC_TokenKind_Assign); + LC_AST *expr = n->sassign.right; + LC_Genf("memset("); + LC_GenCExpr(n->sassign.left); + LC_Genf(", 0, sizeof("); + LC_GenCExpr(n->sassign.left); + LC_Genf("));"); + + LC_ResolvedArrayCompo *rd = expr->ecompo.resolved_array_items; + for (LC_ResolvedCompoArrayItem *it = rd->first; it; it = it->next) { + LC_GenCExpr(n->sassign.left); + LC_Genf("[%d] = ", it->index); + LC_GenCExpr(it->comp->ecompo_item.expr); + LC_Genf(";"); + } + + } else { + LC_GenCExpr(n->sassign.left); + LC_Genf(" %s ", LC_TokenKindToOperator(n->sassign.op)); + LC_GenCExpr(n->sassign.right); + } + } break; + default: LC_ReportASTError(n, "internal compiler error: got unhandled case in %s", __FUNCTION__); + } + + if (semicolon) LC_Genf(";"); +} + +LC_FUNCTION void LC_GenCStmt(LC_AST *n) { + LC_ASSERT(n, LC_IsStmt(n)); + LC_GenCLineDirective(n); + switch (n->kind) { + case LC_ASTKind_StmtConst: + case LC_ASTKind_StmtDefer: break; + case LC_ASTKind_StmtNote: { + LC_GenLine(); + LC_GenCNote(n->snote.expr); + LC_Genf(";"); + } break; + + case LC_ASTKind_StmtReturn: { + LC_GenCDefersReturn(n); + LC_GenLinef("return"); + if (n->sreturn.expr) { + LC_Genf(" "); + LC_GenCExpr(n->sreturn.expr); + } + LC_Genf(";"); + } break; + + case LC_ASTKind_StmtContinue: + case LC_ASTKind_StmtBreak: { + const char *stmt = n->kind == LC_ASTKind_StmtBreak ? "break" : "continue"; + LC_GenCDefersLoopBreak(n); + if (n->sbreak.name) { + LC_GenLinef("goto %s_%s;", (char *)n->sbreak.name, stmt); + } else { + LC_GenLinef("%s;", stmt); + } + } break; + + case LC_ASTKind_StmtBlock: { + LC_GenLinef("/*block*/"); + LC_GenCStmtBlock(n); + } break; + + case LC_ASTKind_StmtSwitch: { + LC_GenLinef("switch("); + LC_GenCExpr(n->sswitch.expr); + LC_Genf(") {"); + + L->printer.indent += 1; + LC_ASTFor(it, n->sswitch.first) { + LC_GenCLineDirective(it); + if (it->kind == LC_ASTKind_StmtSwitchCase) { + LC_ASTFor(label_it, it->scase.first) { + LC_GenLinef("case "); + LC_GenCExpr(label_it); + LC_Genf(":"); + } + } + if (it->kind == LC_ASTKind_StmtSwitchDefault) { + LC_GenLinef("default:"); + } + LC_GenCStmtBlock(it->scase.body); + if (LC_HasNote(it, L->ifallthrough)) { + LC_Genf(" /*@fallthough*/"); + } else { + LC_Genf(" break;"); + } + } + L->printer.indent -= 1; + LC_GenLinef("}"); + } break; + + case LC_ASTKind_StmtFor: { + LC_GenLinef("for ("); + if (n->sfor.init) LC_GenCStmt2(n->sfor.init, GC_Stmt_OmitSemicolonAndNewLine); + LC_Genf(";"); + if (n->sfor.cond) { + LC_Genf(" "); + LC_GenCExpr(n->sfor.cond); + } + LC_Genf(";"); + if (n->sfor.inc) { + LC_Genf(" "); + LC_GenCStmt2(n->sfor.inc, GC_Stmt_OmitSemicolonAndNewLine); + } + LC_Genf(")"); + LC_GenCStmtBlock(n->sfor.body); + } break; + + case LC_ASTKind_StmtIf: { + LC_GenLinef("if "); + LC_GenCExprParen(n->sif.expr); + LC_GenCStmtBlock(n->sif.body); + LC_ASTFor(it, n->sif.first) { + LC_GenCLineDirective(it); + LC_GenLinef("else"); + if (it->kind == LC_ASTKind_StmtElseIf) { + LC_Genf(" if "); + LC_GenCExprParen(it->sif.expr); + } + LC_GenCStmtBlock(it->sif.body); + } + } break; + + default: LC_GenCStmt2(n, 0); + } +} + +LC_FUNCTION void LC_GenCExprParen(LC_AST *expr) { + bool paren = expr->kind != LC_ASTKind_ExprBinary; + if (paren) LC_Genf("("); + LC_GenCExpr(expr); + if (paren) LC_Genf(")"); +} + +LC_FUNCTION void LC_GenCStmtBlock(LC_AST *n) { + LC_PushAST(&L->printer.out_block_stack, n); + LC_ASSERT(n, n->kind == LC_ASTKind_StmtBlock); + LC_Genf(" {"); + L->printer.indent += 1; + LC_ASTFor(it, n->sblock.first) { + LC_GenCStmt(it); + } + LC_GenCDefers(n); + if (n->sblock.name) LC_GenLinef("%s_continue:;", (char *)n->sblock.name); + L->printer.indent -= 1; + LC_GenLinef("}"); + if (n->sblock.name) LC_GenLinef("%s_break:;", (char *)n->sblock.name); + LC_PopAST(&L->printer.out_block_stack); +} + +LC_FUNCTION void LC_GenCProcDecl(LC_Decl *decl) { + LC_StringList out = {0}; + LC_Type *type = decl->type; + LC_AST *n = decl->ast; + LC_AST *typespec = n->dproc.type; + + LC_Addf(L->arena, &out, "%s(", (char *)decl->foreign_name); + if (type->tagg.mems.count == 0) { + LC_Addf(L->arena, &out, "void"); + } else { + int i = 0; + LC_ASTFor(it, typespec->tproc.first) { + LC_Type *type = it->type; + LC_Addf(L->arena, &out, "%s%s", i == 0 ? "" : ", ", LC_GenCType(type, (char *)it->tproc_arg.name)); + i += 1; + } + } + if (type->tproc.vargs) { + LC_Addf(L->arena, &out, ", ..."); + } + LC_Addf(L->arena, &out, ")"); + char *front = LC_MergeString(L->arena, out).str; + char *result = LC_GenCType(type->tproc.ret, front); + + LC_GenLine(); + bool is_public = LC_HasNote(n, L->iapi) || decl->foreign_name == L->imain; + if (!is_public) LC_Genf("static "); + LC_Genf("%s", result); +} + +LC_FUNCTION void LC_GenCAggForwardDecl(LC_Decl *decl) { + LC_ASSERT(decl->ast, LC_IsAgg(decl->ast)); + char *agg = LC_GenLCAggName(decl->type); + LC_GenLinef("typedef %s %s %s;", agg, (char *)decl->foreign_name, (char *)decl->foreign_name); +} + +LC_FUNCTION void LC_GenCTypeDecl(LC_Decl *decl) { + LC_AST *n = decl->ast; + LC_ASSERT(n, decl->kind == LC_DeclKind_Type); + if (n->kind == LC_ASTKind_DeclTypedef) { + LC_Type *type = decl->typedef_renamed_type_decl ? decl->typedef_renamed_type_decl->type : decl->type; + LC_GenLinef("typedef %s;", LC_GenCType(type, (char *)decl->foreign_name)); + } else { + LC_Type *type = decl->type; + LC_Intern name = decl->foreign_name; + { + bool packed = LC_HasNote(n, L->ipacked) ? true : false; + if (packed) LC_GenLinef("#pragma pack(push, 1)"); + + LC_GenLinef("%s %s {", LC_GenLCAggName(type), name ? (char *)name : ""); + L->printer.indent += 1; + for (LC_TypeMember *it = type->tagg.mems.first; it; it = it->next) { + LC_GenLinef("%s;", LC_GenCType(it->type, (char *)it->name)); + } + L->printer.indent -= 1; + LC_GenLinef("};"); + if (packed) LC_GenLinef("#pragma pack(pop)"); + LC_GenLine(); + } + } +} + +LC_FUNCTION void LC_GenCVarFDecl(LC_Decl *decl) { + if (!LC_HasNote(decl->ast, L->iapi)) return; + LC_Type *type = decl->type; // make string arrays assignable + LC_GenLinef("extern "); + if (LC_HasNote(decl->ast, L->ithread_local)) LC_Genf("_Thread_local "); + LC_Genf("%s;", LC_GenCType(type, (char *)decl->foreign_name)); +} + +LC_FUNCTION void LC_GenCHeader(LC_AST *package) { + // C notes + LC_ASTFor(file, package->apackage.ffile) { + LC_ASTFor(it, file->afile.fdecl) { + if (it->kind != LC_ASTKind_DeclNote) continue; + + LC_AST *note = it->dnote.expr; + if (note->ecompo.name->eident.name == L->ic) { + LC_GenLinef("%s", (char *)LC_GetStringFromSingleArgNote(note)); + } + } + } + + // struct forward decls + LC_DeclFor(decl, package->apackage.first_ordered) { + if (decl->is_foreign) continue; + LC_AST *n = decl->ast; + if (decl->kind == LC_DeclKind_Type && LC_IsAgg(n)) LC_GenCAggForwardDecl(decl); + } + + // type decls + LC_GenLine(); + LC_DeclFor(decl, package->apackage.first_ordered) { + if (decl->is_foreign) continue; + LC_AST *n = decl->ast; + if (decl->kind == LC_DeclKind_Type) LC_GenCTypeDecl(decl); + } + + // proc and var forward decls + LC_DeclFor(decl, package->apackage.first_ordered) { + if (decl->is_foreign) continue; + LC_AST *n = decl->ast; + if (decl->kind == LC_DeclKind_Var) { + LC_GenCVarFDecl(decl); + } else if (decl->kind == LC_DeclKind_Proc) { + LC_GenCProcDecl(decl); + LC_Genf(";"); + } + } +} + +LC_FUNCTION void LC_GenCImpl(LC_AST *package) { + // implementation of vars + LC_DeclFor(decl, package->apackage.first_ordered) { + if (decl->kind == LC_DeclKind_Var && !decl->is_foreign) { + LC_AST *n = decl->ast; + LC_Type *type = decl->type; // make string arrays assignable + LC_GenLine(); + if (!LC_HasNote(n, L->iapi)) LC_Genf("static "); + if (LC_HasNote(n, L->ithread_local)) LC_Genf("_Thread_local "); + LC_Genf("%s", LC_GenCType(type, (char *)decl->foreign_name)); + + GC_SpecialCase_GlobalScopeStringDecl = true; + LC_GenCVarExpr(n, true); + GC_SpecialCase_GlobalScopeStringDecl = false; + LC_Genf(";"); + LC_GenLine(); + } + } + + // implementation of procs + LC_DeclFor(decl, package->apackage.first_ordered) { + LC_AST *n = decl->ast; + if (decl->kind == LC_DeclKind_Proc && n->dproc.body && !decl->is_foreign) { + LC_GenCLineDirective(n); + LC_GenCProcDecl(decl); + LC_GenCStmtBlock(n->dproc.body); + LC_GenLine(); + } + } +} + +LC_FUNCTION void WalkAndCountDeclRefs(LC_ASTWalker *ctx, LC_AST *n) { + LC_Decl *decl = NULL; + if (n->kind == LC_ASTKind_ExprIdent || n->kind == LC_ASTKind_TypespecIdent) { + if (n->eident.resolved_decl) decl = n->eident.resolved_decl; + } + if (n->kind == LC_ASTKind_ExprField) { + if (n->efield.resolved_decl) decl = n->efield.resolved_decl; + } + if (decl) { + LC_Map *map_of_visits = (LC_Map *)ctx->user_data; + intptr_t visited = (intptr_t)LC_MapGetP(map_of_visits, decl); + LC_MapInsertP(map_of_visits, decl, (void *)(visited + 1)); + if (visited == 0 && decl->ast->kind != LC_ASTKind_Null) { + LC_WalkAST(ctx, decl->ast); + } + } +} + +LC_FUNCTION LC_Map LC_CountDeclRefs(LC_Arena *arena) { + LC_Map map = {arena}; + LC_MapReserve(&map, 512); + + LC_AST *package = LC_GetPackageByName(L->first_package); + LC_ASTWalker walker = LC_GetDefaultWalker(arena, WalkAndCountDeclRefs); + walker.user_data = (void *)↦ + walker.visit_notes = true; + LC_WalkAST(&walker, package); + + return map; +} + +LC_FUNCTION void LC_RemoveUnreferencedGlobalDecls(LC_Map *map_of_visits) { + for (LC_ASTRef *it = L->ordered_packages.first; it; it = it->next) { + for (LC_Decl *decl = it->ast->apackage.first_ordered; decl;) { + intptr_t ref_count = (intptr_t)LC_MapGetP(map_of_visits, decl); + + LC_Decl *remove = decl; + decl = decl->next; + if (ref_count == 0 && remove->foreign_name != LC_ILit("main")) { + LC_DLLRemove(it->ast->apackage.first_ordered, it->ast->apackage.last_ordered, remove); + } + } + } +} + +LC_FUNCTION void LC_ErrorOnUnreferencedLocals(LC_Map *map_of_visits) { + LC_Decl *first = (LC_Decl *)L->decl_arena->memory.data; + for (int i = 0; i < L->decl_count; i += 1) { + LC_Decl *decl = first + i; + if (decl->package == L->builtin_package) { + continue; + } + + intptr_t ref_count = (intptr_t)LC_MapGetP(map_of_visits, decl); + if (ref_count == 0) { + if (LC_IsStmt(decl->ast)) { + if (!LC_HasNote(decl->ast, L->iunused)) LC_ReportASTError(decl->ast, "unused local variable '%s'", decl->name); + } + } + } +} + +LC_FUNCTION void LC_FindUnusedLocalsAndRemoveUnusedGlobalDecls(void) { + if (L->errors) return; + LC_TempArena check = LC_BeginTemp(L->arena); + + LC_Map map = LC_CountDeclRefs(check.arena); + LC_ErrorOnUnreferencedLocals(&map); + LC_RemoveUnreferencedGlobalDecls(&map); + + LC_EndTemp(check); +} +LC_FUNCTION LC_Operand LC_ImportPackage(LC_AST *import, LC_AST *dst, LC_AST *src) { + DeclScope *dst_scope = dst->apackage.scope; + int scope_size = LC_NextPow2(src->apackage.scope->len * 2 + 1); + if (import && import->gimport.name) { + LC_PUSH_PACKAGE(dst); + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Import, import->gimport.name, import); + decl->scope = LC_CreateScope(scope_size); + LC_PutGlobalDecl(decl); + import->gimport.resolved_decl = decl; + LC_POP_PACKAGE(); + dst_scope = decl->scope; + } + + for (int i = 0; i < src->apackage.scope->cap; i += 1) { + LC_MapEntry entry = src->apackage.scope->entries[i]; + if (entry.key != 0) { + LC_Decl *decl = (LC_Decl *)entry.value; + if (decl->package != src) continue; + LC_Decl *existing = (LC_Decl *)LC_MapGetU64(dst_scope, decl->name); + if (existing && decl->package == L->builtin_package) { + continue; + } + if (existing) { + LC_MarkDeclError(existing); + LC_MarkDeclError(decl); + return LC_ReportASTErrorEx(decl->ast, existing->ast, "name colission while importing '%s' into '%s', there are 2 decls with the same name '%s'", src->apackage.name, dst->apackage.name, decl->name); + } + LC_MapInsertU64(dst_scope, decl->name, decl); + } + } + + if (import && import->gimport.name) { + LC_ASSERT(import, dst_scope->cap == scope_size); + } + + if (import) import->gimport.resolved = true; + return LC_OPNull; +} + +LC_FUNCTION LC_Intern LC_MakePackageNameFromPath(LC_String path) { + if (path.str[path.len - 1] == '/') path = LC_Chop(path, 1); + LC_String s8name = LC_SkipToLastSlash(path); + if (!LC_IsDir(L->arena, path) && LC_EndsWith(path, LC_Lit(".lc"), true)) { + s8name = LC_ChopLastPeriod(s8name); + } + if (s8name.len == 0) { + L->errors += 1; + LC_SendErrorMessagef(NULL, NULL, "failed to extract name from path %.*s", LC_Expand(path)); + return LC_GetUniqueIntern("invalid_package_name"); + } + LC_Intern result = LC_InternStrLen(s8name.str, (int)s8name.len); + return result; +} + +LC_FUNCTION bool LC_PackageNameValid(LC_Intern name) { + char *str = (char *)name; + if (LC_IsDigit(str[0])) return false; + for (int i = 0; str[i]; i += 1) { + bool is_valid = LC_IsIdent(str[i]) || LC_IsDigit(str[i]); + if (!is_valid) return false; + } + return true; +} + +LC_FUNCTION bool LC_PackageNameDuplicate(LC_Intern name) { + LC_ASTFor(it, L->fpackage) { + if (it->apackage.name == name) return true; + } + return false; +} + +LC_FUNCTION void LC_AddPackageToList(LC_AST *n) { + LC_Intern name = n->apackage.name; + if (LC_PackageNameDuplicate(name)) { + LC_SendErrorMessagef(NULL, NULL, "found 2 packages with the same name: '%s' / '%.*s'\n", name, LC_Expand(n->apackage.path)); + L->errors += 1; + return; + } + if (!LC_PackageNameValid(name)) { + LC_SendErrorMessagef(NULL, NULL, "invalid package name, please change the name of the package directory: '%s'\n", name); + L->errors += 1; + return; + } + LC_DLLAdd(L->fpackage, L->lpackage, n); +} + +LC_FUNCTION LC_AST *LC_RegisterPackage(LC_String path) { + LC_ASSERT(NULL, path.len != 0); + LC_AST *n = LC_CreateAST(NULL, LC_ASTKind_Package); + n->apackage.name = LC_MakePackageNameFromPath(path); + n->apackage.path = path; + LC_AddPackageToList(n); + return n; +} + +LC_FUNCTION LC_AST *LC_FindImportInRefList(LC_ASTRefList *arr, LC_Intern path) { + for (LC_ASTRef *it = arr->first; it; it = it->next) { + if (it->ast->gimport.path == path) return it->ast; + } + return NULL; +} + +LC_FUNCTION void LC_AddASTToRefList(LC_ASTRefList *refs, LC_AST *ast) { + LC_ASTRef *ref = LC_PushStruct(L->arena, LC_ASTRef); + ref->ast = ast; + LC_DLLAdd(refs->first, refs->last, ref); +} + +LC_FUNCTION LC_ASTRefList LC_GetPackageImports(LC_AST *package) { + LC_ASSERT(package, package->kind == LC_ASTKind_Package); + + LC_ASTRefList refs = {0}; + LC_ASTFor(file, package->apackage.ffile) { + LC_ASTFor(import, file->afile.fimport) { + LC_AST *found = LC_FindImportInRefList(&refs, import->gimport.path); + if (found) { + LC_ReportASTErrorEx(import, found, "duplicate import of: '%s', into package '%s'\n", import->gimport.path, package->apackage.name); + continue; + } + LC_AddASTToRefList(&refs, import); + } + } + + return refs; +} + +LC_FUNCTION void LC_RegisterPackageDir(char *dir) { + LC_String sdir = LC_MakeFromChar(dir); + if (!LC_IsDir(L->arena, sdir)) { + LC_SendErrorMessagef(NULL, NULL, "dir with name '%s', doesn't exist\n", dir); + return; + } + LC_AddNode(L->arena, &L->package_dirs, sdir); +} + +LC_FUNCTION LC_AST *LC_GetPackageByName(LC_Intern name) { + LC_ASTFor(it, L->fpackage) { + if (it->apackage.name == name) return it; + } + + LC_AST *result = NULL; + for (LC_StringNode *it = L->package_dirs.first; it; it = it->next) { + LC_String s = it->string; + LC_String path = LC_Format(L->arena, "%.*s/%s", LC_Expand(s), (char *)name); + if (LC_IsDir(L->arena, path)) { + if (result != NULL) { + LC_SendErrorMessagef(NULL, NULL, "found 2 directories with the same name: '%.*s', '%.*s'\n", LC_Expand(path), LC_Expand(result->apackage.path)); + L->errors += 1; + break; + } + result = LC_RegisterPackage(path); + } + } + + return result; +} + +LC_FUNCTION LC_StringList LC_ListFilesInPackage(LC_Arena *arena, LC_String path) { + LC_StringList result = LC_MakeEmptyList(); + for (LC_FileIter it = LC_IterateFiles(arena, path); LC_IsValid(it); LC_Advance(&it)) { + if (LC_EndsWith(it.absolute_path, LC_Lit(".lc"), LC_IgnoreCase)) { + LC_AddNode(arena, &result, it.absolute_path); + } + } + return result; +} + +LC_FUNCTION LoadedFile LC_ReadFileHook(LC_AST *package, LC_String path) { + LoadedFile result = {path}; + if (L->on_file_load) { + L->on_file_load(package, &result); + } else { + result.content = LC_ReadFile(L->arena, result.path); + } + + return result; +} + +LC_FUNCTION void LC_ParsePackage(LC_AST *n) { + LC_ASSERT(n, n->kind == LC_ASTKind_Package); + LC_ASSERT(n, n->apackage.scope == NULL); + n->apackage.scope = LC_CreateScope(256); + + LC_StringList files = n->apackage.injected_filepaths; + if (files.node_count == 0) { + files = LC_ListFilesInPackage(L->arena, n->apackage.path); + if (files.first == NULL) { + LC_SendErrorMessagef(NULL, NULL, "no valid .lc files in '%.*s'", LC_Expand(n->apackage.path)); + n->apackage.state = LC_DeclState_Error; + L->errors += 1; + return; + } + } + + for (LC_StringNode *it = files.first; it; it = it->next) { + LoadedFile file = LC_ReadFileHook(n, it->string); + if (file.content.str == NULL) file.content.str = ""; + + LC_AST *ast_file = LC_ParseFile(n, file.path.str, file.content.str, file.line); + if (!ast_file) { + n->apackage.state = LC_DeclState_Error; + return; + } + } +} + +LC_FUNCTION void LC_ParsePackagesUsingRegistry(LC_Intern name) { + LC_AST *n = LC_GetPackageByName(name); + if (!n) { + LC_SendErrorMessagef(NULL, NULL, "no package with name '%s'\n", name); + L->errors += 1; + return; + } + if (n->apackage.scope) { + return; + } + LC_ParsePackage(n); + LC_ASTRefList imports = LC_GetPackageImports(n); + for (LC_ASTRef *it = imports.first; it; it = it->next) { + LC_ParsePackagesUsingRegistry(it->ast->gimport.path); + } +} + +LC_FUNCTION void LC_AddOrderedPackageToRefList(LC_AST *n) { + LC_ASTRefList *ordered = &L->ordered_packages; + for (LC_ASTRef *it = ordered->first; it; it = it->next) { + if (it->ast->apackage.name == n->apackage.name) { + return; + } + } + LC_AddASTToRefList(ordered, n); +} + +// Here we use import statements to produce a list of ordered packages. +// While we are at it we also resolve most top level declarations. I say +// most because aggregations are handled a bit differently, their resolution +// is deffered. This is added because a pointer doesn't require full typeinfo of +// an aggregate. It's just a number. +LC_FUNCTION LC_AST *LC_OrderPackagesAndBasicResolve(LC_AST *pos, LC_Intern name) { + LC_AST *n = LC_GetPackageByName(name); + if (n->apackage.state == LC_DeclState_Error) { + return NULL; + } + if (n->apackage.state == LC_DeclState_Resolved) { + // This function can be called multiple times, I assume user might + // want to use type information to generate something. Pattern: + // typecheck -> generate -> typecheck is expected! + LC_PackageDecls(n); + return n; + } + if (n->apackage.state == LC_DeclState_Resolving) { + LC_ReportASTError(pos, "circular import '%s'", name); + n->apackage.state = LC_DeclState_Error; + return NULL; + } + LC_ASSERT(pos, n->apackage.state == LC_DeclState_Unresolved); + n->apackage.state = LC_DeclState_Resolving; + + LC_Operand op = LC_ImportPackage(NULL, n, L->builtin_package); + LC_ASSERT(pos, !LC_IsError(op)); + + // Resolve all imports regardless of errors. + // If current package has wrong import it means it's also + // wrong but it should still look into all imports + // despite this. + int wrong_import = 0; + LC_ASTRefList refs = LC_GetPackageImports(n); + for (LC_ASTRef *it = refs.first; it; it = it->next) { + LC_AST *import = LC_OrderPackagesAndBasicResolve(it->ast, it->ast->gimport.path); + if (!import) { + n->apackage.state = LC_DeclState_Error; + wrong_import += 1; + continue; + } + + LC_Operand op = LC_ImportPackage(it->ast, n, import); + if (LC_IsError(op)) { + n->apackage.state = LC_DeclState_Error; + wrong_import += 1; + continue; + } + } + + if (wrong_import) return NULL; + + LC_PackageDecls(n); + LC_AddOrderedPackageToRefList(n); + n->apackage.state = LC_DeclState_Resolved; + return n; +} + +LC_FUNCTION void LC_OrderAndResolveTopLevelDecls(LC_Intern name) { + L->first_package = name; + LC_OrderPackagesAndBasicResolve(NULL, name); + + // Resolve still incomplete aggregate types, this operates on all packages + // that didn't have errors so even if something broke in package ordering + // it should still be fine to go forward with this and also proc body analysis + for (LC_ASTRef *it = L->ordered_packages.first; it; it = it->next) { + LC_AST *package = it->ast; + LC_ASSERT(package, package->apackage.state == LC_DeclState_Resolved); + LC_ResolveIncompleteTypes(package); + } +} + +LC_FUNCTION void LC_ResolveAllProcBodies(void) { + // We don't need to check errors, only valid packages should have been put into + // the list. + for (LC_ASTRef *it = L->ordered_packages.first; it; it = it->next) { + LC_AST *package = it->ast; + LC_ASSERT(package, package->apackage.state == LC_DeclState_Resolved); + LC_ResolveProcBodies(package); + } +} + +LC_FUNCTION LC_ASTRefList LC_ResolvePackageByName(LC_Intern name) { + LC_ParsePackagesUsingRegistry(name); + LC_ASTRefList empty = {0}; + if (L->errors) return empty; + + LC_OrderAndResolveTopLevelDecls(name); + LC_ResolveAllProcBodies(); + return L->ordered_packages; +} + +LC_FUNCTION LC_String LC_GenerateUnityBuild(LC_ASTRefList packages) { + if (L->errors) return LC_MakeEmptyString(); + + LC_BeginStringGen(L->arena); + + LC_GenLinef("#include "); + LC_GenLinef("#include "); + LC_GenLinef("#ifndef LC_String_IMPL"); + LC_GenLinef("#define LC_String_IMPL"); + LC_GenLinef("typedef struct { char *str; long long len; } LC_String;"); + LC_GenLinef("#endif"); + LC_GenLinef("#ifndef LC_Any_IMPL"); + LC_GenLinef("#define LC_Any_IMPL"); + LC_GenLinef("typedef struct { int type; void *data; } LC_Any;"); + LC_GenLinef("#endif"); + + LC_GenLinef("#ifndef LC_Alignof"); + LC_GenLinef("#if defined(__TINYC__)"); + LC_GenLinef("#define LC_Alignof(...) __alignof__(__VA_ARGS__)"); + LC_GenLinef("#else"); + LC_GenLinef("#define LC_Alignof(...) _Alignof(__VA_ARGS__)"); + LC_GenLinef("#endif"); + LC_GenLinef("#endif"); + LC_GenLinef("void *memset(void *, int, size_t);"); + + for (LC_ASTRef *it = packages.first; it; it = it->next) LC_GenCHeader(it->ast); + for (LC_ASTRef *it = packages.first; it; it = it->next) LC_GenCImpl(it->ast); + LC_String s = LC_EndStringGen(L->arena); + return s; +} + +LC_FUNCTION void LC_AddSingleFilePackage(LC_Intern name, LC_String path) { + LC_AST *n = LC_CreateAST(0, LC_ASTKind_Package); + n->apackage.name = name; + n->apackage.path = path; + LC_AddNode(L->arena, &n->apackage.injected_filepaths, path); + LC_AddPackageToList(n); +} +LC_FUNCTION LC_Lang *LC_LangAlloc(void) { + LC_Arena *arena = LC_BootstrapArena(); + LC_Arena *lex_arena = LC_PushStruct(arena, LC_Arena); + LC_Arena *decl_arena = LC_PushStruct(arena, LC_Arena); + LC_Arena *ast_arena = LC_PushStruct(arena, LC_Arena); + LC_Arena *type_arena = LC_PushStruct(arena, LC_Arena); + LC_InitArena(lex_arena); + LC_InitArena(decl_arena); + LC_InitArena(ast_arena); + LC_InitArena(type_arena); + + LC_Lang *l = LC_PushStruct(arena, LC_Lang); + l->arena = arena; + l->lex_arena = lex_arena; + l->decl_arena = decl_arena; + l->ast_arena = ast_arena; + l->type_arena = type_arena; + + l->emit_line_directives = true; + l->breakpoint_on_error = true; + l->use_colored_terminal_output = true; + + return l; +} + +LC_FUNCTION void LC_LangEnd(LC_Lang *lang) { + LC_DeallocateArena(lang->lex_arena); + LC_DeallocateArena(lang->type_arena); + LC_DeallocateArena(lang->decl_arena); + LC_DeallocateArena(lang->ast_arena); + LC_DeallocateArena(lang->arena); + if (L == lang) L = NULL; +} + +LC_FUNCTION void LC_LangBegin(LC_Lang *l) { + L = l; + + // Init default target settings + { + if (L->os == LC_OS_Invalid) { + L->os = LC_OS_LINUX; +#if LC_OPERATING_SYSTEM_WINDOWS + L->os = LC_OS_WINDOWS; +#elif LC_OPERATING_SYSTEM_MAC + L->os = LC_OS_MAC; +#endif + } + if (L->arch == LC_ARCH_Invalid) { + L->arch = LC_ARCH_X64; + } + if (L->gen == LC_GEN_Invalid) { + L->gen = LC_GEN_C; + } + } + + // + // Init declared notes, interns and foreign names checker + // + { + L->declared_notes.arena = L->arena; + L->interns.arena = L->arena; + L->foreign_names.arena = L->arena; + L->implicit_any.arena = L->arena; + + LC_MapReserve(&L->declared_notes, 128); + LC_MapReserve(&L->interns, 4096); + LC_MapReserve(&L->foreign_names, 256); + LC_MapReserve(&L->implicit_any, 64); + +#define X(x) l->k##x = LC_InternStrLen(#x, sizeof(#x) - 1); + LC_LIST_KEYWORDS +#undef X + l->first_keyword = l->kfor; + l->last_keyword = l->kfalse; + +#define X(x, declare) l->i##x = LC_InternStrLen(#x, sizeof(#x) - 1); + LC_LIST_INTERNS +#undef X +#define X(x, declare) \ + if (declare) LC_DeclareNote(L->i##x); + LC_LIST_INTERNS +#undef X + } + + // Nulls + { + L->NullLEX.begin = "builtin declarations"; + L->NullLEX.file = LC_ILit("builtin declarations"); + L->BuiltinToken.lex = &L->NullLEX; + L->BuiltinToken.str = "builtin declarations"; + L->BuiltinToken.len = sizeof("builtin declarations") - 1; + L->NullAST.pos = &L->BuiltinToken; + } + + { + LC_AST *builtins = LC_CreateAST(0, LC_ASTKind_Package); + L->builtin_package = builtins; + builtins->apackage.name = LC_ILit("builtins"); + builtins->apackage.scope = LC_CreateScope(256); + LC_AddPackageToList(builtins); + } + + LC_InitDeclStack(&L->resolver.locals, 128); + L->resolver.duplicate_map.arena = L->arena; + LC_MapReserve(&L->resolver.duplicate_map, 32); + + L->resolver.stmt_block_stack.arena = L->arena; + L->printer.out_block_stack.arena = L->arena; + + LC_PUSH_PACKAGE(L->builtin_package); + + // + // Init default type sizes using current platform + // + // Here we use the sizes of our current platform but + // later on it gets swapped based on LC override global variables in + // InitTarget + // + { + l->type_map.arena = L->arena; + LC_MapReserve(&l->type_map, 256); + + typedef long long llong; + typedef unsigned long long ullong; + typedef unsigned long ulong; + typedef unsigned short ushort; + typedef unsigned char uchar; + typedef unsigned int uint; + + L->pointer_align = LC_Alignof(void *); + L->pointer_size = sizeof(void *); + + int i = 0; +#define X(TNAME, IS_UNSIGNED) \ + l->types[i].kind = LC_TypeKind_##TNAME; \ + l->types[i].size = sizeof(TNAME); \ + l->types[i].align = LC_Alignof(TNAME); \ + l->types[i].is_unsigned = IS_UNSIGNED; \ + l->t##TNAME = l->types + i++; + + LC_LIST_TYPES +#undef X + + // + // Overwrite types with target + // + if (L->arch == LC_ARCH_X64) { + LC_SetPointerSizeAndAlign(8, 8); + if (L->os == LC_OS_WINDOWS) { + L->tlong->size = 4; + L->tlong->align = 4; + L->tulong->size = 4; + L->tulong->align = 4; + } else { + L->tlong->size = 8; + L->tlong->align = 8; + L->tulong->size = 8; + L->tulong->align = 8; + } + } else if (L->arch == LC_ARCH_X86) { + LC_SetPointerSizeAndAlign(4, 4); + L->tlong->size = 4; + L->tlong->align = 4; + L->tulong->size = 4; + L->tulong->align = 4; + } + + l->types[i].kind = LC_TypeKind_void; + l->tvoid = l->types + i++; + + // Init decls for types + for (int i = 0; i < T_Count; i += 1) { + char *it = (char *)LC_TypeKindToString((LC_TypeKind)i) + 12; + LC_Intern intern = LC_ILit(it); + LC_Type *t = l->types + i; + t->id = ++l->typeids; + + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Type, intern, &L->NullAST); + decl->state = LC_DeclState_Resolved; + decl->type = t; + t->decl = decl; + LC_AddDeclToScope(L->builtin_package->apackage.scope, decl); + + if (t->kind == LC_TypeKind_uchar) decl->foreign_name = LC_ILit("unsigned char"); + if (t->kind == LC_TypeKind_ushort) decl->foreign_name = LC_ILit("unsigned short"); + if (t->kind == LC_TypeKind_uint) decl->foreign_name = LC_ILit("unsigned"); + if (t->kind == LC_TypeKind_ulong) decl->foreign_name = LC_ILit("unsigned long"); + if (t->kind == LC_TypeKind_llong) decl->foreign_name = LC_ILit("long long"); + if (t->kind == LC_TypeKind_ullong) decl->foreign_name = LC_ILit("unsigned long long"); + } + } + + l->tpvoid = LC_CreatePointerType(l->tvoid); + l->tpchar = LC_CreatePointerType(l->tchar); + + { + l->tuntypedint = LC_CreateUntypedInt(L->tint); + l->tuntypedbool = LC_CreateUntypedInt(L->tbool); + l->tuntypednil = LC_CreateUntypedInt(L->tullong); + + l->ttuntypedfloat.kind = LC_TypeKind_UntypedFloat; + l->ttuntypedfloat.id = ++L->typeids; + l->tuntypedfloat = &L->ttuntypedfloat; + l->tuntypedfloat->tutdefault = l->tdouble; + l->tuntypedfloat->decl = LC_CreateDecl(LC_DeclKind_Type, LC_ILit("UntypedFloat"), &L->NullAST); + + l->ttuntypedstring.kind = LC_TypeKind_UntypedString; + l->ttuntypedstring.id = ++L->typeids; + l->tuntypedstring = &L->ttuntypedstring; + l->tuntypedstring->tutdefault = l->tpchar; + l->tuntypedstring->decl = LC_CreateDecl(LC_DeclKind_Type, LC_ILit("UntypedString"), &L->NullAST); + } + + // Add builtin "String" type + { + L->ttstring.kind = LC_TypeKind_Incomplete; + L->ttstring.id = ++L->typeids; + L->tstring = &L->ttstring; + + LC_AST *ast = LC_ParseDeclf("String :: struct { str: *char; len: int; }"); + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Type, ast->dbase.name, ast); + decl->foreign_name = LC_ILit("LC_String"); + decl->state = LC_DeclState_Resolved; + decl->type = L->tstring; + L->tstring->decl = decl; + LC_AddDeclToScope(L->builtin_package->apackage.scope, decl); + LC_Operand result = LC_ResolveTypeAggregate(ast, decl->type); + LC_ASSERT(ast, !LC_IsError(result)); + } + + // Add builtin "Any" type + { + L->ttany.kind = LC_TypeKind_Incomplete; + L->ttany.id = ++L->typeids; + L->tany = &L->ttany; + + LC_AST *ast = LC_ParseDeclf("Any :: struct { type: int; data: *void; }"); + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Type, ast->dbase.name, ast); + decl->foreign_name = LC_ILit("LC_Any"); + decl->state = LC_DeclState_Resolved; + decl->type = L->tany; + L->tany->decl = decl; + LC_AddDeclToScope(L->builtin_package->apackage.scope, decl); + LC_Operand result = LC_ResolveTypeAggregate(ast, decl->type); + LC_ASSERT(ast, !LC_IsError(result)); + } + + LC_Decl *decl_nil = LC_AddConstIntDecl("nil", 0); + decl_nil->type = L->tuntypednil; + + for (int i = LC_ARCH_X64; i < LC_ARCH_Count; i += 1) LC_AddBuiltinConstInt((char *)LC_ARCHToString((LC_ARCH)i), i); + for (int i = LC_OS_WINDOWS; i < LC_OS_Count; i += 1) LC_AddBuiltinConstInt((char *)LC_OSToString((LC_OS)i), i); + for (int i = LC_GEN_C; i < LC_GEN_Count; i += 1) LC_AddBuiltinConstInt((char *)LC_GENToString((LC_GEN)i), i); + LC_AddBuiltinConstInt("LC_ARCH", L->arch); + LC_AddBuiltinConstInt("LC_GEN", L->gen); + LC_AddBuiltinConstInt("LC_OS", L->os); + + LC_POP_PACKAGE(); +} + + +#if _WIN32 + typedef struct LC_Win32_FileIter { + HANDLE handle; + WIN32_FIND_DATAW data; +} LC_Win32_FileIter; + +LC_FUNCTION bool LC_IsDir(LC_Arena *arena, LC_String path) { + wchar_t wbuff[1024]; + LC_CreateWidecharFromChar(wbuff, LC_StrLenof(wbuff), path.str, path.len); + DWORD dwAttrib = GetFileAttributesW(wbuff); + return dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY); +} + +LC_FUNCTION LC_String LC_GetAbsolutePath(LC_Arena *arena, LC_String relative) { + wchar_t wpath[1024]; + LC_CreateWidecharFromChar(wpath, LC_StrLenof(wpath), relative.str, relative.len); + wchar_t wpath_abs[1024]; + DWORD written = GetFullPathNameW((wchar_t *)wpath, LC_StrLenof(wpath_abs), wpath_abs, 0); + if (written == 0) + return LC_MakeEmptyString(); + LC_String path = LC_FromWidecharEx(arena, wpath_abs, written); + LC_NormalizePathUnsafe(path); + return path; +} + +LC_FUNCTION bool LC_IsValid(LC_FileIter it) { + return it.is_valid; +} + +LC_FUNCTION void LC_Advance(LC_FileIter *it) { + while (FindNextFileW(it->w32->handle, &it->w32->data) != 0) { + WIN32_FIND_DATAW *data = &it->w32->data; + + // Skip '.' and '..' + if (data->cFileName[0] == '.' && data->cFileName[1] == '.' && data->cFileName[2] == 0) continue; + if (data->cFileName[0] == '.' && data->cFileName[1] == 0) continue; + + it->is_directory = data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; + it->filename = LC_FromWidecharEx(it->arena, data->cFileName, LC_WideLength(data->cFileName)); + const char *is_dir = it->is_directory ? "/" : ""; + const char *separator = it->path.str[it->path.len - 1] == '/' ? "" : "/"; + it->relative_path = LC_Format(it->arena, "%.*s%s%.*s%s", LC_Expand(it->path), separator, LC_Expand(it->filename), is_dir); + it->absolute_path = LC_GetAbsolutePath(it->arena, it->relative_path); + it->is_valid = true; + + if (it->is_directory) { + LC_ASSERT(NULL, it->relative_path.str[it->relative_path.len - 1] == '/'); + LC_ASSERT(NULL, it->absolute_path.str[it->absolute_path.len - 1] == '/'); + } + return; + } + + it->is_valid = false; + DWORD error = GetLastError(); + LC_ASSERT(NULL, error == ERROR_NO_MORE_FILES); + FindClose(it->w32->handle); +} + +LC_FUNCTION LC_FileIter LC_IterateFiles(LC_Arena *scratch_arena, LC_String path) { + LC_FileIter it = {0}; + it.arena = scratch_arena; + it.path = path; + + LC_String modified_path = LC_Format(it.arena, "%.*s\\*", LC_Expand(path)); + wchar_t *wbuff = LC_PushArray(it.arena, wchar_t, modified_path.len + 1); + int64_t wsize = LC_CreateWidecharFromChar(wbuff, modified_path.len + 1, modified_path.str, modified_path.len); + LC_ASSERT(NULL, wsize); + + it.w32 = LC_PushStruct(it.arena, LC_Win32_FileIter); + it.w32->handle = FindFirstFileW(wbuff, &it.w32->data); + if (it.w32->handle == INVALID_HANDLE_VALUE) { + it.is_valid = false; + return it; + } + + LC_ASSERT(NULL, it.w32->data.cFileName[0] == '.' && it.w32->data.cFileName[1] == 0); + LC_Advance(&it); + return it; +} + +LC_FUNCTION LC_String LC_ReadFile(LC_Arena *arena, LC_String path) { + LC_String result = LC_MakeEmptyString(); + + wchar_t wpath[1024]; + LC_CreateWidecharFromChar(wpath, LC_StrLenof(wpath), path.str, path.len); + HANDLE handle = CreateFileW(wpath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (handle != INVALID_HANDLE_VALUE) { + LARGE_INTEGER file_size; + if (GetFileSizeEx(handle, &file_size)) { + if (file_size.QuadPart != 0) { + result.len = (int64_t)file_size.QuadPart; + result.str = (char *)LC_PushSizeNonZeroed(arena, result.len + 1); + DWORD read; + if (ReadFile(handle, result.str, (DWORD)result.len, &read, NULL)) { // @todo: can only read 32 byte size files? + if (read == result.len) { + result.str[result.len] = 0; + } + } + } + } + CloseHandle(handle); + } + + return result; +} + +LC_FUNCTION bool LC_EnableTerminalColors(void) { + HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); + if (hOut != INVALID_HANDLE_VALUE) { + DWORD dwMode = 0; + if (GetConsoleMode(hOut, &dwMode)) { + dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; + if (SetConsoleMode(hOut, dwMode)) { + return true; + } + } + } + return false; +} + +#elif __linux__ || __APPLE__ || __unix__ + #include + #include + #include + #include + #include + #include + + LC_FUNCTION bool LC_EnableTerminalColors(void) { + return true; +} + +LC_FUNCTION bool LC_IsDir(LC_Arena *arena, LC_String path) { + bool result = false; + LC_TempArena ch = LC_BeginTemp(arena); + LC_String copy = LC_CopyString(arena, path); + + struct stat s; + if (stat(copy.str, &s) != 0) { + result = false; + } else { + result = S_ISDIR(s.st_mode); + } + + LC_EndTemp(ch); + return result; +} + +LC_FUNCTION LC_String LC_GetAbsolutePath(LC_Arena *arena, LC_String relative) { + LC_String copy = LC_CopyString(arena, relative); + char *buffer = (char *)LC_PushSizeNonZeroed(arena, PATH_MAX); + realpath((char *)copy.str, buffer); + LC_String result = LC_MakeFromChar(buffer); + return result; +} + +LC_FUNCTION bool LC_IsValid(LC_FileIter it) { + return it.is_valid; +} + +LC_FUNCTION void LC_Advance(LC_FileIter *it) { + struct dirent *file = 0; + while ((file = readdir((DIR *)it->dir)) != NULL) { + if (file->d_name[0] == '.' && file->d_name[1] == '.' && file->d_name[2] == 0) continue; + if (file->d_name[0] == '.' && file->d_name[1] == 0) continue; + + it->is_directory = file->d_type == DT_DIR; + it->filename = LC_CopyChar(it->arena, file->d_name); + + const char *dir_char_ending = it->is_directory ? "/" : ""; + const char *separator = it->path.str[it->path.len - 1] == '/' ? "" : "/"; + it->relative_path = LC_Format(it->arena, "%.*s%s%s%s", LC_Expand(it->path), separator, file->d_name, dir_char_ending); + it->absolute_path = LC_GetAbsolutePath(it->arena, it->relative_path); + if (it->is_directory) it->absolute_path = LC_Format(it->arena, "%.*s/", LC_Expand(it->absolute_path)); + it->is_valid = true; + return; + } + it->is_valid = false; + closedir((DIR *)it->dir); +} + +LC_FUNCTION LC_FileIter LC_IterateFiles(LC_Arena *arena, LC_String path) { + LC_FileIter it = {0}; + it.arena = arena; + it.path = path = LC_CopyString(arena, path); + it.dir = (void *)opendir((char *)path.str); + if (!it.dir) return it; + + LC_Advance(&it); + return it; +} + +LC_FUNCTION LC_String LC_ReadFile(LC_Arena *arena, LC_String path) { + LC_String result = LC_MakeEmptyString(); + + // ftell returns insane size if file is + // a directory **on some machines** KEKW + if (LC_IsDir(arena, path)) { + return result; + } + + path = LC_CopyString(arena, path); + FILE *f = fopen(path.str, "rb"); + if (f) { + fseek(f, 0, SEEK_END); + result.len = ftell(f); + fseek(f, 0, SEEK_SET); + + result.str = (char *)LC_PushSizeNonZeroed(arena, result.len + 1); + fread(result.str, result.len, 1, f); + result.str[result.len] = 0; + + fclose(f); + } + + return result; +} + +#endif + +#ifndef LC_USE_CUSTOM_ARENA + #if defined(LC_USE_ADDRESS_SANITIZER) + #include +#endif + +#if !defined(ASAN_POISON_MEMORY_REGION) + #define LC_ASAN_POISON_MEMORY_REGION(addr, size) ((void)(addr), (void)(size)) + #define LC_ASAN_UNPOISON_MEMORY_REGION(addr, size) ((void)(addr), (void)(size)) +#else + #define LC_ASAN_POISON_MEMORY_REGION(addr, size) ASAN_POISON_MEMORY_REGION(addr, size) + #define LC_ASAN_UNPOISON_MEMORY_REGION(addr, size) ASAN_UNPOISON_MEMORY_REGION(addr, size) +#endif + +#define LC_DEFAULT_RESERVE_SIZE LC_GIB(1) +#define LC_DEFAULT_ALIGNMENT 8 +#define LC_COMMIT_ADD_SIZE LC_MIB(4) + +LC_FUNCTION uint8_t *LC_V_AdvanceCommit(LC_VMemory *m, size_t *commit_size, size_t page_size) { + size_t aligned_up_commit = LC_AlignUp(*commit_size, page_size); + size_t to_be_total_commited_size = aligned_up_commit + m->commit; + size_t to_be_total_commited_size_clamped_to_reserve = LC_CLAMP_TOP(to_be_total_commited_size, m->reserve); + size_t adjusted_to_boundary_commit = to_be_total_commited_size_clamped_to_reserve - m->commit; + LC_Assertf(adjusted_to_boundary_commit, "Reached the virtual memory reserved boundary"); + *commit_size = adjusted_to_boundary_commit; + + if (adjusted_to_boundary_commit == 0) { + return 0; + } + uint8_t *result = m->data + m->commit; + return result; +} + +LC_FUNCTION void LC_PopToPos(LC_Arena *arena, size_t pos) { + LC_Assertf(arena->len >= arena->base_len, "Bug: arena->len shouldn't ever be smaller then arena->base_len"); + pos = LC_CLAMP(pos, arena->base_len, arena->len); + size_t size = arena->len - pos; + arena->len = pos; + LC_ASAN_POISON_MEMORY_REGION(arena->memory.data + arena->len, size); +} + +LC_FUNCTION void LC_PopSize(LC_Arena *arena, size_t size) { + LC_PopToPos(arena, arena->len - size); +} + +LC_FUNCTION void LC_DeallocateArena(LC_Arena *arena) { + LC_VDeallocate(&arena->memory); +} + +LC_FUNCTION void LC_ResetArena(LC_Arena *arena) { + LC_PopToPos(arena, 0); +} + +LC_FUNCTION size_t LC__AlignLen(LC_Arena *a) { + size_t align_offset = a->alignment ? LC_GetAlignOffset((uintptr_t)a->memory.data + (uintptr_t)a->len, a->alignment) : 0; + size_t aligned = a->len + align_offset; + return aligned; +} + +LC_FUNCTION void *LC__PushSizeNonZeroed(LC_Arena *a, size_t size) { + size_t align_offset = a->alignment ? LC_GetAlignOffset((uintptr_t)a->memory.data + (uintptr_t)a->len, a->alignment) : 0; + size_t aligned_len = a->len + align_offset; + size_t size_with_alignment = size + align_offset; + + if (a->len + size_with_alignment > a->memory.commit) { + if (a->memory.reserve == 0) { + LC_Assertf(0, "Pushing on uninitialized arena with zero initialization turned off"); + } + bool result = LC_VCommit(&a->memory, size_with_alignment + LC_COMMIT_ADD_SIZE); + LC_Assertf(result, "%s(%d): Failed to commit memory more memory! reserve: %zu commit: %zu len: %zu size_with_alignment: %zu", LC_BeginTempdSourceLoc.file, LC_BeginTempdSourceLoc.line, a->memory.reserve, a->memory.commit, a->len, size_with_alignment); + (void)result; + } + + uint8_t *result = a->memory.data + aligned_len; + a->len += size_with_alignment; + LC_Assertf(a->len <= a->memory.commit, "%s(%d): Reached commit boundary! reserve: %zu commit: %zu len: %zu base_len: %zu alignment: %d size_with_alignment: %zu", LC_BeginTempdSourceLoc.file, LC_BeginTempdSourceLoc.line, a->memory.reserve, a->memory.commit, a->len, a->base_len, a->alignment, size_with_alignment); + LC_ASAN_UNPOISON_MEMORY_REGION(result, size); + return (void *)result; +} + +LC_FUNCTION void *LC__PushSize(LC_Arena *arena, size_t size) { + void *result = LC__PushSizeNonZeroed(arena, size); + LC_MemoryZero(result, size); + return result; +} + +LC_FUNCTION LC_Arena LC_PushArena(LC_Arena *arena, size_t size) { + LC_Arena result; + LC_MemoryZero(&result, sizeof(result)); + result.memory.data = LC_PushArrayNonZeroed(arena, uint8_t, size); + result.memory.commit = size; + result.memory.reserve = size; + result.alignment = arena->alignment; + return result; +} + +LC_FUNCTION LC_Arena *LC_PushArenaP(LC_Arena *arena, size_t size) { + LC_Arena *result = LC_PushStruct(arena, LC_Arena); + *result = LC_PushArena(arena, size); + return result; +} + +LC_FUNCTION void LC_InitArenaEx(LC_Arena *a, size_t reserve) { + a->memory = LC_VReserve(reserve); + LC_ASAN_POISON_MEMORY_REGION(a->memory.data, a->memory.reserve); + a->alignment = LC_DEFAULT_ALIGNMENT; +} + +LC_FUNCTION void LC_InitArena(LC_Arena *a) { + LC_InitArenaEx(a, LC_DEFAULT_RESERVE_SIZE); +} + +LC_FUNCTION LC_Arena *LC_BootstrapArena(void) { + LC_Arena bootstrap_arena = {0}; + LC_InitArena(&bootstrap_arena); + + LC_Arena *arena = LC_PushStruct(&bootstrap_arena, LC_Arena); + *arena = bootstrap_arena; + arena->base_len = arena->len; + return arena; +} + +LC_FUNCTION void LC_InitArenaFromBuffer(LC_Arena *arena, void *buffer, size_t size) { + arena->memory.data = (uint8_t *)buffer; + arena->memory.commit = size; + arena->memory.reserve = size; + arena->alignment = LC_DEFAULT_ALIGNMENT; + LC_ASAN_POISON_MEMORY_REGION(arena->memory.data, arena->memory.reserve); +} + +LC_FUNCTION LC_TempArena LC_BeginTemp(LC_Arena *arena) { + LC_TempArena result; + result.pos = arena->len; + result.arena = arena; + return result; +} + +LC_FUNCTION void LC_EndTemp(LC_TempArena checkpoint) { + LC_PopToPos(checkpoint.arena, checkpoint.pos); +} + #if _WIN32 + const size_t LC_V_WIN32_PAGE_SIZE = 4096; + +LC_FUNCTION LC_VMemory LC_VReserve(size_t size) { + LC_VMemory result; + LC_MemoryZero(&result, sizeof(result)); + size_t adjusted_size = LC_AlignUp(size, LC_V_WIN32_PAGE_SIZE); + result.data = (uint8_t *)VirtualAlloc(0, adjusted_size, MEM_RESERVE, PAGE_READWRITE); + LC_Assertf(result.data, "Failed to reserve virtual memory"); + result.reserve = adjusted_size; + return result; +} + +LC_FUNCTION bool LC_VCommit(LC_VMemory *m, size_t commit) { + uint8_t *pointer = LC_V_AdvanceCommit(m, &commit, LC_V_WIN32_PAGE_SIZE); + if (pointer) { + void *result = VirtualAlloc(pointer, commit, MEM_COMMIT, PAGE_READWRITE); + LC_Assertf(result, "Failed to commit more memory"); + if (result) { + m->commit += commit; + return true; + } + } + return false; +} + +LC_FUNCTION void LC_VDeallocate(LC_VMemory *m) { + BOOL result = VirtualFree(m->data, 0, MEM_RELEASE); + LC_Assertf(result != 0, "Failed to release LC_VMemory"); +} + +LC_FUNCTION bool LC_VDecommitPos(LC_VMemory *m, size_t pos) { + size_t aligned = LC_AlignDown(pos, LC_V_WIN32_PAGE_SIZE); + size_t adjusted_pos = LC_CLAMP_TOP(aligned, m->commit); + size_t size_to_decommit = m->commit - adjusted_pos; + if (size_to_decommit) { + uint8_t *base_address = m->data + adjusted_pos; + BOOL result = VirtualFree(base_address, size_to_decommit, MEM_DECOMMIT); + if (result) { + m->commit -= size_to_decommit; + return true; + } + } + return false; +} + #elif __linux__ || __APPLE__ || __unix__ + #define LC_V_UNIX_PAGE_SIZE 4096 + +LC_FUNCTION LC_VMemory LC_VReserve(size_t size) { + LC_VMemory result = {}; + size_t size_aligned = LC_AlignUp(size, LC_V_UNIX_PAGE_SIZE); + result.data = (uint8_t *)mmap(0, size_aligned, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + LC_Assertf(result.data, "Failed to reserve memory using mmap!!"); + if (result.data) { + result.reserve = size_aligned; + } + return result; +} + +LC_FUNCTION bool LC_VCommit(LC_VMemory *m, size_t commit) { + uint8_t *pointer = LC_V_AdvanceCommit(m, &commit, LC_V_UNIX_PAGE_SIZE); + if (pointer) { + int mprotect_result = mprotect(pointer, commit, PROT_READ | PROT_WRITE); + LC_Assertf(mprotect_result == 0, "Failed to commit more memory using mmap"); + if (mprotect_result == 0) { + m->commit += commit; + return true; + } + } + return false; +} + +LC_FUNCTION void LC_VDeallocate(LC_VMemory *m) { + int result = munmap(m->data, m->reserve); + LC_Assertf(result == 0, "Failed to release virtual memory using munmap"); +} + #endif +#endif + +#if __clang__ + #pragma clang diagnostic pop +#endif + +#endif // LIB_COMPILER_IMPLEMENTATION + +/* +Copyright (c) 2024 Krzosa Karol + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ diff --git a/pkgs/libc/assert.lc b/pkgs/libc/assert.lc new file mode 100644 index 0000000..7d26c45 --- /dev/null +++ b/pkgs/libc/assert.lc @@ -0,0 +1,13 @@ +#`#include `; +@foreign assert :: proc(b: bool); @foreign + +#` +#if defined(_MSC_VER) + #define lc_assertion_debug_break() (__debugbreak(), 0) +#else + #define lc_assertion_debug_break() (__builtin_trap(), 0) +#endif +`; + + +debug_break :: proc(): int; @foreign(lc_assertion_debug_break) diff --git a/pkgs/libc/ctype.lc b/pkgs/libc/ctype.lc new file mode 100644 index 0000000..7d76404 --- /dev/null +++ b/pkgs/libc/ctype.lc @@ -0,0 +1,17 @@ +#`#include`; + +isalnum :: proc(c: int): int; @foreign +isalpha :: proc(c: int): int; @foreign +isblank :: proc(c: int): int; @foreign +iscntrl :: proc(c: int): int; @foreign +isdigit :: proc(c: int): int; @foreign +isgraph :: proc(c: int): int; @foreign +islower :: proc(c: int): int; @foreign +isprint :: proc(c: int): int; @foreign +ispunct :: proc(c: int): int; @foreign +isspace :: proc(c: int): int; @foreign +isupper :: proc(c: int): int; @foreign +isxdigit :: proc(c: int): int; @foreign + +tolower :: proc(c: int): int; @foreign +toupper :: proc(c: int): int; @foreign \ No newline at end of file diff --git a/pkgs/libc/errno.lc b/pkgs/libc/errno.lc new file mode 100644 index 0000000..3b706fd --- /dev/null +++ b/pkgs/libc/errno.lc @@ -0,0 +1,2 @@ +#`#include`; +errno: int; @foreign \ No newline at end of file diff --git a/pkgs/libc/math.lc b/pkgs/libc/math.lc new file mode 100644 index 0000000..1038436 --- /dev/null +++ b/pkgs/libc/math.lc @@ -0,0 +1,122 @@ +#`#include `; + +acos :: proc(x: double): double; @foreign +acosf :: proc(x: float): float; @foreign +asin :: proc(x: double): double; @foreign +asinf :: proc(x: float): float; @foreign +atan :: proc(x: double): double; @foreign +atanf :: proc(x: float): float; @foreign +atan2 :: proc(y: double, x: double): double; @foreign +atan2f :: proc(y: float, x: float): float; @foreign +cos :: proc(x: double): double; @foreign +cosf :: proc(x: float): float; @foreign +sin :: proc(x: double): double; @foreign +sinf :: proc(x: float): float; @foreign +tan :: proc(x: double): double; @foreign +tanf :: proc(x: float): float; @foreign + +acosh :: proc(x: double): double; @foreign +acoshf :: proc(x: float): float; @foreign +asinh :: proc(x: double): double; @foreign +asinhf :: proc(x: float): float; @foreign +atanh :: proc(x: double): double; @foreign +atanhf :: proc(x: float): float; @foreign +cosh :: proc(x: double): double; @foreign +coshf :: proc(x: float): float; @foreign +sinh :: proc(x: double): double; @foreign +sinhf :: proc(x: float): float; @foreign +tanh :: proc(x: double): double; @foreign +tanhf :: proc(x: float): float; @foreign + +exp :: proc(x: double): double; @foreign +expf :: proc(x: float): float; @foreign +exp2 :: proc(x: double): double; @foreign +exp2f :: proc(x: float): float; @foreign +expm1 :: proc(x: double): double; @foreign +expm1f :: proc(x: float): float; @foreign +frexp :: proc(value: double, exp: *int): double; @foreign +frexpf :: proc(value: float, exp: *int): float; @foreign +ilogb :: proc(x: double): int; @foreign +ilogbf :: proc(x: float): int; @foreign +ldexp :: proc(x: double, exp: int): double; @foreign +ldexpf :: proc(x: float, exp: int): float; @foreign +log :: proc(x: double): double; @foreign +logf :: proc(x: float): float; @foreign +log10 :: proc(x: double): double; @foreign +log10f :: proc(x: float): float; @foreign +log1p :: proc(x: double): double; @foreign +log1pf :: proc(x: float): float; @foreign +log2 :: proc(x: double): double; @foreign +log2f :: proc(x: float): float; @foreign +logb :: proc(x: double): double; @foreign +logbf :: proc(x: float): float; @foreign +modf :: proc(value: double, iptr: *double): double; @foreign +modff :: proc(value: float, iptr: *float): float; @foreign +scalbn :: proc(x: double, n: int): double; @foreign +scalbnf :: proc(x: float, n: int): float; @foreign +scalbln :: proc(x: double, n: long): double; @foreign +scalblnf :: proc(x: float, n: long): float; @foreign + +cbrt :: proc(x: double): double; @foreign +cbrtf :: proc(x: float): float; @foreign +fabs :: proc(x: double): double; @foreign +fabsf :: proc(x: float): float; @foreign +hypot :: proc(x: double, y: double): double; @foreign +hypotf :: proc(x: float, y: float): float; @foreign +pow :: proc(x: double, y: double): double; @foreign +powf :: proc(x: float, y: float): float; @foreign +sqrt :: proc(x: double): double; @foreign +sqrtf :: proc(x: float): float; @foreign + +erf :: proc(x: double): double; @foreign +erff :: proc(x: float): float; @foreign +erfc :: proc(x: double): double; @foreign +erfcf :: proc(x: float): float; @foreign +lgamma :: proc(x: double): double; @foreign +lgammaf :: proc(x: float): float; @foreign +tgamma :: proc(x: double): double; @foreign +tgammaf :: proc(x: float): float; @foreign + +ceil :: proc(x: double): double; @foreign +ceilf :: proc(x: float): float; @foreign +floor :: proc(x: double): double; @foreign +floorf :: proc(x: float): float; @foreign +nearbyint :: proc(x: double): double; @foreign +nearbyintf :: proc(x: float): float; @foreign +rint :: proc(x: double): double; @foreign +rintf :: proc(x: float): float; @foreign +lrint :: proc(x: double): long; @foreign +lrintf :: proc(x: float): long; @foreign +llrint :: proc(x: double): llong; @foreign +llrintf :: proc(x: float): llong; @foreign +round :: proc(x: double): double; @foreign +roundf :: proc(x: float): float; @foreign +lround :: proc(x: double): long; @foreign +lroundf :: proc(x: float): long; @foreign +llround :: proc(x: double): llong; @foreign +llroundf :: proc(x: float): llong; @foreign +trunc :: proc(x: double): double; @foreign +truncf :: proc(x: float): float; @foreign + +fmod :: proc(x: double, y: double): double; @foreign +fmodf :: proc(x: float, y: float): float; @foreign +remainder :: proc(x: double, y: double): double; @foreign +remainderf :: proc(x: float, y: float): float; @foreign +remquo :: proc(x: double, y: double, quo: *int): double; @foreign +remquof :: proc(x: float, y: float, quo: *int): float; @foreign + +copysign :: proc(x: double, y: double): double; @foreign +copysignf :: proc(x: float, y: float): float; @foreign +nan :: proc(tagp: *char): double; @foreign +nanf :: proc(tagp: *char): float; @foreign +nextafter :: proc(x: double, y: double): double; @foreign +nextafterf :: proc(x: float, y: float): float; @foreign + +fdim :: proc(x: double, y: double): double; @foreign +fdimf :: proc(x: float, y: float): float; @foreign +fmax :: proc(x: double, y: double): double; @foreign +fmaxf :: proc(x: float, y: float): float; @foreign +fmin :: proc(x: double, y: double): double; @foreign +fminf :: proc(x: float, y: float): float; @foreign +fma :: proc(x: double, y: double, z: double): double; @foreign +fmaf :: proc(x: float, y: float, z: float): float; @foreign \ No newline at end of file diff --git a/pkgs/libc/size_t.lc b/pkgs/libc/size_t.lc new file mode 100644 index 0000000..279b937 --- /dev/null +++ b/pkgs/libc/size_t.lc @@ -0,0 +1,3 @@ +import std_types "std_types"; + +size_t :: typedef std_types.usize; @foreign @weak \ No newline at end of file diff --git a/pkgs/libc/stdarg.lc b/pkgs/libc/stdarg.lc new file mode 100644 index 0000000..d2c23ce --- /dev/null +++ b/pkgs/libc/stdarg.lc @@ -0,0 +1,12 @@ +#` +#include +#define lc_va_arg_any(va) va_arg(va, LC_Any) +`; + +va_list :: struct { a: ullong; } @foreign +va_start :: proc(args: va_list, arg: *void); @foreign +va_end :: proc(args: va_list); @foreign +va_copy :: proc(args: va_list, src: va_list); @foreign +// va_arg :: proc(args: va_list, arg: *void); @foreign + +va_arg_any :: proc(args: va_list): Any; @foreign(lc_va_arg_any) diff --git a/pkgs/libc/stdio.lc b/pkgs/libc/stdio.lc new file mode 100644 index 0000000..70f455f --- /dev/null +++ b/pkgs/libc/stdio.lc @@ -0,0 +1,61 @@ +#`#include`; + +SEEK_SET :: 0; +SEEK_CUR :: 1; +SEEK_END :: 2; + +FILE :: struct {a: int;} @foreign +fpos_t :: typedef long; @foreign + +stderr: *FILE; @foreign +stdin: *FILE; @foreign +stdout: *FILE; @foreign + +remove :: proc(filename: *char): int; @foreign +rename :: proc(old: *char, new: *char): int; @foreign +tmpfile :: proc(): *FILE; @foreign +tmpnam :: proc(s: *char): *char; @foreign + +fclose :: proc(stream: *FILE): int; @foreign +fflush :: proc(stream: *FILE): int; @foreign +fopen :: proc(filename: *char, mode: *char): *FILE; @foreign +freopen :: proc(filename: *char, mode: *char, stream: *FILE): *FILE; @foreign +setbuf :: proc(stream: *FILE, buf: *char); @foreign +setvbuf :: proc(stream: *FILE, buf: *char, mode: int, size: size_t): int; @foreign + +fprintf :: proc(stream: *FILE, format: *char, ...): int; @foreign +fscanf :: proc(stream: *FILE, format: *char, ...): int; @foreign +printf :: proc(format: *char, ...): int; @foreign +scanf :: proc(format: *char, ...): int; @foreign +snprintf :: proc(s: *char, n: size_t, format: *char, ...): int; @foreign +sscanf :: proc(s: *char, format: *char, ...): int; @foreign +vfprintf :: proc(stream: *FILE, format: *char, arg: *va_list): int; @foreign +vfscanf :: proc(stream: *FILE, format: *char, arg: *va_list): int; @foreign +vprintf :: proc(format: *char, arg: *va_list): int; @foreign +vscanf :: proc(format: *char, arg: *va_list): int; @foreign +vsnprintf :: proc(s: *char, n: size_t, format: *char, arg: *va_list): int; @foreign +vsprintf :: proc(s: *char, format: *char, arg: *va_list): int; @foreign +vsscanf :: proc(s: *char, format: *char, arg: *va_list): int; @foreign + +fgetc :: proc(stream: *FILE): int; @foreign +fgets :: proc(s: *char, n: int, stream: *FILE): *char; @foreign +fputc :: proc(s: *char, stream: *FILE): int; @foreign +getc :: proc(stream: *FILE): int; @foreign +getchar :: proc(): int; @foreign +putc :: proc(c: int, stream: *FILE): int; @foreign +putchar :: proc(c: int): int; @foreign +puts :: proc(s: *char): int; @foreign +ungetc :: proc(c: int, stream: *FILE): int; @foreign +fread :: proc(ptr: *void, size: size_t, nmemb: size_t, stream: *FILE): size_t; @foreign +fwrite :: proc(ptr: *void, size: size_t, nmemb: size_t, stream: *FILE): size_t; @foreign + +fgetpos :: proc(stream: *FILE, pos: *fpos_t): int; @foreign +fseek :: proc(stream: *FILE, offset: long, whence: int): int; @foreign +fsetpos :: proc(stream: *FILE, pos: *fpos_t): int; @foreign +ftell :: proc(stream: *FILE): long; @foreign +rewind :: proc(stream: *FILE); @foreign + +clearerr :: proc(stream: *FILE); @foreign +feof :: proc(stream: *FILE): int; @foreign +ferror :: proc(stream: *FILE): int; @foreign +perror :: proc(s: *char); @foreign \ No newline at end of file diff --git a/pkgs/libc/stdlib.lc b/pkgs/libc/stdlib.lc new file mode 100644 index 0000000..13ee76f --- /dev/null +++ b/pkgs/libc/stdlib.lc @@ -0,0 +1,48 @@ +#`#include`; + +wchar_t :: typedef std_types.u16; @foreign +div_t :: struct { quot: int; rem: int; } @foreign +ldiv_t :: struct { quot: long; rem: long; } @foreign +lldiv_t :: struct { quot: llong; rem: llong; } @foreign + +atof :: proc(nptr: *char): double; @foreign +atoi :: proc(nptr: *char): int; @foreign +atol :: proc(nptr: *char): long; @foreign +atoll :: proc(nptr: *char): llong; @foreign +strtod :: proc(nptr: *char, endptr: **char): double; @foreign +strtof :: proc(nptr: *char, endptr: **char): float; @foreign +strtol :: proc(nptr: *char, endptr: **char, base: int): long; @foreign +strtoll :: proc(nptr: *char, endptr: **char, base: int): llong; @foreign +strtoul :: proc(nptr: *char, endptr: **char, base: int): ulong; @foreign +strtoull :: proc(nptr: *char, endptr: **char, base: int): ullong; @foreign + +rand :: proc(): int; @foreign +srand :: proc(seed: uint); @foreign + +calloc :: proc(nmemb: size_t, size: size_t): *void; @foreign +free :: proc(ptr: *void); @foreign +malloc :: proc(size: size_t): *void; @foreign +realloc :: proc(ptr: *void, size: size_t): *void; @foreign + +abort :: proc(); @foreign +atexit :: proc(func: proc()): int; @foreign +at_quick_exit :: proc(func: proc()): int; @foreign +exit :: proc(status: int); @foreign +_Exit :: proc(status: int); @foreign +getenv :: proc(name: *char): *char; @foreign +quick_exit :: proc(status: int); @foreign +system :: proc(cmd: *char): int; @foreign + +abs :: proc(j: int): int; @foreign +labs :: proc(j: long): long; @foreign +llabs :: proc(j: llong): llong; @foreign +div :: proc(numer: int, denom: int): div_t; @foreign +ldiv :: proc(numer: long, denom: long): ldiv_t; @foreign +lldiv :: proc(numer: llong, denom: llong): lldiv_t; @foreign + +mblen :: proc(s: *char, n: size_t): int; @foreign +mbtowc :: proc(pwc: *wchar_t, s: *char, n: size_t): int; @foreign +wctomb :: proc(s: *char, wc: wchar_t): int; @foreign + +mbstowcs :: proc(pwcs: *wchar_t, s: *char, n: size_t): size_t; @foreign +wcstombs :: proc(s: *char, pwcs: *wchar_t, n: size_t): size_t; @foreign \ No newline at end of file diff --git a/pkgs/libc/string.lc b/pkgs/libc/string.lc new file mode 100644 index 0000000..d2ead25 --- /dev/null +++ b/pkgs/libc/string.lc @@ -0,0 +1,28 @@ +#`#include`; + + +memset :: proc(s: *void, value: int, n: size_t): *void; @foreign +memcpy :: proc(s1: *void, s2: *void, n: size_t): *void; @foreign +memmove :: proc(s1: *void, s2: *void, n: size_t): *void; @foreign +strcpy :: proc(s1: *char, s2: *char): *char; @foreign +strncpy :: proc(s1: *char, s2: *char, n: size_t): *char; @foreign + +strcat :: proc(s1: *char, s2: *char): *char; @foreign +strncat :: proc(s1: *char, s2: *char, n: size_t): *char; @foreign + +memcmp :: proc(s1: *void, s2: *void, n: size_t): int; @foreign +strcmp :: proc(s1: *char, s2: *char): int; @foreign +strcoll :: proc(s1: *char, s2: *char): int; @foreign +strncmp :: proc(s1: *char, s2: *char, n: size_t): int; @foreign +strxfrm :: proc(s1: *char, s2: *char, n: size_t): size_t; @foreign + +memchr :: proc(s : *void, c: int, n: size_t): *void; @foreign +strchr :: proc(s : *char, c: int): *char; @foreign +strcspn :: proc(s1: *char, s2: *char): size_t; @foreign +strpbrk :: proc(s1: *char, s2: *char): *char; @foreign +strrchr :: proc(s : *char, c: int): *char; @foreign +strcpn :: proc(s1: *char, s2: *char): *char; @foreign +strtok :: proc(s1: *char, s2: *char): *char; @foreign + +strerror :: proc(errnum: int): *char; @foreign +strlen :: proc(s: *char): size_t; @foreign \ No newline at end of file diff --git a/pkgs/raylib/raylib-5.0_win64_msvc16/LICENSE b/pkgs/raylib/raylib-5.0_win64_msvc16/LICENSE new file mode 100644 index 0000000..ca631da --- /dev/null +++ b/pkgs/raylib/raylib-5.0_win64_msvc16/LICENSE @@ -0,0 +1,16 @@ +Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) + +This software is provided "as-is", without any express or implied warranty. In no event +will the authors be held liable for any damages arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, including commercial +applications, and to alter it and redistribute it freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not claim that you + wrote the original software. If you use this software in a product, an acknowledgment + in the product documentation would be appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be misrepresented + as being the original software. + + 3. This notice may not be removed or altered from any source distribution. diff --git a/pkgs/raylib/raylib-5.0_win64_msvc16/include/raylib.h b/pkgs/raylib/raylib-5.0_win64_msvc16/include/raylib.h new file mode 100644 index 0000000..460919f --- /dev/null +++ b/pkgs/raylib/raylib-5.0_win64_msvc16/include/raylib.h @@ -0,0 +1,1662 @@ +/********************************************************************************************** +* +* raylib v5.0 - A simple and easy-to-use library to enjoy videogames programming (www.raylib.com) +* +* FEATURES: +* - NO external dependencies, all required libraries included with raylib +* - Multiplatform: Windows, Linux, FreeBSD, OpenBSD, NetBSD, DragonFly, +* MacOS, Haiku, Android, Raspberry Pi, DRM native, HTML5. +* - Written in plain C code (C99) in PascalCase/camelCase notation +* - Hardware accelerated with OpenGL (1.1, 2.1, 3.3, 4.3 or ES2 - choose at compile) +* - Unique OpenGL abstraction layer (usable as standalone module): [rlgl] +* - Multiple Fonts formats supported (TTF, XNA fonts, AngelCode fonts) +* - Outstanding texture formats support, including compressed formats (DXT, ETC, ASTC) +* - Full 3d support for 3d Shapes, Models, Billboards, Heightmaps and more! +* - Flexible Materials system, supporting classic maps and PBR maps +* - Animated 3D models supported (skeletal bones animation) (IQM) +* - Shaders support, including Model shaders and Postprocessing shaders +* - Powerful math module for Vector, Matrix and Quaternion operations: [raymath] +* - Audio loading and playing with streaming support (WAV, OGG, MP3, FLAC, XM, MOD) +* - VR stereo rendering with configurable HMD device parameters +* - Bindings to multiple programming languages available! +* +* NOTES: +* - One default Font is loaded on InitWindow()->LoadFontDefault() [core, text] +* - One default Texture2D is loaded on rlglInit(), 1x1 white pixel R8G8B8A8 [rlgl] (OpenGL 3.3 or ES2) +* - One default Shader is loaded on rlglInit()->rlLoadShaderDefault() [rlgl] (OpenGL 3.3 or ES2) +* - One default RenderBatch is loaded on rlglInit()->rlLoadRenderBatch() [rlgl] (OpenGL 3.3 or ES2) +* +* DEPENDENCIES (included): +* [rcore] rglfw (Camilla Löwy - github.com/glfw/glfw) for window/context management and input (PLATFORM_DESKTOP) +* [rlgl] glad (David Herberth - github.com/Dav1dde/glad) for OpenGL 3.3 extensions loading (PLATFORM_DESKTOP) +* [raudio] miniaudio (David Reid - github.com/mackron/miniaudio) for audio device/context management +* +* OPTIONAL DEPENDENCIES (included): +* [rcore] msf_gif (Miles Fogle) for GIF recording +* [rcore] sinfl (Micha Mettke) for DEFLATE decompression algorithm +* [rcore] sdefl (Micha Mettke) for DEFLATE compression algorithm +* [rtextures] stb_image (Sean Barret) for images loading (BMP, TGA, PNG, JPEG, HDR...) +* [rtextures] stb_image_write (Sean Barret) for image writing (BMP, TGA, PNG, JPG) +* [rtextures] stb_image_resize (Sean Barret) for image resizing algorithms +* [rtext] stb_truetype (Sean Barret) for ttf fonts loading +* [rtext] stb_rect_pack (Sean Barret) for rectangles packing +* [rmodels] par_shapes (Philip Rideout) for parametric 3d shapes generation +* [rmodels] tinyobj_loader_c (Syoyo Fujita) for models loading (OBJ, MTL) +* [rmodels] cgltf (Johannes Kuhlmann) for models loading (glTF) +* [rmodels] Model3D (bzt) for models loading (M3D, https://bztsrc.gitlab.io/model3d) +* [raudio] dr_wav (David Reid) for WAV audio file loading +* [raudio] dr_flac (David Reid) for FLAC audio file loading +* [raudio] dr_mp3 (David Reid) for MP3 audio file loading +* [raudio] stb_vorbis (Sean Barret) for OGG audio loading +* [raudio] jar_xm (Joshua Reisenauer) for XM audio module loading +* [raudio] jar_mod (Joshua Reisenauer) for MOD audio module loading +* +* +* LICENSE: zlib/libpng +* +* raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, +* BSD-like license that allows static linking with closed source software: +* +* Copyright (c) 2013-2023 Ramon Santamaria (@raysan5) +* +* This software is provided "as-is", without any express or implied warranty. In no event +* will the authors be held liable for any damages arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, including commercial +* applications, and to alter it and redistribute it freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not claim that you +* wrote the original software. If you use this software in a product, an acknowledgment +* in the product documentation would be appreciated but is not required. +* +* 2. Altered source versions must be plainly marked as such, and must not be misrepresented +* as being the original software. +* +* 3. This notice may not be removed or altered from any source distribution. +* +**********************************************************************************************/ + +#ifndef RAYLIB_H +#define RAYLIB_H + +#include // Required for: va_list - Only used by TraceLogCallback + +#define RAYLIB_VERSION_MAJOR 5 +#define RAYLIB_VERSION_MINOR 0 +#define RAYLIB_VERSION_PATCH 0 +#define RAYLIB_VERSION "5.0" + +// Function specifiers in case library is build/used as a shared library (Windows) +// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll +#if defined(_WIN32) + #if defined(BUILD_LIBTYPE_SHARED) + #if defined(__TINYC__) + #define __declspec(x) __attribute__((x)) + #endif + #define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) + #elif defined(USE_LIBTYPE_SHARED) + #define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) + #endif +#endif + +#ifndef RLAPI + #define RLAPI // Functions defined as 'extern' by default (implicit specifiers) +#endif + +//---------------------------------------------------------------------------------- +// Some basic Defines +//---------------------------------------------------------------------------------- +#ifndef PI + #define PI 3.14159265358979323846f +#endif +#ifndef DEG2RAD + #define DEG2RAD (PI/180.0f) +#endif +#ifndef RAD2DEG + #define RAD2DEG (180.0f/PI) +#endif + +// Allow custom memory allocators +// NOTE: Require recompiling raylib sources +#ifndef RL_MALLOC + #define RL_MALLOC(sz) malloc(sz) +#endif +#ifndef RL_CALLOC + #define RL_CALLOC(n,sz) calloc(n,sz) +#endif +#ifndef RL_REALLOC + #define RL_REALLOC(ptr,sz) realloc(ptr,sz) +#endif +#ifndef RL_FREE + #define RL_FREE(ptr) free(ptr) +#endif + +// NOTE: MSVC C++ compiler does not support compound literals (C99 feature) +// Plain structures in C++ (without constructors) can be initialized with { } +// This is called aggregate initialization (C++11 feature) +#if defined(__cplusplus) + #define CLITERAL(type) type +#else + #define CLITERAL(type) (type) +#endif + +// Some compilers (mostly macos clang) default to C++98, +// where aggregate initialization can't be used +// So, give a more clear error stating how to fix this +#if !defined(_MSC_VER) && (defined(__cplusplus) && __cplusplus < 201103L) + #error "C++11 or later is required. Add -std=c++11" +#endif + +// NOTE: We set some defines with some data types declared by raylib +// Other modules (raymath, rlgl) also require some of those types, so, +// to be able to use those other modules as standalone (not depending on raylib) +// this defines are very useful for internal check and avoid type (re)definitions +#define RL_COLOR_TYPE +#define RL_RECTANGLE_TYPE +#define RL_VECTOR2_TYPE +#define RL_VECTOR3_TYPE +#define RL_VECTOR4_TYPE +#define RL_QUATERNION_TYPE +#define RL_MATRIX_TYPE + +// Some Basic Colors +// NOTE: Custom raylib color palette for amazing visuals on WHITE background +#define LIGHTGRAY CLITERAL(Color){ 200, 200, 200, 255 } // Light Gray +#define GRAY CLITERAL(Color){ 130, 130, 130, 255 } // Gray +#define DARKGRAY CLITERAL(Color){ 80, 80, 80, 255 } // Dark Gray +#define YELLOW CLITERAL(Color){ 253, 249, 0, 255 } // Yellow +#define GOLD CLITERAL(Color){ 255, 203, 0, 255 } // Gold +#define ORANGE CLITERAL(Color){ 255, 161, 0, 255 } // Orange +#define PINK CLITERAL(Color){ 255, 109, 194, 255 } // Pink +#define RED CLITERAL(Color){ 230, 41, 55, 255 } // Red +#define MAROON CLITERAL(Color){ 190, 33, 55, 255 } // Maroon +#define GREEN CLITERAL(Color){ 0, 228, 48, 255 } // Green +#define LIME CLITERAL(Color){ 0, 158, 47, 255 } // Lime +#define DARKGREEN CLITERAL(Color){ 0, 117, 44, 255 } // Dark Green +#define SKYBLUE CLITERAL(Color){ 102, 191, 255, 255 } // Sky Blue +#define BLUE CLITERAL(Color){ 0, 121, 241, 255 } // Blue +#define DARKBLUE CLITERAL(Color){ 0, 82, 172, 255 } // Dark Blue +#define PURPLE CLITERAL(Color){ 200, 122, 255, 255 } // Purple +#define VIOLET CLITERAL(Color){ 135, 60, 190, 255 } // Violet +#define DARKPURPLE CLITERAL(Color){ 112, 31, 126, 255 } // Dark Purple +#define BEIGE CLITERAL(Color){ 211, 176, 131, 255 } // Beige +#define BROWN CLITERAL(Color){ 127, 106, 79, 255 } // Brown +#define DARKBROWN CLITERAL(Color){ 76, 63, 47, 255 } // Dark Brown + +#define WHITE CLITERAL(Color){ 255, 255, 255, 255 } // White +#define BLACK CLITERAL(Color){ 0, 0, 0, 255 } // Black +#define BLANK CLITERAL(Color){ 0, 0, 0, 0 } // Blank (Transparent) +#define MAGENTA CLITERAL(Color){ 255, 0, 255, 255 } // Magenta +#define RAYWHITE CLITERAL(Color){ 245, 245, 245, 255 } // My own White (raylib logo) + +//---------------------------------------------------------------------------------- +// Structures Definition +//---------------------------------------------------------------------------------- +// Boolean type +#if (defined(__STDC__) && __STDC_VERSION__ >= 199901L) || (defined(_MSC_VER) && _MSC_VER >= 1800) + #include +#elif !defined(__cplusplus) && !defined(bool) + typedef enum bool { false = 0, true = !false } bool; + #define RL_BOOL_TYPE +#endif + +// Vector2, 2 components +typedef struct Vector2 { + float x; // Vector x component + float y; // Vector y component +} Vector2; + +// Vector3, 3 components +typedef struct Vector3 { + float x; // Vector x component + float y; // Vector y component + float z; // Vector z component +} Vector3; + +// Vector4, 4 components +typedef struct Vector4 { + float x; // Vector x component + float y; // Vector y component + float z; // Vector z component + float w; // Vector w component +} Vector4; + +// Quaternion, 4 components (Vector4 alias) +typedef Vector4 Quaternion; + +// Matrix, 4x4 components, column major, OpenGL style, right-handed +typedef struct Matrix { + float m0, m4, m8, m12; // Matrix first row (4 components) + float m1, m5, m9, m13; // Matrix second row (4 components) + float m2, m6, m10, m14; // Matrix third row (4 components) + float m3, m7, m11, m15; // Matrix fourth row (4 components) +} Matrix; + +// Color, 4 components, R8G8B8A8 (32bit) +typedef struct Color { + unsigned char r; // Color red value + unsigned char g; // Color green value + unsigned char b; // Color blue value + unsigned char a; // Color alpha value +} Color; + +// Rectangle, 4 components +typedef struct Rectangle { + float x; // Rectangle top-left corner position x + float y; // Rectangle top-left corner position y + float width; // Rectangle width + float height; // Rectangle height +} Rectangle; + +// Image, pixel data stored in CPU memory (RAM) +typedef struct Image { + void *data; // Image raw data + int width; // Image base width + int height; // Image base height + int mipmaps; // Mipmap levels, 1 by default + int format; // Data format (PixelFormat type) +} Image; + +// Texture, tex data stored in GPU memory (VRAM) +typedef struct Texture { + unsigned int id; // OpenGL texture id + int width; // Texture base width + int height; // Texture base height + int mipmaps; // Mipmap levels, 1 by default + int format; // Data format (PixelFormat type) +} Texture; + +// Texture2D, same as Texture +typedef Texture Texture2D; + +// TextureCubemap, same as Texture +typedef Texture TextureCubemap; + +// RenderTexture, fbo for texture rendering +typedef struct RenderTexture { + unsigned int id; // OpenGL framebuffer object id + Texture texture; // Color buffer attachment texture + Texture depth; // Depth buffer attachment texture +} RenderTexture; + +// RenderTexture2D, same as RenderTexture +typedef RenderTexture RenderTexture2D; + +// NPatchInfo, n-patch layout info +typedef struct NPatchInfo { + Rectangle source; // Texture source rectangle + int left; // Left border offset + int top; // Top border offset + int right; // Right border offset + int bottom; // Bottom border offset + int layout; // Layout of the n-patch: 3x3, 1x3 or 3x1 +} NPatchInfo; + +// GlyphInfo, font characters glyphs info +typedef struct GlyphInfo { + int value; // Character value (Unicode) + int offsetX; // Character offset X when drawing + int offsetY; // Character offset Y when drawing + int advanceX; // Character advance position X + Image image; // Character image data +} GlyphInfo; + +// Font, font texture and GlyphInfo array data +typedef struct Font { + int baseSize; // Base size (default chars height) + int glyphCount; // Number of glyph characters + int glyphPadding; // Padding around the glyph characters + Texture2D texture; // Texture atlas containing the glyphs + Rectangle *recs; // Rectangles in texture for the glyphs + GlyphInfo *glyphs; // Glyphs info data +} Font; + +// Camera, defines position/orientation in 3d space +typedef struct Camera3D { + Vector3 position; // Camera position + Vector3 target; // Camera target it looks-at + Vector3 up; // Camera up vector (rotation over its axis) + float fovy; // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane width in orthographic + int projection; // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC +} Camera3D; + +typedef Camera3D Camera; // Camera type fallback, defaults to Camera3D + +// Camera2D, defines position/orientation in 2d space +typedef struct Camera2D { + Vector2 offset; // Camera offset (displacement from target) + Vector2 target; // Camera target (rotation and zoom origin) + float rotation; // Camera rotation in degrees + float zoom; // Camera zoom (scaling), should be 1.0f by default +} Camera2D; + +// Mesh, vertex data and vao/vbo +typedef struct Mesh { + int vertexCount; // Number of vertices stored in arrays + int triangleCount; // Number of triangles stored (indexed or not) + + // Vertex attributes data + float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) + float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) + float *texcoords2; // Vertex texture second coordinates (UV - 2 components per vertex) (shader-location = 5) + float *normals; // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) + float *tangents; // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) + unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) + unsigned short *indices; // Vertex indices (in case vertex data comes indexed) + + // Animation vertex data + float *animVertices; // Animated vertex positions (after bones transformations) + float *animNormals; // Animated normals (after bones transformations) + unsigned char *boneIds; // Vertex bone ids, max 255 bone ids, up to 4 bones influence by vertex (skinning) + float *boneWeights; // Vertex bone weight, up to 4 bones influence by vertex (skinning) + + // OpenGL identifiers + unsigned int vaoId; // OpenGL Vertex Array Object id + unsigned int *vboId; // OpenGL Vertex Buffer Objects id (default vertex data) +} Mesh; + +// Shader +typedef struct Shader { + unsigned int id; // Shader program id + int *locs; // Shader locations array (RL_MAX_SHADER_LOCATIONS) +} Shader; + +// MaterialMap +typedef struct MaterialMap { + Texture2D texture; // Material map texture + Color color; // Material map color + float value; // Material map value +} MaterialMap; + +// Material, includes shader and maps +typedef struct Material { + Shader shader; // Material shader + MaterialMap *maps; // Material maps array (MAX_MATERIAL_MAPS) + float params[4]; // Material generic parameters (if required) +} Material; + +// Transform, vertex transformation data +typedef struct Transform { + Vector3 translation; // Translation + Quaternion rotation; // Rotation + Vector3 scale; // Scale +} Transform; + +// Bone, skeletal animation bone +typedef struct BoneInfo { + char name[32]; // Bone name + int parent; // Bone parent +} BoneInfo; + +// Model, meshes, materials and animation data +typedef struct Model { + Matrix transform; // Local transform matrix + + int meshCount; // Number of meshes + int materialCount; // Number of materials + Mesh *meshes; // Meshes array + Material *materials; // Materials array + int *meshMaterial; // Mesh material number + + // Animation data + int boneCount; // Number of bones + BoneInfo *bones; // Bones information (skeleton) + Transform *bindPose; // Bones base transformation (pose) +} Model; + +// ModelAnimation +typedef struct ModelAnimation { + int boneCount; // Number of bones + int frameCount; // Number of animation frames + BoneInfo *bones; // Bones information (skeleton) + Transform **framePoses; // Poses array by frame + char name[32]; // Animation name +} ModelAnimation; + +// Ray, ray for raycasting +typedef struct Ray { + Vector3 position; // Ray position (origin) + Vector3 direction; // Ray direction +} Ray; + +// RayCollision, ray hit information +typedef struct RayCollision { + bool hit; // Did the ray hit something? + float distance; // Distance to the nearest hit + Vector3 point; // Point of the nearest hit + Vector3 normal; // Surface normal of hit +} RayCollision; + +// BoundingBox +typedef struct BoundingBox { + Vector3 min; // Minimum vertex box-corner + Vector3 max; // Maximum vertex box-corner +} BoundingBox; + +// Wave, audio wave data +typedef struct Wave { + unsigned int frameCount; // Total number of frames (considering channels) + unsigned int sampleRate; // Frequency (samples per second) + unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) + unsigned int channels; // Number of channels (1-mono, 2-stereo, ...) + void *data; // Buffer data pointer +} Wave; + +// Opaque structs declaration +// NOTE: Actual structs are defined internally in raudio module +typedef struct rAudioBuffer rAudioBuffer; +typedef struct rAudioProcessor rAudioProcessor; + +// AudioStream, custom audio stream +typedef struct AudioStream { + rAudioBuffer *buffer; // Pointer to internal data used by the audio system + rAudioProcessor *processor; // Pointer to internal data processor, useful for audio effects + + unsigned int sampleRate; // Frequency (samples per second) + unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) + unsigned int channels; // Number of channels (1-mono, 2-stereo, ...) +} AudioStream; + +// Sound +typedef struct Sound { + AudioStream stream; // Audio stream + unsigned int frameCount; // Total number of frames (considering channels) +} Sound; + +// Music, audio stream, anything longer than ~10 seconds should be streamed +typedef struct Music { + AudioStream stream; // Audio stream + unsigned int frameCount; // Total number of frames (considering channels) + bool looping; // Music looping enable + + int ctxType; // LC_Type of music context (audio filetype) + void *ctxData; // Audio context data, depends on type +} Music; + +// VrDeviceInfo, Head-Mounted-Display device parameters +typedef struct VrDeviceInfo { + int hResolution; // Horizontal resolution in pixels + int vResolution; // Vertical resolution in pixels + float hScreenSize; // Horizontal size in meters + float vScreenSize; // Vertical size in meters + float vScreenCenter; // Screen center in meters + float eyeToScreenDistance; // Distance between eye and display in meters + float lensSeparationDistance; // Lens separation distance in meters + float interpupillaryDistance; // IPD (distance between pupils) in meters + float lensDistortionValues[4]; // Lens distortion constant parameters + float chromaAbCorrection[4]; // Chromatic aberration correction parameters +} VrDeviceInfo; + +// VrStereoConfig, VR stereo rendering configuration for simulator +typedef struct VrStereoConfig { + Matrix projection[2]; // VR projection matrices (per eye) + Matrix viewOffset[2]; // VR view offset matrices (per eye) + float leftLensCenter[2]; // VR left lens center + float rightLensCenter[2]; // VR right lens center + float leftScreenCenter[2]; // VR left screen center + float rightScreenCenter[2]; // VR right screen center + float scale[2]; // VR distortion scale + float scaleIn[2]; // VR distortion scale in +} VrStereoConfig; + +// File path list +typedef struct FilePathList { + unsigned int capacity; // Filepaths max entries + unsigned int count; // Filepaths entries count + char **paths; // Filepaths entries +} FilePathList; + +// Automation event +typedef struct AutomationEvent { + unsigned int frame; // Event frame + unsigned int type; // Event type (AutomationEventType) + int params[4]; // Event parameters (if required) +} AutomationEvent; + +// Automation event list +typedef struct AutomationEventList { + unsigned int capacity; // Events max entries (MAX_AUTOMATION_EVENTS) + unsigned int count; // Events entries count + AutomationEvent *events; // Events entries +} AutomationEventList; + +//---------------------------------------------------------------------------------- +// Enumerators Definition +//---------------------------------------------------------------------------------- +// System/Window config flags +// NOTE: Every bit registers one state (use it with bit masks) +// By default all flags are set to 0 +typedef enum { + FLAG_VSYNC_HINT = 0x00000040, // Set to try enabling V-Sync on GPU + FLAG_FULLSCREEN_MODE = 0x00000002, // Set to run program in fullscreen + FLAG_WINDOW_RESIZABLE = 0x00000004, // Set to allow resizable window + FLAG_WINDOW_UNDECORATED = 0x00000008, // Set to disable window decoration (frame and buttons) + FLAG_WINDOW_HIDDEN = 0x00000080, // Set to hide window + FLAG_WINDOW_MINIMIZED = 0x00000200, // Set to minimize window (iconify) + FLAG_WINDOW_MAXIMIZED = 0x00000400, // Set to maximize window (expanded to monitor) + FLAG_WINDOW_UNFOCUSED = 0x00000800, // Set to window non focused + FLAG_WINDOW_TOPMOST = 0x00001000, // Set to window always on top + FLAG_WINDOW_ALWAYS_RUN = 0x00000100, // Set to allow windows running while minimized + FLAG_WINDOW_TRANSPARENT = 0x00000010, // Set to allow transparent framebuffer + FLAG_WINDOW_HIGHDPI = 0x00002000, // Set to support HighDPI + FLAG_WINDOW_MOUSE_PASSTHROUGH = 0x00004000, // Set to support mouse passthrough, only supported when FLAG_WINDOW_UNDECORATED + FLAG_BORDERLESS_WINDOWED_MODE = 0x00008000, // Set to run program in borderless windowed mode + FLAG_MSAA_4X_HINT = 0x00000020, // Set to try enabling MSAA 4X + FLAG_INTERLACED_HINT = 0x00010000 // Set to try enabling interlaced video format (for V3D) +} ConfigFlags; + +// Trace log level +// NOTE: Organized by priority level +typedef enum { + LOG_ALL = 0, // Display all logs + LOG_TRACE, // Trace logging, intended for internal use only + LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds + LOG_INFO, // Info logging, used for program execution info + LOG_WARNING, // Warning logging, used on recoverable failures + LOG_ERROR, // Error logging, used on unrecoverable failures + LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE) + LOG_NONE // Disable logging +} TraceLogLevel; + +// Keyboard keys (US keyboard layout) +// NOTE: Use GetKeyPressed() to allow redefining +// required keys for alternative layouts +typedef enum { + KEY_NULL = 0, // Key: NULL, used for no key pressed + // Alphanumeric keys + KEY_APOSTROPHE = 39, // Key: ' + KEY_COMMA = 44, // Key: , + KEY_MINUS = 45, // Key: - + KEY_PERIOD = 46, // Key: . + KEY_SLASH = 47, // Key: / + KEY_ZERO = 48, // Key: 0 + KEY_ONE = 49, // Key: 1 + KEY_TWO = 50, // Key: 2 + KEY_THREE = 51, // Key: 3 + KEY_FOUR = 52, // Key: 4 + KEY_FIVE = 53, // Key: 5 + KEY_SIX = 54, // Key: 6 + KEY_SEVEN = 55, // Key: 7 + KEY_EIGHT = 56, // Key: 8 + KEY_NINE = 57, // Key: 9 + KEY_SEMICOLON = 59, // Key: ; + KEY_EQUAL = 61, // Key: = + KEY_A = 65, // Key: A | a + KEY_B = 66, // Key: B | b + KEY_C = 67, // Key: C | c + KEY_D = 68, // Key: D | d + KEY_E = 69, // Key: E | e + KEY_F = 70, // Key: F | f + KEY_G = 71, // Key: G | g + KEY_H = 72, // Key: H | h + KEY_I = 73, // Key: I | i + KEY_J = 74, // Key: J | j + KEY_K = 75, // Key: K | k + KEY_L = 76, // Key: L | l + KEY_M = 77, // Key: M | m + KEY_N = 78, // Key: N | n + KEY_O = 79, // Key: O | o + KEY_P = 80, // Key: P | p + KEY_Q = 81, // Key: Q | q + KEY_R = 82, // Key: R | r + KEY_S = 83, // Key: S | s + KEY_T = 84, // Key: T | t + KEY_U = 85, // Key: U | u + KEY_V = 86, // Key: V | v + KEY_W = 87, // Key: W | w + KEY_X = 88, // Key: X | x + KEY_Y = 89, // Key: Y | y + KEY_Z = 90, // Key: Z | z + KEY_LEFT_BRACKET = 91, // Key: [ + KEY_BACKSLASH = 92, // Key: '\' + KEY_RIGHT_BRACKET = 93, // Key: ] + KEY_GRAVE = 96, // Key: ` + // Function keys + KEY_SPACE = 32, // Key: Space + KEY_ESCAPE = 256, // Key: Esc + KEY_ENTER = 257, // Key: Enter + KEY_TAB = 258, // Key: Tab + KEY_BACKSPACE = 259, // Key: Backspace + KEY_INSERT = 260, // Key: Ins + KEY_DELETE = 261, // Key: Del + KEY_RIGHT = 262, // Key: Cursor right + KEY_LEFT = 263, // Key: Cursor left + KEY_DOWN = 264, // Key: Cursor down + KEY_UP = 265, // Key: Cursor up + KEY_PAGE_UP = 266, // Key: Page up + KEY_PAGE_DOWN = 267, // Key: Page down + KEY_HOME = 268, // Key: Home + KEY_END = 269, // Key: End + KEY_CAPS_LOCK = 280, // Key: Caps lock + KEY_SCROLL_LOCK = 281, // Key: Scroll down + KEY_NUM_LOCK = 282, // Key: Num lock + KEY_PRINT_SCREEN = 283, // Key: Print screen + KEY_PAUSE = 284, // Key: Pause + KEY_F1 = 290, // Key: F1 + KEY_F2 = 291, // Key: F2 + KEY_F3 = 292, // Key: F3 + KEY_F4 = 293, // Key: F4 + KEY_F5 = 294, // Key: F5 + KEY_F6 = 295, // Key: F6 + KEY_F7 = 296, // Key: F7 + KEY_F8 = 297, // Key: F8 + KEY_F9 = 298, // Key: F9 + KEY_F10 = 299, // Key: F10 + KEY_F11 = 300, // Key: F11 + KEY_F12 = 301, // Key: F12 + KEY_LEFT_SHIFT = 340, // Key: Shift left + KEY_LEFT_CONTROL = 341, // Key: Control left + KEY_LEFT_ALT = 342, // Key: Alt left + KEY_LEFT_SUPER = 343, // Key: Super left + KEY_RIGHT_SHIFT = 344, // Key: Shift right + KEY_RIGHT_CONTROL = 345, // Key: Control right + KEY_RIGHT_ALT = 346, // Key: Alt right + KEY_RIGHT_SUPER = 347, // Key: Super right + KEY_KB_MENU = 348, // Key: KB menu + // Keypad keys + KEY_KP_0 = 320, // Key: Keypad 0 + KEY_KP_1 = 321, // Key: Keypad 1 + KEY_KP_2 = 322, // Key: Keypad 2 + KEY_KP_3 = 323, // Key: Keypad 3 + KEY_KP_4 = 324, // Key: Keypad 4 + KEY_KP_5 = 325, // Key: Keypad 5 + KEY_KP_6 = 326, // Key: Keypad 6 + KEY_KP_7 = 327, // Key: Keypad 7 + KEY_KP_8 = 328, // Key: Keypad 8 + KEY_KP_9 = 329, // Key: Keypad 9 + KEY_KP_DECIMAL = 330, // Key: Keypad . + KEY_KP_DIVIDE = 331, // Key: Keypad / + KEY_KP_MULTIPLY = 332, // Key: Keypad * + KEY_KP_SUBTRACT = 333, // Key: Keypad - + KEY_KP_ADD = 334, // Key: Keypad + + KEY_KP_ENTER = 335, // Key: Keypad Enter + KEY_KP_EQUAL = 336, // Key: Keypad = + // Android key buttons + KEY_BACK = 4, // Key: Android back button + KEY_MENU = 82, // Key: Android menu button + KEY_VOLUME_UP = 24, // Key: Android volume up button + KEY_VOLUME_DOWN = 25 // Key: Android volume down button +} KeyboardKey; + +// Add backwards compatibility support for deprecated names +#define MOUSE_LEFT_BUTTON MOUSE_BUTTON_LEFT +#define MOUSE_RIGHT_BUTTON MOUSE_BUTTON_RIGHT +#define MOUSE_MIDDLE_BUTTON MOUSE_BUTTON_MIDDLE + +// Mouse buttons +typedef enum { + MOUSE_BUTTON_LEFT = 0, // Mouse button left + MOUSE_BUTTON_RIGHT = 1, // Mouse button right + MOUSE_BUTTON_MIDDLE = 2, // Mouse button middle (pressed wheel) + MOUSE_BUTTON_SIDE = 3, // Mouse button side (advanced mouse device) + MOUSE_BUTTON_EXTRA = 4, // Mouse button extra (advanced mouse device) + MOUSE_BUTTON_FORWARD = 5, // Mouse button forward (advanced mouse device) + MOUSE_BUTTON_BACK = 6, // Mouse button back (advanced mouse device) +} MouseButton; + +// Mouse cursor +typedef enum { + MOUSE_CURSOR_DEFAULT = 0, // Default pointer shape + MOUSE_CURSOR_ARROW = 1, // Arrow shape + MOUSE_CURSOR_IBEAM = 2, // Text writing cursor shape + MOUSE_CURSOR_CROSSHAIR = 3, // Cross shape + MOUSE_CURSOR_POINTING_HAND = 4, // Pointing hand cursor + MOUSE_CURSOR_RESIZE_EW = 5, // Horizontal resize/move arrow shape + MOUSE_CURSOR_RESIZE_NS = 6, // Vertical resize/move arrow shape + MOUSE_CURSOR_RESIZE_NWSE = 7, // Top-left to bottom-right diagonal resize/move arrow shape + MOUSE_CURSOR_RESIZE_NESW = 8, // The top-right to bottom-left diagonal resize/move arrow shape + MOUSE_CURSOR_RESIZE_ALL = 9, // The omnidirectional resize/move cursor shape + MOUSE_CURSOR_NOT_ALLOWED = 10 // The operation-not-allowed shape +} MouseCursor; + +// Gamepad buttons +typedef enum { + GAMEPAD_BUTTON_UNKNOWN = 0, // Unknown button, just for error checking + GAMEPAD_BUTTON_LEFT_FACE_UP, // Gamepad left DPAD up button + GAMEPAD_BUTTON_LEFT_FACE_RIGHT, // Gamepad left DPAD right button + GAMEPAD_BUTTON_LEFT_FACE_DOWN, // Gamepad left DPAD down button + GAMEPAD_BUTTON_LEFT_FACE_LEFT, // Gamepad left DPAD left button + GAMEPAD_BUTTON_RIGHT_FACE_UP, // Gamepad right button up (i.e. PS3: Triangle, Xbox: Y) + GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, // Gamepad right button right (i.e. PS3: Square, Xbox: X) + GAMEPAD_BUTTON_RIGHT_FACE_DOWN, // Gamepad right button down (i.e. PS3: Cross, Xbox: A) + GAMEPAD_BUTTON_RIGHT_FACE_LEFT, // Gamepad right button left (i.e. PS3: Circle, Xbox: B) + GAMEPAD_BUTTON_LEFT_TRIGGER_1, // Gamepad top/back trigger left (first), it could be a trailing button + GAMEPAD_BUTTON_LEFT_TRIGGER_2, // Gamepad top/back trigger left (second), it could be a trailing button + GAMEPAD_BUTTON_RIGHT_TRIGGER_1, // Gamepad top/back trigger right (one), it could be a trailing button + GAMEPAD_BUTTON_RIGHT_TRIGGER_2, // Gamepad top/back trigger right (second), it could be a trailing button + GAMEPAD_BUTTON_MIDDLE_LEFT, // Gamepad center buttons, left one (i.e. PS3: Select) + GAMEPAD_BUTTON_MIDDLE, // Gamepad center buttons, middle one (i.e. PS3: PS, Xbox: XBOX) + GAMEPAD_BUTTON_MIDDLE_RIGHT, // Gamepad center buttons, right one (i.e. PS3: Start) + GAMEPAD_BUTTON_LEFT_THUMB, // Gamepad joystick pressed button left + GAMEPAD_BUTTON_RIGHT_THUMB // Gamepad joystick pressed button right +} GamepadButton; + +// Gamepad axis +typedef enum { + GAMEPAD_AXIS_LEFT_X = 0, // Gamepad left stick X axis + GAMEPAD_AXIS_LEFT_Y = 1, // Gamepad left stick Y axis + GAMEPAD_AXIS_RIGHT_X = 2, // Gamepad right stick X axis + GAMEPAD_AXIS_RIGHT_Y = 3, // Gamepad right stick Y axis + GAMEPAD_AXIS_LEFT_TRIGGER = 4, // Gamepad back trigger left, pressure level: [1..-1] + GAMEPAD_AXIS_RIGHT_TRIGGER = 5 // Gamepad back trigger right, pressure level: [1..-1] +} GamepadAxis; + +// Material map index +typedef enum { + MATERIAL_MAP_ALBEDO = 0, // Albedo material (same as: MATERIAL_MAP_DIFFUSE) + MATERIAL_MAP_METALNESS, // Metalness material (same as: MATERIAL_MAP_SPECULAR) + MATERIAL_MAP_NORMAL, // Normal material + MATERIAL_MAP_ROUGHNESS, // Roughness material + MATERIAL_MAP_OCCLUSION, // Ambient occlusion material + MATERIAL_MAP_EMISSION, // Emission material + MATERIAL_MAP_HEIGHT, // Heightmap material + MATERIAL_MAP_CUBEMAP, // Cubemap material (NOTE: Uses GL_TEXTURE_CUBE_MAP) + MATERIAL_MAP_IRRADIANCE, // Irradiance material (NOTE: Uses GL_TEXTURE_CUBE_MAP) + MATERIAL_MAP_PREFILTER, // Prefilter material (NOTE: Uses GL_TEXTURE_CUBE_MAP) + MATERIAL_MAP_BRDF // Brdf material +} MaterialMapIndex; + +#define MATERIAL_MAP_DIFFUSE MATERIAL_MAP_ALBEDO +#define MATERIAL_MAP_SPECULAR MATERIAL_MAP_METALNESS + +// Shader location index +typedef enum { + SHADER_LOC_VERTEX_POSITION = 0, // Shader location: vertex attribute: position + SHADER_LOC_VERTEX_TEXCOORD01, // Shader location: vertex attribute: texcoord01 + SHADER_LOC_VERTEX_TEXCOORD02, // Shader location: vertex attribute: texcoord02 + SHADER_LOC_VERTEX_NORMAL, // Shader location: vertex attribute: normal + SHADER_LOC_VERTEX_TANGENT, // Shader location: vertex attribute: tangent + SHADER_LOC_VERTEX_COLOR, // Shader location: vertex attribute: color + SHADER_LOC_MATRIX_MVP, // Shader location: matrix uniform: model-view-projection + SHADER_LOC_MATRIX_VIEW, // Shader location: matrix uniform: view (camera transform) + SHADER_LOC_MATRIX_PROJECTION, // Shader location: matrix uniform: projection + SHADER_LOC_MATRIX_MODEL, // Shader location: matrix uniform: model (transform) + SHADER_LOC_MATRIX_NORMAL, // Shader location: matrix uniform: normal + SHADER_LOC_VECTOR_VIEW, // Shader location: vector uniform: view + SHADER_LOC_COLOR_DIFFUSE, // Shader location: vector uniform: diffuse color + SHADER_LOC_COLOR_SPECULAR, // Shader location: vector uniform: specular color + SHADER_LOC_COLOR_AMBIENT, // Shader location: vector uniform: ambient color + SHADER_LOC_MAP_ALBEDO, // Shader location: sampler2d texture: albedo (same as: SHADER_LOC_MAP_DIFFUSE) + SHADER_LOC_MAP_METALNESS, // Shader location: sampler2d texture: metalness (same as: SHADER_LOC_MAP_SPECULAR) + SHADER_LOC_MAP_NORMAL, // Shader location: sampler2d texture: normal + SHADER_LOC_MAP_ROUGHNESS, // Shader location: sampler2d texture: roughness + SHADER_LOC_MAP_OCCLUSION, // Shader location: sampler2d texture: occlusion + SHADER_LOC_MAP_EMISSION, // Shader location: sampler2d texture: emission + SHADER_LOC_MAP_HEIGHT, // Shader location: sampler2d texture: height + SHADER_LOC_MAP_CUBEMAP, // Shader location: samplerCube texture: cubemap + SHADER_LOC_MAP_IRRADIANCE, // Shader location: samplerCube texture: irradiance + SHADER_LOC_MAP_PREFILTER, // Shader location: samplerCube texture: prefilter + SHADER_LOC_MAP_BRDF // Shader location: sampler2d texture: brdf +} ShaderLocationIndex; + +#define SHADER_LOC_MAP_DIFFUSE SHADER_LOC_MAP_ALBEDO +#define SHADER_LOC_MAP_SPECULAR SHADER_LOC_MAP_METALNESS + +// Shader uniform data type +typedef enum { + SHADER_UNIFORM_FLOAT = 0, // Shader uniform type: float + SHADER_UNIFORM_VEC2, // Shader uniform type: vec2 (2 float) + SHADER_UNIFORM_VEC3, // Shader uniform type: vec3 (3 float) + SHADER_UNIFORM_VEC4, // Shader uniform type: vec4 (4 float) + SHADER_UNIFORM_INT, // Shader uniform type: int + SHADER_UNIFORM_IVEC2, // Shader uniform type: ivec2 (2 int) + SHADER_UNIFORM_IVEC3, // Shader uniform type: ivec3 (3 int) + SHADER_UNIFORM_IVEC4, // Shader uniform type: ivec4 (4 int) + SHADER_UNIFORM_SAMPLER2D // Shader uniform type: sampler2d +} ShaderUniformDataType; + +// Shader attribute data types +typedef enum { + SHADER_ATTRIB_FLOAT = 0, // Shader attribute type: float + SHADER_ATTRIB_VEC2, // Shader attribute type: vec2 (2 float) + SHADER_ATTRIB_VEC3, // Shader attribute type: vec3 (3 float) + SHADER_ATTRIB_VEC4 // Shader attribute type: vec4 (4 float) +} ShaderAttributeDataType; + +// Pixel formats +// NOTE: Support depends on OpenGL version and platform +typedef enum { + PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) + PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA, // 8*2 bpp (2 channels) + PIXELFORMAT_UNCOMPRESSED_R5G6B5, // 16 bpp + PIXELFORMAT_UNCOMPRESSED_R8G8B8, // 24 bpp + PIXELFORMAT_UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) + PIXELFORMAT_UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) + PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, // 32 bpp + PIXELFORMAT_UNCOMPRESSED_R32, // 32 bpp (1 channel - float) + PIXELFORMAT_UNCOMPRESSED_R32G32B32, // 32*3 bpp (3 channels - float) + PIXELFORMAT_UNCOMPRESSED_R32G32B32A32, // 32*4 bpp (4 channels - float) + PIXELFORMAT_UNCOMPRESSED_R16, // 16 bpp (1 channel - half float) + PIXELFORMAT_UNCOMPRESSED_R16G16B16, // 16*3 bpp (3 channels - half float) + PIXELFORMAT_UNCOMPRESSED_R16G16B16A16, // 16*4 bpp (4 channels - half float) + PIXELFORMAT_COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) + PIXELFORMAT_COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) + PIXELFORMAT_COMPRESSED_DXT3_RGBA, // 8 bpp + PIXELFORMAT_COMPRESSED_DXT5_RGBA, // 8 bpp + PIXELFORMAT_COMPRESSED_ETC1_RGB, // 4 bpp + PIXELFORMAT_COMPRESSED_ETC2_RGB, // 4 bpp + PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA, // 8 bpp + PIXELFORMAT_COMPRESSED_PVRT_RGB, // 4 bpp + PIXELFORMAT_COMPRESSED_PVRT_RGBA, // 4 bpp + PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA, // 8 bpp + PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA // 2 bpp +} PixelFormat; + +// Texture parameters: filter mode +// NOTE 1: Filtering considers mipmaps if available in the texture +// NOTE 2: Filter is accordingly set for minification and magnification +typedef enum { + TEXTURE_FILTER_POINT = 0, // No filter, just pixel approximation + TEXTURE_FILTER_BILINEAR, // Linear filtering + TEXTURE_FILTER_TRILINEAR, // Trilinear filtering (linear with mipmaps) + TEXTURE_FILTER_ANISOTROPIC_4X, // Anisotropic filtering 4x + TEXTURE_FILTER_ANISOTROPIC_8X, // Anisotropic filtering 8x + TEXTURE_FILTER_ANISOTROPIC_16X, // Anisotropic filtering 16x +} TextureFilter; + +// Texture parameters: wrap mode +typedef enum { + TEXTURE_WRAP_REPEAT = 0, // Repeats texture in tiled mode + TEXTURE_WRAP_CLAMP, // Clamps texture to edge pixel in tiled mode + TEXTURE_WRAP_MIRROR_REPEAT, // Mirrors and repeats the texture in tiled mode + TEXTURE_WRAP_MIRROR_CLAMP // Mirrors and clamps to border the texture in tiled mode +} TextureWrap; + +// Cubemap layouts +typedef enum { + CUBEMAP_LAYOUT_AUTO_DETECT = 0, // Automatically detect layout type + CUBEMAP_LAYOUT_LINE_VERTICAL, // Layout is defined by a vertical line with faces + CUBEMAP_LAYOUT_LINE_HORIZONTAL, // Layout is defined by a horizontal line with faces + CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR, // Layout is defined by a 3x4 cross with cubemap faces + CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE, // Layout is defined by a 4x3 cross with cubemap faces + CUBEMAP_LAYOUT_PANORAMA // Layout is defined by a panorama image (equirrectangular map) +} CubemapLayout; + +// Font type, defines generation method +typedef enum { + FONT_DEFAULT = 0, // Default font generation, anti-aliased + FONT_BITMAP, // Bitmap font generation, no anti-aliasing + FONT_SDF // SDF font generation, requires external shader +} FontType; + +// Color blending modes (pre-defined) +typedef enum { + BLEND_ALPHA = 0, // Blend textures considering alpha (default) + BLEND_ADDITIVE, // Blend textures adding colors + BLEND_MULTIPLIED, // Blend textures multiplying colors + BLEND_ADD_COLORS, // Blend textures adding colors (alternative) + BLEND_SUBTRACT_COLORS, // Blend textures subtracting colors (alternative) + BLEND_ALPHA_PREMULTIPLY, // Blend premultiplied textures considering alpha + BLEND_CUSTOM, // Blend textures using custom src/dst factors (use rlSetBlendFactors()) + BLEND_CUSTOM_SEPARATE // Blend textures using custom rgb/alpha separate src/dst factors (use rlSetBlendFactorsSeparate()) +} BlendMode; + +// Gesture +// NOTE: Provided as bit-wise flags to enable only desired gestures +typedef enum { + GESTURE_NONE = 0, // No gesture + GESTURE_TAP = 1, // Tap gesture + GESTURE_DOUBLETAP = 2, // Double tap gesture + GESTURE_HOLD = 4, // Hold gesture + GESTURE_DRAG = 8, // Drag gesture + GESTURE_SWIPE_RIGHT = 16, // Swipe right gesture + GESTURE_SWIPE_LEFT = 32, // Swipe left gesture + GESTURE_SWIPE_UP = 64, // Swipe up gesture + GESTURE_SWIPE_DOWN = 128, // Swipe down gesture + GESTURE_PINCH_IN = 256, // Pinch in gesture + GESTURE_PINCH_OUT = 512 // Pinch out gesture +} Gesture; + +// Camera system modes +typedef enum { + CAMERA_CUSTOM = 0, // Custom camera + CAMERA_FREE, // Free camera + CAMERA_ORBITAL, // Orbital camera + CAMERA_FIRST_PERSON, // First person camera + CAMERA_THIRD_PERSON // Third person camera +} CameraMode; + +// Camera projection +typedef enum { + CAMERA_PERSPECTIVE = 0, // Perspective projection + CAMERA_ORTHOGRAPHIC // Orthographic projection +} CameraProjection; + +// N-patch layout +typedef enum { + NPATCH_NINE_PATCH = 0, // Npatch layout: 3x3 tiles + NPATCH_THREE_PATCH_VERTICAL, // Npatch layout: 1x3 tiles + NPATCH_THREE_PATCH_HORIZONTAL // Npatch layout: 3x1 tiles +} NPatchLayout; + +// Callbacks to hook some internal functions +// WARNING: These callbacks are intended for advance users +typedef void (*TraceLogCallback)(int logLevel, const char *text, va_list args); // Logging: Redirect trace log messages +typedef unsigned char *(*LoadFileDataCallback)(const char *fileName, int *dataSize); // FileIO: Load binary data +typedef bool (*SaveFileDataCallback)(const char *fileName, void *data, int dataSize); // FileIO: Save binary data +typedef char *(*LoadFileTextCallback)(const char *fileName); // FileIO: Load text data +typedef bool (*SaveFileTextCallback)(const char *fileName, char *text); // FileIO: Save text data + +//------------------------------------------------------------------------------------ +// Global Variables Definition +//------------------------------------------------------------------------------------ +// It's lonely here... + +//------------------------------------------------------------------------------------ +// Window and Graphics Device Functions (Module: core) +//------------------------------------------------------------------------------------ + +#if defined(__cplusplus) +extern "C" { // Prevents name mangling of functions +#endif + +// Window-related functions +RLAPI void InitWindow(int width, int height, const char *title); // Initialize window and OpenGL context +RLAPI void CloseWindow(void); // Close window and unload OpenGL context +RLAPI bool WindowShouldClose(void); // Check if application should close (KEY_ESCAPE pressed or windows close icon clicked) +RLAPI bool IsWindowReady(void); // Check if window has been initialized successfully +RLAPI bool IsWindowFullscreen(void); // Check if window is currently fullscreen +RLAPI bool IsWindowHidden(void); // Check if window is currently hidden (only PLATFORM_DESKTOP) +RLAPI bool IsWindowMinimized(void); // Check if window is currently minimized (only PLATFORM_DESKTOP) +RLAPI bool IsWindowMaximized(void); // Check if window is currently maximized (only PLATFORM_DESKTOP) +RLAPI bool IsWindowFocused(void); // Check if window is currently focused (only PLATFORM_DESKTOP) +RLAPI bool IsWindowResized(void); // Check if window has been resized last frame +RLAPI bool IsWindowState(unsigned int flag); // Check if one specific window flag is enabled +RLAPI void SetWindowState(unsigned int flags); // Set window configuration state using flags (only PLATFORM_DESKTOP) +RLAPI void ClearWindowState(unsigned int flags); // Clear window configuration state flags +RLAPI void ToggleFullscreen(void); // Toggle window state: fullscreen/windowed (only PLATFORM_DESKTOP) +RLAPI void ToggleBorderlessWindowed(void); // Toggle window state: borderless windowed (only PLATFORM_DESKTOP) +RLAPI void MaximizeWindow(void); // Set window state: maximized, if resizable (only PLATFORM_DESKTOP) +RLAPI void MinimizeWindow(void); // Set window state: minimized, if resizable (only PLATFORM_DESKTOP) +RLAPI void RestoreWindow(void); // Set window state: not minimized/maximized (only PLATFORM_DESKTOP) +RLAPI void SetWindowIcon(Image image); // Set icon for window (single image, RGBA 32bit, only PLATFORM_DESKTOP) +RLAPI void SetWindowIcons(Image *images, int count); // Set icon for window (multiple images, RGBA 32bit, only PLATFORM_DESKTOP) +RLAPI void SetWindowTitle(const char *title); // Set title for window (only PLATFORM_DESKTOP and PLATFORM_WEB) +RLAPI void SetWindowPosition(int x, int y); // Set window position on screen (only PLATFORM_DESKTOP) +RLAPI void SetWindowMonitor(int monitor); // Set monitor for the current window +RLAPI void SetWindowMinSize(int width, int height); // Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) +RLAPI void SetWindowMaxSize(int width, int height); // Set window maximum dimensions (for FLAG_WINDOW_RESIZABLE) +RLAPI void SetWindowSize(int width, int height); // Set window dimensions +RLAPI void SetWindowOpacity(float opacity); // Set window opacity [0.0f..1.0f] (only PLATFORM_DESKTOP) +RLAPI void SetWindowFocused(void); // Set window focused (only PLATFORM_DESKTOP) +RLAPI void *GetWindowHandle(void); // Get native window handle +RLAPI int GetScreenWidth(void); // Get current screen width +RLAPI int GetScreenHeight(void); // Get current screen height +RLAPI int GetRenderWidth(void); // Get current render width (it considers HiDPI) +RLAPI int GetRenderHeight(void); // Get current render height (it considers HiDPI) +RLAPI int GetMonitorCount(void); // Get number of connected monitors +RLAPI int GetCurrentMonitor(void); // Get current connected monitor +RLAPI Vector2 GetMonitorPosition(int monitor); // Get specified monitor position +RLAPI int GetMonitorWidth(int monitor); // Get specified monitor width (current video mode used by monitor) +RLAPI int GetMonitorHeight(int monitor); // Get specified monitor height (current video mode used by monitor) +RLAPI int GetMonitorPhysicalWidth(int monitor); // Get specified monitor physical width in millimetres +RLAPI int GetMonitorPhysicalHeight(int monitor); // Get specified monitor physical height in millimetres +RLAPI int GetMonitorRefreshRate(int monitor); // Get specified monitor refresh rate +RLAPI Vector2 GetWindowPosition(void); // Get window position XY on monitor +RLAPI Vector2 GetWindowScaleDPI(void); // Get window scale DPI factor +RLAPI const char *GetMonitorName(int monitor); // Get the human-readable, UTF-8 encoded name of the specified monitor +RLAPI void SetClipboardText(const char *text); // Set clipboard text content +RLAPI const char *GetClipboardText(void); // Get clipboard text content +RLAPI void EnableEventWaiting(void); // Enable waiting for events on EndDrawing(), no automatic event polling +RLAPI void DisableEventWaiting(void); // Disable waiting for events on EndDrawing(), automatic events polling + +// Cursor-related functions +RLAPI void ShowCursor(void); // Shows cursor +RLAPI void HideCursor(void); // Hides cursor +RLAPI bool IsCursorHidden(void); // Check if cursor is not visible +RLAPI void EnableCursor(void); // Enables cursor (unlock cursor) +RLAPI void DisableCursor(void); // Disables cursor (lock cursor) +RLAPI bool IsCursorOnScreen(void); // Check if cursor is on the screen + +// Drawing-related functions +RLAPI void ClearBackground(Color color); // Set background color (framebuffer clear color) +RLAPI void BeginDrawing(void); // Setup canvas (framebuffer) to start drawing +RLAPI void EndDrawing(void); // End canvas drawing and swap buffers (double buffering) +RLAPI void BeginMode2D(Camera2D camera); // Begin 2D mode with custom camera (2D) +RLAPI void EndMode2D(void); // Ends 2D mode with custom camera +RLAPI void BeginMode3D(Camera3D camera); // Begin 3D mode with custom camera (3D) +RLAPI void EndMode3D(void); // Ends 3D mode and returns to default 2D orthographic mode +RLAPI void BeginTextureMode(RenderTexture2D target); // Begin drawing to render texture +RLAPI void EndTextureMode(void); // Ends drawing to render texture +RLAPI void BeginShaderMode(Shader shader); // Begin custom shader drawing +RLAPI void EndShaderMode(void); // End custom shader drawing (use default shader) +RLAPI void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied, subtract, custom) +RLAPI void EndBlendMode(void); // End blending mode (reset to default: alpha blending) +RLAPI void BeginScissorMode(int x, int y, int width, int height); // Begin scissor mode (define screen area for following drawing) +RLAPI void EndScissorMode(void); // End scissor mode +RLAPI void BeginVrStereoMode(VrStereoConfig config); // Begin stereo rendering (requires VR simulator) +RLAPI void EndVrStereoMode(void); // End stereo rendering (requires VR simulator) + +// VR stereo config functions for VR simulator +RLAPI VrStereoConfig LoadVrStereoConfig(VrDeviceInfo device); // Load VR stereo config for VR simulator device parameters +RLAPI void UnloadVrStereoConfig(VrStereoConfig config); // Unload VR stereo config + +// Shader management functions +// NOTE: Shader functionality is not available on OpenGL 1.1 +RLAPI Shader LoadShader(const char *vsFileName, const char *fsFileName); // Load shader from files and bind default locations +RLAPI Shader LoadShaderFromMemory(const char *vsCode, const char *fsCode); // Load shader from code strings and bind default locations +RLAPI bool IsShaderReady(Shader shader); // Check if a shader is ready +RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location +RLAPI int GetShaderLocationAttrib(Shader shader, const char *attribName); // Get shader attribute location +RLAPI void SetShaderValue(Shader shader, int locIndex, const void *value, int uniformType); // Set shader uniform value +RLAPI void SetShaderValueV(Shader shader, int locIndex, const void *value, int uniformType, int count); // Set shader uniform value vector +RLAPI void SetShaderValueMatrix(Shader shader, int locIndex, Matrix mat); // Set shader uniform value (matrix 4x4) +RLAPI void SetShaderValueTexture(Shader shader, int locIndex, Texture2D texture); // Set shader uniform value for texture (sampler2d) +RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM) + +// Screen-space-related functions +RLAPI Ray GetMouseRay(Vector2 mousePosition, Camera camera); // Get a ray trace from mouse position +RLAPI Matrix GetCameraMatrix(Camera camera); // Get camera transform matrix (view matrix) +RLAPI Matrix GetCameraMatrix2D(Camera2D camera); // Get camera 2d transform matrix +RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Get the screen space position for a 3d world space position +RLAPI Vector2 GetScreenToWorld2D(Vector2 position, Camera2D camera); // Get the world space position for a 2d camera screen space position +RLAPI Vector2 GetWorldToScreenEx(Vector3 position, Camera camera, int width, int height); // Get size position for a 3d world space position +RLAPI Vector2 GetWorldToScreen2D(Vector2 position, Camera2D camera); // Get the screen space position for a 2d camera world space position + +// Timing-related functions +RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum) +RLAPI float GetFrameTime(void); // Get time in seconds for last frame drawn (delta time) +RLAPI double GetTime(void); // Get elapsed time in seconds since InitWindow() +RLAPI int GetFPS(void); // Get current FPS + +// Custom frame control functions +// NOTE: Those functions are intended for advance users that want full control over the frame processing +// By default EndDrawing() does this job: draws everything + SwapScreenBuffer() + manage frame timing + PollInputEvents() +// To avoid that behaviour and control frame processes manually, enable in config.h: SUPPORT_CUSTOM_FRAME_CONTROL +RLAPI void SwapScreenBuffer(void); // Swap back buffer with front buffer (screen drawing) +RLAPI void PollInputEvents(void); // Register all input events +RLAPI void WaitTime(double seconds); // Wait for some time (halt program execution) + +// Random values generation functions +RLAPI void SetRandomSeed(unsigned int seed); // Set the seed for the random number generator +RLAPI int GetRandomValue(int min, int max); // Get a random value between min and max (both included) +RLAPI int *LoadRandomSequence(unsigned int count, int min, int max); // Load random values sequence, no values repeated +RLAPI void UnloadRandomSequence(int *sequence); // Unload random values sequence + +// Misc. functions +RLAPI void TakeScreenshot(const char *fileName); // Takes a screenshot of current screen (filename extension defines format) +RLAPI void SetConfigFlags(unsigned int flags); // Setup init configuration flags (view FLAGS) +RLAPI void OpenURL(const char *url); // Open URL with default system browser (if available) + +// NOTE: Following functions implemented in module [utils] +//------------------------------------------------------------------ +RLAPI void TraceLog(int logLevel, const char *text, ...); // Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR...) +RLAPI void SetTraceLogLevel(int logLevel); // Set the current threshold (minimum) log level +RLAPI void *MemAlloc(unsigned int size); // Internal memory allocator +RLAPI void *MemRealloc(void *ptr, unsigned int size); // Internal memory reallocator +RLAPI void MemFree(void *ptr); // Internal memory free + +// Set custom callbacks +// WARNING: Callbacks setup is intended for advance users +RLAPI void SetTraceLogCallback(TraceLogCallback callback); // Set custom trace log +RLAPI void SetLoadFileDataCallback(LoadFileDataCallback callback); // Set custom file binary data loader +RLAPI void SetSaveFileDataCallback(SaveFileDataCallback callback); // Set custom file binary data saver +RLAPI void SetLoadFileTextCallback(LoadFileTextCallback callback); // Set custom file text data loader +RLAPI void SetSaveFileTextCallback(SaveFileTextCallback callback); // Set custom file text data saver + +// Files management functions +RLAPI unsigned char *LoadFileData(const char *fileName, int *dataSize); // Load file data as byte array (read) +RLAPI void UnloadFileData(unsigned char *data); // Unload file data allocated by LoadFileData() +RLAPI bool SaveFileData(const char *fileName, void *data, int dataSize); // Save data to file from byte array (write), returns true on success +RLAPI bool ExportDataAsCode(const unsigned char *data, int dataSize, const char *fileName); // Export data to code (.h), returns true on success +RLAPI char *LoadFileText(const char *fileName); // Load text data from file (read), returns a '\0' terminated string +RLAPI void UnloadFileText(char *text); // Unload file text data allocated by LoadFileText() +RLAPI bool SaveFileText(const char *fileName, char *text); // Save text data to file (write), string must be '\0' terminated, returns true on success +//------------------------------------------------------------------ + +// File system functions +RLAPI bool FileExists(const char *fileName); // Check if file exists +RLAPI bool DirectoryExists(const char *dirPath); // Check if a directory path exists +RLAPI bool IsFileExtension(const char *fileName, const char *ext); // Check file extension (including point: .png, .wav) +RLAPI int GetFileLength(const char *fileName); // Get file length in bytes (NOTE: GetFileSize() conflicts with windows.h) +RLAPI const char *GetFileExtension(const char *fileName); // Get pointer to extension for a filename string (includes dot: '.png') +RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string +RLAPI const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (uses static string) +RLAPI const char *GetDirectoryPath(const char *filePath); // Get full path for a given fileName with path (uses static string) +RLAPI const char *GetPrevDirectoryPath(const char *dirPath); // Get previous directory path for a given path (uses static string) +RLAPI const char *GetWorkingDirectory(void); // Get current working directory (uses static string) +RLAPI const char *GetApplicationDirectory(void); // Get the directory of the running application (uses static string) +RLAPI bool ChangeDirectory(const char *dir); // Change working directory, return true on success +RLAPI bool IsPathFile(const char *path); // Check if a given path is a file or a directory +RLAPI FilePathList LoadDirectoryFiles(const char *dirPath); // Load directory filepaths +RLAPI FilePathList LoadDirectoryFilesEx(const char *basePath, const char *filter, bool scanSubdirs); // Load directory filepaths with extension filtering and recursive directory scan +RLAPI void UnloadDirectoryFiles(FilePathList files); // Unload filepaths +RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window +RLAPI FilePathList LoadDroppedFiles(void); // Load dropped filepaths +RLAPI void UnloadDroppedFiles(FilePathList files); // Unload dropped filepaths +RLAPI long GetFileModTime(const char *fileName); // Get file modification time (last write time) + +// Compression/Encoding functionality +RLAPI unsigned char *CompressData(const unsigned char *data, int dataSize, int *compDataSize); // Compress data (DEFLATE algorithm), memory must be MemFree() +RLAPI unsigned char *DecompressData(const unsigned char *compData, int compDataSize, int *dataSize); // Decompress data (DEFLATE algorithm), memory must be MemFree() +RLAPI char *EncodeDataBase64(const unsigned char *data, int dataSize, int *outputSize); // Encode data to Base64 string, memory must be MemFree() +RLAPI unsigned char *DecodeDataBase64(const unsigned char *data, int *outputSize); // Decode Base64 string data, memory must be MemFree() + +// Automation events functionality +RLAPI AutomationEventList LoadAutomationEventList(const char *fileName); // Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS +RLAPI void UnloadAutomationEventList(AutomationEventList *list); // Unload automation events list from file +RLAPI bool ExportAutomationEventList(AutomationEventList list, const char *fileName); // Export automation events list as text file +RLAPI void SetAutomationEventList(AutomationEventList *list); // Set automation event list to record to +RLAPI void SetAutomationEventBaseFrame(int frame); // Set automation event internal base frame to start recording +RLAPI void StartAutomationEventRecording(void); // Start recording automation events (AutomationEventList must be set) +RLAPI void StopAutomationEventRecording(void); // Stop recording automation events +RLAPI void PlayAutomationEvent(AutomationEvent event); // Play a recorded automation event + +//------------------------------------------------------------------------------------ +// Input Handling Functions (Module: core) +//------------------------------------------------------------------------------------ + +// Input-related functions: keyboard +RLAPI bool IsKeyPressed(int key); // Check if a key has been pressed once +RLAPI bool IsKeyPressedRepeat(int key); // Check if a key has been pressed again (Only PLATFORM_DESKTOP) +RLAPI bool IsKeyDown(int key); // Check if a key is being pressed +RLAPI bool IsKeyReleased(int key); // Check if a key has been released once +RLAPI bool IsKeyUp(int key); // Check if a key is NOT being pressed +RLAPI int GetKeyPressed(void); // Get key pressed (keycode), call it multiple times for keys queued, returns 0 when the queue is empty +RLAPI int GetCharPressed(void); // Get char pressed (unicode), call it multiple times for chars queued, returns 0 when the queue is empty +RLAPI void SetExitKey(int key); // Set a custom key to exit program (default is ESC) + +// Input-related functions: gamepads +RLAPI bool IsGamepadAvailable(int gamepad); // Check if a gamepad is available +RLAPI const char *GetGamepadName(int gamepad); // Get gamepad internal name id +RLAPI bool IsGamepadButtonPressed(int gamepad, int button); // Check if a gamepad button has been pressed once +RLAPI bool IsGamepadButtonDown(int gamepad, int button); // Check if a gamepad button is being pressed +RLAPI bool IsGamepadButtonReleased(int gamepad, int button); // Check if a gamepad button has been released once +RLAPI bool IsGamepadButtonUp(int gamepad, int button); // Check if a gamepad button is NOT being pressed +RLAPI int GetGamepadButtonPressed(void); // Get the last gamepad button pressed +RLAPI int GetGamepadAxisCount(int gamepad); // Get gamepad axis count for a gamepad +RLAPI float GetGamepadAxisMovement(int gamepad, int axis); // Get axis movement value for a gamepad axis +RLAPI int SetGamepadMappings(const char *mappings); // Set internal gamepad mappings (SDL_GameControllerDB) + +// Input-related functions: mouse +RLAPI bool IsMouseButtonPressed(int button); // Check if a mouse button has been pressed once +RLAPI bool IsMouseButtonDown(int button); // Check if a mouse button is being pressed +RLAPI bool IsMouseButtonReleased(int button); // Check if a mouse button has been released once +RLAPI bool IsMouseButtonUp(int button); // Check if a mouse button is NOT being pressed +RLAPI int GetMouseX(void); // Get mouse position X +RLAPI int GetMouseY(void); // Get mouse position Y +RLAPI Vector2 GetMousePosition(void); // Get mouse position XY +RLAPI Vector2 GetMouseDelta(void); // Get mouse delta between frames +RLAPI void SetMousePosition(int x, int y); // Set mouse position XY +RLAPI void SetMouseOffset(int offsetX, int offsetY); // Set mouse offset +RLAPI void SetMouseScale(float scaleX, float scaleY); // Set mouse scaling +RLAPI float GetMouseWheelMove(void); // Get mouse wheel movement for X or Y, whichever is larger +RLAPI Vector2 GetMouseWheelMoveV(void); // Get mouse wheel movement for both X and Y +RLAPI void SetMouseCursor(int cursor); // Set mouse cursor + +// Input-related functions: touch +RLAPI int GetTouchX(void); // Get touch position X for touch point 0 (relative to screen size) +RLAPI int GetTouchY(void); // Get touch position Y for touch point 0 (relative to screen size) +RLAPI Vector2 GetTouchPosition(int index); // Get touch position XY for a touch point index (relative to screen size) +RLAPI int GetTouchPointId(int index); // Get touch point identifier for given index +RLAPI int GetTouchPointCount(void); // Get number of touch points + +//------------------------------------------------------------------------------------ +// Gestures and Touch Handling Functions (Module: rgestures) +//------------------------------------------------------------------------------------ +RLAPI void SetGesturesEnabled(unsigned int flags); // Enable a set of gestures using flags +RLAPI bool IsGestureDetected(unsigned int gesture); // Check if a gesture have been detected +RLAPI int GetGestureDetected(void); // Get latest detected gesture +RLAPI float GetGestureHoldDuration(void); // Get gesture hold time in milliseconds +RLAPI Vector2 GetGestureDragVector(void); // Get gesture drag vector +RLAPI float GetGestureDragAngle(void); // Get gesture drag angle +RLAPI Vector2 GetGesturePinchVector(void); // Get gesture pinch delta +RLAPI float GetGesturePinchAngle(void); // Get gesture pinch angle + +//------------------------------------------------------------------------------------ +// Camera System Functions (Module: rcamera) +//------------------------------------------------------------------------------------ +RLAPI void UpdateCamera(Camera *camera, int mode); // Update camera position for selected mode +RLAPI void UpdateCameraPro(Camera *camera, Vector3 movement, Vector3 rotation, float zoom); // Update camera movement/rotation + +//------------------------------------------------------------------------------------ +// Basic Shapes Drawing Functions (Module: shapes) +//------------------------------------------------------------------------------------ +// Set texture and rectangle to be used on shapes drawing +// NOTE: It can be useful when using basic shapes and one single font, +// defining a font char white rectangle would allow drawing everything in a single draw call +RLAPI void SetShapesTexture(Texture2D texture, Rectangle source); // Set texture and rectangle to be used on shapes drawing + +// Basic shapes drawing functions +RLAPI void DrawPixel(int posX, int posY, Color color); // Draw a pixel +RLAPI void DrawPixelV(Vector2 position, Color color); // Draw a pixel (Vector version) +RLAPI void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw a line +RLAPI void DrawLineV(Vector2 startPos, Vector2 endPos, Color color); // Draw a line (using gl lines) +RLAPI void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line (using triangles/quads) +RLAPI void DrawLineStrip(Vector2 *points, int pointCount, Color color); // Draw lines sequence (using gl lines) +RLAPI void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw line segment cubic-bezier in-out interpolation +RLAPI void DrawCircle(int centerX, int centerY, float radius, Color color); // Draw a color-filled circle +RLAPI void DrawCircleSector(Vector2 center, float radius, float startAngle, float endAngle, int segments, Color color); // Draw a piece of a circle +RLAPI void DrawCircleSectorLines(Vector2 center, float radius, float startAngle, float endAngle, int segments, Color color); // Draw circle sector outline +RLAPI void DrawCircleGradient(int centerX, int centerY, float radius, Color color1, Color color2); // Draw a gradient-filled circle +RLAPI void DrawCircleV(Vector2 center, float radius, Color color); // Draw a color-filled circle (Vector version) +RLAPI void DrawCircleLines(int centerX, int centerY, float radius, Color color); // Draw circle outline +RLAPI void DrawCircleLinesV(Vector2 center, float radius, Color color); // Draw circle outline (Vector version) +RLAPI void DrawEllipse(int centerX, int centerY, float radiusH, float radiusV, Color color); // Draw ellipse +RLAPI void DrawEllipseLines(int centerX, int centerY, float radiusH, float radiusV, Color color); // Draw ellipse outline +RLAPI void DrawRing(Vector2 center, float innerRadius, float outerRadius, float startAngle, float endAngle, int segments, Color color); // Draw ring +RLAPI void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, float startAngle, float endAngle, int segments, Color color); // Draw ring outline +RLAPI void DrawRectangle(int posX, int posY, int width, int height, Color color); // Draw a color-filled rectangle +RLAPI void DrawRectangleV(Vector2 position, Vector2 size, Color color); // Draw a color-filled rectangle (Vector version) +RLAPI void DrawRectangleRec(Rectangle rec, Color color); // Draw a color-filled rectangle +RLAPI void DrawRectanglePro(Rectangle rec, Vector2 origin, float rotation, Color color); // Draw a color-filled rectangle with pro parameters +RLAPI void DrawRectangleGradientV(int posX, int posY, int width, int height, Color color1, Color color2);// Draw a vertical-gradient-filled rectangle +RLAPI void DrawRectangleGradientH(int posX, int posY, int width, int height, Color color1, Color color2);// Draw a horizontal-gradient-filled rectangle +RLAPI void DrawRectangleGradientEx(Rectangle rec, Color col1, Color col2, Color col3, Color col4); // Draw a gradient-filled rectangle with custom vertex colors +RLAPI void DrawRectangleLines(int posX, int posY, int width, int height, Color color); // Draw rectangle outline +RLAPI void DrawRectangleLinesEx(Rectangle rec, float lineThick, Color color); // Draw rectangle outline with extended parameters +RLAPI void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges +RLAPI void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, float lineThick, Color color); // Draw rectangle with rounded edges outline +RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle (vertex in counter-clockwise order!) +RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline (vertex in counter-clockwise order!) +RLAPI void DrawTriangleFan(Vector2 *points, int pointCount, Color color); // Draw a triangle fan defined by points (first vertex is the center) +RLAPI void DrawTriangleStrip(Vector2 *points, int pointCount, Color color); // Draw a triangle strip defined by points +RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a regular polygon (Vector version) +RLAPI void DrawPolyLines(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a polygon outline of n sides +RLAPI void DrawPolyLinesEx(Vector2 center, int sides, float radius, float rotation, float lineThick, Color color); // Draw a polygon outline of n sides with extended parameters + +// Splines drawing functions +RLAPI void DrawSplineLinear(Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Linear, minimum 2 points +RLAPI void DrawSplineBasis(Vector2 *points, int pointCount, float thick, Color color); // Draw spline: B-Spline, minimum 4 points +RLAPI void DrawSplineCatmullRom(Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Catmull-Rom, minimum 4 points +RLAPI void DrawSplineBezierQuadratic(Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Quadratic Bezier, minimum 3 points (1 control point): [p1, c2, p3, c4...] +RLAPI void DrawSplineBezierCubic(Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Cubic Bezier, minimum 4 points (2 control points): [p1, c2, c3, p4, c5, c6...] +RLAPI void DrawSplineSegmentLinear(Vector2 p1, Vector2 p2, float thick, Color color); // Draw spline segment: Linear, 2 points +RLAPI void DrawSplineSegmentBasis(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float thick, Color color); // Draw spline segment: B-Spline, 4 points +RLAPI void DrawSplineSegmentCatmullRom(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float thick, Color color); // Draw spline segment: Catmull-Rom, 4 points +RLAPI void DrawSplineSegmentBezierQuadratic(Vector2 p1, Vector2 c2, Vector2 p3, float thick, Color color); // Draw spline segment: Quadratic Bezier, 2 points, 1 control point +RLAPI void DrawSplineSegmentBezierCubic(Vector2 p1, Vector2 c2, Vector2 c3, Vector2 p4, float thick, Color color); // Draw spline segment: Cubic Bezier, 2 points, 2 control points + +// Spline segment point evaluation functions, for a given t [0.0f .. 1.0f] +RLAPI Vector2 GetSplinePointLinear(Vector2 startPos, Vector2 endPos, float t); // Get (evaluate) spline point: Linear +RLAPI Vector2 GetSplinePointBasis(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float t); // Get (evaluate) spline point: B-Spline +RLAPI Vector2 GetSplinePointCatmullRom(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float t); // Get (evaluate) spline point: Catmull-Rom +RLAPI Vector2 GetSplinePointBezierQuad(Vector2 p1, Vector2 c2, Vector2 p3, float t); // Get (evaluate) spline point: Quadratic Bezier +RLAPI Vector2 GetSplinePointBezierCubic(Vector2 p1, Vector2 c2, Vector2 c3, Vector2 p4, float t); // Get (evaluate) spline point: Cubic Bezier + +// Basic shapes collision detection functions +RLAPI bool CheckCollisionRecs(Rectangle rec1, Rectangle rec2); // Check collision between two rectangles +RLAPI bool CheckCollisionCircles(Vector2 center1, float radius1, Vector2 center2, float radius2); // Check collision between two circles +RLAPI bool CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec); // Check collision between circle and rectangle +RLAPI bool CheckCollisionPointRec(Vector2 point, Rectangle rec); // Check if point is inside rectangle +RLAPI bool CheckCollisionPointCircle(Vector2 point, Vector2 center, float radius); // Check if point is inside circle +RLAPI bool CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Vector2 p3); // Check if point is inside a triangle +RLAPI bool CheckCollisionPointPoly(Vector2 point, Vector2 *points, int pointCount); // Check if point is within a polygon described by array of vertices +RLAPI bool CheckCollisionLines(Vector2 startPos1, Vector2 endPos1, Vector2 startPos2, Vector2 endPos2, Vector2 *collisionPoint); // Check the collision between two lines defined by two points each, returns collision point by reference +RLAPI bool CheckCollisionPointLine(Vector2 point, Vector2 p1, Vector2 p2, int threshold); // Check if point belongs to line created between two points [p1] and [p2] with defined margin in pixels [threshold] +RLAPI Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2); // Get collision rectangle for two rectangles collision + +//------------------------------------------------------------------------------------ +// Texture Loading and Drawing Functions (Module: textures) +//------------------------------------------------------------------------------------ + +// Image loading functions +// NOTE: These functions do not require GPU access +RLAPI Image LoadImage(const char *fileName); // Load image from file into CPU memory (RAM) +RLAPI Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize); // Load image from RAW file data +RLAPI Image LoadImageSvg(const char *fileNameOrString, int width, int height); // Load image from SVG file data or string with specified size +RLAPI Image LoadImageAnim(const char *fileName, int *frames); // Load image sequence from file (frames appended to image.data) +RLAPI Image LoadImageFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load image from memory buffer, fileType refers to extension: i.e. '.png' +RLAPI Image LoadImageFromTexture(Texture2D texture); // Load image from GPU texture data +RLAPI Image LoadImageFromScreen(void); // Load image from screen buffer and (screenshot) +RLAPI bool IsImageReady(Image image); // Check if an image is ready +RLAPI void UnloadImage(Image image); // Unload image from CPU memory (RAM) +RLAPI bool ExportImage(Image image, const char *fileName); // Export image data to file, returns true on success +RLAPI unsigned char *ExportImageToMemory(Image image, const char *fileType, int *fileSize); // Export image to memory buffer +RLAPI bool ExportImageAsCode(Image image, const char *fileName); // Export image as code file defining an array of bytes, returns true on success + +// Image generation functions +RLAPI Image GenImageColor(int width, int height, Color color); // Generate image: plain color +RLAPI Image GenImageGradientLinear(int width, int height, int direction, Color start, Color end); // Generate image: linear gradient, direction in degrees [0..360], 0=Vertical gradient +RLAPI Image GenImageGradientRadial(int width, int height, float density, Color inner, Color outer); // Generate image: radial gradient +RLAPI Image GenImageGradientSquare(int width, int height, float density, Color inner, Color outer); // Generate image: square gradient +RLAPI Image GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2); // Generate image: checked +RLAPI Image GenImageWhiteNoise(int width, int height, float factor); // Generate image: white noise +RLAPI Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float scale); // Generate image: perlin noise +RLAPI Image GenImageCellular(int width, int height, int tileSize); // Generate image: cellular algorithm, bigger tileSize means bigger cells +RLAPI Image GenImageText(int width, int height, const char *text); // Generate image: grayscale image from text data + +// Image manipulation functions +RLAPI Image ImageCopy(Image image); // Create an image duplicate (useful for transformations) +RLAPI Image ImageFromImage(Image image, Rectangle rec); // Create an image from another image piece +RLAPI Image ImageText(const char *text, int fontSize, Color color); // Create an image from text (default font) +RLAPI Image ImageTextEx(Font font, const char *text, float fontSize, float spacing, Color tint); // Create an image from text (custom sprite font) +RLAPI void ImageFormat(Image *image, int newFormat); // Convert image data to desired format +RLAPI void ImageToPOT(Image *image, Color fill); // Convert image to POT (power-of-two) +RLAPI void ImageCrop(Image *image, Rectangle crop); // Crop an image to a defined rectangle +RLAPI void ImageAlphaCrop(Image *image, float threshold); // Crop image depending on alpha value +RLAPI void ImageAlphaClear(Image *image, Color color, float threshold); // Clear alpha channel to desired color +RLAPI void ImageAlphaMask(Image *image, Image alphaMask); // Apply alpha mask to image +RLAPI void ImageAlphaPremultiply(Image *image); // Premultiply alpha channel +RLAPI void ImageBlurGaussian(Image *image, int blurSize); // Apply Gaussian blur using a box blur approximation +RLAPI void ImageResize(Image *image, int newWidth, int newHeight); // Resize image (Bicubic scaling algorithm) +RLAPI void ImageResizeNN(Image *image, int newWidth,int newHeight); // Resize image (Nearest-Neighbor scaling algorithm) +RLAPI void ImageResizeCanvas(Image *image, int newWidth, int newHeight, int offsetX, int offsetY, Color fill); // Resize canvas and fill with color +RLAPI void ImageMipmaps(Image *image); // Compute all mipmap levels for a provided image +RLAPI void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp); // Dither image data to 16bpp or lower (Floyd-Steinberg dithering) +RLAPI void ImageFlipVertical(Image *image); // Flip image vertically +RLAPI void ImageFlipHorizontal(Image *image); // Flip image horizontally +RLAPI void ImageRotate(Image *image, int degrees); // Rotate image by input angle in degrees (-359 to 359) +RLAPI void ImageRotateCW(Image *image); // Rotate image clockwise 90deg +RLAPI void ImageRotateCCW(Image *image); // Rotate image counter-clockwise 90deg +RLAPI void ImageColorTint(Image *image, Color color); // Modify image color: tint +RLAPI void ImageColorInvert(Image *image); // Modify image color: invert +RLAPI void ImageColorGrayscale(Image *image); // Modify image color: grayscale +RLAPI void ImageColorContrast(Image *image, float contrast); // Modify image color: contrast (-100 to 100) +RLAPI void ImageColorBrightness(Image *image, int brightness); // Modify image color: brightness (-255 to 255) +RLAPI void ImageColorReplace(Image *image, Color color, Color replace); // Modify image color: replace color +RLAPI Color *LoadImageColors(Image image); // Load color data from image as a Color array (RGBA - 32bit) +RLAPI Color *LoadImagePalette(Image image, int maxPaletteSize, int *colorCount); // Load colors palette from image as a Color array (RGBA - 32bit) +RLAPI void UnloadImageColors(Color *colors); // Unload color data loaded with LoadImageColors() +RLAPI void UnloadImagePalette(Color *colors); // Unload colors palette loaded with LoadImagePalette() +RLAPI Rectangle GetImageAlphaBorder(Image image, float threshold); // Get image alpha border rectangle +RLAPI Color GetImageColor(Image image, int x, int y); // Get image pixel color at (x, y) position + +// Image drawing functions +// NOTE: Image software-rendering functions (CPU) +RLAPI void ImageClearBackground(Image *dst, Color color); // Clear image background with given color +RLAPI void ImageDrawPixel(Image *dst, int posX, int posY, Color color); // Draw pixel within an image +RLAPI void ImageDrawPixelV(Image *dst, Vector2 position, Color color); // Draw pixel within an image (Vector version) +RLAPI void ImageDrawLine(Image *dst, int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw line within an image +RLAPI void ImageDrawLineV(Image *dst, Vector2 start, Vector2 end, Color color); // Draw line within an image (Vector version) +RLAPI void ImageDrawCircle(Image *dst, int centerX, int centerY, int radius, Color color); // Draw a filled circle within an image +RLAPI void ImageDrawCircleV(Image *dst, Vector2 center, int radius, Color color); // Draw a filled circle within an image (Vector version) +RLAPI void ImageDrawCircleLines(Image *dst, int centerX, int centerY, int radius, Color color); // Draw circle outline within an image +RLAPI void ImageDrawCircleLinesV(Image *dst, Vector2 center, int radius, Color color); // Draw circle outline within an image (Vector version) +RLAPI void ImageDrawRectangle(Image *dst, int posX, int posY, int width, int height, Color color); // Draw rectangle within an image +RLAPI void ImageDrawRectangleV(Image *dst, Vector2 position, Vector2 size, Color color); // Draw rectangle within an image (Vector version) +RLAPI void ImageDrawRectangleRec(Image *dst, Rectangle rec, Color color); // Draw rectangle within an image +RLAPI void ImageDrawRectangleLines(Image *dst, Rectangle rec, int thick, Color color); // Draw rectangle lines within an image +RLAPI void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec, Color tint); // Draw a source image within a destination image (tint applied to source) +RLAPI void ImageDrawText(Image *dst, const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) within an image (destination) +RLAPI void ImageDrawTextEx(Image *dst, Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text (custom sprite font) within an image (destination) + +// Texture loading functions +// NOTE: These functions require GPU access +RLAPI Texture2D LoadTexture(const char *fileName); // Load texture from file into GPU memory (VRAM) +RLAPI Texture2D LoadTextureFromImage(Image image); // Load texture from image data +RLAPI TextureCubemap LoadTextureCubemap(Image image, int layout); // Load cubemap from image, multiple image cubemap layouts supported +RLAPI RenderTexture2D LoadRenderTexture(int width, int height); // Load texture for rendering (framebuffer) +RLAPI bool IsTextureReady(Texture2D texture); // Check if a texture is ready +RLAPI void UnloadTexture(Texture2D texture); // Unload texture from GPU memory (VRAM) +RLAPI bool IsRenderTextureReady(RenderTexture2D target); // Check if a render texture is ready +RLAPI void UnloadRenderTexture(RenderTexture2D target); // Unload render texture from GPU memory (VRAM) +RLAPI void UpdateTexture(Texture2D texture, const void *pixels); // Update GPU texture with new data +RLAPI void UpdateTextureRec(Texture2D texture, Rectangle rec, const void *pixels); // Update GPU texture rectangle with new data + +// Texture configuration functions +RLAPI void GenTextureMipmaps(Texture2D *texture); // Generate GPU mipmaps for a texture +RLAPI void SetTextureFilter(Texture2D texture, int filter); // Set texture scaling filter mode +RLAPI void SetTextureWrap(Texture2D texture, int wrap); // Set texture wrapping mode + +// Texture drawing functions +RLAPI void DrawTexture(Texture2D texture, int posX, int posY, Color tint); // Draw a Texture2D +RLAPI void DrawTextureV(Texture2D texture, Vector2 position, Color tint); // Draw a Texture2D with position defined as Vector2 +RLAPI void DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float scale, Color tint); // Draw a Texture2D with extended parameters +RLAPI void DrawTextureRec(Texture2D texture, Rectangle source, Vector2 position, Color tint); // Draw a part of a texture defined by a rectangle +RLAPI void DrawTexturePro(Texture2D texture, Rectangle source, Rectangle dest, Vector2 origin, float rotation, Color tint); // Draw a part of a texture defined by a rectangle with 'pro' parameters +RLAPI void DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo, Rectangle dest, Vector2 origin, float rotation, Color tint); // Draws a texture (or part of it) that stretches or shrinks nicely + +// Color/pixel related functions +RLAPI Color Fade(Color color, float alpha); // Get color with alpha applied, alpha goes from 0.0f to 1.0f +RLAPI int ColorToInt(Color color); // Get hexadecimal value for a Color +RLAPI Vector4 ColorNormalize(Color color); // Get Color normalized as float [0..1] +RLAPI Color ColorFromNormalized(Vector4 normalized); // Get Color from normalized values [0..1] +RLAPI Vector3 ColorToHSV(Color color); // Get HSV values for a Color, hue [0..360], saturation/value [0..1] +RLAPI Color ColorFromHSV(float hue, float saturation, float value); // Get a Color from HSV values, hue [0..360], saturation/value [0..1] +RLAPI Color ColorTint(Color color, Color tint); // Get color multiplied with another color +RLAPI Color ColorBrightness(Color color, float factor); // Get color with brightness correction, brightness factor goes from -1.0f to 1.0f +RLAPI Color ColorContrast(Color color, float contrast); // Get color with contrast correction, contrast values between -1.0f and 1.0f +RLAPI Color ColorAlpha(Color color, float alpha); // Get color with alpha applied, alpha goes from 0.0f to 1.0f +RLAPI Color ColorAlphaBlend(Color dst, Color src, Color tint); // Get src alpha-blended into dst color with tint +RLAPI Color GetColor(unsigned int hexValue); // Get Color structure from hexadecimal value +RLAPI Color GetPixelColor(void *srcPtr, int format); // Get Color from a source pixel pointer of certain format +RLAPI void SetPixelColor(void *dstPtr, Color color, int format); // Set color formatted into destination pixel pointer +RLAPI int GetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes for certain format + +//------------------------------------------------------------------------------------ +// Font Loading and Text Drawing Functions (Module: text) +//------------------------------------------------------------------------------------ + +// Font loading/unloading functions +RLAPI Font GetFontDefault(void); // Get the default Font +RLAPI Font LoadFont(const char *fileName); // Load font from file into GPU memory (VRAM) +RLAPI Font LoadFontEx(const char *fileName, int fontSize, int *codepoints, int codepointCount); // Load font from file with extended parameters, use NULL for codepoints and 0 for codepointCount to load the default character set +RLAPI Font LoadFontFromImage(Image image, Color key, int firstChar); // Load font from Image (XNA style) +RLAPI Font LoadFontFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int fontSize, int *codepoints, int codepointCount); // Load font from memory buffer, fileType refers to extension: i.e. '.ttf' +RLAPI bool IsFontReady(Font font); // Check if a font is ready +RLAPI GlyphInfo *LoadFontData(const unsigned char *fileData, int dataSize, int fontSize, int *codepoints, int codepointCount, int type); // Load font data for further use +RLAPI Image GenImageFontAtlas(const GlyphInfo *glyphs, Rectangle **glyphRecs, int glyphCount, int fontSize, int padding, int packMethod); // Generate image font atlas using chars info +RLAPI void UnloadFontData(GlyphInfo *glyphs, int glyphCount); // Unload font chars info data (RAM) +RLAPI void UnloadFont(Font font); // Unload font from GPU memory (VRAM) +RLAPI bool ExportFontAsCode(Font font, const char *fileName); // Export font as code file, returns true on success + +// Text drawing functions +RLAPI void DrawFPS(int posX, int posY); // Draw current FPS +RLAPI void DrawText(const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) +RLAPI void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text using font and additional parameters +RLAPI void DrawTextPro(Font font, const char *text, Vector2 position, Vector2 origin, float rotation, float fontSize, float spacing, Color tint); // Draw text using Font and pro parameters (rotation) +RLAPI void DrawTextCodepoint(Font font, int codepoint, Vector2 position, float fontSize, Color tint); // Draw one character (codepoint) +RLAPI void DrawTextCodepoints(Font font, const int *codepoints, int codepointCount, Vector2 position, float fontSize, float spacing, Color tint); // Draw multiple character (codepoint) + +// Text font info functions +RLAPI void SetTextLineSpacing(int spacing); // Set vertical line spacing when drawing with line-breaks +RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font +RLAPI Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing); // Measure string size for Font +RLAPI int GetGlyphIndex(Font font, int codepoint); // Get glyph index position in font for a codepoint (unicode character), fallback to '?' if not found +RLAPI GlyphInfo GetGlyphInfo(Font font, int codepoint); // Get glyph font info data for a codepoint (unicode character), fallback to '?' if not found +RLAPI Rectangle GetGlyphAtlasRec(Font font, int codepoint); // Get glyph rectangle in font atlas for a codepoint (unicode character), fallback to '?' if not found + +// Text codepoints management functions (unicode characters) +RLAPI char *LoadUTF8(const int *codepoints, int length); // Load UTF-8 text encoded from codepoints array +RLAPI void UnloadUTF8(char *text); // Unload UTF-8 text encoded from codepoints array +RLAPI int *LoadCodepoints(const char *text, int *count); // Load all codepoints from a UTF-8 text string, codepoints count returned by parameter +RLAPI void UnloadCodepoints(int *codepoints); // Unload codepoints data from memory +RLAPI int GetCodepointCount(const char *text); // Get total number of codepoints in a UTF-8 encoded string +RLAPI int GetCodepoint(const char *text, int *codepointSize); // Get next codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure +RLAPI int GetCodepointNext(const char *text, int *codepointSize); // Get next codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure +RLAPI int GetCodepointPrevious(const char *text, int *codepointSize); // Get previous codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure +RLAPI const char *CodepointToUTF8(int codepoint, int *utf8Size); // Encode one codepoint into UTF-8 byte array (array length returned as parameter) + +// Text strings management functions (no UTF-8 strings, only byte chars) +// NOTE: Some strings allocate memory internally for returned strings, just be careful! +RLAPI int TextCopy(char *dst, const char *src); // Copy one string to another, returns bytes copied +RLAPI bool TextIsEqual(const char *text1, const char *text2); // Check if two text string are equal +RLAPI unsigned int TextLength(const char *text); // Get text length, checks for '\0' ending +RLAPI const char *TextFormat(const char *text, ...); // Text formatting with variables (sprintf() style) +RLAPI const char *TextSubtext(const char *text, int position, int length); // Get a piece of a text string +RLAPI char *TextReplace(char *text, const char *replace, const char *by); // Replace text string (WARNING: memory must be freed!) +RLAPI char *TextInsert(const char *text, const char *insert, int position); // Insert text in a position (WARNING: memory must be freed!) +RLAPI const char *TextJoin(const char **textList, int count, const char *delimiter); // Join text strings with delimiter +RLAPI const char **TextSplit(const char *text, char delimiter, int *count); // Split text into multiple strings +RLAPI void TextAppend(char *text, const char *append, int *position); // Append text at specific position and move cursor! +RLAPI int TextFindIndex(const char *text, const char *find); // Find first text occurrence within a string +RLAPI const char *TextToUpper(const char *text); // Get upper case version of provided string +RLAPI const char *TextToLower(const char *text); // Get lower case version of provided string +RLAPI const char *TextToPascal(const char *text); // Get Pascal case notation version of provided string +RLAPI int TextToInteger(const char *text); // Get integer value from text (negative values not supported) + +//------------------------------------------------------------------------------------ +// Basic 3d Shapes Drawing Functions (Module: models) +//------------------------------------------------------------------------------------ + +// Basic geometric 3D shapes drawing functions +RLAPI void DrawLine3D(Vector3 startPos, Vector3 endPos, Color color); // Draw a line in 3D world space +RLAPI void DrawPoint3D(Vector3 position, Color color); // Draw a point in 3D space, actually a small line +RLAPI void DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color); // Draw a circle in 3D world space +RLAPI void DrawTriangle3D(Vector3 v1, Vector3 v2, Vector3 v3, Color color); // Draw a color-filled triangle (vertex in counter-clockwise order!) +RLAPI void DrawTriangleStrip3D(Vector3 *points, int pointCount, Color color); // Draw a triangle strip defined by points +RLAPI void DrawCube(Vector3 position, float width, float height, float length, Color color); // Draw cube +RLAPI void DrawCubeV(Vector3 position, Vector3 size, Color color); // Draw cube (Vector version) +RLAPI void DrawCubeWires(Vector3 position, float width, float height, float length, Color color); // Draw cube wires +RLAPI void DrawCubeWiresV(Vector3 position, Vector3 size, Color color); // Draw cube wires (Vector version) +RLAPI void DrawSphere(Vector3 centerPos, float radius, Color color); // Draw sphere +RLAPI void DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere with extended parameters +RLAPI void DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere wires +RLAPI void DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color); // Draw a cylinder/cone +RLAPI void DrawCylinderEx(Vector3 startPos, Vector3 endPos, float startRadius, float endRadius, int sides, Color color); // Draw a cylinder with base at startPos and top at endPos +RLAPI void DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color); // Draw a cylinder/cone wires +RLAPI void DrawCylinderWiresEx(Vector3 startPos, Vector3 endPos, float startRadius, float endRadius, int sides, Color color); // Draw a cylinder wires with base at startPos and top at endPos +RLAPI void DrawCapsule(Vector3 startPos, Vector3 endPos, float radius, int slices, int rings, Color color); // Draw a capsule with the center of its sphere caps at startPos and endPos +RLAPI void DrawCapsuleWires(Vector3 startPos, Vector3 endPos, float radius, int slices, int rings, Color color); // Draw capsule wireframe with the center of its sphere caps at startPos and endPos +RLAPI void DrawPlane(Vector3 centerPos, Vector2 size, Color color); // Draw a plane XZ +RLAPI void DrawRay(Ray ray, Color color); // Draw a ray line +RLAPI void DrawGrid(int slices, float spacing); // Draw a grid (centered at (0, 0, 0)) + +//------------------------------------------------------------------------------------ +// Model 3d Loading and Drawing Functions (Module: models) +//------------------------------------------------------------------------------------ + +// Model management functions +RLAPI Model LoadModel(const char *fileName); // Load model from files (meshes and materials) +RLAPI Model LoadModelFromMesh(Mesh mesh); // Load model from generated mesh (default material) +RLAPI bool IsModelReady(Model model); // Check if a model is ready +RLAPI void UnloadModel(Model model); // Unload model (including meshes) from memory (RAM and/or VRAM) +RLAPI BoundingBox GetModelBoundingBox(Model model); // Compute model bounding box limits (considers all meshes) + +// Model drawing functions +RLAPI void DrawModel(Model model, Vector3 position, float scale, Color tint); // Draw a model (with texture if set) +RLAPI void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model with extended parameters +RLAPI void DrawModelWires(Model model, Vector3 position, float scale, Color tint); // Draw a model wires (with texture if set) +RLAPI void DrawModelWiresEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model wires (with texture if set) with extended parameters +RLAPI void DrawBoundingBox(BoundingBox box, Color color); // Draw bounding box (wires) +RLAPI void DrawBillboard(Camera camera, Texture2D texture, Vector3 position, float size, Color tint); // Draw a billboard texture +RLAPI void DrawBillboardRec(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector2 size, Color tint); // Draw a billboard texture defined by source +RLAPI void DrawBillboardPro(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector3 up, Vector2 size, Vector2 origin, float rotation, Color tint); // Draw a billboard texture defined by source and rotation + +// Mesh management functions +RLAPI void UploadMesh(Mesh *mesh, bool dynamic); // Upload mesh vertex data in GPU and provide VAO/VBO ids +RLAPI void UpdateMeshBuffer(Mesh mesh, int index, const void *data, int dataSize, int offset); // Update mesh vertex data in GPU for a specific buffer index +RLAPI void UnloadMesh(Mesh mesh); // Unload mesh data from CPU and GPU +RLAPI void DrawMesh(Mesh mesh, Material material, Matrix transform); // Draw a 3d mesh with material and transform +RLAPI void DrawMeshInstanced(Mesh mesh, Material material, const Matrix *transforms, int instances); // Draw multiple mesh instances with material and different transforms +RLAPI bool ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file, returns true on success +RLAPI BoundingBox GetMeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits +RLAPI void GenMeshTangents(Mesh *mesh); // Compute mesh tangents + +// Mesh generation functions +RLAPI Mesh GenMeshPoly(int sides, float radius); // Generate polygonal mesh +RLAPI Mesh GenMeshPlane(float width, float length, int resX, int resZ); // Generate plane mesh (with subdivisions) +RLAPI Mesh GenMeshCube(float width, float height, float length); // Generate cuboid mesh +RLAPI Mesh GenMeshSphere(float radius, int rings, int slices); // Generate sphere mesh (standard sphere) +RLAPI Mesh GenMeshHemiSphere(float radius, int rings, int slices); // Generate half-sphere mesh (no bottom cap) +RLAPI Mesh GenMeshCylinder(float radius, float height, int slices); // Generate cylinder mesh +RLAPI Mesh GenMeshCone(float radius, float height, int slices); // Generate cone/pyramid mesh +RLAPI Mesh GenMeshTorus(float radius, float size, int radSeg, int sides); // Generate torus mesh +RLAPI Mesh GenMeshKnot(float radius, float size, int radSeg, int sides); // Generate trefoil knot mesh +RLAPI Mesh GenMeshHeightmap(Image heightmap, Vector3 size); // Generate heightmap mesh from image data +RLAPI Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize); // Generate cubes-based map mesh from image data + +// Material loading/unloading functions +RLAPI Material *LoadMaterials(const char *fileName, int *materialCount); // Load materials from model file +RLAPI Material LoadMaterialDefault(void); // Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) +RLAPI bool IsMaterialReady(Material material); // Check if a material is ready +RLAPI void UnloadMaterial(Material material); // Unload material from GPU memory (VRAM) +RLAPI void SetMaterialTexture(Material *material, int mapType, Texture2D texture); // Set texture for a material map type (MATERIAL_MAP_DIFFUSE, MATERIAL_MAP_SPECULAR...) +RLAPI void SetModelMeshMaterial(Model *model, int meshId, int materialId); // Set material for a mesh + +// Model animations loading/unloading functions +RLAPI ModelAnimation *LoadModelAnimations(const char *fileName, int *animCount); // Load model animations from file +RLAPI void UpdateModelAnimation(Model model, ModelAnimation anim, int frame); // Update model animation pose +RLAPI void UnloadModelAnimation(ModelAnimation anim); // Unload animation data +RLAPI void UnloadModelAnimations(ModelAnimation *animations, int animCount); // Unload animation array data +RLAPI bool IsModelAnimationValid(Model model, ModelAnimation anim); // Check model animation skeleton match + +// Collision detection functions +RLAPI bool CheckCollisionSpheres(Vector3 center1, float radius1, Vector3 center2, float radius2); // Check collision between two spheres +RLAPI bool CheckCollisionBoxes(BoundingBox box1, BoundingBox box2); // Check collision between two bounding boxes +RLAPI bool CheckCollisionBoxSphere(BoundingBox box, Vector3 center, float radius); // Check collision between box and sphere +RLAPI RayCollision GetRayCollisionSphere(Ray ray, Vector3 center, float radius); // Get collision info between ray and sphere +RLAPI RayCollision GetRayCollisionBox(Ray ray, BoundingBox box); // Get collision info between ray and box +RLAPI RayCollision GetRayCollisionMesh(Ray ray, Mesh mesh, Matrix transform); // Get collision info between ray and mesh +RLAPI RayCollision GetRayCollisionTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3); // Get collision info between ray and triangle +RLAPI RayCollision GetRayCollisionQuad(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4); // Get collision info between ray and quad + +//------------------------------------------------------------------------------------ +// Audio Loading and Playing Functions (Module: audio) +//------------------------------------------------------------------------------------ +typedef void (*AudioCallback)(void *bufferData, unsigned int frames); + +// Audio device management functions +RLAPI void InitAudioDevice(void); // Initialize audio device and context +RLAPI void CloseAudioDevice(void); // Close the audio device and context +RLAPI bool IsAudioDeviceReady(void); // Check if audio device has been initialized successfully +RLAPI void SetMasterVolume(float volume); // Set master volume (listener) +RLAPI float GetMasterVolume(void); // Get master volume (listener) + +// Wave/Sound loading/unloading functions +RLAPI Wave LoadWave(const char *fileName); // Load wave data from file +RLAPI Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load wave from memory buffer, fileType refers to extension: i.e. '.wav' +RLAPI bool IsWaveReady(Wave wave); // Checks if wave data is ready +RLAPI Sound LoadSound(const char *fileName); // Load sound from file +RLAPI Sound LoadSoundFromWave(Wave wave); // Load sound from wave data +RLAPI Sound LoadSoundAlias(Sound source); // Create a new sound that shares the same sample data as the source sound, does not own the sound data +RLAPI bool IsSoundReady(Sound sound); // Checks if a sound is ready +RLAPI void UpdateSound(Sound sound, const void *data, int sampleCount); // Update sound buffer with new data +RLAPI void UnloadWave(Wave wave); // Unload wave data +RLAPI void UnloadSound(Sound sound); // Unload sound +RLAPI void UnloadSoundAlias(Sound alias); // Unload a sound alias (does not deallocate sample data) +RLAPI bool ExportWave(Wave wave, const char *fileName); // Export wave data to file, returns true on success +RLAPI bool ExportWaveAsCode(Wave wave, const char *fileName); // Export wave sample data to code (.h), returns true on success + +// Wave/Sound management functions +RLAPI void PlaySound(Sound sound); // Play a sound +RLAPI void StopSound(Sound sound); // Stop playing a sound +RLAPI void PauseSound(Sound sound); // Pause a sound +RLAPI void ResumeSound(Sound sound); // Resume a paused sound +RLAPI bool IsSoundPlaying(Sound sound); // Check if a sound is currently playing +RLAPI void SetSoundVolume(Sound sound, float volume); // Set volume for a sound (1.0 is max level) +RLAPI void SetSoundPitch(Sound sound, float pitch); // Set pitch for a sound (1.0 is base level) +RLAPI void SetSoundPan(Sound sound, float pan); // Set pan for a sound (0.5 is center) +RLAPI Wave WaveCopy(Wave wave); // Copy a wave to a new wave +RLAPI void WaveCrop(Wave *wave, int initSample, int finalSample); // Crop a wave to defined samples range +RLAPI void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels); // Convert wave data to desired format +RLAPI float *LoadWaveSamples(Wave wave); // Load samples data from wave as a 32bit float data array +RLAPI void UnloadWaveSamples(float *samples); // Unload samples data loaded with LoadWaveSamples() + +// Music management functions +RLAPI Music LoadMusicStream(const char *fileName); // Load music stream from file +RLAPI Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, int dataSize); // Load music stream from data +RLAPI bool IsMusicReady(Music music); // Checks if a music stream is ready +RLAPI void UnloadMusicStream(Music music); // Unload music stream +RLAPI void PlayMusicStream(Music music); // Start music playing +RLAPI bool IsMusicStreamPlaying(Music music); // Check if music is playing +RLAPI void UpdateMusicStream(Music music); // Updates buffers for music streaming +RLAPI void StopMusicStream(Music music); // Stop music playing +RLAPI void PauseMusicStream(Music music); // Pause music playing +RLAPI void ResumeMusicStream(Music music); // Resume playing paused music +RLAPI void SeekMusicStream(Music music, float position); // Seek music to a position (in seconds) +RLAPI void SetMusicVolume(Music music, float volume); // Set volume for music (1.0 is max level) +RLAPI void SetMusicPitch(Music music, float pitch); // Set pitch for a music (1.0 is base level) +RLAPI void SetMusicPan(Music music, float pan); // Set pan for a music (0.5 is center) +RLAPI float GetMusicTimeLength(Music music); // Get music time length (in seconds) +RLAPI float GetMusicTimePlayed(Music music); // Get current music time played (in seconds) + +// AudioStream management functions +RLAPI AudioStream LoadAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels); // Load audio stream (to stream raw audio pcm data) +RLAPI bool IsAudioStreamReady(AudioStream stream); // Checks if an audio stream is ready +RLAPI void UnloadAudioStream(AudioStream stream); // Unload audio stream and free memory +RLAPI void UpdateAudioStream(AudioStream stream, const void *data, int frameCount); // Update audio stream buffers with data +RLAPI bool IsAudioStreamProcessed(AudioStream stream); // Check if any audio stream buffers requires refill +RLAPI void PlayAudioStream(AudioStream stream); // Play audio stream +RLAPI void PauseAudioStream(AudioStream stream); // Pause audio stream +RLAPI void ResumeAudioStream(AudioStream stream); // Resume audio stream +RLAPI bool IsAudioStreamPlaying(AudioStream stream); // Check if audio stream is playing +RLAPI void StopAudioStream(AudioStream stream); // Stop audio stream +RLAPI void SetAudioStreamVolume(AudioStream stream, float volume); // Set volume for audio stream (1.0 is max level) +RLAPI void SetAudioStreamPitch(AudioStream stream, float pitch); // Set pitch for audio stream (1.0 is base level) +RLAPI void SetAudioStreamPan(AudioStream stream, float pan); // Set pan for audio stream (0.5 is centered) +RLAPI void SetAudioStreamBufferSizeDefault(int size); // Default size for new audio streams +RLAPI void SetAudioStreamCallback(AudioStream stream, AudioCallback callback); // Audio thread callback to request new data + +RLAPI void AttachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Attach audio stream processor to stream, receives the samples as s +RLAPI void DetachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Detach audio stream processor from stream + +RLAPI void AttachAudioMixedProcessor(AudioCallback processor); // Attach audio stream processor to the entire audio pipeline, receives the samples as s +RLAPI void DetachAudioMixedProcessor(AudioCallback processor); // Detach audio stream processor from the entire audio pipeline + +#if defined(__cplusplus) +} +#endif + +#endif // RAYLIB_H diff --git a/pkgs/raylib/raylib-5.0_win64_msvc16/include/raymath.h b/pkgs/raylib/raylib-5.0_win64_msvc16/include/raymath.h new file mode 100644 index 0000000..40a8a84 --- /dev/null +++ b/pkgs/raylib/raylib-5.0_win64_msvc16/include/raymath.h @@ -0,0 +1,2190 @@ +/********************************************************************************************** +* +* raymath v1.5 - Math functions to work with Vector2, Vector3, Matrix and Quaternions +* +* CONVENTIONS: +* - Matrix structure is defined as row-major (memory layout) but parameters naming AND all +* math operations performed by the library consider the structure as it was column-major +* It is like transposed versions of the matrices are used for all the maths +* It benefits some functions making them cache-friendly and also avoids matrix +* transpositions sometimes required by OpenGL +* Example: In memory order, row0 is [m0 m4 m8 m12] but in semantic math row0 is [m0 m1 m2 m3] +* - Functions are always self-contained, no function use another raymath function inside, +* required code is directly re-implemented inside +* - Functions input parameters are always received by value (2 unavoidable exceptions) +* - Functions use always a "result" variable for return +* - Functions are always defined inline +* - Angles are always in radians (DEG2RAD/RAD2DEG macros provided for convenience) +* - No compound literals used to make sure libray is compatible with C++ +* +* CONFIGURATION: +* #define RAYMATH_IMPLEMENTATION +* Generates the implementation of the library into the included file. +* If not defined, the library is in header only mode and can be included in other headers +* or source files without problems. But only ONE file should hold the implementation. +* +* #define RAYMATH_STATIC_INLINE +* Define static inline functions code, so #include header suffices for use. +* This may use up lots of memory. +* +* +* LICENSE: zlib/libpng +* +* Copyright (c) 2015-2023 Ramon Santamaria (@raysan5) +* +* This software is provided "as-is", without any express or implied warranty. In no event +* will the authors be held liable for any damages arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, including commercial +* applications, and to alter it and redistribute it freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not claim that you +* wrote the original software. If you use this software in a product, an acknowledgment +* in the product documentation would be appreciated but is not required. +* +* 2. Altered source versions must be plainly marked as such, and must not be misrepresented +* as being the original software. +* +* 3. This notice may not be removed or altered from any source distribution. +* +**********************************************************************************************/ + +#ifndef RAYMATH_H +#define RAYMATH_H + +#if defined(RAYMATH_IMPLEMENTATION) && defined(RAYMATH_STATIC_INLINE) + #error "Specifying both RAYMATH_IMPLEMENTATION and RAYMATH_STATIC_INLINE is contradictory" +#endif + +// Function specifiers definition +#if defined(RAYMATH_IMPLEMENTATION) + #if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) + #define RMAPI __declspec(dllexport) extern inline // We are building raylib as a Win32 shared library (.dll). + #elif defined(_WIN32) && defined(USE_LIBTYPE_SHARED) + #define RMAPI __declspec(dllimport) // We are using raylib as a Win32 shared library (.dll) + #else + #define RMAPI extern inline // Provide external definition + #endif +#elif defined(RAYMATH_STATIC_INLINE) + #define RMAPI static inline // Functions may be inlined, no external out-of-line definition +#else + #if defined(__TINYC__) + #define RMAPI static inline // plain inline not supported by tinycc (See issue #435) + #else + #define RMAPI inline // Functions may be inlined or external definition used + #endif +#endif + +//---------------------------------------------------------------------------------- +// Defines and Macros +//---------------------------------------------------------------------------------- +#ifndef PI + #define PI 3.14159265358979323846f +#endif + +#ifndef EPSILON + #define EPSILON 0.000001f +#endif + +#ifndef DEG2RAD + #define DEG2RAD (PI/180.0f) +#endif + +#ifndef RAD2DEG + #define RAD2DEG (180.0f/PI) +#endif + +// Get float vector for Matrix +#ifndef MatrixToFloat + #define MatrixToFloat(mat) (MatrixToFloatV(mat).v) +#endif + +// Get float vector for Vector3 +#ifndef Vector3ToFloat + #define Vector3ToFloat(vec) (Vector3ToFloatV(vec).v) +#endif + +//---------------------------------------------------------------------------------- +// Types and Structures Definition +//---------------------------------------------------------------------------------- +#if !defined(RL_VECTOR2_TYPE) +// Vector2 type +typedef struct Vector2 { + float x; + float y; +} Vector2; +#define RL_VECTOR2_TYPE +#endif + +#if !defined(RL_VECTOR3_TYPE) +// Vector3 type +typedef struct Vector3 { + float x; + float y; + float z; +} Vector3; +#define RL_VECTOR3_TYPE +#endif + +#if !defined(RL_VECTOR4_TYPE) +// Vector4 type +typedef struct Vector4 { + float x; + float y; + float z; + float w; +} Vector4; +#define RL_VECTOR4_TYPE +#endif + +#if !defined(RL_QUATERNION_TYPE) +// Quaternion type +typedef Vector4 Quaternion; +#define RL_QUATERNION_TYPE +#endif + +#if !defined(RL_MATRIX_TYPE) +// Matrix type (OpenGL style 4x4 - right handed, column major) +typedef struct Matrix { + float m0, m4, m8, m12; // Matrix first row (4 components) + float m1, m5, m9, m13; // Matrix second row (4 components) + float m2, m6, m10, m14; // Matrix third row (4 components) + float m3, m7, m11, m15; // Matrix fourth row (4 components) +} Matrix; +#define RL_MATRIX_TYPE +#endif + +// NOTE: Helper types to be used instead of array return types for *ToFloat functions +typedef struct float3 { + float v[3]; +} float3; + +typedef struct float16 { + float v[16]; +} float16; + +#include // Required for: sinf(), cosf(), tan(), atan2f(), sqrtf(), floor(), fminf(), fmaxf(), fabs() + +//---------------------------------------------------------------------------------- +// Module Functions Definition - Utils math +//---------------------------------------------------------------------------------- + +// Clamp float value +RMAPI float Clamp(float value, float min, float max) +{ + float result = (value < min)? min : value; + + if (result > max) result = max; + + return result; +} + +// Calculate linear interpolation between two floats +RMAPI float Lerp(float start, float end, float amount) +{ + float result = start + amount*(end - start); + + return result; +} + +// Normalize input value within input range +RMAPI float Normalize(float value, float start, float end) +{ + float result = (value - start)/(end - start); + + return result; +} + +// Remap input value within input range to output range +RMAPI float Remap(float value, float inputStart, float inputEnd, float outputStart, float outputEnd) +{ + float result = (value - inputStart)/(inputEnd - inputStart)*(outputEnd - outputStart) + outputStart; + + return result; +} + +// Wrap input value from min to max +RMAPI float Wrap(float value, float min, float max) +{ + float result = value - (max - min)*floorf((value - min)/(max - min)); + + return result; +} + +// Check whether two given floats are almost equal +RMAPI int FloatEquals(float x, float y) +{ +#if !defined(EPSILON) + #define EPSILON 0.000001f +#endif + + int result = (fabsf(x - y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(x), fabsf(y)))); + + return result; +} + +//---------------------------------------------------------------------------------- +// Module Functions Definition - Vector2 math +//---------------------------------------------------------------------------------- + +// Vector with components value 0.0f +RMAPI Vector2 Vector2Zero(void) +{ + Vector2 result = { 0.0f, 0.0f }; + + return result; +} + +// Vector with components value 1.0f +RMAPI Vector2 Vector2One(void) +{ + Vector2 result = { 1.0f, 1.0f }; + + return result; +} + +// Add two vectors (v1 + v2) +RMAPI Vector2 Vector2Add(Vector2 v1, Vector2 v2) +{ + Vector2 result = { v1.x + v2.x, v1.y + v2.y }; + + return result; +} + +// Add vector and float value +RMAPI Vector2 Vector2AddValue(Vector2 v, float add) +{ + Vector2 result = { v.x + add, v.y + add }; + + return result; +} + +// Subtract two vectors (v1 - v2) +RMAPI Vector2 Vector2Subtract(Vector2 v1, Vector2 v2) +{ + Vector2 result = { v1.x - v2.x, v1.y - v2.y }; + + return result; +} + +// Subtract vector by float value +RMAPI Vector2 Vector2SubtractValue(Vector2 v, float sub) +{ + Vector2 result = { v.x - sub, v.y - sub }; + + return result; +} + +// Calculate vector length +RMAPI float Vector2Length(Vector2 v) +{ + float result = sqrtf((v.x*v.x) + (v.y*v.y)); + + return result; +} + +// Calculate vector square length +RMAPI float Vector2LengthSqr(Vector2 v) +{ + float result = (v.x*v.x) + (v.y*v.y); + + return result; +} + +// Calculate two vectors dot product +RMAPI float Vector2DotProduct(Vector2 v1, Vector2 v2) +{ + float result = (v1.x*v2.x + v1.y*v2.y); + + return result; +} + +// Calculate distance between two vectors +RMAPI float Vector2Distance(Vector2 v1, Vector2 v2) +{ + float result = sqrtf((v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y)); + + return result; +} + +// Calculate square distance between two vectors +RMAPI float Vector2DistanceSqr(Vector2 v1, Vector2 v2) +{ + float result = ((v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y)); + + return result; +} + +// Calculate angle between two vectors +// NOTE: Angle is calculated from origin point (0, 0) +RMAPI float Vector2Angle(Vector2 v1, Vector2 v2) +{ + float result = 0.0f; + + float dot = v1.x*v2.x + v1.y*v2.y; + float det = v1.x*v2.y - v1.y*v2.x; + + result = atan2f(det, dot); + + return result; +} + +// Calculate angle defined by a two vectors line +// NOTE: Parameters need to be normalized +// Current implementation should be aligned with glm::angle +RMAPI float Vector2LineAngle(Vector2 start, Vector2 end) +{ + float result = 0.0f; + + // TODO(10/9/2023): Currently angles move clockwise, determine if this is wanted behavior + result = -atan2f(end.y - start.y, end.x - start.x); + + return result; +} + +// Scale vector (multiply by value) +RMAPI Vector2 Vector2Scale(Vector2 v, float scale) +{ + Vector2 result = { v.x*scale, v.y*scale }; + + return result; +} + +// Multiply vector by vector +RMAPI Vector2 Vector2Multiply(Vector2 v1, Vector2 v2) +{ + Vector2 result = { v1.x*v2.x, v1.y*v2.y }; + + return result; +} + +// Negate vector +RMAPI Vector2 Vector2Negate(Vector2 v) +{ + Vector2 result = { -v.x, -v.y }; + + return result; +} + +// Divide vector by vector +RMAPI Vector2 Vector2Divide(Vector2 v1, Vector2 v2) +{ + Vector2 result = { v1.x/v2.x, v1.y/v2.y }; + + return result; +} + +// Normalize provided vector +RMAPI Vector2 Vector2Normalize(Vector2 v) +{ + Vector2 result = { 0 }; + float length = sqrtf((v.x*v.x) + (v.y*v.y)); + + if (length > 0) + { + float ilength = 1.0f/length; + result.x = v.x*ilength; + result.y = v.y*ilength; + } + + return result; +} + +// Transforms a Vector2 by a given Matrix +RMAPI Vector2 Vector2Transform(Vector2 v, Matrix mat) +{ + Vector2 result = { 0 }; + + float x = v.x; + float y = v.y; + float z = 0; + + result.x = mat.m0*x + mat.m4*y + mat.m8*z + mat.m12; + result.y = mat.m1*x + mat.m5*y + mat.m9*z + mat.m13; + + return result; +} + +// Calculate linear interpolation between two vectors +RMAPI Vector2 Vector2Lerp(Vector2 v1, Vector2 v2, float amount) +{ + Vector2 result = { 0 }; + + result.x = v1.x + amount*(v2.x - v1.x); + result.y = v1.y + amount*(v2.y - v1.y); + + return result; +} + +// Calculate reflected vector to normal +RMAPI Vector2 Vector2Reflect(Vector2 v, Vector2 normal) +{ + Vector2 result = { 0 }; + + float dotProduct = (v.x*normal.x + v.y*normal.y); // Dot product + + result.x = v.x - (2.0f*normal.x)*dotProduct; + result.y = v.y - (2.0f*normal.y)*dotProduct; + + return result; +} + +// Rotate vector by angle +RMAPI Vector2 Vector2Rotate(Vector2 v, float angle) +{ + Vector2 result = { 0 }; + + float cosres = cosf(angle); + float sinres = sinf(angle); + + result.x = v.x*cosres - v.y*sinres; + result.y = v.x*sinres + v.y*cosres; + + return result; +} + +// Move Vector towards target +RMAPI Vector2 Vector2MoveTowards(Vector2 v, Vector2 target, float maxDistance) +{ + Vector2 result = { 0 }; + + float dx = target.x - v.x; + float dy = target.y - v.y; + float value = (dx*dx) + (dy*dy); + + if ((value == 0) || ((maxDistance >= 0) && (value <= maxDistance*maxDistance))) return target; + + float dist = sqrtf(value); + + result.x = v.x + dx/dist*maxDistance; + result.y = v.y + dy/dist*maxDistance; + + return result; +} + +// Invert the given vector +RMAPI Vector2 Vector2Invert(Vector2 v) +{ + Vector2 result = { 1.0f/v.x, 1.0f/v.y }; + + return result; +} + +// Clamp the components of the vector between +// min and max values specified by the given vectors +RMAPI Vector2 Vector2Clamp(Vector2 v, Vector2 min, Vector2 max) +{ + Vector2 result = { 0 }; + + result.x = fminf(max.x, fmaxf(min.x, v.x)); + result.y = fminf(max.y, fmaxf(min.y, v.y)); + + return result; +} + +// Clamp the magnitude of the vector between two min and max values +RMAPI Vector2 Vector2ClampValue(Vector2 v, float min, float max) +{ + Vector2 result = v; + + float length = (v.x*v.x) + (v.y*v.y); + if (length > 0.0f) + { + length = sqrtf(length); + + if (length < min) + { + float scale = min/length; + result.x = v.x*scale; + result.y = v.y*scale; + } + else if (length > max) + { + float scale = max/length; + result.x = v.x*scale; + result.y = v.y*scale; + } + } + + return result; +} + +// Check whether two given vectors are almost equal +RMAPI int Vector2Equals(Vector2 p, Vector2 q) +{ +#if !defined(EPSILON) + #define EPSILON 0.000001f +#endif + + int result = ((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && + ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))); + + return result; +} + +//---------------------------------------------------------------------------------- +// Module Functions Definition - Vector3 math +//---------------------------------------------------------------------------------- + +// Vector with components value 0.0f +RMAPI Vector3 Vector3Zero(void) +{ + Vector3 result = { 0.0f, 0.0f, 0.0f }; + + return result; +} + +// Vector with components value 1.0f +RMAPI Vector3 Vector3One(void) +{ + Vector3 result = { 1.0f, 1.0f, 1.0f }; + + return result; +} + +// Add two vectors +RMAPI Vector3 Vector3Add(Vector3 v1, Vector3 v2) +{ + Vector3 result = { v1.x + v2.x, v1.y + v2.y, v1.z + v2.z }; + + return result; +} + +// Add vector and float value +RMAPI Vector3 Vector3AddValue(Vector3 v, float add) +{ + Vector3 result = { v.x + add, v.y + add, v.z + add }; + + return result; +} + +// Subtract two vectors +RMAPI Vector3 Vector3Subtract(Vector3 v1, Vector3 v2) +{ + Vector3 result = { v1.x - v2.x, v1.y - v2.y, v1.z - v2.z }; + + return result; +} + +// Subtract vector by float value +RMAPI Vector3 Vector3SubtractValue(Vector3 v, float sub) +{ + Vector3 result = { v.x - sub, v.y - sub, v.z - sub }; + + return result; +} + +// Multiply vector by scalar +RMAPI Vector3 Vector3Scale(Vector3 v, float scalar) +{ + Vector3 result = { v.x*scalar, v.y*scalar, v.z*scalar }; + + return result; +} + +// Multiply vector by vector +RMAPI Vector3 Vector3Multiply(Vector3 v1, Vector3 v2) +{ + Vector3 result = { v1.x*v2.x, v1.y*v2.y, v1.z*v2.z }; + + return result; +} + +// Calculate two vectors cross product +RMAPI Vector3 Vector3CrossProduct(Vector3 v1, Vector3 v2) +{ + Vector3 result = { v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x }; + + return result; +} + +// Calculate one vector perpendicular vector +RMAPI Vector3 Vector3Perpendicular(Vector3 v) +{ + Vector3 result = { 0 }; + + float min = (float) fabs(v.x); + Vector3 cardinalAxis = {1.0f, 0.0f, 0.0f}; + + if (fabsf(v.y) < min) + { + min = (float) fabs(v.y); + Vector3 tmp = {0.0f, 1.0f, 0.0f}; + cardinalAxis = tmp; + } + + if (fabsf(v.z) < min) + { + Vector3 tmp = {0.0f, 0.0f, 1.0f}; + cardinalAxis = tmp; + } + + // Cross product between vectors + result.x = v.y*cardinalAxis.z - v.z*cardinalAxis.y; + result.y = v.z*cardinalAxis.x - v.x*cardinalAxis.z; + result.z = v.x*cardinalAxis.y - v.y*cardinalAxis.x; + + return result; +} + +// Calculate vector length +RMAPI float Vector3Length(const Vector3 v) +{ + float result = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); + + return result; +} + +// Calculate vector square length +RMAPI float Vector3LengthSqr(const Vector3 v) +{ + float result = v.x*v.x + v.y*v.y + v.z*v.z; + + return result; +} + +// Calculate two vectors dot product +RMAPI float Vector3DotProduct(Vector3 v1, Vector3 v2) +{ + float result = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); + + return result; +} + +// Calculate distance between two vectors +RMAPI float Vector3Distance(Vector3 v1, Vector3 v2) +{ + float result = 0.0f; + + float dx = v2.x - v1.x; + float dy = v2.y - v1.y; + float dz = v2.z - v1.z; + result = sqrtf(dx*dx + dy*dy + dz*dz); + + return result; +} + +// Calculate square distance between two vectors +RMAPI float Vector3DistanceSqr(Vector3 v1, Vector3 v2) +{ + float result = 0.0f; + + float dx = v2.x - v1.x; + float dy = v2.y - v1.y; + float dz = v2.z - v1.z; + result = dx*dx + dy*dy + dz*dz; + + return result; +} + +// Calculate angle between two vectors +RMAPI float Vector3Angle(Vector3 v1, Vector3 v2) +{ + float result = 0.0f; + + Vector3 cross = { v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x }; + float len = sqrtf(cross.x*cross.x + cross.y*cross.y + cross.z*cross.z); + float dot = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); + result = atan2f(len, dot); + + return result; +} + +// Negate provided vector (invert direction) +RMAPI Vector3 Vector3Negate(Vector3 v) +{ + Vector3 result = { -v.x, -v.y, -v.z }; + + return result; +} + +// Divide vector by vector +RMAPI Vector3 Vector3Divide(Vector3 v1, Vector3 v2) +{ + Vector3 result = { v1.x/v2.x, v1.y/v2.y, v1.z/v2.z }; + + return result; +} + +// Normalize provided vector +RMAPI Vector3 Vector3Normalize(Vector3 v) +{ + Vector3 result = v; + + float length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); + if (length != 0.0f) + { + float ilength = 1.0f/length; + + result.x *= ilength; + result.y *= ilength; + result.z *= ilength; + } + + return result; +} + +//Calculate the projection of the vector v1 on to v2 +RMAPI Vector3 Vector3Project(Vector3 v1, Vector3 v2) +{ + Vector3 result = { 0 }; + + float v1dv2 = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); + float v2dv2 = (v2.x*v2.x + v2.y*v2.y + v2.z*v2.z); + + float mag = v1dv2/v2dv2; + + result.x = v2.x*mag; + result.y = v2.y*mag; + result.z = v2.z*mag; + + return result; +} + +//Calculate the rejection of the vector v1 on to v2 +RMAPI Vector3 Vector3Reject(Vector3 v1, Vector3 v2) +{ + Vector3 result = { 0 }; + + float v1dv2 = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); + float v2dv2 = (v2.x*v2.x + v2.y*v2.y + v2.z*v2.z); + + float mag = v1dv2/v2dv2; + + result.x = v1.x - (v2.x*mag); + result.y = v1.y - (v2.y*mag); + result.z = v1.z - (v2.z*mag); + + return result; +} + +// Orthonormalize provided vectors +// Makes vectors normalized and orthogonal to each other +// Gram-Schmidt function implementation +RMAPI void Vector3OrthoNormalize(Vector3 *v1, Vector3 *v2) +{ + float length = 0.0f; + float ilength = 0.0f; + + // Vector3Normalize(*v1); + Vector3 v = *v1; + length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); + if (length == 0.0f) length = 1.0f; + ilength = 1.0f/length; + v1->x *= ilength; + v1->y *= ilength; + v1->z *= ilength; + + // Vector3CrossProduct(*v1, *v2) + Vector3 vn1 = { v1->y*v2->z - v1->z*v2->y, v1->z*v2->x - v1->x*v2->z, v1->x*v2->y - v1->y*v2->x }; + + // Vector3Normalize(vn1); + v = vn1; + length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); + if (length == 0.0f) length = 1.0f; + ilength = 1.0f/length; + vn1.x *= ilength; + vn1.y *= ilength; + vn1.z *= ilength; + + // Vector3CrossProduct(vn1, *v1) + Vector3 vn2 = { vn1.y*v1->z - vn1.z*v1->y, vn1.z*v1->x - vn1.x*v1->z, vn1.x*v1->y - vn1.y*v1->x }; + + *v2 = vn2; +} + +// Transforms a Vector3 by a given Matrix +RMAPI Vector3 Vector3Transform(Vector3 v, Matrix mat) +{ + Vector3 result = { 0 }; + + float x = v.x; + float y = v.y; + float z = v.z; + + result.x = mat.m0*x + mat.m4*y + mat.m8*z + mat.m12; + result.y = mat.m1*x + mat.m5*y + mat.m9*z + mat.m13; + result.z = mat.m2*x + mat.m6*y + mat.m10*z + mat.m14; + + return result; +} + +// Transform a vector by quaternion rotation +RMAPI Vector3 Vector3RotateByQuaternion(Vector3 v, Quaternion q) +{ + Vector3 result = { 0 }; + + result.x = v.x*(q.x*q.x + q.w*q.w - q.y*q.y - q.z*q.z) + v.y*(2*q.x*q.y - 2*q.w*q.z) + v.z*(2*q.x*q.z + 2*q.w*q.y); + result.y = v.x*(2*q.w*q.z + 2*q.x*q.y) + v.y*(q.w*q.w - q.x*q.x + q.y*q.y - q.z*q.z) + v.z*(-2*q.w*q.x + 2*q.y*q.z); + result.z = v.x*(-2*q.w*q.y + 2*q.x*q.z) + v.y*(2*q.w*q.x + 2*q.y*q.z)+ v.z*(q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z); + + return result; +} + +// Rotates a vector around an axis +RMAPI Vector3 Vector3RotateByAxisAngle(Vector3 v, Vector3 axis, float angle) +{ + // Using Euler-Rodrigues Formula + // Ref.: https://en.wikipedia.org/w/index.php?title=Euler%E2%80%93Rodrigues_formula + + Vector3 result = v; + + // Vector3Normalize(axis); + float length = sqrtf(axis.x*axis.x + axis.y*axis.y + axis.z*axis.z); + if (length == 0.0f) length = 1.0f; + float ilength = 1.0f / length; + axis.x *= ilength; + axis.y *= ilength; + axis.z *= ilength; + + angle /= 2.0f; + float a = sinf(angle); + float b = axis.x*a; + float c = axis.y*a; + float d = axis.z*a; + a = cosf(angle); + Vector3 w = { b, c, d }; + + // Vector3CrossProduct(w, v) + Vector3 wv = { w.y*v.z - w.z*v.y, w.z*v.x - w.x*v.z, w.x*v.y - w.y*v.x }; + + // Vector3CrossProduct(w, wv) + Vector3 wwv = { w.y*wv.z - w.z*wv.y, w.z*wv.x - w.x*wv.z, w.x*wv.y - w.y*wv.x }; + + // Vector3Scale(wv, 2*a) + a *= 2; + wv.x *= a; + wv.y *= a; + wv.z *= a; + + // Vector3Scale(wwv, 2) + wwv.x *= 2; + wwv.y *= 2; + wwv.z *= 2; + + result.x += wv.x; + result.y += wv.y; + result.z += wv.z; + + result.x += wwv.x; + result.y += wwv.y; + result.z += wwv.z; + + return result; +} + +// Calculate linear interpolation between two vectors +RMAPI Vector3 Vector3Lerp(Vector3 v1, Vector3 v2, float amount) +{ + Vector3 result = { 0 }; + + result.x = v1.x + amount*(v2.x - v1.x); + result.y = v1.y + amount*(v2.y - v1.y); + result.z = v1.z + amount*(v2.z - v1.z); + + return result; +} + +// Calculate reflected vector to normal +RMAPI Vector3 Vector3Reflect(Vector3 v, Vector3 normal) +{ + Vector3 result = { 0 }; + + // I is the original vector + // N is the normal of the incident plane + // R = I - (2*N*(DotProduct[I, N])) + + float dotProduct = (v.x*normal.x + v.y*normal.y + v.z*normal.z); + + result.x = v.x - (2.0f*normal.x)*dotProduct; + result.y = v.y - (2.0f*normal.y)*dotProduct; + result.z = v.z - (2.0f*normal.z)*dotProduct; + + return result; +} + +// Get min value for each pair of components +RMAPI Vector3 Vector3Min(Vector3 v1, Vector3 v2) +{ + Vector3 result = { 0 }; + + result.x = fminf(v1.x, v2.x); + result.y = fminf(v1.y, v2.y); + result.z = fminf(v1.z, v2.z); + + return result; +} + +// Get max value for each pair of components +RMAPI Vector3 Vector3Max(Vector3 v1, Vector3 v2) +{ + Vector3 result = { 0 }; + + result.x = fmaxf(v1.x, v2.x); + result.y = fmaxf(v1.y, v2.y); + result.z = fmaxf(v1.z, v2.z); + + return result; +} + +// Compute barycenter coordinates (u, v, w) for point p with respect to triangle (a, b, c) +// NOTE: Assumes P is on the plane of the triangle +RMAPI Vector3 Vector3Barycenter(Vector3 p, Vector3 a, Vector3 b, Vector3 c) +{ + Vector3 result = { 0 }; + + Vector3 v0 = { b.x - a.x, b.y - a.y, b.z - a.z }; // Vector3Subtract(b, a) + Vector3 v1 = { c.x - a.x, c.y - a.y, c.z - a.z }; // Vector3Subtract(c, a) + Vector3 v2 = { p.x - a.x, p.y - a.y, p.z - a.z }; // Vector3Subtract(p, a) + float d00 = (v0.x*v0.x + v0.y*v0.y + v0.z*v0.z); // Vector3DotProduct(v0, v0) + float d01 = (v0.x*v1.x + v0.y*v1.y + v0.z*v1.z); // Vector3DotProduct(v0, v1) + float d11 = (v1.x*v1.x + v1.y*v1.y + v1.z*v1.z); // Vector3DotProduct(v1, v1) + float d20 = (v2.x*v0.x + v2.y*v0.y + v2.z*v0.z); // Vector3DotProduct(v2, v0) + float d21 = (v2.x*v1.x + v2.y*v1.y + v2.z*v1.z); // Vector3DotProduct(v2, v1) + + float denom = d00*d11 - d01*d01; + + result.y = (d11*d20 - d01*d21)/denom; + result.z = (d00*d21 - d01*d20)/denom; + result.x = 1.0f - (result.z + result.y); + + return result; +} + +// Projects a Vector3 from screen space into object space +// NOTE: We are avoiding calling other raymath functions despite available +RMAPI Vector3 Vector3Unproject(Vector3 source, Matrix projection, Matrix view) +{ + Vector3 result = { 0 }; + + // Calculate unprojected matrix (multiply view matrix by projection matrix) and invert it + Matrix matViewProj = { // MatrixMultiply(view, projection); + view.m0*projection.m0 + view.m1*projection.m4 + view.m2*projection.m8 + view.m3*projection.m12, + view.m0*projection.m1 + view.m1*projection.m5 + view.m2*projection.m9 + view.m3*projection.m13, + view.m0*projection.m2 + view.m1*projection.m6 + view.m2*projection.m10 + view.m3*projection.m14, + view.m0*projection.m3 + view.m1*projection.m7 + view.m2*projection.m11 + view.m3*projection.m15, + view.m4*projection.m0 + view.m5*projection.m4 + view.m6*projection.m8 + view.m7*projection.m12, + view.m4*projection.m1 + view.m5*projection.m5 + view.m6*projection.m9 + view.m7*projection.m13, + view.m4*projection.m2 + view.m5*projection.m6 + view.m6*projection.m10 + view.m7*projection.m14, + view.m4*projection.m3 + view.m5*projection.m7 + view.m6*projection.m11 + view.m7*projection.m15, + view.m8*projection.m0 + view.m9*projection.m4 + view.m10*projection.m8 + view.m11*projection.m12, + view.m8*projection.m1 + view.m9*projection.m5 + view.m10*projection.m9 + view.m11*projection.m13, + view.m8*projection.m2 + view.m9*projection.m6 + view.m10*projection.m10 + view.m11*projection.m14, + view.m8*projection.m3 + view.m9*projection.m7 + view.m10*projection.m11 + view.m11*projection.m15, + view.m12*projection.m0 + view.m13*projection.m4 + view.m14*projection.m8 + view.m15*projection.m12, + view.m12*projection.m1 + view.m13*projection.m5 + view.m14*projection.m9 + view.m15*projection.m13, + view.m12*projection.m2 + view.m13*projection.m6 + view.m14*projection.m10 + view.m15*projection.m14, + view.m12*projection.m3 + view.m13*projection.m7 + view.m14*projection.m11 + view.m15*projection.m15 }; + + // Calculate inverted matrix -> MatrixInvert(matViewProj); + // Cache the matrix values (speed optimization) + float a00 = matViewProj.m0, a01 = matViewProj.m1, a02 = matViewProj.m2, a03 = matViewProj.m3; + float a10 = matViewProj.m4, a11 = matViewProj.m5, a12 = matViewProj.m6, a13 = matViewProj.m7; + float a20 = matViewProj.m8, a21 = matViewProj.m9, a22 = matViewProj.m10, a23 = matViewProj.m11; + float a30 = matViewProj.m12, a31 = matViewProj.m13, a32 = matViewProj.m14, a33 = matViewProj.m15; + + float b00 = a00*a11 - a01*a10; + float b01 = a00*a12 - a02*a10; + float b02 = a00*a13 - a03*a10; + float b03 = a01*a12 - a02*a11; + float b04 = a01*a13 - a03*a11; + float b05 = a02*a13 - a03*a12; + float b06 = a20*a31 - a21*a30; + float b07 = a20*a32 - a22*a30; + float b08 = a20*a33 - a23*a30; + float b09 = a21*a32 - a22*a31; + float b10 = a21*a33 - a23*a31; + float b11 = a22*a33 - a23*a32; + + // Calculate the invert determinant (inlined to avoid double-caching) + float invDet = 1.0f/(b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06); + + Matrix matViewProjInv = { + (a11*b11 - a12*b10 + a13*b09)*invDet, + (-a01*b11 + a02*b10 - a03*b09)*invDet, + (a31*b05 - a32*b04 + a33*b03)*invDet, + (-a21*b05 + a22*b04 - a23*b03)*invDet, + (-a10*b11 + a12*b08 - a13*b07)*invDet, + (a00*b11 - a02*b08 + a03*b07)*invDet, + (-a30*b05 + a32*b02 - a33*b01)*invDet, + (a20*b05 - a22*b02 + a23*b01)*invDet, + (a10*b10 - a11*b08 + a13*b06)*invDet, + (-a00*b10 + a01*b08 - a03*b06)*invDet, + (a30*b04 - a31*b02 + a33*b00)*invDet, + (-a20*b04 + a21*b02 - a23*b00)*invDet, + (-a10*b09 + a11*b07 - a12*b06)*invDet, + (a00*b09 - a01*b07 + a02*b06)*invDet, + (-a30*b03 + a31*b01 - a32*b00)*invDet, + (a20*b03 - a21*b01 + a22*b00)*invDet }; + + // Create quaternion from source point + Quaternion quat = { source.x, source.y, source.z, 1.0f }; + + // Multiply quat point by unprojecte matrix + Quaternion qtransformed = { // QuaternionTransform(quat, matViewProjInv) + matViewProjInv.m0*quat.x + matViewProjInv.m4*quat.y + matViewProjInv.m8*quat.z + matViewProjInv.m12*quat.w, + matViewProjInv.m1*quat.x + matViewProjInv.m5*quat.y + matViewProjInv.m9*quat.z + matViewProjInv.m13*quat.w, + matViewProjInv.m2*quat.x + matViewProjInv.m6*quat.y + matViewProjInv.m10*quat.z + matViewProjInv.m14*quat.w, + matViewProjInv.m3*quat.x + matViewProjInv.m7*quat.y + matViewProjInv.m11*quat.z + matViewProjInv.m15*quat.w }; + + // Normalized world points in vectors + result.x = qtransformed.x/qtransformed.w; + result.y = qtransformed.y/qtransformed.w; + result.z = qtransformed.z/qtransformed.w; + + return result; +} + +// Get Vector3 as float array +RMAPI float3 Vector3ToFloatV(Vector3 v) +{ + float3 buffer = { 0 }; + + buffer.v[0] = v.x; + buffer.v[1] = v.y; + buffer.v[2] = v.z; + + return buffer; +} + +// Invert the given vector +RMAPI Vector3 Vector3Invert(Vector3 v) +{ + Vector3 result = { 1.0f/v.x, 1.0f/v.y, 1.0f/v.z }; + + return result; +} + +// Clamp the components of the vector between +// min and max values specified by the given vectors +RMAPI Vector3 Vector3Clamp(Vector3 v, Vector3 min, Vector3 max) +{ + Vector3 result = { 0 }; + + result.x = fminf(max.x, fmaxf(min.x, v.x)); + result.y = fminf(max.y, fmaxf(min.y, v.y)); + result.z = fminf(max.z, fmaxf(min.z, v.z)); + + return result; +} + +// Clamp the magnitude of the vector between two values +RMAPI Vector3 Vector3ClampValue(Vector3 v, float min, float max) +{ + Vector3 result = v; + + float length = (v.x*v.x) + (v.y*v.y) + (v.z*v.z); + if (length > 0.0f) + { + length = sqrtf(length); + + if (length < min) + { + float scale = min/length; + result.x = v.x*scale; + result.y = v.y*scale; + result.z = v.z*scale; + } + else if (length > max) + { + float scale = max/length; + result.x = v.x*scale; + result.y = v.y*scale; + result.z = v.z*scale; + } + } + + return result; +} + +// Check whether two given vectors are almost equal +RMAPI int Vector3Equals(Vector3 p, Vector3 q) +{ +#if !defined(EPSILON) + #define EPSILON 0.000001f +#endif + + int result = ((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && + ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && + ((fabsf(p.z - q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))); + + return result; +} + +// Compute the direction of a refracted ray +// v: normalized direction of the incoming ray +// n: normalized normal vector of the interface of two optical media +// r: ratio of the refractive index of the medium from where the ray comes +// to the refractive index of the medium on the other side of the surface +RMAPI Vector3 Vector3Refract(Vector3 v, Vector3 n, float r) +{ + Vector3 result = { 0 }; + + float dot = v.x*n.x + v.y*n.y + v.z*n.z; + float d = 1.0f - r*r*(1.0f - dot*dot); + + if (d >= 0.0f) + { + d = sqrtf(d); + v.x = r*v.x - (r*dot + d)*n.x; + v.y = r*v.y - (r*dot + d)*n.y; + v.z = r*v.z - (r*dot + d)*n.z; + + result = v; + } + + return result; +} + +//---------------------------------------------------------------------------------- +// Module Functions Definition - Matrix math +//---------------------------------------------------------------------------------- + +// Compute matrix determinant +RMAPI float MatrixDeterminant(Matrix mat) +{ + float result = 0.0f; + + // Cache the matrix values (speed optimization) + float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; + float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; + float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; + float a30 = mat.m12, a31 = mat.m13, a32 = mat.m14, a33 = mat.m15; + + result = a30*a21*a12*a03 - a20*a31*a12*a03 - a30*a11*a22*a03 + a10*a31*a22*a03 + + a20*a11*a32*a03 - a10*a21*a32*a03 - a30*a21*a02*a13 + a20*a31*a02*a13 + + a30*a01*a22*a13 - a00*a31*a22*a13 - a20*a01*a32*a13 + a00*a21*a32*a13 + + a30*a11*a02*a23 - a10*a31*a02*a23 - a30*a01*a12*a23 + a00*a31*a12*a23 + + a10*a01*a32*a23 - a00*a11*a32*a23 - a20*a11*a02*a33 + a10*a21*a02*a33 + + a20*a01*a12*a33 - a00*a21*a12*a33 - a10*a01*a22*a33 + a00*a11*a22*a33; + + return result; +} + +// Get the trace of the matrix (sum of the values along the diagonal) +RMAPI float MatrixTrace(Matrix mat) +{ + float result = (mat.m0 + mat.m5 + mat.m10 + mat.m15); + + return result; +} + +// Transposes provided matrix +RMAPI Matrix MatrixTranspose(Matrix mat) +{ + Matrix result = { 0 }; + + result.m0 = mat.m0; + result.m1 = mat.m4; + result.m2 = mat.m8; + result.m3 = mat.m12; + result.m4 = mat.m1; + result.m5 = mat.m5; + result.m6 = mat.m9; + result.m7 = mat.m13; + result.m8 = mat.m2; + result.m9 = mat.m6; + result.m10 = mat.m10; + result.m11 = mat.m14; + result.m12 = mat.m3; + result.m13 = mat.m7; + result.m14 = mat.m11; + result.m15 = mat.m15; + + return result; +} + +// Invert provided matrix +RMAPI Matrix MatrixInvert(Matrix mat) +{ + Matrix result = { 0 }; + + // Cache the matrix values (speed optimization) + float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; + float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; + float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; + float a30 = mat.m12, a31 = mat.m13, a32 = mat.m14, a33 = mat.m15; + + float b00 = a00*a11 - a01*a10; + float b01 = a00*a12 - a02*a10; + float b02 = a00*a13 - a03*a10; + float b03 = a01*a12 - a02*a11; + float b04 = a01*a13 - a03*a11; + float b05 = a02*a13 - a03*a12; + float b06 = a20*a31 - a21*a30; + float b07 = a20*a32 - a22*a30; + float b08 = a20*a33 - a23*a30; + float b09 = a21*a32 - a22*a31; + float b10 = a21*a33 - a23*a31; + float b11 = a22*a33 - a23*a32; + + // Calculate the invert determinant (inlined to avoid double-caching) + float invDet = 1.0f/(b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06); + + result.m0 = (a11*b11 - a12*b10 + a13*b09)*invDet; + result.m1 = (-a01*b11 + a02*b10 - a03*b09)*invDet; + result.m2 = (a31*b05 - a32*b04 + a33*b03)*invDet; + result.m3 = (-a21*b05 + a22*b04 - a23*b03)*invDet; + result.m4 = (-a10*b11 + a12*b08 - a13*b07)*invDet; + result.m5 = (a00*b11 - a02*b08 + a03*b07)*invDet; + result.m6 = (-a30*b05 + a32*b02 - a33*b01)*invDet; + result.m7 = (a20*b05 - a22*b02 + a23*b01)*invDet; + result.m8 = (a10*b10 - a11*b08 + a13*b06)*invDet; + result.m9 = (-a00*b10 + a01*b08 - a03*b06)*invDet; + result.m10 = (a30*b04 - a31*b02 + a33*b00)*invDet; + result.m11 = (-a20*b04 + a21*b02 - a23*b00)*invDet; + result.m12 = (-a10*b09 + a11*b07 - a12*b06)*invDet; + result.m13 = (a00*b09 - a01*b07 + a02*b06)*invDet; + result.m14 = (-a30*b03 + a31*b01 - a32*b00)*invDet; + result.m15 = (a20*b03 - a21*b01 + a22*b00)*invDet; + + return result; +} + +// Get identity matrix +RMAPI Matrix MatrixIdentity(void) +{ + Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f }; + + return result; +} + +// Add two matrices +RMAPI Matrix MatrixAdd(Matrix left, Matrix right) +{ + Matrix result = { 0 }; + + result.m0 = left.m0 + right.m0; + result.m1 = left.m1 + right.m1; + result.m2 = left.m2 + right.m2; + result.m3 = left.m3 + right.m3; + result.m4 = left.m4 + right.m4; + result.m5 = left.m5 + right.m5; + result.m6 = left.m6 + right.m6; + result.m7 = left.m7 + right.m7; + result.m8 = left.m8 + right.m8; + result.m9 = left.m9 + right.m9; + result.m10 = left.m10 + right.m10; + result.m11 = left.m11 + right.m11; + result.m12 = left.m12 + right.m12; + result.m13 = left.m13 + right.m13; + result.m14 = left.m14 + right.m14; + result.m15 = left.m15 + right.m15; + + return result; +} + +// Subtract two matrices (left - right) +RMAPI Matrix MatrixSubtract(Matrix left, Matrix right) +{ + Matrix result = { 0 }; + + result.m0 = left.m0 - right.m0; + result.m1 = left.m1 - right.m1; + result.m2 = left.m2 - right.m2; + result.m3 = left.m3 - right.m3; + result.m4 = left.m4 - right.m4; + result.m5 = left.m5 - right.m5; + result.m6 = left.m6 - right.m6; + result.m7 = left.m7 - right.m7; + result.m8 = left.m8 - right.m8; + result.m9 = left.m9 - right.m9; + result.m10 = left.m10 - right.m10; + result.m11 = left.m11 - right.m11; + result.m12 = left.m12 - right.m12; + result.m13 = left.m13 - right.m13; + result.m14 = left.m14 - right.m14; + result.m15 = left.m15 - right.m15; + + return result; +} + +// Get two matrix multiplication +// NOTE: When multiplying matrices... the order matters! +RMAPI Matrix MatrixMultiply(Matrix left, Matrix right) +{ + Matrix result = { 0 }; + + result.m0 = left.m0*right.m0 + left.m1*right.m4 + left.m2*right.m8 + left.m3*right.m12; + result.m1 = left.m0*right.m1 + left.m1*right.m5 + left.m2*right.m9 + left.m3*right.m13; + result.m2 = left.m0*right.m2 + left.m1*right.m6 + left.m2*right.m10 + left.m3*right.m14; + result.m3 = left.m0*right.m3 + left.m1*right.m7 + left.m2*right.m11 + left.m3*right.m15; + result.m4 = left.m4*right.m0 + left.m5*right.m4 + left.m6*right.m8 + left.m7*right.m12; + result.m5 = left.m4*right.m1 + left.m5*right.m5 + left.m6*right.m9 + left.m7*right.m13; + result.m6 = left.m4*right.m2 + left.m5*right.m6 + left.m6*right.m10 + left.m7*right.m14; + result.m7 = left.m4*right.m3 + left.m5*right.m7 + left.m6*right.m11 + left.m7*right.m15; + result.m8 = left.m8*right.m0 + left.m9*right.m4 + left.m10*right.m8 + left.m11*right.m12; + result.m9 = left.m8*right.m1 + left.m9*right.m5 + left.m10*right.m9 + left.m11*right.m13; + result.m10 = left.m8*right.m2 + left.m9*right.m6 + left.m10*right.m10 + left.m11*right.m14; + result.m11 = left.m8*right.m3 + left.m9*right.m7 + left.m10*right.m11 + left.m11*right.m15; + result.m12 = left.m12*right.m0 + left.m13*right.m4 + left.m14*right.m8 + left.m15*right.m12; + result.m13 = left.m12*right.m1 + left.m13*right.m5 + left.m14*right.m9 + left.m15*right.m13; + result.m14 = left.m12*right.m2 + left.m13*right.m6 + left.m14*right.m10 + left.m15*right.m14; + result.m15 = left.m12*right.m3 + left.m13*right.m7 + left.m14*right.m11 + left.m15*right.m15; + + return result; +} + +// Get translation matrix +RMAPI Matrix MatrixTranslate(float x, float y, float z) +{ + Matrix result = { 1.0f, 0.0f, 0.0f, x, + 0.0f, 1.0f, 0.0f, y, + 0.0f, 0.0f, 1.0f, z, + 0.0f, 0.0f, 0.0f, 1.0f }; + + return result; +} + +// Create rotation matrix from axis and angle +// NOTE: Angle should be provided in radians +RMAPI Matrix MatrixRotate(Vector3 axis, float angle) +{ + Matrix result = { 0 }; + + float x = axis.x, y = axis.y, z = axis.z; + + float lengthSquared = x*x + y*y + z*z; + + if ((lengthSquared != 1.0f) && (lengthSquared != 0.0f)) + { + float ilength = 1.0f/sqrtf(lengthSquared); + x *= ilength; + y *= ilength; + z *= ilength; + } + + float sinres = sinf(angle); + float cosres = cosf(angle); + float t = 1.0f - cosres; + + result.m0 = x*x*t + cosres; + result.m1 = y*x*t + z*sinres; + result.m2 = z*x*t - y*sinres; + result.m3 = 0.0f; + + result.m4 = x*y*t - z*sinres; + result.m5 = y*y*t + cosres; + result.m6 = z*y*t + x*sinres; + result.m7 = 0.0f; + + result.m8 = x*z*t + y*sinres; + result.m9 = y*z*t - x*sinres; + result.m10 = z*z*t + cosres; + result.m11 = 0.0f; + + result.m12 = 0.0f; + result.m13 = 0.0f; + result.m14 = 0.0f; + result.m15 = 1.0f; + + return result; +} + +// Get x-rotation matrix +// NOTE: Angle must be provided in radians +RMAPI Matrix MatrixRotateX(float angle) +{ + Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() + + float cosres = cosf(angle); + float sinres = sinf(angle); + + result.m5 = cosres; + result.m6 = sinres; + result.m9 = -sinres; + result.m10 = cosres; + + return result; +} + +// Get y-rotation matrix +// NOTE: Angle must be provided in radians +RMAPI Matrix MatrixRotateY(float angle) +{ + Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() + + float cosres = cosf(angle); + float sinres = sinf(angle); + + result.m0 = cosres; + result.m2 = -sinres; + result.m8 = sinres; + result.m10 = cosres; + + return result; +} + +// Get z-rotation matrix +// NOTE: Angle must be provided in radians +RMAPI Matrix MatrixRotateZ(float angle) +{ + Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() + + float cosres = cosf(angle); + float sinres = sinf(angle); + + result.m0 = cosres; + result.m1 = sinres; + result.m4 = -sinres; + result.m5 = cosres; + + return result; +} + + +// Get xyz-rotation matrix +// NOTE: Angle must be provided in radians +RMAPI Matrix MatrixRotateXYZ(Vector3 angle) +{ + Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() + + float cosz = cosf(-angle.z); + float sinz = sinf(-angle.z); + float cosy = cosf(-angle.y); + float siny = sinf(-angle.y); + float cosx = cosf(-angle.x); + float sinx = sinf(-angle.x); + + result.m0 = cosz*cosy; + result.m1 = (cosz*siny*sinx) - (sinz*cosx); + result.m2 = (cosz*siny*cosx) + (sinz*sinx); + + result.m4 = sinz*cosy; + result.m5 = (sinz*siny*sinx) + (cosz*cosx); + result.m6 = (sinz*siny*cosx) - (cosz*sinx); + + result.m8 = -siny; + result.m9 = cosy*sinx; + result.m10= cosy*cosx; + + return result; +} + +// Get zyx-rotation matrix +// NOTE: Angle must be provided in radians +RMAPI Matrix MatrixRotateZYX(Vector3 angle) +{ + Matrix result = { 0 }; + + float cz = cosf(angle.z); + float sz = sinf(angle.z); + float cy = cosf(angle.y); + float sy = sinf(angle.y); + float cx = cosf(angle.x); + float sx = sinf(angle.x); + + result.m0 = cz*cy; + result.m4 = cz*sy*sx - cx*sz; + result.m8 = sz*sx + cz*cx*sy; + result.m12 = 0; + + result.m1 = cy*sz; + result.m5 = cz*cx + sz*sy*sx; + result.m9 = cx*sz*sy - cz*sx; + result.m13 = 0; + + result.m2 = -sy; + result.m6 = cy*sx; + result.m10 = cy*cx; + result.m14 = 0; + + result.m3 = 0; + result.m7 = 0; + result.m11 = 0; + result.m15 = 1; + + return result; +} + +// Get scaling matrix +RMAPI Matrix MatrixScale(float x, float y, float z) +{ + Matrix result = { x, 0.0f, 0.0f, 0.0f, + 0.0f, y, 0.0f, 0.0f, + 0.0f, 0.0f, z, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f }; + + return result; +} + +// Get perspective projection matrix +RMAPI Matrix MatrixFrustum(double left, double right, double bottom, double top, double near, double far) +{ + Matrix result = { 0 }; + + float rl = (float)(right - left); + float tb = (float)(top - bottom); + float fn = (float)(far - near); + + result.m0 = ((float)near*2.0f)/rl; + result.m1 = 0.0f; + result.m2 = 0.0f; + result.m3 = 0.0f; + + result.m4 = 0.0f; + result.m5 = ((float)near*2.0f)/tb; + result.m6 = 0.0f; + result.m7 = 0.0f; + + result.m8 = ((float)right + (float)left)/rl; + result.m9 = ((float)top + (float)bottom)/tb; + result.m10 = -((float)far + (float)near)/fn; + result.m11 = -1.0f; + + result.m12 = 0.0f; + result.m13 = 0.0f; + result.m14 = -((float)far*(float)near*2.0f)/fn; + result.m15 = 0.0f; + + return result; +} + +// Get perspective projection matrix +// NOTE: Fovy angle must be provided in radians +RMAPI Matrix MatrixPerspective(double fovY, double aspect, double nearPlane, double farPlane) +{ + Matrix result = { 0 }; + + double top = nearPlane*tan(fovY*0.5); + double bottom = -top; + double right = top*aspect; + double left = -right; + + // MatrixFrustum(-right, right, -top, top, near, far); + float rl = (float)(right - left); + float tb = (float)(top - bottom); + float fn = (float)(farPlane - nearPlane); + + result.m0 = ((float)nearPlane*2.0f)/rl; + result.m5 = ((float)nearPlane*2.0f)/tb; + result.m8 = ((float)right + (float)left)/rl; + result.m9 = ((float)top + (float)bottom)/tb; + result.m10 = -((float)farPlane + (float)nearPlane)/fn; + result.m11 = -1.0f; + result.m14 = -((float)farPlane*(float)nearPlane*2.0f)/fn; + + return result; +} + +// Get orthographic projection matrix +RMAPI Matrix MatrixOrtho(double left, double right, double bottom, double top, double nearPlane, double farPlane) +{ + Matrix result = { 0 }; + + float rl = (float)(right - left); + float tb = (float)(top - bottom); + float fn = (float)(farPlane - nearPlane); + + result.m0 = 2.0f/rl; + result.m1 = 0.0f; + result.m2 = 0.0f; + result.m3 = 0.0f; + result.m4 = 0.0f; + result.m5 = 2.0f/tb; + result.m6 = 0.0f; + result.m7 = 0.0f; + result.m8 = 0.0f; + result.m9 = 0.0f; + result.m10 = -2.0f/fn; + result.m11 = 0.0f; + result.m12 = -((float)left + (float)right)/rl; + result.m13 = -((float)top + (float)bottom)/tb; + result.m14 = -((float)farPlane + (float)nearPlane)/fn; + result.m15 = 1.0f; + + return result; +} + +// Get camera look-at matrix (view matrix) +RMAPI Matrix MatrixLookAt(Vector3 eye, Vector3 target, Vector3 up) +{ + Matrix result = { 0 }; + + float length = 0.0f; + float ilength = 0.0f; + + // Vector3Subtract(eye, target) + Vector3 vz = { eye.x - target.x, eye.y - target.y, eye.z - target.z }; + + // Vector3Normalize(vz) + Vector3 v = vz; + length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); + if (length == 0.0f) length = 1.0f; + ilength = 1.0f/length; + vz.x *= ilength; + vz.y *= ilength; + vz.z *= ilength; + + // Vector3CrossProduct(up, vz) + Vector3 vx = { up.y*vz.z - up.z*vz.y, up.z*vz.x - up.x*vz.z, up.x*vz.y - up.y*vz.x }; + + // Vector3Normalize(x) + v = vx; + length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); + if (length == 0.0f) length = 1.0f; + ilength = 1.0f/length; + vx.x *= ilength; + vx.y *= ilength; + vx.z *= ilength; + + // Vector3CrossProduct(vz, vx) + Vector3 vy = { vz.y*vx.z - vz.z*vx.y, vz.z*vx.x - vz.x*vx.z, vz.x*vx.y - vz.y*vx.x }; + + result.m0 = vx.x; + result.m1 = vy.x; + result.m2 = vz.x; + result.m3 = 0.0f; + result.m4 = vx.y; + result.m5 = vy.y; + result.m6 = vz.y; + result.m7 = 0.0f; + result.m8 = vx.z; + result.m9 = vy.z; + result.m10 = vz.z; + result.m11 = 0.0f; + result.m12 = -(vx.x*eye.x + vx.y*eye.y + vx.z*eye.z); // Vector3DotProduct(vx, eye) + result.m13 = -(vy.x*eye.x + vy.y*eye.y + vy.z*eye.z); // Vector3DotProduct(vy, eye) + result.m14 = -(vz.x*eye.x + vz.y*eye.y + vz.z*eye.z); // Vector3DotProduct(vz, eye) + result.m15 = 1.0f; + + return result; +} + +// Get float array of matrix data +RMAPI float16 MatrixToFloatV(Matrix mat) +{ + float16 result = { 0 }; + + result.v[0] = mat.m0; + result.v[1] = mat.m1; + result.v[2] = mat.m2; + result.v[3] = mat.m3; + result.v[4] = mat.m4; + result.v[5] = mat.m5; + result.v[6] = mat.m6; + result.v[7] = mat.m7; + result.v[8] = mat.m8; + result.v[9] = mat.m9; + result.v[10] = mat.m10; + result.v[11] = mat.m11; + result.v[12] = mat.m12; + result.v[13] = mat.m13; + result.v[14] = mat.m14; + result.v[15] = mat.m15; + + return result; +} + +//---------------------------------------------------------------------------------- +// Module Functions Definition - Quaternion math +//---------------------------------------------------------------------------------- + +// Add two quaternions +RMAPI Quaternion QuaternionAdd(Quaternion q1, Quaternion q2) +{ + Quaternion result = {q1.x + q2.x, q1.y + q2.y, q1.z + q2.z, q1.w + q2.w}; + + return result; +} + +// Add quaternion and float value +RMAPI Quaternion QuaternionAddValue(Quaternion q, float add) +{ + Quaternion result = {q.x + add, q.y + add, q.z + add, q.w + add}; + + return result; +} + +// Subtract two quaternions +RMAPI Quaternion QuaternionSubtract(Quaternion q1, Quaternion q2) +{ + Quaternion result = {q1.x - q2.x, q1.y - q2.y, q1.z - q2.z, q1.w - q2.w}; + + return result; +} + +// Subtract quaternion and float value +RMAPI Quaternion QuaternionSubtractValue(Quaternion q, float sub) +{ + Quaternion result = {q.x - sub, q.y - sub, q.z - sub, q.w - sub}; + + return result; +} + +// Get identity quaternion +RMAPI Quaternion QuaternionIdentity(void) +{ + Quaternion result = { 0.0f, 0.0f, 0.0f, 1.0f }; + + return result; +} + +// Computes the length of a quaternion +RMAPI float QuaternionLength(Quaternion q) +{ + float result = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); + + return result; +} + +// Normalize provided quaternion +RMAPI Quaternion QuaternionNormalize(Quaternion q) +{ + Quaternion result = { 0 }; + + float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); + if (length == 0.0f) length = 1.0f; + float ilength = 1.0f/length; + + result.x = q.x*ilength; + result.y = q.y*ilength; + result.z = q.z*ilength; + result.w = q.w*ilength; + + return result; +} + +// Invert provided quaternion +RMAPI Quaternion QuaternionInvert(Quaternion q) +{ + Quaternion result = q; + + float lengthSq = q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w; + + if (lengthSq != 0.0f) + { + float invLength = 1.0f/lengthSq; + + result.x *= -invLength; + result.y *= -invLength; + result.z *= -invLength; + result.w *= invLength; + } + + return result; +} + +// Calculate two quaternion multiplication +RMAPI Quaternion QuaternionMultiply(Quaternion q1, Quaternion q2) +{ + Quaternion result = { 0 }; + + float qax = q1.x, qay = q1.y, qaz = q1.z, qaw = q1.w; + float qbx = q2.x, qby = q2.y, qbz = q2.z, qbw = q2.w; + + result.x = qax*qbw + qaw*qbx + qay*qbz - qaz*qby; + result.y = qay*qbw + qaw*qby + qaz*qbx - qax*qbz; + result.z = qaz*qbw + qaw*qbz + qax*qby - qay*qbx; + result.w = qaw*qbw - qax*qbx - qay*qby - qaz*qbz; + + return result; +} + +// Scale quaternion by float value +RMAPI Quaternion QuaternionScale(Quaternion q, float mul) +{ + Quaternion result = { 0 }; + + result.x = q.x*mul; + result.y = q.y*mul; + result.z = q.z*mul; + result.w = q.w*mul; + + return result; +} + +// Divide two quaternions +RMAPI Quaternion QuaternionDivide(Quaternion q1, Quaternion q2) +{ + Quaternion result = { q1.x/q2.x, q1.y/q2.y, q1.z/q2.z, q1.w/q2.w }; + + return result; +} + +// Calculate linear interpolation between two quaternions +RMAPI Quaternion QuaternionLerp(Quaternion q1, Quaternion q2, float amount) +{ + Quaternion result = { 0 }; + + result.x = q1.x + amount*(q2.x - q1.x); + result.y = q1.y + amount*(q2.y - q1.y); + result.z = q1.z + amount*(q2.z - q1.z); + result.w = q1.w + amount*(q2.w - q1.w); + + return result; +} + +// Calculate slerp-optimized interpolation between two quaternions +RMAPI Quaternion QuaternionNlerp(Quaternion q1, Quaternion q2, float amount) +{ + Quaternion result = { 0 }; + + // QuaternionLerp(q1, q2, amount) + result.x = q1.x + amount*(q2.x - q1.x); + result.y = q1.y + amount*(q2.y - q1.y); + result.z = q1.z + amount*(q2.z - q1.z); + result.w = q1.w + amount*(q2.w - q1.w); + + // QuaternionNormalize(q); + Quaternion q = result; + float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); + if (length == 0.0f) length = 1.0f; + float ilength = 1.0f/length; + + result.x = q.x*ilength; + result.y = q.y*ilength; + result.z = q.z*ilength; + result.w = q.w*ilength; + + return result; +} + +// Calculates spherical linear interpolation between two quaternions +RMAPI Quaternion QuaternionSlerp(Quaternion q1, Quaternion q2, float amount) +{ + Quaternion result = { 0 }; + +#if !defined(EPSILON) + #define EPSILON 0.000001f +#endif + + float cosHalfTheta = q1.x*q2.x + q1.y*q2.y + q1.z*q2.z + q1.w*q2.w; + + if (cosHalfTheta < 0) + { + q2.x = -q2.x; q2.y = -q2.y; q2.z = -q2.z; q2.w = -q2.w; + cosHalfTheta = -cosHalfTheta; + } + + if (fabsf(cosHalfTheta) >= 1.0f) result = q1; + else if (cosHalfTheta > 0.95f) result = QuaternionNlerp(q1, q2, amount); + else + { + float halfTheta = acosf(cosHalfTheta); + float sinHalfTheta = sqrtf(1.0f - cosHalfTheta*cosHalfTheta); + + if (fabsf(sinHalfTheta) < EPSILON) + { + result.x = (q1.x*0.5f + q2.x*0.5f); + result.y = (q1.y*0.5f + q2.y*0.5f); + result.z = (q1.z*0.5f + q2.z*0.5f); + result.w = (q1.w*0.5f + q2.w*0.5f); + } + else + { + float ratioA = sinf((1 - amount)*halfTheta)/sinHalfTheta; + float ratioB = sinf(amount*halfTheta)/sinHalfTheta; + + result.x = (q1.x*ratioA + q2.x*ratioB); + result.y = (q1.y*ratioA + q2.y*ratioB); + result.z = (q1.z*ratioA + q2.z*ratioB); + result.w = (q1.w*ratioA + q2.w*ratioB); + } + } + + return result; +} + +// Calculate quaternion based on the rotation from one vector to another +RMAPI Quaternion QuaternionFromVector3ToVector3(Vector3 from, Vector3 to) +{ + Quaternion result = { 0 }; + + float cos2Theta = (from.x*to.x + from.y*to.y + from.z*to.z); // Vector3DotProduct(from, to) + Vector3 cross = { from.y*to.z - from.z*to.y, from.z*to.x - from.x*to.z, from.x*to.y - from.y*to.x }; // Vector3CrossProduct(from, to) + + result.x = cross.x; + result.y = cross.y; + result.z = cross.z; + result.w = 1.0f + cos2Theta; + + // QuaternionNormalize(q); + // NOTE: Normalize to essentially nlerp the original and identity to 0.5 + Quaternion q = result; + float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); + if (length == 0.0f) length = 1.0f; + float ilength = 1.0f/length; + + result.x = q.x*ilength; + result.y = q.y*ilength; + result.z = q.z*ilength; + result.w = q.w*ilength; + + return result; +} + +// Get a quaternion for a given rotation matrix +RMAPI Quaternion QuaternionFromMatrix(Matrix mat) +{ + Quaternion result = { 0 }; + + float fourWSquaredMinus1 = mat.m0 + mat.m5 + mat.m10; + float fourXSquaredMinus1 = mat.m0 - mat.m5 - mat.m10; + float fourYSquaredMinus1 = mat.m5 - mat.m0 - mat.m10; + float fourZSquaredMinus1 = mat.m10 - mat.m0 - mat.m5; + + int biggestIndex = 0; + float fourBiggestSquaredMinus1 = fourWSquaredMinus1; + if (fourXSquaredMinus1 > fourBiggestSquaredMinus1) + { + fourBiggestSquaredMinus1 = fourXSquaredMinus1; + biggestIndex = 1; + } + + if (fourYSquaredMinus1 > fourBiggestSquaredMinus1) + { + fourBiggestSquaredMinus1 = fourYSquaredMinus1; + biggestIndex = 2; + } + + if (fourZSquaredMinus1 > fourBiggestSquaredMinus1) + { + fourBiggestSquaredMinus1 = fourZSquaredMinus1; + biggestIndex = 3; + } + + float biggestVal = sqrtf(fourBiggestSquaredMinus1 + 1.0f)*0.5f; + float mult = 0.25f / biggestVal; + + switch (biggestIndex) + { + case 0: + result.w = biggestVal; + result.x = (mat.m6 - mat.m9)*mult; + result.y = (mat.m8 - mat.m2)*mult; + result.z = (mat.m1 - mat.m4)*mult; + break; + case 1: + result.x = biggestVal; + result.w = (mat.m6 - mat.m9)*mult; + result.y = (mat.m1 + mat.m4)*mult; + result.z = (mat.m8 + mat.m2)*mult; + break; + case 2: + result.y = biggestVal; + result.w = (mat.m8 - mat.m2)*mult; + result.x = (mat.m1 + mat.m4)*mult; + result.z = (mat.m6 + mat.m9)*mult; + break; + case 3: + result.z = biggestVal; + result.w = (mat.m1 - mat.m4)*mult; + result.x = (mat.m8 + mat.m2)*mult; + result.y = (mat.m6 + mat.m9)*mult; + break; + } + + return result; +} + +// Get a matrix for a given quaternion +RMAPI Matrix QuaternionToMatrix(Quaternion q) +{ + Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() + + float a2 = q.x*q.x; + float b2 = q.y*q.y; + float c2 = q.z*q.z; + float ac = q.x*q.z; + float ab = q.x*q.y; + float bc = q.y*q.z; + float ad = q.w*q.x; + float bd = q.w*q.y; + float cd = q.w*q.z; + + result.m0 = 1 - 2*(b2 + c2); + result.m1 = 2*(ab + cd); + result.m2 = 2*(ac - bd); + + result.m4 = 2*(ab - cd); + result.m5 = 1 - 2*(a2 + c2); + result.m6 = 2*(bc + ad); + + result.m8 = 2*(ac + bd); + result.m9 = 2*(bc - ad); + result.m10 = 1 - 2*(a2 + b2); + + return result; +} + +// Get rotation quaternion for an angle and axis +// NOTE: Angle must be provided in radians +RMAPI Quaternion QuaternionFromAxisAngle(Vector3 axis, float angle) +{ + Quaternion result = { 0.0f, 0.0f, 0.0f, 1.0f }; + + float axisLength = sqrtf(axis.x*axis.x + axis.y*axis.y + axis.z*axis.z); + + if (axisLength != 0.0f) + { + angle *= 0.5f; + + float length = 0.0f; + float ilength = 0.0f; + + // Vector3Normalize(axis) + Vector3 v = axis; + length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); + if (length == 0.0f) length = 1.0f; + ilength = 1.0f/length; + axis.x *= ilength; + axis.y *= ilength; + axis.z *= ilength; + + float sinres = sinf(angle); + float cosres = cosf(angle); + + result.x = axis.x*sinres; + result.y = axis.y*sinres; + result.z = axis.z*sinres; + result.w = cosres; + + // QuaternionNormalize(q); + Quaternion q = result; + length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); + if (length == 0.0f) length = 1.0f; + ilength = 1.0f/length; + result.x = q.x*ilength; + result.y = q.y*ilength; + result.z = q.z*ilength; + result.w = q.w*ilength; + } + + return result; +} + +// Get the rotation angle and axis for a given quaternion +RMAPI void QuaternionToAxisAngle(Quaternion q, Vector3 *outAxis, float *outAngle) +{ + if (fabsf(q.w) > 1.0f) + { + // QuaternionNormalize(q); + float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); + if (length == 0.0f) length = 1.0f; + float ilength = 1.0f/length; + + q.x = q.x*ilength; + q.y = q.y*ilength; + q.z = q.z*ilength; + q.w = q.w*ilength; + } + + Vector3 resAxis = { 0.0f, 0.0f, 0.0f }; + float resAngle = 2.0f*acosf(q.w); + float den = sqrtf(1.0f - q.w*q.w); + + if (den > EPSILON) + { + resAxis.x = q.x/den; + resAxis.y = q.y/den; + resAxis.z = q.z/den; + } + else + { + // This occurs when the angle is zero. + // Not a problem: just set an arbitrary normalized axis. + resAxis.x = 1.0f; + } + + *outAxis = resAxis; + *outAngle = resAngle; +} + +// Get the quaternion equivalent to Euler angles +// NOTE: Rotation order is ZYX +RMAPI Quaternion QuaternionFromEuler(float pitch, float yaw, float roll) +{ + Quaternion result = { 0 }; + + float x0 = cosf(pitch*0.5f); + float x1 = sinf(pitch*0.5f); + float y0 = cosf(yaw*0.5f); + float y1 = sinf(yaw*0.5f); + float z0 = cosf(roll*0.5f); + float z1 = sinf(roll*0.5f); + + result.x = x1*y0*z0 - x0*y1*z1; + result.y = x0*y1*z0 + x1*y0*z1; + result.z = x0*y0*z1 - x1*y1*z0; + result.w = x0*y0*z0 + x1*y1*z1; + + return result; +} + +// Get the Euler angles equivalent to quaternion (roll, pitch, yaw) +// NOTE: Angles are returned in a Vector3 struct in radians +RMAPI Vector3 QuaternionToEuler(Quaternion q) +{ + Vector3 result = { 0 }; + + // Roll (x-axis rotation) + float x0 = 2.0f*(q.w*q.x + q.y*q.z); + float x1 = 1.0f - 2.0f*(q.x*q.x + q.y*q.y); + result.x = atan2f(x0, x1); + + // Pitch (y-axis rotation) + float y0 = 2.0f*(q.w*q.y - q.z*q.x); + y0 = y0 > 1.0f ? 1.0f : y0; + y0 = y0 < -1.0f ? -1.0f : y0; + result.y = asinf(y0); + + // Yaw (z-axis rotation) + float z0 = 2.0f*(q.w*q.z + q.x*q.y); + float z1 = 1.0f - 2.0f*(q.y*q.y + q.z*q.z); + result.z = atan2f(z0, z1); + + return result; +} + +// Transform a quaternion given a transformation matrix +RMAPI Quaternion QuaternionTransform(Quaternion q, Matrix mat) +{ + Quaternion result = { 0 }; + + result.x = mat.m0*q.x + mat.m4*q.y + mat.m8*q.z + mat.m12*q.w; + result.y = mat.m1*q.x + mat.m5*q.y + mat.m9*q.z + mat.m13*q.w; + result.z = mat.m2*q.x + mat.m6*q.y + mat.m10*q.z + mat.m14*q.w; + result.w = mat.m3*q.x + mat.m7*q.y + mat.m11*q.z + mat.m15*q.w; + + return result; +} + +// Check whether two given quaternions are almost equal +RMAPI int QuaternionEquals(Quaternion p, Quaternion q) +{ +#if !defined(EPSILON) + #define EPSILON 0.000001f +#endif + + int result = (((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && + ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && + ((fabsf(p.z - q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) && + ((fabsf(p.w - q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w)))))) || + (((fabsf(p.x + q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && + ((fabsf(p.y + q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && + ((fabsf(p.z + q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) && + ((fabsf(p.w + q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w)))))); + + return result; +} + +#endif // RAYMATH_H diff --git a/pkgs/raylib/raylib-5.0_win64_msvc16/include/rlgl.h b/pkgs/raylib/raylib-5.0_win64_msvc16/include/rlgl.h new file mode 100644 index 0000000..de7055c --- /dev/null +++ b/pkgs/raylib/raylib-5.0_win64_msvc16/include/rlgl.h @@ -0,0 +1,4859 @@ +/********************************************************************************************** +* +* rlgl v4.5 - A multi-OpenGL abstraction layer with an immediate-mode style API +* +* DESCRIPTION: +* An abstraction layer for multiple OpenGL versions (1.1, 2.1, 3.3 Core, 4.3 Core, ES 2.0) +* that provides a pseudo-OpenGL 1.1 immediate-mode style API (rlVertex, rlTranslate, rlRotate...) +* +* ADDITIONAL NOTES: +* When choosing an OpenGL backend different than OpenGL 1.1, some internal buffer are +* initialized on rlglInit() to accumulate vertex data. +* +* When an internal state change is required all the stored vertex data is renderer in batch, +* additionally, rlDrawRenderBatchActive() could be called to force flushing of the batch. +* +* Some resources are also loaded for convenience, here the complete list: +* - Default batch (RLGL.defaultBatch): RenderBatch system to accumulate vertex data +* - Default texture (RLGL.defaultTextureId): 1x1 white pixel R8G8B8A8 +* - Default shader (RLGL.State.defaultShaderId, RLGL.State.defaultShaderLocs) +* +* Internal buffer (and resources) must be manually unloaded calling rlglClose(). +* +* CONFIGURATION: +* #define GRAPHICS_API_OPENGL_11 +* #define GRAPHICS_API_OPENGL_21 +* #define GRAPHICS_API_OPENGL_33 +* #define GRAPHICS_API_OPENGL_43 +* #define GRAPHICS_API_OPENGL_ES2 +* #define GRAPHICS_API_OPENGL_ES3 +* Use selected OpenGL graphics backend, should be supported by platform +* Those preprocessor defines are only used on rlgl module, if OpenGL version is +* required by any other module, use rlGetVersion() to check it +* +* #define RLGL_IMPLEMENTATION +* Generates the implementation of the library into the included file. +* If not defined, the library is in header only mode and can be included in other headers +* or source files without problems. But only ONE file should hold the implementation. +* +* #define RLGL_RENDER_TEXTURES_HINT +* Enable framebuffer objects (fbo) support (enabled by default) +* Some GPUs could not support them despite the OpenGL version +* +* #define RLGL_SHOW_GL_DETAILS_INFO +* Show OpenGL extensions and capabilities detailed logs on init +* +* #define RLGL_ENABLE_OPENGL_DEBUG_CONTEXT +* Enable debug context (only available on OpenGL 4.3) +* +* rlgl capabilities could be customized just defining some internal +* values before library inclusion (default values listed): +* +* #define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 8192 // Default internal render batch elements limits +* #define RL_DEFAULT_BATCH_BUFFERS 1 // Default number of batch buffers (multi-buffering) +* #define RL_DEFAULT_BATCH_DRAWCALLS 256 // Default number of batch draw calls (by state changes: mode, texture) +* #define RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS 4 // Maximum number of textures units that can be activated on batch drawing (SetShaderValueTexture()) +* +* #define RL_MAX_MATRIX_STACK_SIZE 32 // Maximum size of internal Matrix stack +* #define RL_MAX_SHADER_LOCATIONS 32 // Maximum number of shader locations supported +* #define RL_CULL_DISTANCE_NEAR 0.01 // Default projection matrix near cull distance +* #define RL_CULL_DISTANCE_FAR 1000.0 // Default projection matrix far cull distance +* +* When loading a shader, the following vertex attributes and uniform +* location names are tried to be set automatically: +* +* #define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: 0 +* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: 1 +* #define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: 2 +* #define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: 3 +* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: 4 +* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: 5 +* #define RL_DEFAULT_SHADER_UNIFORM_NAME_MVP "mvp" // model-view-projection matrix +* #define RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW "matView" // view matrix +* #define RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION "matProjection" // projection matrix +* #define RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL "matModel" // model matrix +* #define RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL "matNormal" // normal matrix (transpose(inverse(matModelView)) +* #define RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR "colDiffuse" // color diffuse (base tint color, multiplied by texture color) +* #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 "texture0" // texture0 (texture slot active 0) +* #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 "texture1" // texture1 (texture slot active 1) +* #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 "texture2" // texture2 (texture slot active 2) +* +* DEPENDENCIES: +* - OpenGL libraries (depending on platform and OpenGL version selected) +* - GLAD OpenGL extensions loading library (only for OpenGL 3.3 Core, 4.3 Core) +* +* +* LICENSE: zlib/libpng +* +* Copyright (c) 2014-2023 Ramon Santamaria (@raysan5) +* +* This software is provided "as-is", without any express or implied warranty. In no event +* will the authors be held liable for any damages arising from the use of this software. +* +* Permission is granted to anyone to use this software for any purpose, including commercial +* applications, and to alter it and redistribute it freely, subject to the following restrictions: +* +* 1. The origin of this software must not be misrepresented; you must not claim that you +* wrote the original software. If you use this software in a product, an acknowledgment +* in the product documentation would be appreciated but is not required. +* +* 2. Altered source versions must be plainly marked as such, and must not be misrepresented +* as being the original software. +* +* 3. This notice may not be removed or altered from any source distribution. +* +**********************************************************************************************/ + +#ifndef RLGL_H +#define RLGL_H + +#define RLGL_VERSION "4.5" + +// Function specifiers in case library is build/used as a shared library (Windows) +// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll +#if defined(_WIN32) + #if defined(BUILD_LIBTYPE_SHARED) + #define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) + #elif defined(USE_LIBTYPE_SHARED) + #define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) + #endif +#endif + +// Function specifiers definition +#ifndef RLAPI + #define RLAPI // Functions defined as 'extern' by default (implicit specifiers) +#endif + +// Support TRACELOG macros +#ifndef TRACELOG + #define TRACELOG(level, ...) (void)0 + #define TRACELOGD(...) (void)0 +#endif + +// Allow custom memory allocators +#ifndef RL_MALLOC + #define RL_MALLOC(sz) malloc(sz) +#endif +#ifndef RL_CALLOC + #define RL_CALLOC(n,sz) calloc(n,sz) +#endif +#ifndef RL_REALLOC + #define RL_REALLOC(n,sz) realloc(n,sz) +#endif +#ifndef RL_FREE + #define RL_FREE(p) free(p) +#endif + +// Security check in case no GRAPHICS_API_OPENGL_* defined +#if !defined(GRAPHICS_API_OPENGL_11) && \ + !defined(GRAPHICS_API_OPENGL_21) && \ + !defined(GRAPHICS_API_OPENGL_33) && \ + !defined(GRAPHICS_API_OPENGL_43) && \ + !defined(GRAPHICS_API_OPENGL_ES2) && \ + !defined(GRAPHICS_API_OPENGL_ES3) + #define GRAPHICS_API_OPENGL_33 +#endif + +// Security check in case multiple GRAPHICS_API_OPENGL_* defined +#if defined(GRAPHICS_API_OPENGL_11) + #if defined(GRAPHICS_API_OPENGL_21) + #undef GRAPHICS_API_OPENGL_21 + #endif + #if defined(GRAPHICS_API_OPENGL_33) + #undef GRAPHICS_API_OPENGL_33 + #endif + #if defined(GRAPHICS_API_OPENGL_43) + #undef GRAPHICS_API_OPENGL_43 + #endif + #if defined(GRAPHICS_API_OPENGL_ES2) + #undef GRAPHICS_API_OPENGL_ES2 + #endif +#endif + +// OpenGL 2.1 uses most of OpenGL 3.3 Core functionality +// WARNING: Specific parts are checked with #if defines +#if defined(GRAPHICS_API_OPENGL_21) + #define GRAPHICS_API_OPENGL_33 +#endif + +// OpenGL 4.3 uses OpenGL 3.3 Core functionality +#if defined(GRAPHICS_API_OPENGL_43) + #define GRAPHICS_API_OPENGL_33 +#endif + +// OpenGL ES 3.0 uses OpenGL ES 2.0 functionality (and more) +#if defined(GRAPHICS_API_OPENGL_ES3) + #define GRAPHICS_API_OPENGL_ES2 +#endif + +// Support framebuffer objects by default +// NOTE: Some driver implementation do not support it, despite they should +#define RLGL_RENDER_TEXTURES_HINT + +//---------------------------------------------------------------------------------- +// Defines and Macros +//---------------------------------------------------------------------------------- + +// Default internal render batch elements limits +#ifndef RL_DEFAULT_BATCH_BUFFER_ELEMENTS + #if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) + // This is the maximum amount of elements (quads) per batch + // NOTE: Be careful with text, every letter maps to a quad + #define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 8192 + #endif + #if defined(GRAPHICS_API_OPENGL_ES2) + // We reduce memory sizes for embedded systems (RPI and HTML5) + // NOTE: On HTML5 (emscripten) this is allocated on heap, + // by default it's only 16MB!...just take care... + #define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 2048 + #endif +#endif +#ifndef RL_DEFAULT_BATCH_BUFFERS + #define RL_DEFAULT_BATCH_BUFFERS 1 // Default number of batch buffers (multi-buffering) +#endif +#ifndef RL_DEFAULT_BATCH_DRAWCALLS + #define RL_DEFAULT_BATCH_DRAWCALLS 256 // Default number of batch draw calls (by state changes: mode, texture) +#endif +#ifndef RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS + #define RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS 4 // Maximum number of textures units that can be activated on batch drawing (SetShaderValueTexture()) +#endif + +// Internal Matrix stack +#ifndef RL_MAX_MATRIX_STACK_SIZE + #define RL_MAX_MATRIX_STACK_SIZE 32 // Maximum size of Matrix stack +#endif + +// Shader limits +#ifndef RL_MAX_SHADER_LOCATIONS + #define RL_MAX_SHADER_LOCATIONS 32 // Maximum number of shader locations supported +#endif + +// Projection matrix culling +#ifndef RL_CULL_DISTANCE_NEAR + #define RL_CULL_DISTANCE_NEAR 0.01 // Default near cull distance +#endif +#ifndef RL_CULL_DISTANCE_FAR + #define RL_CULL_DISTANCE_FAR 1000.0 // Default far cull distance +#endif + +// Texture parameters (equivalent to OpenGL defines) +#define RL_TEXTURE_WRAP_S 0x2802 // GL_TEXTURE_WRAP_S +#define RL_TEXTURE_WRAP_T 0x2803 // GL_TEXTURE_WRAP_T +#define RL_TEXTURE_MAG_FILTER 0x2800 // GL_TEXTURE_MAG_FILTER +#define RL_TEXTURE_MIN_FILTER 0x2801 // GL_TEXTURE_MIN_FILTER + +#define RL_TEXTURE_FILTER_NEAREST 0x2600 // GL_NEAREST +#define RL_TEXTURE_FILTER_LINEAR 0x2601 // GL_LINEAR +#define RL_TEXTURE_FILTER_MIP_NEAREST 0x2700 // GL_NEAREST_MIPMAP_NEAREST +#define RL_TEXTURE_FILTER_NEAREST_MIP_LINEAR 0x2702 // GL_NEAREST_MIPMAP_LINEAR +#define RL_TEXTURE_FILTER_LINEAR_MIP_NEAREST 0x2701 // GL_LINEAR_MIPMAP_NEAREST +#define RL_TEXTURE_FILTER_MIP_LINEAR 0x2703 // GL_LINEAR_MIPMAP_LINEAR +#define RL_TEXTURE_FILTER_ANISOTROPIC 0x3000 // Anisotropic filter (custom identifier) +#define RL_TEXTURE_MIPMAP_BIAS_RATIO 0x4000 // Texture mipmap bias, percentage ratio (custom identifier) + +#define RL_TEXTURE_WRAP_REPEAT 0x2901 // GL_REPEAT +#define RL_TEXTURE_WRAP_CLAMP 0x812F // GL_CLAMP_TO_EDGE +#define RL_TEXTURE_WRAP_MIRROR_REPEAT 0x8370 // GL_MIRRORED_REPEAT +#define RL_TEXTURE_WRAP_MIRROR_CLAMP 0x8742 // GL_MIRROR_CLAMP_EXT + +// Matrix modes (equivalent to OpenGL) +#define RL_MODELVIEW 0x1700 // GL_MODELVIEW +#define RL_PROJECTION 0x1701 // GL_PROJECTION +#define RL_TEXTURE 0x1702 // GL_TEXTURE + +// Primitive assembly draw modes +#define RL_LINES 0x0001 // GL_LINES +#define RL_TRIANGLES 0x0004 // GL_TRIANGLES +#define RL_QUADS 0x0007 // GL_QUADS + +// GL equivalent data types +#define RL_UNSIGNED_BYTE 0x1401 // GL_UNSIGNED_BYTE +#define RL_FLOAT 0x1406 // GL_FLOAT + +// GL buffer usage hint +#define RL_STREAM_DRAW 0x88E0 // GL_STREAM_DRAW +#define RL_STREAM_READ 0x88E1 // GL_STREAM_READ +#define RL_STREAM_COPY 0x88E2 // GL_STREAM_COPY +#define RL_STATIC_DRAW 0x88E4 // GL_STATIC_DRAW +#define RL_STATIC_READ 0x88E5 // GL_STATIC_READ +#define RL_STATIC_COPY 0x88E6 // GL_STATIC_COPY +#define RL_DYNAMIC_DRAW 0x88E8 // GL_DYNAMIC_DRAW +#define RL_DYNAMIC_READ 0x88E9 // GL_DYNAMIC_READ +#define RL_DYNAMIC_COPY 0x88EA // GL_DYNAMIC_COPY + +// GL Shader type +#define RL_FRAGMENT_SHADER 0x8B30 // GL_FRAGMENT_SHADER +#define RL_VERTEX_SHADER 0x8B31 // GL_VERTEX_SHADER +#define RL_COMPUTE_SHADER 0x91B9 // GL_COMPUTE_SHADER + +// GL blending factors +#define RL_ZERO 0 // GL_ZERO +#define RL_ONE 1 // GL_ONE +#define RL_SRC_COLOR 0x0300 // GL_SRC_COLOR +#define RL_ONE_MINUS_SRC_COLOR 0x0301 // GL_ONE_MINUS_SRC_COLOR +#define RL_SRC_ALPHA 0x0302 // GL_SRC_ALPHA +#define RL_ONE_MINUS_SRC_ALPHA 0x0303 // GL_ONE_MINUS_SRC_ALPHA +#define RL_DST_ALPHA 0x0304 // GL_DST_ALPHA +#define RL_ONE_MINUS_DST_ALPHA 0x0305 // GL_ONE_MINUS_DST_ALPHA +#define RL_DST_COLOR 0x0306 // GL_DST_COLOR +#define RL_ONE_MINUS_DST_COLOR 0x0307 // GL_ONE_MINUS_DST_COLOR +#define RL_SRC_ALPHA_SATURATE 0x0308 // GL_SRC_ALPHA_SATURATE +#define RL_CONSTANT_COLOR 0x8001 // GL_CONSTANT_COLOR +#define RL_ONE_MINUS_CONSTANT_COLOR 0x8002 // GL_ONE_MINUS_CONSTANT_COLOR +#define RL_CONSTANT_ALPHA 0x8003 // GL_CONSTANT_ALPHA +#define RL_ONE_MINUS_CONSTANT_ALPHA 0x8004 // GL_ONE_MINUS_CONSTANT_ALPHA + +// GL blending functions/equations +#define RL_FUNC_ADD 0x8006 // GL_FUNC_ADD +#define RL_MIN 0x8007 // GL_MIN +#define RL_MAX 0x8008 // GL_MAX +#define RL_FUNC_SUBTRACT 0x800A // GL_FUNC_SUBTRACT +#define RL_FUNC_REVERSE_SUBTRACT 0x800B // GL_FUNC_REVERSE_SUBTRACT +#define RL_BLEND_EQUATION 0x8009 // GL_BLEND_EQUATION +#define RL_BLEND_EQUATION_RGB 0x8009 // GL_BLEND_EQUATION_RGB // (Same as BLEND_EQUATION) +#define RL_BLEND_EQUATION_ALPHA 0x883D // GL_BLEND_EQUATION_ALPHA +#define RL_BLEND_DST_RGB 0x80C8 // GL_BLEND_DST_RGB +#define RL_BLEND_SRC_RGB 0x80C9 // GL_BLEND_SRC_RGB +#define RL_BLEND_DST_ALPHA 0x80CA // GL_BLEND_DST_ALPHA +#define RL_BLEND_SRC_ALPHA 0x80CB // GL_BLEND_SRC_ALPHA +#define RL_BLEND_COLOR 0x8005 // GL_BLEND_COLOR + + +//---------------------------------------------------------------------------------- +// Types and Structures Definition +//---------------------------------------------------------------------------------- +#if (defined(__STDC__) && __STDC_VERSION__ >= 199901L) || (defined(_MSC_VER) && _MSC_VER >= 1800) + #include +#elif !defined(__cplusplus) && !defined(bool) && !defined(RL_BOOL_TYPE) + // Boolean type +typedef enum bool { false = 0, true = !false } bool; +#endif + +#if !defined(RL_MATRIX_TYPE) +// Matrix, 4x4 components, column major, OpenGL style, right handed +typedef struct Matrix { + float m0, m4, m8, m12; // Matrix first row (4 components) + float m1, m5, m9, m13; // Matrix second row (4 components) + float m2, m6, m10, m14; // Matrix third row (4 components) + float m3, m7, m11, m15; // Matrix fourth row (4 components) +} Matrix; +#define RL_MATRIX_TYPE +#endif + +// Dynamic vertex buffers (position + texcoords + colors + indices arrays) +typedef struct rlVertexBuffer { + int elementCount; // Number of elements in the buffer (QUADS) + + float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) + float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) + unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) +#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) + unsigned int *indices; // Vertex indices (in case vertex data comes indexed) (6 indices per quad) +#endif +#if defined(GRAPHICS_API_OPENGL_ES2) + unsigned short *indices; // Vertex indices (in case vertex data comes indexed) (6 indices per quad) +#endif + unsigned int vaoId; // OpenGL Vertex Array Object id + unsigned int vboId[4]; // OpenGL Vertex Buffer Objects id (4 types of vertex data) +} rlVertexBuffer; + +// Draw call type +// NOTE: Only texture changes register a new draw, other state-change-related elements are not +// used at this moment (vaoId, shaderId, matrices), raylib just forces a batch draw call if any +// of those state-change happens (this is done in core module) +typedef struct rlDrawCall { + int mode; // Drawing mode: LINES, TRIANGLES, QUADS + int vertexCount; // Number of vertex of the draw + int vertexAlignment; // Number of vertex required for index alignment (LINES, TRIANGLES) + //unsigned int vaoId; // Vertex array id to be used on the draw -> Using RLGL.currentBatch->vertexBuffer.vaoId + //unsigned int shaderId; // Shader id to be used on the draw -> Using RLGL.currentShaderId + unsigned int textureId; // Texture id to be used on the draw -> Use to create new draw call if changes + + //Matrix projection; // Projection matrix for this draw -> Using RLGL.projection by default + //Matrix modelview; // Modelview matrix for this draw -> Using RLGL.modelview by default +} rlDrawCall; + +// rlRenderBatch type +typedef struct rlRenderBatch { + int bufferCount; // Number of vertex buffers (multi-buffering support) + int currentBuffer; // Current buffer tracking in case of multi-buffering + rlVertexBuffer *vertexBuffer; // Dynamic buffer(s) for vertex data + + rlDrawCall *draws; // Draw calls array, depends on textureId + int drawCounter; // Draw calls counter + float currentDepth; // Current depth value for next draw +} rlRenderBatch; + +// OpenGL version +typedef enum { + RL_OPENGL_11 = 1, // OpenGL 1.1 + RL_OPENGL_21, // OpenGL 2.1 (GLSL 120) + RL_OPENGL_33, // OpenGL 3.3 (GLSL 330) + RL_OPENGL_43, // OpenGL 4.3 (using GLSL 330) + RL_OPENGL_ES_20, // OpenGL ES 2.0 (GLSL 100) + RL_OPENGL_ES_30 // OpenGL ES 3.0 (GLSL 300 es) +} rlGlVersion; + +// Trace log level +// NOTE: Organized by priority level +typedef enum { + RL_LOG_ALL = 0, // Display all logs + RL_LOG_TRACE, // Trace logging, intended for internal use only + RL_LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds + RL_LOG_INFO, // Info logging, used for program execution info + RL_LOG_WARNING, // Warning logging, used on recoverable failures + RL_LOG_ERROR, // Error logging, used on unrecoverable failures + RL_LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE) + RL_LOG_NONE // Disable logging +} rlTraceLogLevel; + +// Texture pixel formats +// NOTE: Support depends on OpenGL version +typedef enum { + RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) + RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA, // 8*2 bpp (2 channels) + RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5, // 16 bpp + RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8, // 24 bpp + RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) + RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) + RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, // 32 bpp + RL_PIXELFORMAT_UNCOMPRESSED_R32, // 32 bpp (1 channel - float) + RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32, // 32*3 bpp (3 channels - float) + RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32, // 32*4 bpp (4 channels - float) + RL_PIXELFORMAT_UNCOMPRESSED_R16, // 16 bpp (1 channel - half float) + RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16, // 16*3 bpp (3 channels - half float) + RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16, // 16*4 bpp (4 channels - half float) + RL_PIXELFORMAT_COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) + RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) + RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA, // 8 bpp + RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA, // 8 bpp + RL_PIXELFORMAT_COMPRESSED_ETC1_RGB, // 4 bpp + RL_PIXELFORMAT_COMPRESSED_ETC2_RGB, // 4 bpp + RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA, // 8 bpp + RL_PIXELFORMAT_COMPRESSED_PVRT_RGB, // 4 bpp + RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA, // 4 bpp + RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA, // 8 bpp + RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA // 2 bpp +} rlPixelFormat; + +// Texture parameters: filter mode +// NOTE 1: Filtering considers mipmaps if available in the texture +// NOTE 2: Filter is accordingly set for minification and magnification +typedef enum { + RL_TEXTURE_FILTER_POINT = 0, // No filter, just pixel approximation + RL_TEXTURE_FILTER_BILINEAR, // Linear filtering + RL_TEXTURE_FILTER_TRILINEAR, // Trilinear filtering (linear with mipmaps) + RL_TEXTURE_FILTER_ANISOTROPIC_4X, // Anisotropic filtering 4x + RL_TEXTURE_FILTER_ANISOTROPIC_8X, // Anisotropic filtering 8x + RL_TEXTURE_FILTER_ANISOTROPIC_16X, // Anisotropic filtering 16x +} rlTextureFilter; + +// Color blending modes (pre-defined) +typedef enum { + RL_BLEND_ALPHA = 0, // Blend textures considering alpha (default) + RL_BLEND_ADDITIVE, // Blend textures adding colors + RL_BLEND_MULTIPLIED, // Blend textures multiplying colors + RL_BLEND_ADD_COLORS, // Blend textures adding colors (alternative) + RL_BLEND_SUBTRACT_COLORS, // Blend textures subtracting colors (alternative) + RL_BLEND_ALPHA_PREMULTIPLY, // Blend premultiplied textures considering alpha + RL_BLEND_CUSTOM, // Blend textures using custom src/dst factors (use rlSetBlendFactors()) + RL_BLEND_CUSTOM_SEPARATE // Blend textures using custom src/dst factors (use rlSetBlendFactorsSeparate()) +} rlBlendMode; + +// Shader location point type +typedef enum { + RL_SHADER_LOC_VERTEX_POSITION = 0, // Shader location: vertex attribute: position + RL_SHADER_LOC_VERTEX_TEXCOORD01, // Shader location: vertex attribute: texcoord01 + RL_SHADER_LOC_VERTEX_TEXCOORD02, // Shader location: vertex attribute: texcoord02 + RL_SHADER_LOC_VERTEX_NORMAL, // Shader location: vertex attribute: normal + RL_SHADER_LOC_VERTEX_TANGENT, // Shader location: vertex attribute: tangent + RL_SHADER_LOC_VERTEX_COLOR, // Shader location: vertex attribute: color + RL_SHADER_LOC_MATRIX_MVP, // Shader location: matrix uniform: model-view-projection + RL_SHADER_LOC_MATRIX_VIEW, // Shader location: matrix uniform: view (camera transform) + RL_SHADER_LOC_MATRIX_PROJECTION, // Shader location: matrix uniform: projection + RL_SHADER_LOC_MATRIX_MODEL, // Shader location: matrix uniform: model (transform) + RL_SHADER_LOC_MATRIX_NORMAL, // Shader location: matrix uniform: normal + RL_SHADER_LOC_VECTOR_VIEW, // Shader location: vector uniform: view + RL_SHADER_LOC_COLOR_DIFFUSE, // Shader location: vector uniform: diffuse color + RL_SHADER_LOC_COLOR_SPECULAR, // Shader location: vector uniform: specular color + RL_SHADER_LOC_COLOR_AMBIENT, // Shader location: vector uniform: ambient color + RL_SHADER_LOC_MAP_ALBEDO, // Shader location: sampler2d texture: albedo (same as: RL_SHADER_LOC_MAP_DIFFUSE) + RL_SHADER_LOC_MAP_METALNESS, // Shader location: sampler2d texture: metalness (same as: RL_SHADER_LOC_MAP_SPECULAR) + RL_SHADER_LOC_MAP_NORMAL, // Shader location: sampler2d texture: normal + RL_SHADER_LOC_MAP_ROUGHNESS, // Shader location: sampler2d texture: roughness + RL_SHADER_LOC_MAP_OCCLUSION, // Shader location: sampler2d texture: occlusion + RL_SHADER_LOC_MAP_EMISSION, // Shader location: sampler2d texture: emission + RL_SHADER_LOC_MAP_HEIGHT, // Shader location: sampler2d texture: height + RL_SHADER_LOC_MAP_CUBEMAP, // Shader location: samplerCube texture: cubemap + RL_SHADER_LOC_MAP_IRRADIANCE, // Shader location: samplerCube texture: irradiance + RL_SHADER_LOC_MAP_PREFILTER, // Shader location: samplerCube texture: prefilter + RL_SHADER_LOC_MAP_BRDF // Shader location: sampler2d texture: brdf +} rlShaderLocationIndex; + +#define RL_SHADER_LOC_MAP_DIFFUSE RL_SHADER_LOC_MAP_ALBEDO +#define RL_SHADER_LOC_MAP_SPECULAR RL_SHADER_LOC_MAP_METALNESS + +// Shader uniform data type +typedef enum { + RL_SHADER_UNIFORM_FLOAT = 0, // Shader uniform type: float + RL_SHADER_UNIFORM_VEC2, // Shader uniform type: vec2 (2 float) + RL_SHADER_UNIFORM_VEC3, // Shader uniform type: vec3 (3 float) + RL_SHADER_UNIFORM_VEC4, // Shader uniform type: vec4 (4 float) + RL_SHADER_UNIFORM_INT, // Shader uniform type: int + RL_SHADER_UNIFORM_IVEC2, // Shader uniform type: ivec2 (2 int) + RL_SHADER_UNIFORM_IVEC3, // Shader uniform type: ivec3 (3 int) + RL_SHADER_UNIFORM_IVEC4, // Shader uniform type: ivec4 (4 int) + RL_SHADER_UNIFORM_SAMPLER2D // Shader uniform type: sampler2d +} rlShaderUniformDataType; + +// Shader attribute data types +typedef enum { + RL_SHADER_ATTRIB_FLOAT = 0, // Shader attribute type: float + RL_SHADER_ATTRIB_VEC2, // Shader attribute type: vec2 (2 float) + RL_SHADER_ATTRIB_VEC3, // Shader attribute type: vec3 (3 float) + RL_SHADER_ATTRIB_VEC4 // Shader attribute type: vec4 (4 float) +} rlShaderAttributeDataType; + +// Framebuffer attachment type +// NOTE: By default up to 8 color channels defined, but it can be more +typedef enum { + RL_ATTACHMENT_COLOR_CHANNEL0 = 0, // Framebuffer attachment type: color 0 + RL_ATTACHMENT_COLOR_CHANNEL1 = 1, // Framebuffer attachment type: color 1 + RL_ATTACHMENT_COLOR_CHANNEL2 = 2, // Framebuffer attachment type: color 2 + RL_ATTACHMENT_COLOR_CHANNEL3 = 3, // Framebuffer attachment type: color 3 + RL_ATTACHMENT_COLOR_CHANNEL4 = 4, // Framebuffer attachment type: color 4 + RL_ATTACHMENT_COLOR_CHANNEL5 = 5, // Framebuffer attachment type: color 5 + RL_ATTACHMENT_COLOR_CHANNEL6 = 6, // Framebuffer attachment type: color 6 + RL_ATTACHMENT_COLOR_CHANNEL7 = 7, // Framebuffer attachment type: color 7 + RL_ATTACHMENT_DEPTH = 100, // Framebuffer attachment type: depth + RL_ATTACHMENT_STENCIL = 200, // Framebuffer attachment type: stencil +} rlFramebufferAttachType; + +// Framebuffer texture attachment type +typedef enum { + RL_ATTACHMENT_CUBEMAP_POSITIVE_X = 0, // Framebuffer texture attachment type: cubemap, +X side + RL_ATTACHMENT_CUBEMAP_NEGATIVE_X = 1, // Framebuffer texture attachment type: cubemap, -X side + RL_ATTACHMENT_CUBEMAP_POSITIVE_Y = 2, // Framebuffer texture attachment type: cubemap, +Y side + RL_ATTACHMENT_CUBEMAP_NEGATIVE_Y = 3, // Framebuffer texture attachment type: cubemap, -Y side + RL_ATTACHMENT_CUBEMAP_POSITIVE_Z = 4, // Framebuffer texture attachment type: cubemap, +Z side + RL_ATTACHMENT_CUBEMAP_NEGATIVE_Z = 5, // Framebuffer texture attachment type: cubemap, -Z side + RL_ATTACHMENT_TEXTURE2D = 100, // Framebuffer texture attachment type: texture2d + RL_ATTACHMENT_RENDERBUFFER = 200, // Framebuffer texture attachment type: renderbuffer +} rlFramebufferAttachTextureType; + +// Face culling mode +typedef enum { + RL_CULL_FACE_FRONT = 0, + RL_CULL_FACE_BACK +} rlCullMode; + +//------------------------------------------------------------------------------------ +// Functions Declaration - Matrix operations +//------------------------------------------------------------------------------------ + +#if defined(__cplusplus) +extern "C" { // Prevents name mangling of functions +#endif + +RLAPI void rlMatrixMode(int mode); // Choose the current matrix to be transformed +RLAPI void rlPushMatrix(void); // Push the current matrix to stack +RLAPI void rlPopMatrix(void); // Pop latest inserted matrix from stack +RLAPI void rlLoadIdentity(void); // Reset current matrix to identity matrix +RLAPI void rlTranslatef(float x, float y, float z); // Multiply the current matrix by a translation matrix +RLAPI void rlRotatef(float angle, float x, float y, float z); // Multiply the current matrix by a rotation matrix +RLAPI void rlScalef(float x, float y, float z); // Multiply the current matrix by a scaling matrix +RLAPI void rlMultMatrixf(const float *matf); // Multiply the current matrix by another matrix +RLAPI void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar); +RLAPI void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar); +RLAPI void rlViewport(int x, int y, int width, int height); // Set the viewport area + +//------------------------------------------------------------------------------------ +// Functions Declaration - Vertex level operations +//------------------------------------------------------------------------------------ +RLAPI void rlBegin(int mode); // Initialize drawing mode (how to organize vertex) +RLAPI void rlEnd(void); // Finish vertex providing +RLAPI void rlVertex2i(int x, int y); // Define one vertex (position) - 2 int +RLAPI void rlVertex2f(float x, float y); // Define one vertex (position) - 2 float +RLAPI void rlVertex3f(float x, float y, float z); // Define one vertex (position) - 3 float +RLAPI void rlTexCoord2f(float x, float y); // Define one vertex (texture coordinate) - 2 float +RLAPI void rlNormal3f(float x, float y, float z); // Define one vertex (normal) - 3 float +RLAPI void rlColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a); // Define one vertex (color) - 4 byte +RLAPI void rlColor3f(float x, float y, float z); // Define one vertex (color) - 3 float +RLAPI void rlColor4f(float x, float y, float z, float w); // Define one vertex (color) - 4 float + +//------------------------------------------------------------------------------------ +// Functions Declaration - OpenGL style functions (common to 1.1, 3.3+, ES2) +// NOTE: This functions are used to completely abstract raylib code from OpenGL layer, +// some of them are direct wrappers over OpenGL calls, some others are custom +//------------------------------------------------------------------------------------ + +// Vertex buffers state +RLAPI bool rlEnableVertexArray(unsigned int vaoId); // Enable vertex array (VAO, if supported) +RLAPI void rlDisableVertexArray(void); // Disable vertex array (VAO, if supported) +RLAPI void rlEnableVertexBuffer(unsigned int id); // Enable vertex buffer (VBO) +RLAPI void rlDisableVertexBuffer(void); // Disable vertex buffer (VBO) +RLAPI void rlEnableVertexBufferElement(unsigned int id);// Enable vertex buffer element (VBO element) +RLAPI void rlDisableVertexBufferElement(void); // Disable vertex buffer element (VBO element) +RLAPI void rlEnableVertexAttribute(unsigned int index); // Enable vertex attribute index +RLAPI void rlDisableVertexAttribute(unsigned int index);// Disable vertex attribute index +#if defined(GRAPHICS_API_OPENGL_11) +RLAPI void rlEnableStatePointer(int vertexAttribType, void *buffer); // Enable attribute state pointer +RLAPI void rlDisableStatePointer(int vertexAttribType); // Disable attribute state pointer +#endif + +// Textures state +RLAPI void rlActiveTextureSlot(int slot); // Select and active a texture slot +RLAPI void rlEnableTexture(unsigned int id); // Enable texture +RLAPI void rlDisableTexture(void); // Disable texture +RLAPI void rlEnableTextureCubemap(unsigned int id); // Enable texture cubemap +RLAPI void rlDisableTextureCubemap(void); // Disable texture cubemap +RLAPI void rlTextureParameters(unsigned int id, int param, int value); // Set texture parameters (filter, wrap) +RLAPI void rlCubemapParameters(unsigned int id, int param, int value); // Set cubemap parameters (filter, wrap) + +// Shader state +RLAPI void rlEnableShader(unsigned int id); // Enable shader program +RLAPI void rlDisableShader(void); // Disable shader program + +// Framebuffer state +RLAPI void rlEnableFramebuffer(unsigned int id); // Enable render texture (fbo) +RLAPI void rlDisableFramebuffer(void); // Disable render texture (fbo), return to default framebuffer +RLAPI void rlActiveDrawBuffers(int count); // Activate multiple draw color buffers +RLAPI void rlBlitFramebuffer(int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight, int bufferMask); // Blit active framebuffer to main framebuffer + +// General render state +RLAPI void rlEnableColorBlend(void); // Enable color blending +RLAPI void rlDisableColorBlend(void); // Disable color blending +RLAPI void rlEnableDepthTest(void); // Enable depth test +RLAPI void rlDisableDepthTest(void); // Disable depth test +RLAPI void rlEnableDepthMask(void); // Enable depth write +RLAPI void rlDisableDepthMask(void); // Disable depth write +RLAPI void rlEnableBackfaceCulling(void); // Enable backface culling +RLAPI void rlDisableBackfaceCulling(void); // Disable backface culling +RLAPI void rlSetCullFace(int mode); // Set face culling mode +RLAPI void rlEnableScissorTest(void); // Enable scissor test +RLAPI void rlDisableScissorTest(void); // Disable scissor test +RLAPI void rlScissor(int x, int y, int width, int height); // Scissor test +RLAPI void rlEnableWireMode(void); // Enable wire mode +RLAPI void rlEnablePointMode(void); // Enable point mode +RLAPI void rlDisableWireMode(void); // Disable wire mode ( and point ) maybe rename +RLAPI void rlSetLineWidth(float width); // Set the line drawing width +RLAPI float rlGetLineWidth(void); // Get the line drawing width +RLAPI void rlEnableSmoothLines(void); // Enable line aliasing +RLAPI void rlDisableSmoothLines(void); // Disable line aliasing +RLAPI void rlEnableStereoRender(void); // Enable stereo rendering +RLAPI void rlDisableStereoRender(void); // Disable stereo rendering +RLAPI bool rlIsStereoRenderEnabled(void); // Check if stereo render is enabled + +RLAPI void rlClearColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a); // Clear color buffer with color +RLAPI void rlClearScreenBuffers(void); // Clear used screen buffers (color and depth) +RLAPI void rlCheckErrors(void); // Check and log OpenGL error codes +RLAPI void rlSetBlendMode(int mode); // Set blending mode +RLAPI void rlSetBlendFactors(int glSrcFactor, int glDstFactor, int glEquation); // Set blending mode factor and equation (using OpenGL factors) +RLAPI void rlSetBlendFactorsSeparate(int glSrcRGB, int glDstRGB, int glSrcAlpha, int glDstAlpha, int glEqRGB, int glEqAlpha); // Set blending mode factors and equations separately (using OpenGL factors) + +//------------------------------------------------------------------------------------ +// Functions Declaration - rlgl functionality +//------------------------------------------------------------------------------------ +// rlgl initialization functions +RLAPI void rlglInit(int width, int height); // Initialize rlgl (buffers, shaders, textures, states) +RLAPI void rlglClose(void); // De-initialize rlgl (buffers, shaders, textures) +RLAPI void rlLoadExtensions(void *loader); // Load OpenGL extensions (loader function required) +RLAPI int rlGetVersion(void); // Get current OpenGL version +RLAPI void rlSetFramebufferWidth(int width); // Set current framebuffer width +RLAPI int rlGetFramebufferWidth(void); // Get default framebuffer width +RLAPI void rlSetFramebufferHeight(int height); // Set current framebuffer height +RLAPI int rlGetFramebufferHeight(void); // Get default framebuffer height + +RLAPI unsigned int rlGetTextureIdDefault(void); // Get default texture id +RLAPI unsigned int rlGetShaderIdDefault(void); // Get default shader id +RLAPI int *rlGetShaderLocsDefault(void); // Get default shader locations + +// Render batch management +// NOTE: rlgl provides a default render batch to behave like OpenGL 1.1 immediate mode +// but this render batch API is exposed in case of custom batches are required +RLAPI rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements); // Load a render batch system +RLAPI void rlUnloadRenderBatch(rlRenderBatch batch); // Unload render batch system +RLAPI void rlDrawRenderBatch(rlRenderBatch *batch); // Draw render batch data (Update->Draw->Reset) +RLAPI void rlSetRenderBatchActive(rlRenderBatch *batch); // Set the active render batch for rlgl (NULL for default internal) +RLAPI void rlDrawRenderBatchActive(void); // Update and draw internal render batch +RLAPI bool rlCheckRenderBatchLimit(int vCount); // Check internal buffer overflow for a given number of vertex + +RLAPI void rlSetTexture(unsigned int id); // Set current texture for render batch and check buffers limits + +//------------------------------------------------------------------------------------------------------------------------ + +// Vertex buffers management +RLAPI unsigned int rlLoadVertexArray(void); // Load vertex array (vao) if supported +RLAPI unsigned int rlLoadVertexBuffer(const void *buffer, int size, bool dynamic); // Load a vertex buffer attribute +RLAPI unsigned int rlLoadVertexBufferElement(const void *buffer, int size, bool dynamic); // Load a new attributes element buffer +RLAPI void rlUpdateVertexBuffer(unsigned int bufferId, const void *data, int dataSize, int offset); // Update GPU buffer with new data +RLAPI void rlUpdateVertexBufferElements(unsigned int id, const void *data, int dataSize, int offset); // Update vertex buffer elements with new data +RLAPI void rlUnloadVertexArray(unsigned int vaoId); +RLAPI void rlUnloadVertexBuffer(unsigned int vboId); +RLAPI void rlSetVertexAttribute(unsigned int index, int compSize, int type, bool normalized, int stride, const void *pointer); +RLAPI void rlSetVertexAttributeDivisor(unsigned int index, int divisor); +RLAPI void rlSetVertexAttributeDefault(int locIndex, const void *value, int attribType, int count); // Set vertex attribute default value +RLAPI void rlDrawVertexArray(int offset, int count); +RLAPI void rlDrawVertexArrayElements(int offset, int count, const void *buffer); +RLAPI void rlDrawVertexArrayInstanced(int offset, int count, int instances); +RLAPI void rlDrawVertexArrayElementsInstanced(int offset, int count, const void *buffer, int instances); + +// Textures management +RLAPI unsigned int rlLoadTexture(const void *data, int width, int height, int format, int mipmapCount); // Load texture in GPU +RLAPI unsigned int rlLoadTextureDepth(int width, int height, bool useRenderBuffer); // Load depth texture/renderbuffer (to be attached to fbo) +RLAPI unsigned int rlLoadTextureCubemap(const void *data, int size, int format); // Load texture cubemap +RLAPI void rlUpdateTexture(unsigned int id, int offsetX, int offsetY, int width, int height, int format, const void *data); // Update GPU texture with new data +RLAPI void rlGetGlTextureFormats(int format, unsigned int *glInternalFormat, unsigned int *glFormat, unsigned int *glType); // Get OpenGL internal formats +RLAPI const char *rlGetPixelFormatName(unsigned int format); // Get name string for pixel format +RLAPI void rlUnloadTexture(unsigned int id); // Unload texture from GPU memory +RLAPI void rlGenTextureMipmaps(unsigned int id, int width, int height, int format, int *mipmaps); // Generate mipmap data for selected texture +RLAPI void *rlReadTexturePixels(unsigned int id, int width, int height, int format); // Read texture pixel data +RLAPI unsigned char *rlReadScreenPixels(int width, int height); // Read screen pixel data (color buffer) + +// Framebuffer management (fbo) +RLAPI unsigned int rlLoadFramebuffer(int width, int height); // Load an empty framebuffer +RLAPI void rlFramebufferAttach(unsigned int fboId, unsigned int texId, int attachType, int texType, int mipLevel); // Attach texture/renderbuffer to a framebuffer +RLAPI bool rlFramebufferComplete(unsigned int id); // Verify framebuffer is complete +RLAPI void rlUnloadFramebuffer(unsigned int id); // Delete framebuffer from GPU + +// Shaders management +RLAPI unsigned int rlLoadShaderCode(const char *vsCode, const char *fsCode); // Load shader from code strings +RLAPI unsigned int rlCompileShader(const char *shaderCode, int type); // Compile custom shader and return shader id (type: RL_VERTEX_SHADER, RL_FRAGMENT_SHADER, RL_COMPUTE_SHADER) +RLAPI unsigned int rlLoadShaderProgram(unsigned int vShaderId, unsigned int fShaderId); // Load custom shader program +RLAPI void rlUnloadShaderProgram(unsigned int id); // Unload shader program +RLAPI int rlGetLocationUniform(unsigned int shaderId, const char *uniformName); // Get shader location uniform +RLAPI int rlGetLocationAttrib(unsigned int shaderId, const char *attribName); // Get shader location attribute +RLAPI void rlSetUniform(int locIndex, const void *value, int uniformType, int count); // Set shader value uniform +RLAPI void rlSetUniformMatrix(int locIndex, Matrix mat); // Set shader value matrix +RLAPI void rlSetUniformSampler(int locIndex, unsigned int textureId); // Set shader value sampler +RLAPI void rlSetShader(unsigned int id, int *locs); // Set shader currently active (id and locations) + +// Compute shader management +RLAPI unsigned int rlLoadComputeShaderProgram(unsigned int shaderId); // Load compute shader program +RLAPI void rlComputeShaderDispatch(unsigned int groupX, unsigned int groupY, unsigned int groupZ); // Dispatch compute shader (equivalent to *draw* for graphics pipeline) + +// Shader buffer storage object management (ssbo) +RLAPI unsigned int rlLoadShaderBuffer(unsigned int size, const void *data, int usageHint); // Load shader storage buffer object (SSBO) +RLAPI void rlUnloadShaderBuffer(unsigned int ssboId); // Unload shader storage buffer object (SSBO) +RLAPI void rlUpdateShaderBuffer(unsigned int id, const void *data, unsigned int dataSize, unsigned int offset); // Update SSBO buffer data +RLAPI void rlBindShaderBuffer(unsigned int id, unsigned int index); // Bind SSBO buffer +RLAPI void rlReadShaderBuffer(unsigned int id, void *dest, unsigned int count, unsigned int offset); // Read SSBO buffer data (GPU->CPU) +RLAPI void rlCopyShaderBuffer(unsigned int destId, unsigned int srcId, unsigned int destOffset, unsigned int srcOffset, unsigned int count); // Copy SSBO data between buffers +RLAPI unsigned int rlGetShaderBufferSize(unsigned int id); // Get SSBO buffer size + +// Buffer management +RLAPI void rlBindImageTexture(unsigned int id, unsigned int index, int format, bool readonly); // Bind image texture + +// Matrix state management +RLAPI Matrix rlGetMatrixModelview(void); // Get internal modelview matrix +RLAPI Matrix rlGetMatrixProjection(void); // Get internal projection matrix +RLAPI Matrix rlGetMatrixTransform(void); // Get internal accumulated transform matrix +RLAPI Matrix rlGetMatrixProjectionStereo(int eye); // Get internal projection matrix for stereo render (selected eye) +RLAPI Matrix rlGetMatrixViewOffsetStereo(int eye); // Get internal view offset matrix for stereo render (selected eye) +RLAPI void rlSetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) +RLAPI void rlSetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) +RLAPI void rlSetMatrixProjectionStereo(Matrix right, Matrix left); // Set eyes projection matrices for stereo rendering +RLAPI void rlSetMatrixViewOffsetStereo(Matrix right, Matrix left); // Set eyes view offsets matrices for stereo rendering + +// Quick and dirty cube/quad buffers load->draw->unload +RLAPI void rlLoadDrawCube(void); // Load and draw a cube +RLAPI void rlLoadDrawQuad(void); // Load and draw a quad + +#if defined(__cplusplus) +} +#endif + +#endif // RLGL_H + +/*********************************************************************************** +* +* RLGL IMPLEMENTATION +* +************************************************************************************/ + +#if defined(RLGL_IMPLEMENTATION) + +#if defined(GRAPHICS_API_OPENGL_11) + #if defined(__APPLE__) + #include // OpenGL 1.1 library for OSX + #include // OpenGL extensions library + #else + // APIENTRY for OpenGL function pointer declarations is required + #if !defined(APIENTRY) + #if defined(_WIN32) + #define APIENTRY __stdcall + #else + #define APIENTRY + #endif + #endif + // WINGDIAPI definition. Some Windows OpenGL headers need it + #if !defined(WINGDIAPI) && defined(_WIN32) + #define WINGDIAPI __declspec(dllimport) + #endif + + #include // OpenGL 1.1 library + #endif +#endif + +#if defined(GRAPHICS_API_OPENGL_33) + #define GLAD_MALLOC RL_MALLOC + #define GLAD_FREE RL_FREE + + #define GLAD_GL_IMPLEMENTATION + #include "external/glad.h" // GLAD extensions loading library, includes OpenGL headers +#endif + +#if defined(GRAPHICS_API_OPENGL_ES3) + #include // OpenGL ES 3.0 library + #define GL_GLEXT_PROTOTYPES + #include // OpenGL ES 2.0 extensions library +#elif defined(GRAPHICS_API_OPENGL_ES2) + // NOTE: OpenGL ES 2.0 can be enabled on PLATFORM_DESKTOP, + // in that case, functions are loaded from a custom glad for OpenGL ES 2.0 + #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_DESKTOP_SDL) + #define GLAD_GLES2_IMPLEMENTATION + #include "external/glad_gles2.h" + #else + #define GL_GLEXT_PROTOTYPES + //#include // EGL library -> not required, platform layer + #include // OpenGL ES 2.0 library + #include // OpenGL ES 2.0 extensions library + #endif + + // It seems OpenGL ES 2.0 instancing entry points are not defined on Raspberry Pi + // provided headers (despite being defined in official Khronos GLES2 headers) + #if defined(PLATFORM_DRM) + typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount); + typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); + typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISOREXTPROC) (GLuint index, GLuint divisor); + #endif +#endif + +#include // Required for: malloc(), free() +#include // Required for: strcmp(), strlen() [Used in rlglInit(), on extensions loading] +#include // Required for: sqrtf(), sinf(), cosf(), floor(), log() + +//---------------------------------------------------------------------------------- +// Defines and Macros +//---------------------------------------------------------------------------------- +#ifndef PI + #define PI 3.14159265358979323846f +#endif +#ifndef DEG2RAD + #define DEG2RAD (PI/180.0f) +#endif +#ifndef RAD2DEG + #define RAD2DEG (180.0f/PI) +#endif + +#ifndef GL_SHADING_LANGUAGE_VERSION + #define GL_SHADING_LANGUAGE_VERSION 0x8B8C +#endif + +#ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT + #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 +#endif +#ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT + #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 +#endif +#ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT + #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 +#endif +#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT + #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 +#endif +#ifndef GL_ETC1_RGB8_OES + #define GL_ETC1_RGB8_OES 0x8D64 +#endif +#ifndef GL_COMPRESSED_RGB8_ETC2 + #define GL_COMPRESSED_RGB8_ETC2 0x9274 +#endif +#ifndef GL_COMPRESSED_RGBA8_ETC2_EAC + #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 +#endif +#ifndef GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG + #define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00 +#endif +#ifndef GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG + #define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02 +#endif +#ifndef GL_COMPRESSED_RGBA_ASTC_4x4_KHR + #define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93b0 +#endif +#ifndef GL_COMPRESSED_RGBA_ASTC_8x8_KHR + #define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93b7 +#endif + +#ifndef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT + #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF +#endif +#ifndef GL_TEXTURE_MAX_ANISOTROPY_EXT + #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +#endif + +#if defined(GRAPHICS_API_OPENGL_11) + #define GL_UNSIGNED_SHORT_5_6_5 0x8363 + #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 + #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#endif + +#if defined(GRAPHICS_API_OPENGL_21) + #define GL_LUMINANCE 0x1909 + #define GL_LUMINANCE_ALPHA 0x190A +#endif + +#if defined(GRAPHICS_API_OPENGL_ES2) + #define glClearDepth glClearDepthf + #if !defined(GRAPHICS_API_OPENGL_ES3) + #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER + #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER + #endif +#endif + +// Default shader vertex attribute names to set location points +#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION + #define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: 0 +#endif +#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD + #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: 1 +#endif +#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL + #define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: 2 +#endif +#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR + #define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: 3 +#endif +#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT + #define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: 4 +#endif +#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 + #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: 5 +#endif + +#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_MVP + #define RL_DEFAULT_SHADER_UNIFORM_NAME_MVP "mvp" // model-view-projection matrix +#endif +#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW + #define RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW "matView" // view matrix +#endif +#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION + #define RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION "matProjection" // projection matrix +#endif +#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL + #define RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL "matModel" // model matrix +#endif +#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL + #define RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL "matNormal" // normal matrix (transpose(inverse(matModelView)) +#endif +#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR + #define RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR "colDiffuse" // color diffuse (base tint color, multiplied by texture color) +#endif +#ifndef RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 + #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 "texture0" // texture0 (texture slot active 0) +#endif +#ifndef RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 + #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 "texture1" // texture1 (texture slot active 1) +#endif +#ifndef RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 + #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 "texture2" // texture2 (texture slot active 2) +#endif + +//---------------------------------------------------------------------------------- +// Types and Structures Definition +//---------------------------------------------------------------------------------- +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) +typedef struct rlglData { + rlRenderBatch *currentBatch; // Current render batch + rlRenderBatch defaultBatch; // Default internal render batch + + struct { + int vertexCounter; // Current active render batch vertex counter (generic, used for all batches) + float texcoordx, texcoordy; // Current active texture coordinate (added on glVertex*()) + float normalx, normaly, normalz; // Current active normal (added on glVertex*()) + unsigned char colorr, colorg, colorb, colora; // Current active color (added on glVertex*()) + + int currentMatrixMode; // Current matrix mode + Matrix *currentMatrix; // Current matrix pointer + Matrix modelview; // Default modelview matrix + Matrix projection; // Default projection matrix + Matrix transform; // Transform matrix to be used with rlTranslate, rlRotate, rlScale + bool transformRequired; // Require transform matrix application to current draw-call vertex (if required) + Matrix stack[RL_MAX_MATRIX_STACK_SIZE];// Matrix stack for push/pop + int stackCounter; // Matrix stack counter + + unsigned int defaultTextureId; // Default texture used on shapes/poly drawing (required by shader) + unsigned int activeTextureId[RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS]; // Active texture ids to be enabled on batch drawing (0 active by default) + unsigned int defaultVShaderId; // Default vertex shader id (used by default shader program) + unsigned int defaultFShaderId; // Default fragment shader id (used by default shader program) + unsigned int defaultShaderId; // Default shader program id, supports vertex color and diffuse texture + int *defaultShaderLocs; // Default shader locations pointer to be used on rendering + unsigned int currentShaderId; // Current shader id to be used on rendering (by default, defaultShaderId) + int *currentShaderLocs; // Current shader locations pointer to be used on rendering (by default, defaultShaderLocs) + + bool stereoRender; // Stereo rendering flag + Matrix projectionStereo[2]; // VR stereo rendering eyes projection matrices + Matrix viewOffsetStereo[2]; // VR stereo rendering eyes view offset matrices + + // Blending variables + int currentBlendMode; // Blending mode active + int glBlendSrcFactor; // Blending source factor + int glBlendDstFactor; // Blending destination factor + int glBlendEquation; // Blending equation + int glBlendSrcFactorRGB; // Blending source RGB factor + int glBlendDestFactorRGB; // Blending destination RGB factor + int glBlendSrcFactorAlpha; // Blending source alpha factor + int glBlendDestFactorAlpha; // Blending destination alpha factor + int glBlendEquationRGB; // Blending equation for RGB + int glBlendEquationAlpha; // Blending equation for alpha + bool glCustomBlendModeModified; // Custom blending factor and equation modification status + + int framebufferWidth; // Current framebuffer width + int framebufferHeight; // Current framebuffer height + + } State; // Renderer state + struct { + bool vao; // VAO support (OpenGL ES2 could not support VAO extension) (GL_ARB_vertex_array_object) + bool instancing; // Instancing supported (GL_ANGLE_instanced_arrays, GL_EXT_draw_instanced + GL_EXT_instanced_arrays) + bool texNPOT; // NPOT textures full support (GL_ARB_texture_non_power_of_two, GL_OES_texture_npot) + bool texDepth; // Depth textures supported (GL_ARB_depth_texture, GL_OES_depth_texture) + bool texDepthWebGL; // Depth textures supported WebGL specific (GL_WEBGL_depth_texture) + bool texFloat32; // float textures support (32 bit per channel) (GL_OES_texture_float) + bool texFloat16; // half float textures support (16 bit per channel) (GL_OES_texture_half_float) + bool texCompDXT; // DDS texture compression support (GL_EXT_texture_compression_s3tc, GL_WEBGL_compressed_texture_s3tc, GL_WEBKIT_WEBGL_compressed_texture_s3tc) + bool texCompETC1; // ETC1 texture compression support (GL_OES_compressed_ETC1_RGB8_texture, GL_WEBGL_compressed_texture_etc1) + bool texCompETC2; // ETC2/EAC texture compression support (GL_ARB_ES3_compatibility) + bool texCompPVRT; // PVR texture compression support (GL_IMG_texture_compression_pvrtc) + bool texCompASTC; // ASTC texture compression support (GL_KHR_texture_compression_astc_hdr, GL_KHR_texture_compression_astc_ldr) + bool texMirrorClamp; // Clamp mirror wrap mode supported (GL_EXT_texture_mirror_clamp) + bool texAnisoFilter; // Anisotropic texture filtering support (GL_EXT_texture_filter_anisotropic) + bool computeShader; // Compute shaders support (GL_ARB_compute_shader) + bool ssbo; // Shader storage buffer object support (GL_ARB_shader_storage_buffer_object) + + float maxAnisotropyLevel; // Maximum anisotropy level supported (minimum is 2.0f) + int maxDepthBits; // Maximum bits for depth component + + } ExtSupported; // Extensions supported flags +} rlglData; + +typedef void *(*rlglLoadProc)(const char *name); // OpenGL extension functions loader signature (same as GLADloadproc) + +#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 + +//---------------------------------------------------------------------------------- +// Global Variables Definition +//---------------------------------------------------------------------------------- +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) +static rlglData RLGL = { 0 }; +#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 + +#if defined(GRAPHICS_API_OPENGL_ES2) && !defined(GRAPHICS_API_OPENGL_ES3) +// NOTE: VAO functionality is exposed through extensions (OES) +static PFNGLGENVERTEXARRAYSOESPROC glGenVertexArrays = NULL; +static PFNGLBINDVERTEXARRAYOESPROC glBindVertexArray = NULL; +static PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArrays = NULL; + +// NOTE: Instancing functionality could also be available through extension +static PFNGLDRAWARRAYSINSTANCEDEXTPROC glDrawArraysInstanced = NULL; +static PFNGLDRAWELEMENTSINSTANCEDEXTPROC glDrawElementsInstanced = NULL; +static PFNGLVERTEXATTRIBDIVISOREXTPROC glVertexAttribDivisor = NULL; +#endif + +//---------------------------------------------------------------------------------- +// Module specific Functions Declaration +//---------------------------------------------------------------------------------- +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) +static void rlLoadShaderDefault(void); // Load default shader +static void rlUnloadShaderDefault(void); // Unload default shader +#if defined(RLGL_SHOW_GL_DETAILS_INFO) +static const char *rlGetCompressedFormatName(int format); // Get compressed format official GL identifier name +#endif // RLGL_SHOW_GL_DETAILS_INFO +#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 + +static int rlGetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes (image or texture) + +// Auxiliar matrix math functions +static Matrix rlMatrixIdentity(void); // Get identity matrix +static Matrix rlMatrixMultiply(Matrix left, Matrix right); // Multiply two matrices + +//---------------------------------------------------------------------------------- +// Module Functions Definition - Matrix operations +//---------------------------------------------------------------------------------- + +#if defined(GRAPHICS_API_OPENGL_11) +// Fallback to OpenGL 1.1 function calls +//--------------------------------------- +void rlMatrixMode(int mode) +{ + switch (mode) + { + case RL_PROJECTION: glMatrixMode(GL_PROJECTION); break; + case RL_MODELVIEW: glMatrixMode(GL_MODELVIEW); break; + case RL_TEXTURE: glMatrixMode(GL_TEXTURE); break; + default: break; + } +} + +void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar) +{ + glFrustum(left, right, bottom, top, znear, zfar); +} + +void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar) +{ + glOrtho(left, right, bottom, top, znear, zfar); +} + +void rlPushMatrix(void) { glPushMatrix(); } +void rlPopMatrix(void) { glPopMatrix(); } +void rlLoadIdentity(void) { glLoadIdentity(); } +void rlTranslatef(float x, float y, float z) { glTranslatef(x, y, z); } +void rlRotatef(float angle, float x, float y, float z) { glRotatef(angle, x, y, z); } +void rlScalef(float x, float y, float z) { glScalef(x, y, z); } +void rlMultMatrixf(const float *matf) { glMultMatrixf(matf); } +#endif +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) +// Choose the current matrix to be transformed +void rlMatrixMode(int mode) +{ + if (mode == RL_PROJECTION) RLGL.State.currentMatrix = &RLGL.State.projection; + else if (mode == RL_MODELVIEW) RLGL.State.currentMatrix = &RLGL.State.modelview; + //else if (mode == RL_TEXTURE) // Not supported + + RLGL.State.currentMatrixMode = mode; +} + +// Push the current matrix into RLGL.State.stack +void rlPushMatrix(void) +{ + if (RLGL.State.stackCounter >= RL_MAX_MATRIX_STACK_SIZE) TRACELOG(RL_LOG_ERROR, "RLGL: Matrix stack overflow (RL_MAX_MATRIX_STACK_SIZE)"); + + if (RLGL.State.currentMatrixMode == RL_MODELVIEW) + { + RLGL.State.transformRequired = true; + RLGL.State.currentMatrix = &RLGL.State.transform; + } + + RLGL.State.stack[RLGL.State.stackCounter] = *RLGL.State.currentMatrix; + RLGL.State.stackCounter++; +} + +// Pop lattest inserted matrix from RLGL.State.stack +void rlPopMatrix(void) +{ + if (RLGL.State.stackCounter > 0) + { + Matrix mat = RLGL.State.stack[RLGL.State.stackCounter - 1]; + *RLGL.State.currentMatrix = mat; + RLGL.State.stackCounter--; + } + + if ((RLGL.State.stackCounter == 0) && (RLGL.State.currentMatrixMode == RL_MODELVIEW)) + { + RLGL.State.currentMatrix = &RLGL.State.modelview; + RLGL.State.transformRequired = false; + } +} + +// Reset current matrix to identity matrix +void rlLoadIdentity(void) +{ + *RLGL.State.currentMatrix = rlMatrixIdentity(); +} + +// Multiply the current matrix by a translation matrix +void rlTranslatef(float x, float y, float z) +{ + Matrix matTranslation = { + 1.0f, 0.0f, 0.0f, x, + 0.0f, 1.0f, 0.0f, y, + 0.0f, 0.0f, 1.0f, z, + 0.0f, 0.0f, 0.0f, 1.0f + }; + + // NOTE: We transpose matrix with multiplication order + *RLGL.State.currentMatrix = rlMatrixMultiply(matTranslation, *RLGL.State.currentMatrix); +} + +// Multiply the current matrix by a rotation matrix +// NOTE: The provided angle must be in degrees +void rlRotatef(float angle, float x, float y, float z) +{ + Matrix matRotation = rlMatrixIdentity(); + + // Axis vector (x, y, z) normalization + float lengthSquared = x*x + y*y + z*z; + if ((lengthSquared != 1.0f) && (lengthSquared != 0.0f)) + { + float inverseLength = 1.0f/sqrtf(lengthSquared); + x *= inverseLength; + y *= inverseLength; + z *= inverseLength; + } + + // Rotation matrix generation + float sinres = sinf(DEG2RAD*angle); + float cosres = cosf(DEG2RAD*angle); + float t = 1.0f - cosres; + + matRotation.m0 = x*x*t + cosres; + matRotation.m1 = y*x*t + z*sinres; + matRotation.m2 = z*x*t - y*sinres; + matRotation.m3 = 0.0f; + + matRotation.m4 = x*y*t - z*sinres; + matRotation.m5 = y*y*t + cosres; + matRotation.m6 = z*y*t + x*sinres; + matRotation.m7 = 0.0f; + + matRotation.m8 = x*z*t + y*sinres; + matRotation.m9 = y*z*t - x*sinres; + matRotation.m10 = z*z*t + cosres; + matRotation.m11 = 0.0f; + + matRotation.m12 = 0.0f; + matRotation.m13 = 0.0f; + matRotation.m14 = 0.0f; + matRotation.m15 = 1.0f; + + // NOTE: We transpose matrix with multiplication order + *RLGL.State.currentMatrix = rlMatrixMultiply(matRotation, *RLGL.State.currentMatrix); +} + +// Multiply the current matrix by a scaling matrix +void rlScalef(float x, float y, float z) +{ + Matrix matScale = { + x, 0.0f, 0.0f, 0.0f, + 0.0f, y, 0.0f, 0.0f, + 0.0f, 0.0f, z, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + }; + + // NOTE: We transpose matrix with multiplication order + *RLGL.State.currentMatrix = rlMatrixMultiply(matScale, *RLGL.State.currentMatrix); +} + +// Multiply the current matrix by another matrix +void rlMultMatrixf(const float *matf) +{ + // Matrix creation from array + Matrix mat = { matf[0], matf[4], matf[8], matf[12], + matf[1], matf[5], matf[9], matf[13], + matf[2], matf[6], matf[10], matf[14], + matf[3], matf[7], matf[11], matf[15] }; + + *RLGL.State.currentMatrix = rlMatrixMultiply(*RLGL.State.currentMatrix, mat); +} + +// Multiply the current matrix by a perspective matrix generated by parameters +void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar) +{ + Matrix matFrustum = { 0 }; + + float rl = (float)(right - left); + float tb = (float)(top - bottom); + float fn = (float)(zfar - znear); + + matFrustum.m0 = ((float) znear*2.0f)/rl; + matFrustum.m1 = 0.0f; + matFrustum.m2 = 0.0f; + matFrustum.m3 = 0.0f; + + matFrustum.m4 = 0.0f; + matFrustum.m5 = ((float) znear*2.0f)/tb; + matFrustum.m6 = 0.0f; + matFrustum.m7 = 0.0f; + + matFrustum.m8 = ((float)right + (float)left)/rl; + matFrustum.m9 = ((float)top + (float)bottom)/tb; + matFrustum.m10 = -((float)zfar + (float)znear)/fn; + matFrustum.m11 = -1.0f; + + matFrustum.m12 = 0.0f; + matFrustum.m13 = 0.0f; + matFrustum.m14 = -((float)zfar*(float)znear*2.0f)/fn; + matFrustum.m15 = 0.0f; + + *RLGL.State.currentMatrix = rlMatrixMultiply(*RLGL.State.currentMatrix, matFrustum); +} + +// Multiply the current matrix by an orthographic matrix generated by parameters +void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar) +{ + // NOTE: If left-right and top-botton values are equal it could create a division by zero, + // response to it is platform/compiler dependant + Matrix matOrtho = { 0 }; + + float rl = (float)(right - left); + float tb = (float)(top - bottom); + float fn = (float)(zfar - znear); + + matOrtho.m0 = 2.0f/rl; + matOrtho.m1 = 0.0f; + matOrtho.m2 = 0.0f; + matOrtho.m3 = 0.0f; + matOrtho.m4 = 0.0f; + matOrtho.m5 = 2.0f/tb; + matOrtho.m6 = 0.0f; + matOrtho.m7 = 0.0f; + matOrtho.m8 = 0.0f; + matOrtho.m9 = 0.0f; + matOrtho.m10 = -2.0f/fn; + matOrtho.m11 = 0.0f; + matOrtho.m12 = -((float)left + (float)right)/rl; + matOrtho.m13 = -((float)top + (float)bottom)/tb; + matOrtho.m14 = -((float)zfar + (float)znear)/fn; + matOrtho.m15 = 1.0f; + + *RLGL.State.currentMatrix = rlMatrixMultiply(*RLGL.State.currentMatrix, matOrtho); +} +#endif + +// Set the viewport area (transformation from normalized device coordinates to window coordinates) +// NOTE: We store current viewport dimensions +void rlViewport(int x, int y, int width, int height) +{ + glViewport(x, y, width, height); +} + +//---------------------------------------------------------------------------------- +// Module Functions Definition - Vertex level operations +//---------------------------------------------------------------------------------- +#if defined(GRAPHICS_API_OPENGL_11) +// Fallback to OpenGL 1.1 function calls +//--------------------------------------- +void rlBegin(int mode) +{ + switch (mode) + { + case RL_LINES: glBegin(GL_LINES); break; + case RL_TRIANGLES: glBegin(GL_TRIANGLES); break; + case RL_QUADS: glBegin(GL_QUADS); break; + default: break; + } +} + +void rlEnd() { glEnd(); } +void rlVertex2i(int x, int y) { glVertex2i(x, y); } +void rlVertex2f(float x, float y) { glVertex2f(x, y); } +void rlVertex3f(float x, float y, float z) { glVertex3f(x, y, z); } +void rlTexCoord2f(float x, float y) { glTexCoord2f(x, y); } +void rlNormal3f(float x, float y, float z) { glNormal3f(x, y, z); } +void rlColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a) { glColor4ub(r, g, b, a); } +void rlColor3f(float x, float y, float z) { glColor3f(x, y, z); } +void rlColor4f(float x, float y, float z, float w) { glColor4f(x, y, z, w); } +#endif +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) +// Initialize drawing mode (how to organize vertex) +void rlBegin(int mode) +{ + // Draw mode can be RL_LINES, RL_TRIANGLES and RL_QUADS + // NOTE: In all three cases, vertex are accumulated over default internal vertex buffer + if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode != mode) + { + if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount > 0) + { + // Make sure current RLGL.currentBatch->draws[i].vertexCount is aligned a multiple of 4, + // that way, following QUADS drawing will keep aligned with index processing + // It implies adding some extra alignment vertex at the end of the draw, + // those vertex are not processed but they are considered as an additional offset + // for the next set of vertex to be drawn + if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_LINES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount : RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4); + else if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_TRIANGLES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? 1 : (4 - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4))); + else RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = 0; + + if (!rlCheckRenderBatchLimit(RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment)) + { + RLGL.State.vertexCounter += RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment; + RLGL.currentBatch->drawCounter++; + } + } + + if (RLGL.currentBatch->drawCounter >= RL_DEFAULT_BATCH_DRAWCALLS) rlDrawRenderBatch(RLGL.currentBatch); + + RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode = mode; + RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount = 0; + RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId = RLGL.State.defaultTextureId; + } +} + +// Finish vertex providing +void rlEnd(void) +{ + // NOTE: Depth increment is dependant on rlOrtho(): z-near and z-far values, + // as well as depth buffer bit-depth (16bit or 24bit or 32bit) + // Correct increment formula would be: depthInc = (zfar - znear)/pow(2, bits) + RLGL.currentBatch->currentDepth += (1.0f/20000.0f); +} + +// Define one vertex (position) +// NOTE: Vertex position data is the basic information required for drawing +void rlVertex3f(float x, float y, float z) +{ + float tx = x; + float ty = y; + float tz = z; + + // Transform provided vector if required + if (RLGL.State.transformRequired) + { + tx = RLGL.State.transform.m0*x + RLGL.State.transform.m4*y + RLGL.State.transform.m8*z + RLGL.State.transform.m12; + ty = RLGL.State.transform.m1*x + RLGL.State.transform.m5*y + RLGL.State.transform.m9*z + RLGL.State.transform.m13; + tz = RLGL.State.transform.m2*x + RLGL.State.transform.m6*y + RLGL.State.transform.m10*z + RLGL.State.transform.m14; + } + + // WARNING: We can't break primitives when launching a new batch. + // RL_LINES comes in pairs, RL_TRIANGLES come in groups of 3 vertices and RL_QUADS come in groups of 4 vertices. + // We must check current draw.mode when a new vertex is required and finish the batch only if the draw.mode draw.vertexCount is %2, %3 or %4 + if (RLGL.State.vertexCounter > (RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].elementCount*4 - 4)) + { + if ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_LINES) && + (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%2 == 0)) + { + // Reached the maximum number of vertices for RL_LINES drawing + // Launch a draw call but keep current state for next vertices comming + // NOTE: We add +1 vertex to the check for security + rlCheckRenderBatchLimit(2 + 1); + } + else if ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_TRIANGLES) && + (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%3 == 0)) + { + rlCheckRenderBatchLimit(3 + 1); + } + else if ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_QUADS) && + (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4 == 0)) + { + rlCheckRenderBatchLimit(4 + 1); + } + } + + // Add vertices + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].vertices[3*RLGL.State.vertexCounter] = tx; + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].vertices[3*RLGL.State.vertexCounter + 1] = ty; + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].vertices[3*RLGL.State.vertexCounter + 2] = tz; + + // Add current texcoord + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].texcoords[2*RLGL.State.vertexCounter] = RLGL.State.texcoordx; + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].texcoords[2*RLGL.State.vertexCounter + 1] = RLGL.State.texcoordy; + + // WARNING: By default rlVertexBuffer struct does not store normals + + // Add current color + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter] = RLGL.State.colorr; + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter + 1] = RLGL.State.colorg; + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter + 2] = RLGL.State.colorb; + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter + 3] = RLGL.State.colora; + + RLGL.State.vertexCounter++; + RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount++; +} + +// Define one vertex (position) +void rlVertex2f(float x, float y) +{ + rlVertex3f(x, y, RLGL.currentBatch->currentDepth); +} + +// Define one vertex (position) +void rlVertex2i(int x, int y) +{ + rlVertex3f((float)x, (float)y, RLGL.currentBatch->currentDepth); +} + +// Define one vertex (texture coordinate) +// NOTE: Texture coordinates are limited to QUADS only +void rlTexCoord2f(float x, float y) +{ + RLGL.State.texcoordx = x; + RLGL.State.texcoordy = y; +} + +// Define one vertex (normal) +// NOTE: Normals limited to TRIANGLES only? +void rlNormal3f(float x, float y, float z) +{ + RLGL.State.normalx = x; + RLGL.State.normaly = y; + RLGL.State.normalz = z; +} + +// Define one vertex (color) +void rlColor4ub(unsigned char x, unsigned char y, unsigned char z, unsigned char w) +{ + RLGL.State.colorr = x; + RLGL.State.colorg = y; + RLGL.State.colorb = z; + RLGL.State.colora = w; +} + +// Define one vertex (color) +void rlColor4f(float r, float g, float b, float a) +{ + rlColor4ub((unsigned char)(r*255), (unsigned char)(g*255), (unsigned char)(b*255), (unsigned char)(a*255)); +} + +// Define one vertex (color) +void rlColor3f(float x, float y, float z) +{ + rlColor4ub((unsigned char)(x*255), (unsigned char)(y*255), (unsigned char)(z*255), 255); +} + +#endif + +//-------------------------------------------------------------------------------------- +// Module Functions Definition - OpenGL style functions (common to 1.1, 3.3+, ES2) +//-------------------------------------------------------------------------------------- + +// Set current texture to use +void rlSetTexture(unsigned int id) +{ + if (id == 0) + { +#if defined(GRAPHICS_API_OPENGL_11) + rlDisableTexture(); +#else + // NOTE: If quads batch limit is reached, we force a draw call and next batch starts + if (RLGL.State.vertexCounter >= + RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].elementCount*4) + { + rlDrawRenderBatch(RLGL.currentBatch); + } +#endif + } + else + { +#if defined(GRAPHICS_API_OPENGL_11) + rlEnableTexture(id); +#else + if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId != id) + { + if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount > 0) + { + // Make sure current RLGL.currentBatch->draws[i].vertexCount is aligned a multiple of 4, + // that way, following QUADS drawing will keep aligned with index processing + // It implies adding some extra alignment vertex at the end of the draw, + // those vertex are not processed but they are considered as an additional offset + // for the next set of vertex to be drawn + if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_LINES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount : RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4); + else if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_TRIANGLES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? 1 : (4 - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4))); + else RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = 0; + + if (!rlCheckRenderBatchLimit(RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment)) + { + RLGL.State.vertexCounter += RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment; + + RLGL.currentBatch->drawCounter++; + } + } + + if (RLGL.currentBatch->drawCounter >= RL_DEFAULT_BATCH_DRAWCALLS) rlDrawRenderBatch(RLGL.currentBatch); + + RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId = id; + RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount = 0; + } +#endif + } +} + +// Select and active a texture slot +void rlActiveTextureSlot(int slot) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glActiveTexture(GL_TEXTURE0 + slot); +#endif +} + +// Enable texture +void rlEnableTexture(unsigned int id) +{ +#if defined(GRAPHICS_API_OPENGL_11) + glEnable(GL_TEXTURE_2D); +#endif + glBindTexture(GL_TEXTURE_2D, id); +} + +// Disable texture +void rlDisableTexture(void) +{ +#if defined(GRAPHICS_API_OPENGL_11) + glDisable(GL_TEXTURE_2D); +#endif + glBindTexture(GL_TEXTURE_2D, 0); +} + +// Enable texture cubemap +void rlEnableTextureCubemap(unsigned int id) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glBindTexture(GL_TEXTURE_CUBE_MAP, id); +#endif +} + +// Disable texture cubemap +void rlDisableTextureCubemap(void) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glBindTexture(GL_TEXTURE_CUBE_MAP, 0); +#endif +} + +// Set texture parameters (wrap mode/filter mode) +void rlTextureParameters(unsigned int id, int param, int value) +{ + glBindTexture(GL_TEXTURE_2D, id); + +#if !defined(GRAPHICS_API_OPENGL_11) + // Reset anisotropy filter, in case it was set + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); +#endif + + switch (param) + { + case RL_TEXTURE_WRAP_S: + case RL_TEXTURE_WRAP_T: + { + if (value == RL_TEXTURE_WRAP_MIRROR_CLAMP) + { +#if !defined(GRAPHICS_API_OPENGL_11) + if (RLGL.ExtSupported.texMirrorClamp) glTexParameteri(GL_TEXTURE_2D, param, value); + else TRACELOG(RL_LOG_WARNING, "GL: Clamp mirror wrap mode not supported (GL_MIRROR_CLAMP_EXT)"); +#endif + } + else glTexParameteri(GL_TEXTURE_2D, param, value); + + } break; + case RL_TEXTURE_MAG_FILTER: + case RL_TEXTURE_MIN_FILTER: glTexParameteri(GL_TEXTURE_2D, param, value); break; + case RL_TEXTURE_FILTER_ANISOTROPIC: + { +#if !defined(GRAPHICS_API_OPENGL_11) + if (value <= RLGL.ExtSupported.maxAnisotropyLevel) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); + else if (RLGL.ExtSupported.maxAnisotropyLevel > 0.0f) + { + TRACELOG(RL_LOG_WARNING, "GL: Maximum anisotropic filter level supported is %iX", id, (int)RLGL.ExtSupported.maxAnisotropyLevel); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); + } + else TRACELOG(RL_LOG_WARNING, "GL: Anisotropic filtering not supported"); +#endif + } break; +#if defined(GRAPHICS_API_OPENGL_33) + case RL_TEXTURE_MIPMAP_BIAS_RATIO: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, value/100.0f); +#endif + default: break; + } + + glBindTexture(GL_TEXTURE_2D, 0); +} + +// Set cubemap parameters (wrap mode/filter mode) +void rlCubemapParameters(unsigned int id, int param, int value) +{ +#if !defined(GRAPHICS_API_OPENGL_11) + glBindTexture(GL_TEXTURE_CUBE_MAP, id); + + // Reset anisotropy filter, in case it was set + glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); + + switch (param) + { + case RL_TEXTURE_WRAP_S: + case RL_TEXTURE_WRAP_T: + { + if (value == RL_TEXTURE_WRAP_MIRROR_CLAMP) + { + if (RLGL.ExtSupported.texMirrorClamp) glTexParameteri(GL_TEXTURE_CUBE_MAP, param, value); + else TRACELOG(RL_LOG_WARNING, "GL: Clamp mirror wrap mode not supported (GL_MIRROR_CLAMP_EXT)"); + } + else glTexParameteri(GL_TEXTURE_CUBE_MAP, param, value); + + } break; + case RL_TEXTURE_MAG_FILTER: + case RL_TEXTURE_MIN_FILTER: glTexParameteri(GL_TEXTURE_CUBE_MAP, param, value); break; + case RL_TEXTURE_FILTER_ANISOTROPIC: + { + if (value <= RLGL.ExtSupported.maxAnisotropyLevel) glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); + else if (RLGL.ExtSupported.maxAnisotropyLevel > 0.0f) + { + TRACELOG(RL_LOG_WARNING, "GL: Maximum anisotropic filter level supported is %iX", id, (int)RLGL.ExtSupported.maxAnisotropyLevel); + glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); + } + else TRACELOG(RL_LOG_WARNING, "GL: Anisotropic filtering not supported"); + } break; +#if defined(GRAPHICS_API_OPENGL_33) + case RL_TEXTURE_MIPMAP_BIAS_RATIO: glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_LOD_BIAS, value/100.0f); +#endif + default: break; + } + + glBindTexture(GL_TEXTURE_CUBE_MAP, 0); +#endif +} + +// Enable shader program +void rlEnableShader(unsigned int id) +{ +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) + glUseProgram(id); +#endif +} + +// Disable shader program +void rlDisableShader(void) +{ +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) + glUseProgram(0); +#endif +} + +// Enable rendering to texture (fbo) +void rlEnableFramebuffer(unsigned int id) +{ +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) + glBindFramebuffer(GL_FRAMEBUFFER, id); +#endif +} + +// Disable rendering to texture +void rlDisableFramebuffer(void) +{ +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) + glBindFramebuffer(GL_FRAMEBUFFER, 0); +#endif +} + +// Blit active framebuffer to main framebuffer +void rlBlitFramebuffer(int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight, int bufferMask) +{ +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES3)) && defined(RLGL_RENDER_TEXTURES_HINT) + glBlitFramebuffer(srcX, srcY, srcWidth, srcHeight, dstX, dstY, dstWidth, dstHeight, bufferMask, GL_NEAREST); +#endif +} + +// Activate multiple draw color buffers +// NOTE: One color buffer is always active by default +void rlActiveDrawBuffers(int count) +{ +#if ((defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES3)) && defined(RLGL_RENDER_TEXTURES_HINT)) + // NOTE: Maximum number of draw buffers supported is implementation dependant, + // it can be queried with glGet*() but it must be at least 8 + //GLint maxDrawBuffers = 0; + //glGetIntegerv(GL_MAX_DRAW_BUFFERS, &maxDrawBuffers); + + if (count > 0) + { + if (count > 8) TRACELOG(LOG_WARNING, "GL: Max color buffers limited to 8"); + else + { + unsigned int buffers[8] = { +#if defined(GRAPHICS_API_OPENGL_ES3) + GL_COLOR_ATTACHMENT0_EXT, + GL_COLOR_ATTACHMENT1_EXT, + GL_COLOR_ATTACHMENT2_EXT, + GL_COLOR_ATTACHMENT3_EXT, + GL_COLOR_ATTACHMENT4_EXT, + GL_COLOR_ATTACHMENT5_EXT, + GL_COLOR_ATTACHMENT6_EXT, + GL_COLOR_ATTACHMENT7_EXT, +#else + GL_COLOR_ATTACHMENT0, + GL_COLOR_ATTACHMENT1, + GL_COLOR_ATTACHMENT2, + GL_COLOR_ATTACHMENT3, + GL_COLOR_ATTACHMENT4, + GL_COLOR_ATTACHMENT5, + GL_COLOR_ATTACHMENT6, + GL_COLOR_ATTACHMENT7, +#endif + }; + +#if defined(GRAPHICS_API_OPENGL_ES3) + glDrawBuffersEXT(count, buffers); +#else + glDrawBuffers(count, buffers); +#endif + } + } + else TRACELOG(LOG_WARNING, "GL: One color buffer active by default"); +#endif +} + +//---------------------------------------------------------------------------------- +// General render state configuration +//---------------------------------------------------------------------------------- + +// Enable color blending +void rlEnableColorBlend(void) { glEnable(GL_BLEND); } + +// Disable color blending +void rlDisableColorBlend(void) { glDisable(GL_BLEND); } + +// Enable depth test +void rlEnableDepthTest(void) { glEnable(GL_DEPTH_TEST); } + +// Disable depth test +void rlDisableDepthTest(void) { glDisable(GL_DEPTH_TEST); } + +// Enable depth write +void rlEnableDepthMask(void) { glDepthMask(GL_TRUE); } + +// Disable depth write +void rlDisableDepthMask(void) { glDepthMask(GL_FALSE); } + +// Enable backface culling +void rlEnableBackfaceCulling(void) { glEnable(GL_CULL_FACE); } + +// Disable backface culling +void rlDisableBackfaceCulling(void) { glDisable(GL_CULL_FACE); } + +// Set face culling mode +void rlSetCullFace(int mode) +{ + switch (mode) + { + case RL_CULL_FACE_BACK: glCullFace(GL_BACK); break; + case RL_CULL_FACE_FRONT: glCullFace(GL_FRONT); break; + default: break; + } +} + +// Enable scissor test +void rlEnableScissorTest(void) { glEnable(GL_SCISSOR_TEST); } + +// Disable scissor test +void rlDisableScissorTest(void) { glDisable(GL_SCISSOR_TEST); } + +// Scissor test +void rlScissor(int x, int y, int width, int height) { glScissor(x, y, width, height); } + +// Enable wire mode +void rlEnableWireMode(void) +{ +#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) + // NOTE: glPolygonMode() not available on OpenGL ES + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); +#endif +} + +void rlEnablePointMode(void) +{ +#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) + // NOTE: glPolygonMode() not available on OpenGL ES + glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); + glEnable(GL_PROGRAM_POINT_SIZE); +#endif +} +// Disable wire mode +void rlDisableWireMode(void) +{ +#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) + // NOTE: glPolygonMode() not available on OpenGL ES + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); +#endif +} + +// Set the line drawing width +void rlSetLineWidth(float width) { glLineWidth(width); } + +// Get the line drawing width +float rlGetLineWidth(void) +{ + float width = 0; + glGetFloatv(GL_LINE_WIDTH, &width); + return width; +} + +// Enable line aliasing +void rlEnableSmoothLines(void) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_11) + glEnable(GL_LINE_SMOOTH); +#endif +} + +// Disable line aliasing +void rlDisableSmoothLines(void) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_11) + glDisable(GL_LINE_SMOOTH); +#endif +} + +// Enable stereo rendering +void rlEnableStereoRender(void) +{ +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) + RLGL.State.stereoRender = true; +#endif +} + +// Disable stereo rendering +void rlDisableStereoRender(void) +{ +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) + RLGL.State.stereoRender = false; +#endif +} + +// Check if stereo render is enabled +bool rlIsStereoRenderEnabled(void) +{ +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) + return RLGL.State.stereoRender; +#else + return false; +#endif +} + +// Clear color buffer with color +void rlClearColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) +{ + // Color values clamp to 0.0f(0) and 1.0f(255) + float cr = (float)r/255; + float cg = (float)g/255; + float cb = (float)b/255; + float ca = (float)a/255; + + glClearColor(cr, cg, cb, ca); +} + +// Clear used screen buffers (color and depth) +void rlClearScreenBuffers(void) +{ + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear used buffers: Color and Depth (Depth is used for 3D) + //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // Stencil buffer not used... +} + +// Check and log OpenGL error codes +void rlCheckErrors() +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + int check = 1; + while (check) + { + const GLenum err = glGetError(); + switch (err) + { + case GL_NO_ERROR: check = 0; break; + case 0x0500: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_ENUM"); break; + case 0x0501: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_VALUE"); break; + case 0x0502: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_OPERATION"); break; + case 0x0503: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_STACK_OVERFLOW"); break; + case 0x0504: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_STACK_UNDERFLOW"); break; + case 0x0505: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_OUT_OF_MEMORY"); break; + case 0x0506: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_FRAMEBUFFER_OPERATION"); break; + default: TRACELOG(RL_LOG_WARNING, "GL: Error detected: Unknown error code: %x", err); break; + } + } +#endif +} + +// Set blend mode +void rlSetBlendMode(int mode) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + if ((RLGL.State.currentBlendMode != mode) || ((mode == RL_BLEND_CUSTOM || mode == RL_BLEND_CUSTOM_SEPARATE) && RLGL.State.glCustomBlendModeModified)) + { + rlDrawRenderBatch(RLGL.currentBatch); + + switch (mode) + { + case RL_BLEND_ALPHA: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); break; + case RL_BLEND_ADDITIVE: glBlendFunc(GL_SRC_ALPHA, GL_ONE); glBlendEquation(GL_FUNC_ADD); break; + case RL_BLEND_MULTIPLIED: glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); break; + case RL_BLEND_ADD_COLORS: glBlendFunc(GL_ONE, GL_ONE); glBlendEquation(GL_FUNC_ADD); break; + case RL_BLEND_SUBTRACT_COLORS: glBlendFunc(GL_ONE, GL_ONE); glBlendEquation(GL_FUNC_SUBTRACT); break; + case RL_BLEND_ALPHA_PREMULTIPLY: glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); break; + case RL_BLEND_CUSTOM: + { + // NOTE: Using GL blend src/dst factors and GL equation configured with rlSetBlendFactors() + glBlendFunc(RLGL.State.glBlendSrcFactor, RLGL.State.glBlendDstFactor); glBlendEquation(RLGL.State.glBlendEquation); + + } break; + case RL_BLEND_CUSTOM_SEPARATE: + { + // NOTE: Using GL blend src/dst factors and GL equation configured with rlSetBlendFactorsSeparate() + glBlendFuncSeparate(RLGL.State.glBlendSrcFactorRGB, RLGL.State.glBlendDestFactorRGB, RLGL.State.glBlendSrcFactorAlpha, RLGL.State.glBlendDestFactorAlpha); + glBlendEquationSeparate(RLGL.State.glBlendEquationRGB, RLGL.State.glBlendEquationAlpha); + + } break; + default: break; + } + + RLGL.State.currentBlendMode = mode; + RLGL.State.glCustomBlendModeModified = false; + } +#endif +} + +// Set blending mode factor and equation +void rlSetBlendFactors(int glSrcFactor, int glDstFactor, int glEquation) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + if ((RLGL.State.glBlendSrcFactor != glSrcFactor) || + (RLGL.State.glBlendDstFactor != glDstFactor) || + (RLGL.State.glBlendEquation != glEquation)) + { + RLGL.State.glBlendSrcFactor = glSrcFactor; + RLGL.State.glBlendDstFactor = glDstFactor; + RLGL.State.glBlendEquation = glEquation; + + RLGL.State.glCustomBlendModeModified = true; + } +#endif +} + +// Set blending mode factor and equation separately for RGB and alpha +void rlSetBlendFactorsSeparate(int glSrcRGB, int glDstRGB, int glSrcAlpha, int glDstAlpha, int glEqRGB, int glEqAlpha) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + if ((RLGL.State.glBlendSrcFactorRGB != glSrcRGB) || + (RLGL.State.glBlendDestFactorRGB != glDstRGB) || + (RLGL.State.glBlendSrcFactorAlpha != glSrcAlpha) || + (RLGL.State.glBlendDestFactorAlpha != glDstAlpha) || + (RLGL.State.glBlendEquationRGB != glEqRGB) || + (RLGL.State.glBlendEquationAlpha != glEqAlpha)) + { + RLGL.State.glBlendSrcFactorRGB = glSrcRGB; + RLGL.State.glBlendDestFactorRGB = glDstRGB; + RLGL.State.glBlendSrcFactorAlpha = glSrcAlpha; + RLGL.State.glBlendDestFactorAlpha = glDstAlpha; + RLGL.State.glBlendEquationRGB = glEqRGB; + RLGL.State.glBlendEquationAlpha = glEqAlpha; + + RLGL.State.glCustomBlendModeModified = true; + } +#endif +} + +//---------------------------------------------------------------------------------- +// Module Functions Definition - OpenGL Debug +//---------------------------------------------------------------------------------- +#if defined(RLGL_ENABLE_OPENGL_DEBUG_CONTEXT) && defined(GRAPHICS_API_OPENGL_43) +static void GLAPIENTRY rlDebugMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) +{ + // Ignore non-significant error/warning codes (NVidia drivers) + // NOTE: Here there are the details with a sample output: + // - #131169 - Framebuffer detailed info: The driver allocated storage for renderbuffer 2. (severity: low) + // - #131185 - Buffer detailed info: Buffer object 1 (bound to GL_ELEMENT_ARRAY_BUFFER_ARB, usage hint is GL_ENUM_88e4) + // will use VIDEO memory as the source for buffer object operations. (severity: low) + // - #131218 - Program/shader state performance warning: Vertex shader in program 7 is being recompiled based on GL state. (severity: medium) + // - #131204 - Texture state usage warning: The texture object (0) bound to texture image unit 0 does not have + // a defined base level and cannot be used for texture mapping. (severity: low) + if ((id == 131169) || (id == 131185) || (id == 131218) || (id == 131204)) return; + + const char *msgSource = NULL; + switch (source) + { + case GL_DEBUG_SOURCE_API: msgSource = "API"; break; + case GL_DEBUG_SOURCE_WINDOW_SYSTEM: msgSource = "WINDOW_SYSTEM"; break; + case GL_DEBUG_SOURCE_SHADER_COMPILER: msgSource = "SHADER_COMPILER"; break; + case GL_DEBUG_SOURCE_THIRD_PARTY: msgSource = "THIRD_PARTY"; break; + case GL_DEBUG_SOURCE_APPLICATION: msgSource = "APPLICATION"; break; + case GL_DEBUG_SOURCE_OTHER: msgSource = "OTHER"; break; + default: break; + } + + const char *msgType = NULL; + switch (type) + { + case GL_DEBUG_TYPE_ERROR: msgType = "ERROR"; break; + case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: msgType = "DEPRECATED_BEHAVIOR"; break; + case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: msgType = "UNDEFINED_BEHAVIOR"; break; + case GL_DEBUG_TYPE_PORTABILITY: msgType = "PORTABILITY"; break; + case GL_DEBUG_TYPE_PERFORMANCE: msgType = "PERFORMANCE"; break; + case GL_DEBUG_TYPE_MARKER: msgType = "MARKER"; break; + case GL_DEBUG_TYPE_PUSH_GROUP: msgType = "PUSH_GROUP"; break; + case GL_DEBUG_TYPE_POP_GROUP: msgType = "POP_GROUP"; break; + case GL_DEBUG_TYPE_OTHER: msgType = "OTHER"; break; + default: break; + } + + const char *msgSeverity = "DEFAULT"; + switch (severity) + { + case GL_DEBUG_SEVERITY_LOW: msgSeverity = "LOW"; break; + case GL_DEBUG_SEVERITY_MEDIUM: msgSeverity = "MEDIUM"; break; + case GL_DEBUG_SEVERITY_HIGH: msgSeverity = "HIGH"; break; + case GL_DEBUG_SEVERITY_NOTIFICATION: msgSeverity = "NOTIFICATION"; break; + default: break; + } + + TRACELOG(LOG_WARNING, "GL: OpenGL debug message: %s", message); + TRACELOG(LOG_WARNING, " > Type: %s", msgType); + TRACELOG(LOG_WARNING, " > Source = %s", msgSource); + TRACELOG(LOG_WARNING, " > Severity = %s", msgSeverity); +} +#endif + +//---------------------------------------------------------------------------------- +// Module Functions Definition - rlgl functionality +//---------------------------------------------------------------------------------- + +// Initialize rlgl: OpenGL extensions, default buffers/shaders/textures, OpenGL states +void rlglInit(int width, int height) +{ + // Enable OpenGL debug context if required +#if defined(RLGL_ENABLE_OPENGL_DEBUG_CONTEXT) && defined(GRAPHICS_API_OPENGL_43) + if ((glDebugMessageCallback != NULL) && (glDebugMessageControl != NULL)) + { + glDebugMessageCallback(rlDebugMessageCallback, 0); + // glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_ERROR, GL_DEBUG_SEVERITY_HIGH, 0, 0, GL_TRUE); + + // Debug context options: + // - GL_DEBUG_OUTPUT - Faster version but not useful for breakpoints + // - GL_DEBUG_OUTPUT_SYNCHRONUS - Callback is in sync with errors, so a breakpoint can be placed on the callback in order to get a stacktrace for the GL error + glEnable(GL_DEBUG_OUTPUT); + glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); + } +#endif + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + // Init default white texture + unsigned char pixels[4] = { 255, 255, 255, 255 }; // 1 pixel RGBA (4 bytes) + RLGL.State.defaultTextureId = rlLoadTexture(pixels, 1, 1, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1); + + if (RLGL.State.defaultTextureId != 0) TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Default texture loaded successfully", RLGL.State.defaultTextureId); + else TRACELOG(RL_LOG_WARNING, "TEXTURE: Failed to load default texture"); + + // Init default Shader (customized for GL 3.3 and ES2) + // Loaded: RLGL.State.defaultShaderId + RLGL.State.defaultShaderLocs + rlLoadShaderDefault(); + RLGL.State.currentShaderId = RLGL.State.defaultShaderId; + RLGL.State.currentShaderLocs = RLGL.State.defaultShaderLocs; + + // Init default vertex arrays buffers + RLGL.defaultBatch = rlLoadRenderBatch(RL_DEFAULT_BATCH_BUFFERS, RL_DEFAULT_BATCH_BUFFER_ELEMENTS); + RLGL.currentBatch = &RLGL.defaultBatch; + + // Init stack matrices (emulating OpenGL 1.1) + for (int i = 0; i < RL_MAX_MATRIX_STACK_SIZE; i++) RLGL.State.stack[i] = rlMatrixIdentity(); + + // Init internal matrices + RLGL.State.transform = rlMatrixIdentity(); + RLGL.State.projection = rlMatrixIdentity(); + RLGL.State.modelview = rlMatrixIdentity(); + RLGL.State.currentMatrix = &RLGL.State.modelview; +#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 + + // Initialize OpenGL default states + //---------------------------------------------------------- + // Init state: Depth test + glDepthFunc(GL_LEQUAL); // Type of depth testing to apply + glDisable(GL_DEPTH_TEST); // Disable depth testing for 2D (only used for 3D) + + // Init state: Blending mode + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Color blending function (how colors are mixed) + glEnable(GL_BLEND); // Enable color blending (required to work with transparencies) + + // Init state: Culling + // NOTE: All shapes/models triangles are drawn CCW + glCullFace(GL_BACK); // Cull the back face (default) + glFrontFace(GL_CCW); // Front face are defined counter clockwise (default) + glEnable(GL_CULL_FACE); // Enable backface culling + + // Init state: Cubemap seamless +#if defined(GRAPHICS_API_OPENGL_33) + glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); // Seamless cubemaps (not supported on OpenGL ES 2.0) +#endif + +#if defined(GRAPHICS_API_OPENGL_11) + // Init state: Color hints (deprecated in OpenGL 3.0+) + glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Improve quality of color and texture coordinate interpolation + glShadeModel(GL_SMOOTH); // Smooth shading between vertex (vertex colors interpolation) +#endif + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + // Store screen size into global variables + RLGL.State.framebufferWidth = width; + RLGL.State.framebufferHeight = height; + + TRACELOG(RL_LOG_INFO, "RLGL: Default OpenGL state initialized successfully"); + //---------------------------------------------------------- +#endif + + // Init state: Color/Depth buffers clear + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set clear color (black) + glClearDepth(1.0f); // Set clear depth value (default) + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear color and depth buffers (depth buffer required for 3D) +} + +// Vertex Buffer Object deinitialization (memory free) +void rlglClose(void) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + rlUnloadRenderBatch(RLGL.defaultBatch); + + rlUnloadShaderDefault(); // Unload default shader + + glDeleteTextures(1, &RLGL.State.defaultTextureId); // Unload default texture + TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Default texture unloaded successfully", RLGL.State.defaultTextureId); +#endif +} + +// Load OpenGL extensions +// NOTE: External loader function must be provided +void rlLoadExtensions(void *loader) +{ +#if defined(GRAPHICS_API_OPENGL_33) // Also defined for GRAPHICS_API_OPENGL_21 + // NOTE: glad is generated and contains only required OpenGL 3.3 Core extensions (and lower versions) + if (gladLoadGL((GLADloadfunc)loader) == 0) TRACELOG(RL_LOG_WARNING, "GLAD: Cannot load OpenGL extensions"); + else TRACELOG(RL_LOG_INFO, "GLAD: OpenGL extensions loaded successfully"); + + // Get number of supported extensions + GLint numExt = 0; + glGetIntegerv(GL_NUM_EXTENSIONS, &numExt); + TRACELOG(RL_LOG_INFO, "GL: Supported extensions count: %i", numExt); + +#if defined(RLGL_SHOW_GL_DETAILS_INFO) + // Get supported extensions list + // WARNING: glGetStringi() not available on OpenGL 2.1 + TRACELOG(RL_LOG_INFO, "GL: OpenGL extensions:"); + for (int i = 0; i < numExt; i++) TRACELOG(RL_LOG_INFO, " %s", glGetStringi(GL_EXTENSIONS, i)); +#endif + +#if defined(GRAPHICS_API_OPENGL_21) + // Register supported extensions flags + // Optional OpenGL 2.1 extensions + RLGL.ExtSupported.vao = GLAD_GL_ARB_vertex_array_object; + RLGL.ExtSupported.instancing = (GLAD_GL_EXT_draw_instanced && GLAD_GL_ARB_instanced_arrays); + RLGL.ExtSupported.texNPOT = GLAD_GL_ARB_texture_non_power_of_two; + RLGL.ExtSupported.texFloat32 = GLAD_GL_ARB_texture_float; + RLGL.ExtSupported.texFloat16 = GLAD_GL_ARB_texture_float; + RLGL.ExtSupported.texDepth = GLAD_GL_ARB_depth_texture; + RLGL.ExtSupported.maxDepthBits = 32; + RLGL.ExtSupported.texAnisoFilter = GLAD_GL_EXT_texture_filter_anisotropic; + RLGL.ExtSupported.texMirrorClamp = GLAD_GL_EXT_texture_mirror_clamp; +#else + // Register supported extensions flags + // OpenGL 3.3 extensions supported by default (core) + RLGL.ExtSupported.vao = true; + RLGL.ExtSupported.instancing = true; + RLGL.ExtSupported.texNPOT = true; + RLGL.ExtSupported.texFloat32 = true; + RLGL.ExtSupported.texFloat16 = true; + RLGL.ExtSupported.texDepth = true; + RLGL.ExtSupported.maxDepthBits = 32; + RLGL.ExtSupported.texAnisoFilter = true; + RLGL.ExtSupported.texMirrorClamp = true; +#endif + + // Optional OpenGL 3.3 extensions + RLGL.ExtSupported.texCompASTC = GLAD_GL_KHR_texture_compression_astc_hdr && GLAD_GL_KHR_texture_compression_astc_ldr; + RLGL.ExtSupported.texCompDXT = GLAD_GL_EXT_texture_compression_s3tc; // Texture compression: DXT + RLGL.ExtSupported.texCompETC2 = GLAD_GL_ARB_ES3_compatibility; // Texture compression: ETC2/EAC + #if defined(GRAPHICS_API_OPENGL_43) + RLGL.ExtSupported.computeShader = GLAD_GL_ARB_compute_shader; + RLGL.ExtSupported.ssbo = GLAD_GL_ARB_shader_storage_buffer_object; + #endif + +#endif // GRAPHICS_API_OPENGL_33 + +#if defined(GRAPHICS_API_OPENGL_ES3) + // Register supported extensions flags + // OpenGL ES 3.0 extensions supported by default (or it should be) + RLGL.ExtSupported.vao = true; + RLGL.ExtSupported.instancing = true; + RLGL.ExtSupported.texNPOT = true; + RLGL.ExtSupported.texFloat32 = true; + RLGL.ExtSupported.texFloat16 = true; + RLGL.ExtSupported.texDepth = true; + RLGL.ExtSupported.texDepthWebGL = true; + RLGL.ExtSupported.maxDepthBits = 24; + RLGL.ExtSupported.texAnisoFilter = true; + RLGL.ExtSupported.texMirrorClamp = true; + // TODO: Check for additional OpenGL ES 3.0 supported extensions: + //RLGL.ExtSupported.texCompDXT = true; + //RLGL.ExtSupported.texCompETC1 = true; + //RLGL.ExtSupported.texCompETC2 = true; + //RLGL.ExtSupported.texCompPVRT = true; + //RLGL.ExtSupported.texCompASTC = true; + //RLGL.ExtSupported.maxAnisotropyLevel = true; + //RLGL.ExtSupported.computeShader = true; + //RLGL.ExtSupported.ssbo = true; + +#elif defined(GRAPHICS_API_OPENGL_ES2) + + #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_DESKTOP_SDL) + // TODO: Support GLAD loader for OpenGL ES 3.0 + if (gladLoadGLES2((GLADloadfunc)loader) == 0) TRACELOG(RL_LOG_WARNING, "GLAD: Cannot load OpenGL ES2.0 functions"); + else TRACELOG(RL_LOG_INFO, "GLAD: OpenGL ES 2.0 loaded successfully"); + #endif + + // Get supported extensions list + GLint numExt = 0; + const char **extList = RL_MALLOC(512*sizeof(const char *)); // Allocate 512 strings pointers (2 KB) + const char *extensions = (const char *)glGetString(GL_EXTENSIONS); // One big const string + + // NOTE: We have to duplicate string because glGetString() returns a const string + int size = strlen(extensions) + 1; // Get extensions string size in bytes + char *extensionsDup = (char *)RL_CALLOC(size, sizeof(char)); + strcpy(extensionsDup, extensions); + extList[numExt] = extensionsDup; + + for (int i = 0; i < size; i++) + { + if (extensionsDup[i] == ' ') + { + extensionsDup[i] = '\0'; + numExt++; + extList[numExt] = &extensionsDup[i + 1]; + } + } + + TRACELOG(RL_LOG_INFO, "GL: Supported extensions count: %i", numExt); + +#if defined(RLGL_SHOW_GL_DETAILS_INFO) + TRACELOG(RL_LOG_INFO, "GL: OpenGL extensions:"); + for (int i = 0; i < numExt; i++) TRACELOG(RL_LOG_INFO, " %s", extList[i]); +#endif + + // Check required extensions + for (int i = 0; i < numExt; i++) + { + // Check VAO support + // NOTE: Only check on OpenGL ES, OpenGL 3.3 has VAO support as core feature + if (strcmp(extList[i], (const char *)"GL_OES_vertex_array_object") == 0) + { + // The extension is supported by our hardware and driver, try to get related functions pointers + // NOTE: emscripten does not support VAOs natively, it uses emulation and it reduces overall performance... + glGenVertexArrays = (PFNGLGENVERTEXARRAYSOESPROC)((rlglLoadProc)loader)("glGenVertexArraysOES"); + glBindVertexArray = (PFNGLBINDVERTEXARRAYOESPROC)((rlglLoadProc)loader)("glBindVertexArrayOES"); + glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSOESPROC)((rlglLoadProc)loader)("glDeleteVertexArraysOES"); + //glIsVertexArray = (PFNGLISVERTEXARRAYOESPROC)loader("glIsVertexArrayOES"); // NOTE: Fails in WebGL, omitted + + if ((glGenVertexArrays != NULL) && (glBindVertexArray != NULL) && (glDeleteVertexArrays != NULL)) RLGL.ExtSupported.vao = true; + } + + // Check instanced rendering support + if (strcmp(extList[i], (const char *)"GL_ANGLE_instanced_arrays") == 0) // Web ANGLE + { + glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedANGLE"); + glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedANGLE"); + glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISOREXTPROC)((rlglLoadProc)loader)("glVertexAttribDivisorANGLE"); + + if ((glDrawArraysInstanced != NULL) && (glDrawElementsInstanced != NULL) && (glVertexAttribDivisor != NULL)) RLGL.ExtSupported.instancing = true; + } + else + { + if ((strcmp(extList[i], (const char *)"GL_EXT_draw_instanced") == 0) && // Standard EXT + (strcmp(extList[i], (const char *)"GL_EXT_instanced_arrays") == 0)) + { + glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedEXT"); + glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedEXT"); + glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISOREXTPROC)((rlglLoadProc)loader)("glVertexAttribDivisorEXT"); + + if ((glDrawArraysInstanced != NULL) && (glDrawElementsInstanced != NULL) && (glVertexAttribDivisor != NULL)) RLGL.ExtSupported.instancing = true; + } + } + + // Check NPOT textures support + // NOTE: Only check on OpenGL ES, OpenGL 3.3 has NPOT textures full support as core feature + if (strcmp(extList[i], (const char *)"GL_OES_texture_npot") == 0) RLGL.ExtSupported.texNPOT = true; + + // Check texture float support + if (strcmp(extList[i], (const char *)"GL_OES_texture_float") == 0) RLGL.ExtSupported.texFloat32 = true; + if (strcmp(extList[i], (const char *)"GL_OES_texture_half_float") == 0) RLGL.ExtSupported.texFloat16 = true; + + // Check depth texture support + if (strcmp(extList[i], (const char *)"GL_OES_depth_texture") == 0) RLGL.ExtSupported.texDepth = true; + if (strcmp(extList[i], (const char *)"GL_WEBGL_depth_texture") == 0) RLGL.ExtSupported.texDepthWebGL = true; // WebGL requires unsized internal format + if (RLGL.ExtSupported.texDepthWebGL) RLGL.ExtSupported.texDepth = true; + + if (strcmp(extList[i], (const char *)"GL_OES_depth24") == 0) RLGL.ExtSupported.maxDepthBits = 24; // Not available on WebGL + if (strcmp(extList[i], (const char *)"GL_OES_depth32") == 0) RLGL.ExtSupported.maxDepthBits = 32; // Not available on WebGL + + // Check texture compression support: DXT + if ((strcmp(extList[i], (const char *)"GL_EXT_texture_compression_s3tc") == 0) || + (strcmp(extList[i], (const char *)"GL_WEBGL_compressed_texture_s3tc") == 0) || + (strcmp(extList[i], (const char *)"GL_WEBKIT_WEBGL_compressed_texture_s3tc") == 0)) RLGL.ExtSupported.texCompDXT = true; + + // Check texture compression support: ETC1 + if ((strcmp(extList[i], (const char *)"GL_OES_compressed_ETC1_RGB8_texture") == 0) || + (strcmp(extList[i], (const char *)"GL_WEBGL_compressed_texture_etc1") == 0)) RLGL.ExtSupported.texCompETC1 = true; + + // Check texture compression support: ETC2/EAC + if (strcmp(extList[i], (const char *)"GL_ARB_ES3_compatibility") == 0) RLGL.ExtSupported.texCompETC2 = true; + + // Check texture compression support: PVR + if (strcmp(extList[i], (const char *)"GL_IMG_texture_compression_pvrtc") == 0) RLGL.ExtSupported.texCompPVRT = true; + + // Check texture compression support: ASTC + if (strcmp(extList[i], (const char *)"GL_KHR_texture_compression_astc_hdr") == 0) RLGL.ExtSupported.texCompASTC = true; + + // Check anisotropic texture filter support + if (strcmp(extList[i], (const char *)"GL_EXT_texture_filter_anisotropic") == 0) RLGL.ExtSupported.texAnisoFilter = true; + + // Check clamp mirror wrap mode support + if (strcmp(extList[i], (const char *)"GL_EXT_texture_mirror_clamp") == 0) RLGL.ExtSupported.texMirrorClamp = true; + } + + // Free extensions pointers + RL_FREE(extList); + RL_FREE(extensionsDup); // Duplicated string must be deallocated +#endif // GRAPHICS_API_OPENGL_ES2 + + // Check OpenGL information and capabilities + //------------------------------------------------------------------------------ + // Show current OpenGL and GLSL version + TRACELOG(RL_LOG_INFO, "GL: OpenGL device information:"); + TRACELOG(RL_LOG_INFO, " > Vendor: %s", glGetString(GL_VENDOR)); + TRACELOG(RL_LOG_INFO, " > Renderer: %s", glGetString(GL_RENDERER)); + TRACELOG(RL_LOG_INFO, " > Version: %s", glGetString(GL_VERSION)); + TRACELOG(RL_LOG_INFO, " > GLSL: %s", glGetString(GL_SHADING_LANGUAGE_VERSION)); + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + // NOTE: Anisotropy levels capability is an extension + #ifndef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT + #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF + #endif + glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &RLGL.ExtSupported.maxAnisotropyLevel); + +#if defined(RLGL_SHOW_GL_DETAILS_INFO) + // Show some OpenGL GPU capabilities + TRACELOG(RL_LOG_INFO, "GL: OpenGL capabilities:"); + GLint capability = 0; + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &capability); + TRACELOG(RL_LOG_INFO, " GL_MAX_TEXTURE_SIZE: %i", capability); + glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &capability); + TRACELOG(RL_LOG_INFO, " GL_MAX_CUBE_MAP_TEXTURE_SIZE: %i", capability); + glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &capability); + TRACELOG(RL_LOG_INFO, " GL_MAX_TEXTURE_IMAGE_UNITS: %i", capability); + glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &capability); + TRACELOG(RL_LOG_INFO, " GL_MAX_VERTEX_ATTRIBS: %i", capability); + #if !defined(GRAPHICS_API_OPENGL_ES2) + glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &capability); + TRACELOG(RL_LOG_INFO, " GL_MAX_UNIFORM_BLOCK_SIZE: %i", capability); + glGetIntegerv(GL_MAX_DRAW_BUFFERS, &capability); + TRACELOG(RL_LOG_INFO, " GL_MAX_DRAW_BUFFERS: %i", capability); + if (RLGL.ExtSupported.texAnisoFilter) TRACELOG(RL_LOG_INFO, " GL_MAX_TEXTURE_MAX_ANISOTROPY: %.0f", RLGL.ExtSupported.maxAnisotropyLevel); + #endif + glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &capability); + TRACELOG(RL_LOG_INFO, " GL_NUM_COMPRESSED_TEXTURE_FORMATS: %i", capability); + GLint *compFormats = (GLint *)RL_CALLOC(capability, sizeof(GLint)); + glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, compFormats); + for (int i = 0; i < capability; i++) TRACELOG(RL_LOG_INFO, " %s", rlGetCompressedFormatName(compFormats[i])); + RL_FREE(compFormats); + +#if defined(GRAPHICS_API_OPENGL_43) + glGetIntegerv(GL_MAX_VERTEX_ATTRIB_BINDINGS, &capability); + TRACELOG(RL_LOG_INFO, " GL_MAX_VERTEX_ATTRIB_BINDINGS: %i", capability); + glGetIntegerv(GL_MAX_UNIFORM_LOCATIONS, &capability); + TRACELOG(RL_LOG_INFO, " GL_MAX_UNIFORM_LOCATIONS: %i", capability); +#endif // GRAPHICS_API_OPENGL_43 +#else // RLGL_SHOW_GL_DETAILS_INFO + + // Show some basic info about GL supported features + if (RLGL.ExtSupported.vao) TRACELOG(RL_LOG_INFO, "GL: VAO extension detected, VAO functions loaded successfully"); + else TRACELOG(RL_LOG_WARNING, "GL: VAO extension not found, VAO not supported"); + if (RLGL.ExtSupported.texNPOT) TRACELOG(RL_LOG_INFO, "GL: NPOT textures extension detected, full NPOT textures supported"); + else TRACELOG(RL_LOG_WARNING, "GL: NPOT textures extension not found, limited NPOT support (no-mipmaps, no-repeat)"); + if (RLGL.ExtSupported.texCompDXT) TRACELOG(RL_LOG_INFO, "GL: DXT compressed textures supported"); + if (RLGL.ExtSupported.texCompETC1) TRACELOG(RL_LOG_INFO, "GL: ETC1 compressed textures supported"); + if (RLGL.ExtSupported.texCompETC2) TRACELOG(RL_LOG_INFO, "GL: ETC2/EAC compressed textures supported"); + if (RLGL.ExtSupported.texCompPVRT) TRACELOG(RL_LOG_INFO, "GL: PVRT compressed textures supported"); + if (RLGL.ExtSupported.texCompASTC) TRACELOG(RL_LOG_INFO, "GL: ASTC compressed textures supported"); + if (RLGL.ExtSupported.computeShader) TRACELOG(RL_LOG_INFO, "GL: Compute shaders supported"); + if (RLGL.ExtSupported.ssbo) TRACELOG(RL_LOG_INFO, "GL: Shader storage buffer objects supported"); +#endif // RLGL_SHOW_GL_DETAILS_INFO + +#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 +} + +// Get current OpenGL version +int rlGetVersion(void) +{ + int glVersion = 0; +#if defined(GRAPHICS_API_OPENGL_11) + glVersion = RL_OPENGL_11; +#endif +#if defined(GRAPHICS_API_OPENGL_21) + glVersion = RL_OPENGL_21; +#elif defined(GRAPHICS_API_OPENGL_43) + glVersion = RL_OPENGL_43; +#elif defined(GRAPHICS_API_OPENGL_33) + glVersion = RL_OPENGL_33; +#endif +#if defined(GRAPHICS_API_OPENGL_ES3) + glVersion = RL_OPENGL_ES_30; +#elif defined(GRAPHICS_API_OPENGL_ES2) + glVersion = RL_OPENGL_ES_20; +#endif + + return glVersion; +} + +// Set current framebuffer width +void rlSetFramebufferWidth(int width) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + RLGL.State.framebufferWidth = width; +#endif +} + +// Set current framebuffer height +void rlSetFramebufferHeight(int height) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + RLGL.State.framebufferHeight = height; +#endif +} + +// Get default framebuffer width +int rlGetFramebufferWidth(void) +{ + int width = 0; +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + width = RLGL.State.framebufferWidth; +#endif + return width; +} + +// Get default framebuffer height +int rlGetFramebufferHeight(void) +{ + int height = 0; +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + height = RLGL.State.framebufferHeight; +#endif + return height; +} + +// Get default internal texture (white texture) +// NOTE: Default texture is a 1x1 pixel UNCOMPRESSED_R8G8B8A8 +unsigned int rlGetTextureIdDefault(void) +{ + unsigned int id = 0; +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + id = RLGL.State.defaultTextureId; +#endif + return id; +} + +// Get default shader id +unsigned int rlGetShaderIdDefault(void) +{ + unsigned int id = 0; +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + id = RLGL.State.defaultShaderId; +#endif + return id; +} + +// Get default shader locs +int *rlGetShaderLocsDefault(void) +{ + int *locs = NULL; +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + locs = RLGL.State.defaultShaderLocs; +#endif + return locs; +} + +// Render batch management +//------------------------------------------------------------------------------------------------ +// Load render batch +rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements) +{ + rlRenderBatch batch = { 0 }; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + // Initialize CPU (RAM) vertex buffers (position, texcoord, color data and indexes) + //-------------------------------------------------------------------------------------------- + batch.vertexBuffer = (rlVertexBuffer *)RL_MALLOC(numBuffers*sizeof(rlVertexBuffer)); + + for (int i = 0; i < numBuffers; i++) + { + batch.vertexBuffer[i].elementCount = bufferElements; + + batch.vertexBuffer[i].vertices = (float *)RL_MALLOC(bufferElements*3*4*sizeof(float)); // 3 float by vertex, 4 vertex by quad + batch.vertexBuffer[i].texcoords = (float *)RL_MALLOC(bufferElements*2*4*sizeof(float)); // 2 float by texcoord, 4 texcoord by quad + batch.vertexBuffer[i].colors = (unsigned char *)RL_MALLOC(bufferElements*4*4*sizeof(unsigned char)); // 4 float by color, 4 colors by quad +#if defined(GRAPHICS_API_OPENGL_33) + batch.vertexBuffer[i].indices = (unsigned int *)RL_MALLOC(bufferElements*6*sizeof(unsigned int)); // 6 int by quad (indices) +#endif +#if defined(GRAPHICS_API_OPENGL_ES2) + batch.vertexBuffer[i].indices = (unsigned short *)RL_MALLOC(bufferElements*6*sizeof(unsigned short)); // 6 int by quad (indices) +#endif + + for (int j = 0; j < (3*4*bufferElements); j++) batch.vertexBuffer[i].vertices[j] = 0.0f; + for (int j = 0; j < (2*4*bufferElements); j++) batch.vertexBuffer[i].texcoords[j] = 0.0f; + for (int j = 0; j < (4*4*bufferElements); j++) batch.vertexBuffer[i].colors[j] = 0; + + int k = 0; + + // Indices can be initialized right now + for (int j = 0; j < (6*bufferElements); j += 6) + { + batch.vertexBuffer[i].indices[j] = 4*k; + batch.vertexBuffer[i].indices[j + 1] = 4*k + 1; + batch.vertexBuffer[i].indices[j + 2] = 4*k + 2; + batch.vertexBuffer[i].indices[j + 3] = 4*k; + batch.vertexBuffer[i].indices[j + 4] = 4*k + 2; + batch.vertexBuffer[i].indices[j + 5] = 4*k + 3; + + k++; + } + + RLGL.State.vertexCounter = 0; + } + + TRACELOG(RL_LOG_INFO, "RLGL: Render batch vertex buffers loaded successfully in RAM (CPU)"); + //-------------------------------------------------------------------------------------------- + + // Upload to GPU (VRAM) vertex data and initialize VAOs/VBOs + //-------------------------------------------------------------------------------------------- + for (int i = 0; i < numBuffers; i++) + { + if (RLGL.ExtSupported.vao) + { + // Initialize Quads VAO + glGenVertexArrays(1, &batch.vertexBuffer[i].vaoId); + glBindVertexArray(batch.vertexBuffer[i].vaoId); + } + + // Quads - Vertex buffers binding and attributes enable + // Vertex position buffer (shader-location = 0) + glGenBuffers(1, &batch.vertexBuffer[i].vboId[0]); + glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[0]); + glBufferData(GL_ARRAY_BUFFER, bufferElements*3*4*sizeof(float), batch.vertexBuffer[i].vertices, GL_DYNAMIC_DRAW); + glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION]); + glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); + + // Vertex texcoord buffer (shader-location = 1) + glGenBuffers(1, &batch.vertexBuffer[i].vboId[1]); + glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[1]); + glBufferData(GL_ARRAY_BUFFER, bufferElements*2*4*sizeof(float), batch.vertexBuffer[i].texcoords, GL_DYNAMIC_DRAW); + glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01]); + glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); + + // Vertex color buffer (shader-location = 3) + glGenBuffers(1, &batch.vertexBuffer[i].vboId[2]); + glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[2]); + glBufferData(GL_ARRAY_BUFFER, bufferElements*4*4*sizeof(unsigned char), batch.vertexBuffer[i].colors, GL_DYNAMIC_DRAW); + glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR]); + glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); + + // Fill index buffer + glGenBuffers(1, &batch.vertexBuffer[i].vboId[3]); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[3]); +#if defined(GRAPHICS_API_OPENGL_33) + glBufferData(GL_ELEMENT_ARRAY_BUFFER, bufferElements*6*sizeof(int), batch.vertexBuffer[i].indices, GL_STATIC_DRAW); +#endif +#if defined(GRAPHICS_API_OPENGL_ES2) + glBufferData(GL_ELEMENT_ARRAY_BUFFER, bufferElements*6*sizeof(short), batch.vertexBuffer[i].indices, GL_STATIC_DRAW); +#endif + } + + TRACELOG(RL_LOG_INFO, "RLGL: Render batch vertex buffers loaded successfully in VRAM (GPU)"); + + // Unbind the current VAO + if (RLGL.ExtSupported.vao) glBindVertexArray(0); + //-------------------------------------------------------------------------------------------- + + // Init draw calls tracking system + //-------------------------------------------------------------------------------------------- + batch.draws = (rlDrawCall *)RL_MALLOC(RL_DEFAULT_BATCH_DRAWCALLS*sizeof(rlDrawCall)); + + for (int i = 0; i < RL_DEFAULT_BATCH_DRAWCALLS; i++) + { + batch.draws[i].mode = RL_QUADS; + batch.draws[i].vertexCount = 0; + batch.draws[i].vertexAlignment = 0; + //batch.draws[i].vaoId = 0; + //batch.draws[i].shaderId = 0; + batch.draws[i].textureId = RLGL.State.defaultTextureId; + //batch.draws[i].RLGL.State.projection = rlMatrixIdentity(); + //batch.draws[i].RLGL.State.modelview = rlMatrixIdentity(); + } + + batch.bufferCount = numBuffers; // Record buffer count + batch.drawCounter = 1; // Reset draws counter + batch.currentDepth = -1.0f; // Reset depth value + //-------------------------------------------------------------------------------------------- +#endif + + return batch; +} + +// Unload default internal buffers vertex data from CPU and GPU +void rlUnloadRenderBatch(rlRenderBatch batch) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + // Unbind everything + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + + // Unload all vertex buffers data + for (int i = 0; i < batch.bufferCount; i++) + { + // Unbind VAO attribs data + if (RLGL.ExtSupported.vao) + { + glBindVertexArray(batch.vertexBuffer[i].vaoId); + glDisableVertexAttribArray(0); + glDisableVertexAttribArray(1); + glDisableVertexAttribArray(2); + glDisableVertexAttribArray(3); + glBindVertexArray(0); + } + + // Delete VBOs from GPU (VRAM) + glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[0]); + glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[1]); + glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[2]); + glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[3]); + + // Delete VAOs from GPU (VRAM) + if (RLGL.ExtSupported.vao) glDeleteVertexArrays(1, &batch.vertexBuffer[i].vaoId); + + // Free vertex arrays memory from CPU (RAM) + RL_FREE(batch.vertexBuffer[i].vertices); + RL_FREE(batch.vertexBuffer[i].texcoords); + RL_FREE(batch.vertexBuffer[i].colors); + RL_FREE(batch.vertexBuffer[i].indices); + } + + // Unload arrays + RL_FREE(batch.vertexBuffer); + RL_FREE(batch.draws); +#endif +} + +// Draw render batch +// NOTE: We require a pointer to reset batch and increase current buffer (multi-buffer) +void rlDrawRenderBatch(rlRenderBatch *batch) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + // Update batch vertex buffers + //------------------------------------------------------------------------------------------------------------ + // NOTE: If there is not vertex data, buffers doesn't need to be updated (vertexCount > 0) + // TODO: If no data changed on the CPU arrays --> No need to re-update GPU arrays (use a change detector flag?) + if (RLGL.State.vertexCounter > 0) + { + // Activate elements VAO + if (RLGL.ExtSupported.vao) glBindVertexArray(batch->vertexBuffer[batch->currentBuffer].vaoId); + + // Vertex positions buffer + glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[0]); + glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*3*sizeof(float), batch->vertexBuffer[batch->currentBuffer].vertices); + //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].vertices, GL_DYNAMIC_DRAW); // Update all buffer + + // Texture coordinates buffer + glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[1]); + glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*2*sizeof(float), batch->vertexBuffer[batch->currentBuffer].texcoords); + //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].texcoords, GL_DYNAMIC_DRAW); // Update all buffer + + // Colors buffer + glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[2]); + glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*4*sizeof(unsigned char), batch->vertexBuffer[batch->currentBuffer].colors); + //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*4*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].colors, GL_DYNAMIC_DRAW); // Update all buffer + + // NOTE: glMapBuffer() causes sync issue. + // If GPU is working with this buffer, glMapBuffer() will wait(stall) until GPU to finish its job. + // To avoid waiting (idle), you can call first glBufferData() with NULL pointer before glMapBuffer(). + // If you do that, the previous data in PBO will be discarded and glMapBuffer() returns a new + // allocated pointer immediately even if GPU is still working with the previous data. + + // Another option: map the buffer object into client's memory + // Probably this code could be moved somewhere else... + // batch->vertexBuffer[batch->currentBuffer].vertices = (float *)glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE); + // if (batch->vertexBuffer[batch->currentBuffer].vertices) + // { + // Update vertex data + // } + // glUnmapBuffer(GL_ARRAY_BUFFER); + + // Unbind the current VAO + if (RLGL.ExtSupported.vao) glBindVertexArray(0); + } + //------------------------------------------------------------------------------------------------------------ + + // Draw batch vertex buffers (considering VR stereo if required) + //------------------------------------------------------------------------------------------------------------ + Matrix matProjection = RLGL.State.projection; + Matrix matModelView = RLGL.State.modelview; + + int eyeCount = 1; + if (RLGL.State.stereoRender) eyeCount = 2; + + for (int eye = 0; eye < eyeCount; eye++) + { + if (eyeCount == 2) + { + // Setup current eye viewport (half screen width) + rlViewport(eye*RLGL.State.framebufferWidth/2, 0, RLGL.State.framebufferWidth/2, RLGL.State.framebufferHeight); + + // Set current eye view offset to modelview matrix + rlSetMatrixModelview(rlMatrixMultiply(matModelView, RLGL.State.viewOffsetStereo[eye])); + // Set current eye projection matrix + rlSetMatrixProjection(RLGL.State.projectionStereo[eye]); + } + + // Draw buffers + if (RLGL.State.vertexCounter > 0) + { + // Set current shader and upload current MVP matrix + glUseProgram(RLGL.State.currentShaderId); + + // Create modelview-projection matrix and upload to shader + Matrix matMVP = rlMatrixMultiply(RLGL.State.modelview, RLGL.State.projection); + float matMVPfloat[16] = { + matMVP.m0, matMVP.m1, matMVP.m2, matMVP.m3, + matMVP.m4, matMVP.m5, matMVP.m6, matMVP.m7, + matMVP.m8, matMVP.m9, matMVP.m10, matMVP.m11, + matMVP.m12, matMVP.m13, matMVP.m14, matMVP.m15 + }; + glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_MVP], 1, false, matMVPfloat); + + if (RLGL.ExtSupported.vao) glBindVertexArray(batch->vertexBuffer[batch->currentBuffer].vaoId); + else + { + // Bind vertex attrib: position (shader-location = 0) + glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[0]); + glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); + glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION]); + + // Bind vertex attrib: texcoord (shader-location = 1) + glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[1]); + glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); + glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01]); + + // Bind vertex attrib: color (shader-location = 3) + glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[2]); + glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); + glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR]); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[3]); + } + + // Setup some default shader values + glUniform4f(RLGL.State.currentShaderLocs[RL_SHADER_LOC_COLOR_DIFFUSE], 1.0f, 1.0f, 1.0f, 1.0f); + glUniform1i(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MAP_DIFFUSE], 0); // Active default sampler2D: texture0 + + // Activate additional sampler textures + // Those additional textures will be common for all draw calls of the batch + for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) + { + if (RLGL.State.activeTextureId[i] > 0) + { + glActiveTexture(GL_TEXTURE0 + 1 + i); + glBindTexture(GL_TEXTURE_2D, RLGL.State.activeTextureId[i]); + } + } + + // Activate default sampler2D texture0 (one texture is always active for default batch shader) + // NOTE: Batch system accumulates calls by texture0 changes, additional textures are enabled for all the draw calls + glActiveTexture(GL_TEXTURE0); + + for (int i = 0, vertexOffset = 0; i < batch->drawCounter; i++) + { + // Bind current draw call texture, activated as GL_TEXTURE0 and Bound to sampler2D texture0 by default + glBindTexture(GL_TEXTURE_2D, batch->draws[i].textureId); + + if ((batch->draws[i].mode == RL_LINES) || (batch->draws[i].mode == RL_TRIANGLES)) glDrawArrays(batch->draws[i].mode, vertexOffset, batch->draws[i].vertexCount); + else + { +#if defined(GRAPHICS_API_OPENGL_33) + // We need to define the number of indices to be processed: elementCount*6 + // NOTE: The final parameter tells the GPU the offset in bytes from the + // start of the index buffer to the location of the first index to process + glDrawElements(GL_TRIANGLES, batch->draws[i].vertexCount/4*6, GL_UNSIGNED_INT, (GLvoid *)(vertexOffset/4*6*sizeof(GLuint))); +#endif +#if defined(GRAPHICS_API_OPENGL_ES2) + glDrawElements(GL_TRIANGLES, batch->draws[i].vertexCount/4*6, GL_UNSIGNED_SHORT, (GLvoid *)(vertexOffset/4*6*sizeof(GLushort))); +#endif + } + + vertexOffset += (batch->draws[i].vertexCount + batch->draws[i].vertexAlignment); + } + + if (!RLGL.ExtSupported.vao) + { + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } + + glBindTexture(GL_TEXTURE_2D, 0); // Unbind textures + } + + if (RLGL.ExtSupported.vao) glBindVertexArray(0); // Unbind VAO + + glUseProgram(0); // Unbind shader program + } + + // Restore viewport to default measures + if (eyeCount == 2) rlViewport(0, 0, RLGL.State.framebufferWidth, RLGL.State.framebufferHeight); + //------------------------------------------------------------------------------------------------------------ + + // Reset batch buffers + //------------------------------------------------------------------------------------------------------------ + // Reset vertex counter for next frame + RLGL.State.vertexCounter = 0; + + // Reset depth for next draw + batch->currentDepth = -1.0f; + + // Restore projection/modelview matrices + RLGL.State.projection = matProjection; + RLGL.State.modelview = matModelView; + + // Reset RLGL.currentBatch->draws array + for (int i = 0; i < RL_DEFAULT_BATCH_DRAWCALLS; i++) + { + batch->draws[i].mode = RL_QUADS; + batch->draws[i].vertexCount = 0; + batch->draws[i].textureId = RLGL.State.defaultTextureId; + } + + // Reset active texture units for next batch + for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) RLGL.State.activeTextureId[i] = 0; + + // Reset draws counter to one draw for the batch + batch->drawCounter = 1; + //------------------------------------------------------------------------------------------------------------ + + // Change to next buffer in the list (in case of multi-buffering) + batch->currentBuffer++; + if (batch->currentBuffer >= batch->bufferCount) batch->currentBuffer = 0; +#endif +} + +// Set the active render batch for rlgl +void rlSetRenderBatchActive(rlRenderBatch *batch) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + rlDrawRenderBatch(RLGL.currentBatch); + + if (batch != NULL) RLGL.currentBatch = batch; + else RLGL.currentBatch = &RLGL.defaultBatch; +#endif +} + +// Update and draw internal render batch +void rlDrawRenderBatchActive(void) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + rlDrawRenderBatch(RLGL.currentBatch); // NOTE: Stereo rendering is checked inside +#endif +} + +// Check internal buffer overflow for a given number of vertex +// and force a rlRenderBatch draw call if required +bool rlCheckRenderBatchLimit(int vCount) +{ + bool overflow = false; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + if ((RLGL.State.vertexCounter + vCount) >= + (RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].elementCount*4)) + { + overflow = true; + + // Store current primitive drawing mode and texture id + int currentMode = RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode; + int currentTexture = RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId; + + rlDrawRenderBatch(RLGL.currentBatch); // NOTE: Stereo rendering is checked inside + + // Restore state of last batch so we can continue adding vertices + RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode = currentMode; + RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId = currentTexture; + } +#endif + + return overflow; +} + +// Textures data management +//----------------------------------------------------------------------------------------- +// Convert image data to OpenGL texture (returns OpenGL valid Id) +unsigned int rlLoadTexture(const void *data, int width, int height, int format, int mipmapCount) +{ + unsigned int id = 0; + + glBindTexture(GL_TEXTURE_2D, 0); // Free any old binding + + // Check texture format support by OpenGL 1.1 (compressed textures not supported) +#if defined(GRAPHICS_API_OPENGL_11) + if (format >= RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) + { + TRACELOG(RL_LOG_WARNING, "GL: OpenGL 1.1 does not support GPU compressed texture formats"); + return id; + } +#else + if ((!RLGL.ExtSupported.texCompDXT) && ((format == RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) || (format == RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA) || + (format == RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA) || (format == RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA))) + { + TRACELOG(RL_LOG_WARNING, "GL: DXT compressed texture format not supported"); + return id; + } +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + if ((!RLGL.ExtSupported.texCompETC1) && (format == RL_PIXELFORMAT_COMPRESSED_ETC1_RGB)) + { + TRACELOG(RL_LOG_WARNING, "GL: ETC1 compressed texture format not supported"); + return id; + } + + if ((!RLGL.ExtSupported.texCompETC2) && ((format == RL_PIXELFORMAT_COMPRESSED_ETC2_RGB) || (format == RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA))) + { + TRACELOG(RL_LOG_WARNING, "GL: ETC2 compressed texture format not supported"); + return id; + } + + if ((!RLGL.ExtSupported.texCompPVRT) && ((format == RL_PIXELFORMAT_COMPRESSED_PVRT_RGB) || (format == RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA))) + { + TRACELOG(RL_LOG_WARNING, "GL: PVRT compressed texture format not supported"); + return id; + } + + if ((!RLGL.ExtSupported.texCompASTC) && ((format == RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA) || (format == RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA))) + { + TRACELOG(RL_LOG_WARNING, "GL: ASTC compressed texture format not supported"); + return id; + } +#endif +#endif // GRAPHICS_API_OPENGL_11 + + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + + glGenTextures(1, &id); // Generate texture id + + glBindTexture(GL_TEXTURE_2D, id); + + int mipWidth = width; + int mipHeight = height; + int mipOffset = 0; // Mipmap data offset, only used for tracelog + + // NOTE: Added pointer math separately from function to avoid UBSAN complaining + unsigned char *dataPtr = NULL; + if (data != NULL) dataPtr = (unsigned char *)data; + + // Load the different mipmap levels + for (int i = 0; i < mipmapCount; i++) + { + unsigned int mipSize = rlGetPixelDataSize(mipWidth, mipHeight, format); + + unsigned int glInternalFormat, glFormat, glType; + rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); + + TRACELOGD("TEXTURE: Load mipmap level %i (%i x %i), size: %i, offset: %i", i, mipWidth, mipHeight, mipSize, mipOffset); + + if (glInternalFormat != 0) + { + if (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) glTexImage2D(GL_TEXTURE_2D, i, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, dataPtr); +#if !defined(GRAPHICS_API_OPENGL_11) + else glCompressedTexImage2D(GL_TEXTURE_2D, i, glInternalFormat, mipWidth, mipHeight, 0, mipSize, dataPtr); +#endif + +#if defined(GRAPHICS_API_OPENGL_33) + if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) + { + GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ONE }; + glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); + } + else if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA) + { +#if defined(GRAPHICS_API_OPENGL_21) + GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ALPHA }; +#elif defined(GRAPHICS_API_OPENGL_33) + GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_GREEN }; +#endif + glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); + } +#endif + } + + mipWidth /= 2; + mipHeight /= 2; + mipOffset += mipSize; // Increment offset position to next mipmap + if (data != NULL) dataPtr += mipSize; // Increment data pointer to next mipmap + + // Security check for NPOT textures + if (mipWidth < 1) mipWidth = 1; + if (mipHeight < 1) mipHeight = 1; + } + + // Texture parameters configuration + // NOTE: glTexParameteri does NOT affect texture uploading, just the way it's used +#if defined(GRAPHICS_API_OPENGL_ES2) + // NOTE: OpenGL ES 2.0 with no GL_OES_texture_npot support (i.e. WebGL) has limited NPOT support, so CLAMP_TO_EDGE must be used + if (RLGL.ExtSupported.texNPOT) + { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture to repeat on x-axis + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture to repeat on y-axis + } + else + { + // NOTE: If using negative texture coordinates (LoadOBJ()), it does not work! + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // Set texture to clamp on x-axis + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Set texture to clamp on y-axis + } +#else + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture to repeat on x-axis + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture to repeat on y-axis +#endif + + // Magnification and minification filters + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Alternative: GL_LINEAR + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // Alternative: GL_LINEAR + +#if defined(GRAPHICS_API_OPENGL_33) + if (mipmapCount > 1) + { + // Activate Trilinear filtering if mipmaps are available + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + } +#endif + + // At this point we have the texture loaded in GPU and texture parameters configured + + // NOTE: If mipmaps were not in data, they are not generated automatically + + // Unbind current texture + glBindTexture(GL_TEXTURE_2D, 0); + + if (id > 0) TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Texture loaded successfully (%ix%i | %s | %i mipmaps)", id, width, height, rlGetPixelFormatName(format), mipmapCount); + else TRACELOG(RL_LOG_WARNING, "TEXTURE: Failed to load texture"); + + return id; +} + +// Load depth texture/renderbuffer (to be attached to fbo) +// WARNING: OpenGL ES 2.0 requires GL_OES_depth_texture and WebGL requires WEBGL_depth_texture extensions +unsigned int rlLoadTextureDepth(int width, int height, bool useRenderBuffer) +{ + unsigned int id = 0; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + // In case depth textures not supported, we force renderbuffer usage + if (!RLGL.ExtSupported.texDepth) useRenderBuffer = true; + + // NOTE: We let the implementation to choose the best bit-depth + // Possible formats: GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT32 and GL_DEPTH_COMPONENT32F + unsigned int glInternalFormat = GL_DEPTH_COMPONENT; + +#if (defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_ES3)) + // WARNING: WebGL platform requires unsized internal format definition (GL_DEPTH_COMPONENT) + // while other platforms using OpenGL ES 2.0 require/support sized internal formats depending on the GPU capabilities + if (!RLGL.ExtSupported.texDepthWebGL || useRenderBuffer) + { + if (RLGL.ExtSupported.maxDepthBits == 32) glInternalFormat = GL_DEPTH_COMPONENT32_OES; + else if (RLGL.ExtSupported.maxDepthBits == 24) glInternalFormat = GL_DEPTH_COMPONENT24_OES; + else glInternalFormat = GL_DEPTH_COMPONENT16; + } +#endif + + if (!useRenderBuffer && RLGL.ExtSupported.texDepth) + { + glGenTextures(1, &id); + glBindTexture(GL_TEXTURE_2D, id); + glTexImage2D(GL_TEXTURE_2D, 0, glInternalFormat, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + glBindTexture(GL_TEXTURE_2D, 0); + + TRACELOG(RL_LOG_INFO, "TEXTURE: Depth texture loaded successfully"); + } + else + { + // Create the renderbuffer that will serve as the depth attachment for the framebuffer + // NOTE: A renderbuffer is simpler than a texture and could offer better performance on embedded devices + glGenRenderbuffers(1, &id); + glBindRenderbuffer(GL_RENDERBUFFER, id); + glRenderbufferStorage(GL_RENDERBUFFER, glInternalFormat, width, height); + + glBindRenderbuffer(GL_RENDERBUFFER, 0); + + TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Depth renderbuffer loaded successfully (%i bits)", id, (RLGL.ExtSupported.maxDepthBits >= 24)? RLGL.ExtSupported.maxDepthBits : 16); + } +#endif + + return id; +} + +// Load texture cubemap +// NOTE: Cubemap data is expected to be 6 images in a single data array (one after the other), +// expected the following convention: +X, -X, +Y, -Y, +Z, -Z +unsigned int rlLoadTextureCubemap(const void *data, int size, int format) +{ + unsigned int id = 0; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + unsigned int dataSize = rlGetPixelDataSize(size, size, format); + + glGenTextures(1, &id); + glBindTexture(GL_TEXTURE_CUBE_MAP, id); + + unsigned int glInternalFormat, glFormat, glType; + rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); + + if (glInternalFormat != 0) + { + // Load cubemap faces + for (unsigned int i = 0; i < 6; i++) + { + if (data == NULL) + { + if (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) + { + if ((format == RL_PIXELFORMAT_UNCOMPRESSED_R32) || (format == RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32) + || (format == RL_PIXELFORMAT_UNCOMPRESSED_R16) || (format == RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16)) + TRACELOG(RL_LOG_WARNING, "TEXTURES: Cubemap requested format not supported"); + else glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, size, size, 0, glFormat, glType, NULL); + } + else TRACELOG(RL_LOG_WARNING, "TEXTURES: Empty cubemap creation does not support compressed format"); + } + else + { + if (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, size, size, 0, glFormat, glType, (unsigned char *)data + i*dataSize); + else glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, size, size, 0, dataSize, (unsigned char *)data + i*dataSize); + } + +#if defined(GRAPHICS_API_OPENGL_33) + if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) + { + GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ONE }; + glTexParameteriv(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); + } + else if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA) + { +#if defined(GRAPHICS_API_OPENGL_21) + GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ALPHA }; +#elif defined(GRAPHICS_API_OPENGL_33) + GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_GREEN }; +#endif + glTexParameteriv(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); + } +#endif + } + } + + // Set cubemap texture sampling parameters + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); +#if defined(GRAPHICS_API_OPENGL_33) + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); // Flag not supported on OpenGL ES 2.0 +#endif + + glBindTexture(GL_TEXTURE_CUBE_MAP, 0); +#endif + + if (id > 0) TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Cubemap texture loaded successfully (%ix%i)", id, size, size); + else TRACELOG(RL_LOG_WARNING, "TEXTURE: Failed to load cubemap texture"); + + return id; +} + +// Update already loaded texture in GPU with new data +// NOTE: We don't know safely if internal texture format is the expected one... +void rlUpdateTexture(unsigned int id, int offsetX, int offsetY, int width, int height, int format, const void *data) +{ + glBindTexture(GL_TEXTURE_2D, id); + + unsigned int glInternalFormat, glFormat, glType; + rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); + + if ((glInternalFormat != 0) && (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB)) + { + glTexSubImage2D(GL_TEXTURE_2D, 0, offsetX, offsetY, width, height, glFormat, glType, data); + } + else TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] Failed to update for current texture format (%i)", id, format); +} + +// Get OpenGL internal formats and data type from raylib PixelFormat +void rlGetGlTextureFormats(int format, unsigned int *glInternalFormat, unsigned int *glFormat, unsigned int *glType) +{ + *glInternalFormat = 0; + *glFormat = 0; + *glType = 0; + + switch (format) + { + #if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_21) || defined(GRAPHICS_API_OPENGL_ES2) + // NOTE: on OpenGL ES 2.0 (WebGL), internalFormat must match format and options allowed are: GL_LUMINANCE, GL_RGB, GL_RGBA + case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_UNSIGNED_BYTE; break; + case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: *glInternalFormat = GL_LUMINANCE_ALPHA; *glFormat = GL_LUMINANCE_ALPHA; *glType = GL_UNSIGNED_BYTE; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_UNSIGNED_SHORT_5_6_5; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_UNSIGNED_BYTE; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_5_5_5_1; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_4_4_4_4; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_BYTE; break; + #if !defined(GRAPHICS_API_OPENGL_11) + #if defined(GRAPHICS_API_OPENGL_ES3) + case RL_PIXELFORMAT_UNCOMPRESSED_R32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_R32F_EXT; *glFormat = GL_RED_EXT; *glType = GL_FLOAT; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGB32F_EXT; *glFormat = GL_RGB; *glType = GL_FLOAT; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGBA32F_EXT; *glFormat = GL_RGBA; *glType = GL_FLOAT; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_R16F_EXT; *glFormat = GL_RED_EXT; *glType = GL_HALF_FLOAT; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB16F_EXT; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA16F_EXT; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT; break; + #else + case RL_PIXELFORMAT_UNCOMPRESSED_R32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_FLOAT; break; // NOTE: Requires extension OES_texture_float + case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_FLOAT; break; // NOTE: Requires extension OES_texture_float + case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_FLOAT; break; // NOTE: Requires extension OES_texture_float + #if defined(GRAPHICS_API_OPENGL_21) + case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_HALF_FLOAT_ARB; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT_ARB; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT_ARB; break; + #else // defined(GRAPHICS_API_OPENGL_ES2) + case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_HALF_FLOAT_OES; break; // NOTE: Requires extension OES_texture_half_float + case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT_OES; break; // NOTE: Requires extension OES_texture_half_float + case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT_OES; break; // NOTE: Requires extension OES_texture_half_float + #endif + #endif + #endif + #elif defined(GRAPHICS_API_OPENGL_33) + case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: *glInternalFormat = GL_R8; *glFormat = GL_RED; *glType = GL_UNSIGNED_BYTE; break; + case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: *glInternalFormat = GL_RG8; *glFormat = GL_RG; *glType = GL_UNSIGNED_BYTE; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: *glInternalFormat = GL_RGB565; *glFormat = GL_RGB; *glType = GL_UNSIGNED_SHORT_5_6_5; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: *glInternalFormat = GL_RGB8; *glFormat = GL_RGB; *glType = GL_UNSIGNED_BYTE; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: *glInternalFormat = GL_RGB5_A1; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_5_5_5_1; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: *glInternalFormat = GL_RGBA4; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_4_4_4_4; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: *glInternalFormat = GL_RGBA8; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_BYTE; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_R32F; *glFormat = GL_RED; *glType = GL_FLOAT; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGB32F; *glFormat = GL_RGB; *glType = GL_FLOAT; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGBA32F; *glFormat = GL_RGBA; *glType = GL_FLOAT; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_R16F; *glFormat = GL_RED; *glType = GL_HALF_FLOAT; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB16F; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA16F; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT; break; + #endif + #if !defined(GRAPHICS_API_OPENGL_11) + case RL_PIXELFORMAT_COMPRESSED_DXT1_RGB: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; break; + case RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; + case RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; + case RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; + case RL_PIXELFORMAT_COMPRESSED_ETC1_RGB: if (RLGL.ExtSupported.texCompETC1) *glInternalFormat = GL_ETC1_RGB8_OES; break; // NOTE: Requires OpenGL ES 2.0 or OpenGL 4.3 + case RL_PIXELFORMAT_COMPRESSED_ETC2_RGB: if (RLGL.ExtSupported.texCompETC2) *glInternalFormat = GL_COMPRESSED_RGB8_ETC2; break; // NOTE: Requires OpenGL ES 3.0 or OpenGL 4.3 + case RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: if (RLGL.ExtSupported.texCompETC2) *glInternalFormat = GL_COMPRESSED_RGBA8_ETC2_EAC; break; // NOTE: Requires OpenGL ES 3.0 or OpenGL 4.3 + case RL_PIXELFORMAT_COMPRESSED_PVRT_RGB: if (RLGL.ExtSupported.texCompPVRT) *glInternalFormat = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG; break; // NOTE: Requires PowerVR GPU + case RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA: if (RLGL.ExtSupported.texCompPVRT) *glInternalFormat = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; break; // NOTE: Requires PowerVR GPU + case RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: if (RLGL.ExtSupported.texCompASTC) *glInternalFormat = GL_COMPRESSED_RGBA_ASTC_4x4_KHR; break; // NOTE: Requires OpenGL ES 3.1 or OpenGL 4.3 + case RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: if (RLGL.ExtSupported.texCompASTC) *glInternalFormat = GL_COMPRESSED_RGBA_ASTC_8x8_KHR; break; // NOTE: Requires OpenGL ES 3.1 or OpenGL 4.3 + #endif + default: TRACELOG(RL_LOG_WARNING, "TEXTURE: Current format not supported (%i)", format); break; + } +} + +// Unload texture from GPU memory +void rlUnloadTexture(unsigned int id) +{ + glDeleteTextures(1, &id); +} + +// Generate mipmap data for selected texture +// NOTE: Only supports GPU mipmap generation +void rlGenTextureMipmaps(unsigned int id, int width, int height, int format, int *mipmaps) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glBindTexture(GL_TEXTURE_2D, id); + + // Check if texture is power-of-two (POT) + bool texIsPOT = false; + + if (((width > 0) && ((width & (width - 1)) == 0)) && + ((height > 0) && ((height & (height - 1)) == 0))) texIsPOT = true; + + if ((texIsPOT) || (RLGL.ExtSupported.texNPOT)) + { + //glHint(GL_GENERATE_MIPMAP_HINT, GL_DONT_CARE); // Hint for mipmaps generation algorithm: GL_FASTEST, GL_NICEST, GL_DONT_CARE + glGenerateMipmap(GL_TEXTURE_2D); // Generate mipmaps automatically + + #define MIN(a,b) (((a)<(b))? (a):(b)) + #define MAX(a,b) (((a)>(b))? (a):(b)) + + *mipmaps = 1 + (int)floor(log(MAX(width, height))/log(2)); + TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Mipmaps generated automatically, total: %i", id, *mipmaps); + } + else TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] Failed to generate mipmaps", id); + + glBindTexture(GL_TEXTURE_2D, 0); +#else + TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] GPU mipmap generation not supported", id); +#endif +} + + +// Read texture pixel data +void *rlReadTexturePixels(unsigned int id, int width, int height, int format) +{ + void *pixels = NULL; + +#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) + glBindTexture(GL_TEXTURE_2D, id); + + // NOTE: Using texture id, we can retrieve some texture info (but not on OpenGL ES 2.0) + // Possible texture info: GL_TEXTURE_RED_SIZE, GL_TEXTURE_GREEN_SIZE, GL_TEXTURE_BLUE_SIZE, GL_TEXTURE_ALPHA_SIZE + //int width, height, format; + //glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width); + //glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height); + //glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &format); + + // NOTE: Each row written to or read from by OpenGL pixel operations like glGetTexImage are aligned to a 4 byte boundary by default, which may add some padding. + // Use glPixelStorei to modify padding with the GL_[UN]PACK_ALIGNMENT setting. + // GL_PACK_ALIGNMENT affects operations that read from OpenGL memory (glReadPixels, glGetTexImage, etc.) + // GL_UNPACK_ALIGNMENT affects operations that write to OpenGL memory (glTexImage, etc.) + glPixelStorei(GL_PACK_ALIGNMENT, 1); + + unsigned int glInternalFormat, glFormat, glType; + rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); + unsigned int size = rlGetPixelDataSize(width, height, format); + + if ((glInternalFormat != 0) && (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB)) + { + pixels = RL_MALLOC(size); + glGetTexImage(GL_TEXTURE_2D, 0, glFormat, glType, pixels); + } + else TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] Data retrieval not suported for pixel format (%i)", id, format); + + glBindTexture(GL_TEXTURE_2D, 0); +#endif + +#if defined(GRAPHICS_API_OPENGL_ES2) + // glGetTexImage() is not available on OpenGL ES 2.0 + // Texture width and height are required on OpenGL ES 2.0. There is no way to get it from texture id. + // Two possible Options: + // 1 - Bind texture to color fbo attachment and glReadPixels() + // 2 - Create an fbo, activate it, render quad with texture, glReadPixels() + // We are using Option 1, just need to care for texture format on retrieval + // NOTE: This behaviour could be conditioned by graphic driver... + unsigned int fboId = rlLoadFramebuffer(width, height); + + glBindFramebuffer(GL_FRAMEBUFFER, fboId); + glBindTexture(GL_TEXTURE_2D, 0); + + // Attach our texture to FBO + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, id, 0); + + // We read data as RGBA because FBO texture is configured as RGBA, despite binding another texture format + pixels = (unsigned char *)RL_MALLOC(rlGetPixelDataSize(width, height, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8)); + glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + // Clean up temporal fbo + rlUnloadFramebuffer(fboId); +#endif + + return pixels; +} + +// Read screen pixel data (color buffer) +unsigned char *rlReadScreenPixels(int width, int height) +{ + unsigned char *screenData = (unsigned char *)RL_CALLOC(width*height*4, sizeof(unsigned char)); + + // NOTE 1: glReadPixels returns image flipped vertically -> (0,0) is the bottom left corner of the framebuffer + // NOTE 2: We are getting alpha channel! Be careful, it can be transparent if not cleared properly! + glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, screenData); + + // Flip image vertically! + unsigned char *imgData = (unsigned char *)RL_MALLOC(width*height*4*sizeof(unsigned char)); + + for (int y = height - 1; y >= 0; y--) + { + for (int x = 0; x < (width*4); x++) + { + imgData[((height - 1) - y)*width*4 + x] = screenData[(y*width*4) + x]; // Flip line + + // Set alpha component value to 255 (no trasparent image retrieval) + // NOTE: Alpha value has already been applied to RGB in framebuffer, we don't need it! + if (((x + 1)%4) == 0) imgData[((height - 1) - y)*width*4 + x] = 255; + } + } + + RL_FREE(screenData); + + return imgData; // NOTE: image data should be freed +} + +// Framebuffer management (fbo) +//----------------------------------------------------------------------------------------- +// Load a framebuffer to be used for rendering +// NOTE: No textures attached +unsigned int rlLoadFramebuffer(int width, int height) +{ + unsigned int fboId = 0; + +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) + glGenFramebuffers(1, &fboId); // Create the framebuffer object + glBindFramebuffer(GL_FRAMEBUFFER, 0); // Unbind any framebuffer +#endif + + return fboId; +} + +// Attach color buffer texture to an fbo (unloads previous attachment) +// NOTE: Attach type: 0-Color, 1-Depth renderbuffer, 2-Depth texture +void rlFramebufferAttach(unsigned int fboId, unsigned int texId, int attachType, int texType, int mipLevel) +{ +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) + glBindFramebuffer(GL_FRAMEBUFFER, fboId); + + switch (attachType) + { + case RL_ATTACHMENT_COLOR_CHANNEL0: + case RL_ATTACHMENT_COLOR_CHANNEL1: + case RL_ATTACHMENT_COLOR_CHANNEL2: + case RL_ATTACHMENT_COLOR_CHANNEL3: + case RL_ATTACHMENT_COLOR_CHANNEL4: + case RL_ATTACHMENT_COLOR_CHANNEL5: + case RL_ATTACHMENT_COLOR_CHANNEL6: + case RL_ATTACHMENT_COLOR_CHANNEL7: + { + if (texType == RL_ATTACHMENT_TEXTURE2D) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachType, GL_TEXTURE_2D, texId, mipLevel); + else if (texType == RL_ATTACHMENT_RENDERBUFFER) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachType, GL_RENDERBUFFER, texId); + else if (texType >= RL_ATTACHMENT_CUBEMAP_POSITIVE_X) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachType, GL_TEXTURE_CUBE_MAP_POSITIVE_X + texType, texId, mipLevel); + + } break; + case RL_ATTACHMENT_DEPTH: + { + if (texType == RL_ATTACHMENT_TEXTURE2D) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texId, mipLevel); + else if (texType == RL_ATTACHMENT_RENDERBUFFER) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, texId); + + } break; + case RL_ATTACHMENT_STENCIL: + { + if (texType == RL_ATTACHMENT_TEXTURE2D) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, texId, mipLevel); + else if (texType == RL_ATTACHMENT_RENDERBUFFER) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, texId); + + } break; + default: break; + } + + glBindFramebuffer(GL_FRAMEBUFFER, 0); +#endif +} + +// Verify render texture is complete +bool rlFramebufferComplete(unsigned int id) +{ + bool result = false; + +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) + glBindFramebuffer(GL_FRAMEBUFFER, id); + + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + + if (status != GL_FRAMEBUFFER_COMPLETE) + { + switch (status) + { + case GL_FRAMEBUFFER_UNSUPPORTED: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer is unsupported", id); break; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer has incomplete attachment", id); break; +#if defined(GRAPHICS_API_OPENGL_ES2) + case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer has incomplete dimensions", id); break; +#endif + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer has a missing attachment", id); break; + default: break; + } + } + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + result = (status == GL_FRAMEBUFFER_COMPLETE); +#endif + + return result; +} + +// Unload framebuffer from GPU memory +// NOTE: All attached textures/cubemaps/renderbuffers are also deleted +void rlUnloadFramebuffer(unsigned int id) +{ +#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) + // Query depth attachment to automatically delete texture/renderbuffer + int depthType = 0, depthId = 0; + glBindFramebuffer(GL_FRAMEBUFFER, id); // Bind framebuffer to query depth texture type + glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &depthType); + + // TODO: Review warning retrieving object name in WebGL + // WARNING: WebGL: INVALID_ENUM: getFramebufferAttachmentParameter: invalid parameter name + // https://registry.khronos.org/webgl/specs/latest/1.0/ + glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthId); + + unsigned int depthIdU = (unsigned int)depthId; + if (depthType == GL_RENDERBUFFER) glDeleteRenderbuffers(1, &depthIdU); + else if (depthType == GL_TEXTURE) glDeleteTextures(1, &depthIdU); + + // NOTE: If a texture object is deleted while its image is attached to the *currently bound* framebuffer, + // the texture image is automatically detached from the currently bound framebuffer. + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + glDeleteFramebuffers(1, &id); + + TRACELOG(RL_LOG_INFO, "FBO: [ID %i] Unloaded framebuffer from VRAM (GPU)", id); +#endif +} + +// Vertex data management +//----------------------------------------------------------------------------------------- +// Load a new attributes buffer +unsigned int rlLoadVertexBuffer(const void *buffer, int size, bool dynamic) +{ + unsigned int id = 0; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glGenBuffers(1, &id); + glBindBuffer(GL_ARRAY_BUFFER, id); + glBufferData(GL_ARRAY_BUFFER, size, buffer, dynamic? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); +#endif + + return id; +} + +// Load a new attributes element buffer +unsigned int rlLoadVertexBufferElement(const void *buffer, int size, bool dynamic) +{ + unsigned int id = 0; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glGenBuffers(1, &id); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, buffer, dynamic? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); +#endif + + return id; +} + +// Enable vertex buffer (VBO) +void rlEnableVertexBuffer(unsigned int id) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glBindBuffer(GL_ARRAY_BUFFER, id); +#endif +} + +// Disable vertex buffer (VBO) +void rlDisableVertexBuffer(void) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glBindBuffer(GL_ARRAY_BUFFER, 0); +#endif +} + +// Enable vertex buffer element (VBO element) +void rlEnableVertexBufferElement(unsigned int id) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); +#endif +} + +// Disable vertex buffer element (VBO element) +void rlDisableVertexBufferElement(void) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); +#endif +} + +// Update vertex buffer with new data +// NOTE: dataSize and offset must be provided in bytes +void rlUpdateVertexBuffer(unsigned int id, const void *data, int dataSize, int offset) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glBindBuffer(GL_ARRAY_BUFFER, id); + glBufferSubData(GL_ARRAY_BUFFER, offset, dataSize, data); +#endif +} + +// Update vertex buffer elements with new data +// NOTE: dataSize and offset must be provided in bytes +void rlUpdateVertexBufferElements(unsigned int id, const void *data, int dataSize, int offset) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); + glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, offset, dataSize, data); +#endif +} + +// Enable vertex array object (VAO) +bool rlEnableVertexArray(unsigned int vaoId) +{ + bool result = false; +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + if (RLGL.ExtSupported.vao) + { + glBindVertexArray(vaoId); + result = true; + } +#endif + return result; +} + +// Disable vertex array object (VAO) +void rlDisableVertexArray(void) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + if (RLGL.ExtSupported.vao) glBindVertexArray(0); +#endif +} + +// Enable vertex attribute index +void rlEnableVertexAttribute(unsigned int index) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glEnableVertexAttribArray(index); +#endif +} + +// Disable vertex attribute index +void rlDisableVertexAttribute(unsigned int index) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glDisableVertexAttribArray(index); +#endif +} + +// Draw vertex array +void rlDrawVertexArray(int offset, int count) +{ + glDrawArrays(GL_TRIANGLES, offset, count); +} + +// Draw vertex array elements +void rlDrawVertexArrayElements(int offset, int count, const void *buffer) +{ + // NOTE: Added pointer math separately from function to avoid UBSAN complaining + unsigned short *bufferPtr = (unsigned short *)buffer; + if (offset > 0) bufferPtr += offset; + + glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, (const unsigned short *)bufferPtr); +} + +// Draw vertex array instanced +void rlDrawVertexArrayInstanced(int offset, int count, int instances) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glDrawArraysInstanced(GL_TRIANGLES, 0, count, instances); +#endif +} + +// Draw vertex array elements instanced +void rlDrawVertexArrayElementsInstanced(int offset, int count, const void *buffer, int instances) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + // NOTE: Added pointer math separately from function to avoid UBSAN complaining + unsigned short *bufferPtr = (unsigned short *)buffer; + if (offset > 0) bufferPtr += offset; + + glDrawElementsInstanced(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, (const unsigned short *)bufferPtr, instances); +#endif +} + +#if defined(GRAPHICS_API_OPENGL_11) +// Enable vertex state pointer +void rlEnableStatePointer(int vertexAttribType, void *buffer) +{ + if (buffer != NULL) glEnableClientState(vertexAttribType); + switch (vertexAttribType) + { + case GL_VERTEX_ARRAY: glVertexPointer(3, GL_FLOAT, 0, buffer); break; + case GL_TEXTURE_COORD_ARRAY: glTexCoordPointer(2, GL_FLOAT, 0, buffer); break; + case GL_NORMAL_ARRAY: if (buffer != NULL) glNormalPointer(GL_FLOAT, 0, buffer); break; + case GL_COLOR_ARRAY: if (buffer != NULL) glColorPointer(4, GL_UNSIGNED_BYTE, 0, buffer); break; + //case GL_INDEX_ARRAY: if (buffer != NULL) glIndexPointer(GL_SHORT, 0, buffer); break; // Indexed colors + default: break; + } +} + +// Disable vertex state pointer +void rlDisableStatePointer(int vertexAttribType) +{ + glDisableClientState(vertexAttribType); +} +#endif + +// Load vertex array object (VAO) +unsigned int rlLoadVertexArray(void) +{ + unsigned int vaoId = 0; +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + if (RLGL.ExtSupported.vao) + { + glGenVertexArrays(1, &vaoId); + } +#endif + return vaoId; +} + +// Set vertex attribute +void rlSetVertexAttribute(unsigned int index, int compSize, int type, bool normalized, int stride, const void *pointer) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glVertexAttribPointer(index, compSize, type, normalized, stride, pointer); +#endif +} + +// Set vertex attribute divisor +void rlSetVertexAttributeDivisor(unsigned int index, int divisor) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glVertexAttribDivisor(index, divisor); +#endif +} + +// Unload vertex array object (VAO) +void rlUnloadVertexArray(unsigned int vaoId) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + if (RLGL.ExtSupported.vao) + { + glBindVertexArray(0); + glDeleteVertexArrays(1, &vaoId); + TRACELOG(RL_LOG_INFO, "VAO: [ID %i] Unloaded vertex array data from VRAM (GPU)", vaoId); + } +#endif +} + +// Unload vertex buffer (VBO) +void rlUnloadVertexBuffer(unsigned int vboId) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glDeleteBuffers(1, &vboId); + //TRACELOG(RL_LOG_INFO, "VBO: Unloaded vertex data from VRAM (GPU)"); +#endif +} + +// Shaders management +//----------------------------------------------------------------------------------------------- +// Load shader from code strings +// NOTE: If shader string is NULL, using default vertex/fragment shaders +unsigned int rlLoadShaderCode(const char *vsCode, const char *fsCode) +{ + unsigned int id = 0; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + unsigned int vertexShaderId = 0; + unsigned int fragmentShaderId = 0; + + // Compile vertex shader (if provided) + if (vsCode != NULL) vertexShaderId = rlCompileShader(vsCode, GL_VERTEX_SHADER); + // In case no vertex shader was provided or compilation failed, we use default vertex shader + if (vertexShaderId == 0) vertexShaderId = RLGL.State.defaultVShaderId; + + // Compile fragment shader (if provided) + if (fsCode != NULL) fragmentShaderId = rlCompileShader(fsCode, GL_FRAGMENT_SHADER); + // In case no fragment shader was provided or compilation failed, we use default fragment shader + if (fragmentShaderId == 0) fragmentShaderId = RLGL.State.defaultFShaderId; + + // In case vertex and fragment shader are the default ones, no need to recompile, we can just assign the default shader program id + if ((vertexShaderId == RLGL.State.defaultVShaderId) && (fragmentShaderId == RLGL.State.defaultFShaderId)) id = RLGL.State.defaultShaderId; + else + { + // One of or both shader are new, we need to compile a new shader program + id = rlLoadShaderProgram(vertexShaderId, fragmentShaderId); + + // We can detach and delete vertex/fragment shaders (if not default ones) + // NOTE: We detach shader before deletion to make sure memory is freed + if (vertexShaderId != RLGL.State.defaultVShaderId) + { + // WARNING: Shader program linkage could fail and returned id is 0 + if (id > 0) glDetachShader(id, vertexShaderId); + glDeleteShader(vertexShaderId); + } + if (fragmentShaderId != RLGL.State.defaultFShaderId) + { + // WARNING: Shader program linkage could fail and returned id is 0 + if (id > 0) glDetachShader(id, fragmentShaderId); + glDeleteShader(fragmentShaderId); + } + + // In case shader program loading failed, we assign default shader + if (id == 0) + { + // In case shader loading fails, we return the default shader + TRACELOG(RL_LOG_WARNING, "SHADER: Failed to load custom shader code, using default shader"); + id = RLGL.State.defaultShaderId; + } + /* + else + { + // Get available shader uniforms + // NOTE: This information is useful for debug... + int uniformCount = -1; + glGetProgramiv(id, GL_ACTIVE_UNIFORMS, &uniformCount); + + for (int i = 0; i < uniformCount; i++) + { + int namelen = -1; + int num = -1; + char name[256] = { 0 }; // Assume no variable names longer than 256 + GLenum type = GL_ZERO; + + // Get the name of the uniforms + glGetActiveUniform(id, i, sizeof(name) - 1, &namelen, &num, &type, name); + + name[namelen] = 0; + TRACELOGD("SHADER: [ID %i] Active uniform (%s) set at location: %i", id, name, glGetUniformLocation(id, name)); + } + } + */ + } +#endif + + return id; +} + +// Compile custom shader and return shader id +unsigned int rlCompileShader(const char *shaderCode, int type) +{ + unsigned int shader = 0; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + shader = glCreateShader(type); + glShaderSource(shader, 1, &shaderCode, NULL); + + GLint success = 0; + glCompileShader(shader); + glGetShaderiv(shader, GL_COMPILE_STATUS, &success); + + if (success == GL_FALSE) + { + switch (type) + { + case GL_VERTEX_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to compile vertex shader code", shader); break; + case GL_FRAGMENT_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to compile fragment shader code", shader); break; + //case GL_GEOMETRY_SHADER: + #if defined(GRAPHICS_API_OPENGL_43) + case GL_COMPUTE_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to compile compute shader code", shader); break; + #endif + default: break; + } + + int maxLength = 0; + glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength); + + if (maxLength > 0) + { + int length = 0; + char *log = (char *)RL_CALLOC(maxLength, sizeof(char)); + glGetShaderInfoLog(shader, maxLength, &length, log); + TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Compile error: %s", shader, log); + RL_FREE(log); + } + } + else + { + switch (type) + { + case GL_VERTEX_SHADER: TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Vertex shader compiled successfully", shader); break; + case GL_FRAGMENT_SHADER: TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Fragment shader compiled successfully", shader); break; + //case GL_GEOMETRY_SHADER: + #if defined(GRAPHICS_API_OPENGL_43) + case GL_COMPUTE_SHADER: TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Compute shader compiled successfully", shader); break; + #endif + default: break; + } + } +#endif + + return shader; +} + +// Load custom shader strings and return program id +unsigned int rlLoadShaderProgram(unsigned int vShaderId, unsigned int fShaderId) +{ + unsigned int program = 0; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + GLint success = 0; + program = glCreateProgram(); + + glAttachShader(program, vShaderId); + glAttachShader(program, fShaderId); + + // NOTE: Default attribute shader locations must be Bound before linking + glBindAttribLocation(program, 0, RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION); + glBindAttribLocation(program, 1, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD); + glBindAttribLocation(program, 2, RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL); + glBindAttribLocation(program, 3, RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR); + glBindAttribLocation(program, 4, RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT); + glBindAttribLocation(program, 5, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2); + + // NOTE: If some attrib name is no found on the shader, it locations becomes -1 + + glLinkProgram(program); + + // NOTE: All uniform variables are intitialised to 0 when a program links + + glGetProgramiv(program, GL_LINK_STATUS, &success); + + if (success == GL_FALSE) + { + TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to link shader program", program); + + int maxLength = 0; + glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); + + if (maxLength > 0) + { + int length = 0; + char *log = (char *)RL_CALLOC(maxLength, sizeof(char)); + glGetProgramInfoLog(program, maxLength, &length, log); + TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Link error: %s", program, log); + RL_FREE(log); + } + + glDeleteProgram(program); + + program = 0; + } + else + { + // Get the size of compiled shader program (not available on OpenGL ES 2.0) + // NOTE: If GL_LINK_STATUS is GL_FALSE, program binary length is zero. + //GLint binarySize = 0; + //glGetProgramiv(id, GL_PROGRAM_BINARY_LENGTH, &binarySize); + + TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Program shader loaded successfully", program); + } +#endif + return program; +} + +// Unload shader program +void rlUnloadShaderProgram(unsigned int id) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glDeleteProgram(id); + + TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Unloaded shader program data from VRAM (GPU)", id); +#endif +} + +// Get shader location uniform +int rlGetLocationUniform(unsigned int shaderId, const char *uniformName) +{ + int location = -1; +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + location = glGetUniformLocation(shaderId, uniformName); + + //if (location == -1) TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to find shader uniform: %s", shaderId, uniformName); + //else TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Shader uniform (%s) set at location: %i", shaderId, uniformName, location); +#endif + return location; +} + +// Get shader location attribute +int rlGetLocationAttrib(unsigned int shaderId, const char *attribName) +{ + int location = -1; +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + location = glGetAttribLocation(shaderId, attribName); + + //if (location == -1) TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to find shader attribute: %s", shaderId, attribName); + //else TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Shader attribute (%s) set at location: %i", shaderId, attribName, location); +#endif + return location; +} + +// Set shader value uniform +void rlSetUniform(int locIndex, const void *value, int uniformType, int count) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + switch (uniformType) + { + case RL_SHADER_UNIFORM_FLOAT: glUniform1fv(locIndex, count, (float *)value); break; + case RL_SHADER_UNIFORM_VEC2: glUniform2fv(locIndex, count, (float *)value); break; + case RL_SHADER_UNIFORM_VEC3: glUniform3fv(locIndex, count, (float *)value); break; + case RL_SHADER_UNIFORM_VEC4: glUniform4fv(locIndex, count, (float *)value); break; + case RL_SHADER_UNIFORM_INT: glUniform1iv(locIndex, count, (int *)value); break; + case RL_SHADER_UNIFORM_IVEC2: glUniform2iv(locIndex, count, (int *)value); break; + case RL_SHADER_UNIFORM_IVEC3: glUniform3iv(locIndex, count, (int *)value); break; + case RL_SHADER_UNIFORM_IVEC4: glUniform4iv(locIndex, count, (int *)value); break; + case RL_SHADER_UNIFORM_SAMPLER2D: glUniform1iv(locIndex, count, (int *)value); break; + default: TRACELOG(RL_LOG_WARNING, "SHADER: Failed to set uniform value, data type not recognized"); + } +#endif +} + +// Set shader value attribute +void rlSetVertexAttributeDefault(int locIndex, const void *value, int attribType, int count) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + switch (attribType) + { + case RL_SHADER_ATTRIB_FLOAT: if (count == 1) glVertexAttrib1fv(locIndex, (float *)value); break; + case RL_SHADER_ATTRIB_VEC2: if (count == 2) glVertexAttrib2fv(locIndex, (float *)value); break; + case RL_SHADER_ATTRIB_VEC3: if (count == 3) glVertexAttrib3fv(locIndex, (float *)value); break; + case RL_SHADER_ATTRIB_VEC4: if (count == 4) glVertexAttrib4fv(locIndex, (float *)value); break; + default: TRACELOG(RL_LOG_WARNING, "SHADER: Failed to set attrib default value, data type not recognized"); + } +#endif +} + +// Set shader value uniform matrix +void rlSetUniformMatrix(int locIndex, Matrix mat) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + float matfloat[16] = { + mat.m0, mat.m1, mat.m2, mat.m3, + mat.m4, mat.m5, mat.m6, mat.m7, + mat.m8, mat.m9, mat.m10, mat.m11, + mat.m12, mat.m13, mat.m14, mat.m15 + }; + glUniformMatrix4fv(locIndex, 1, false, matfloat); +#endif +} + +// Set shader value uniform sampler +void rlSetUniformSampler(int locIndex, unsigned int textureId) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + // Check if texture is already active + for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) if (RLGL.State.activeTextureId[i] == textureId) return; + + // Register a new active texture for the internal batch system + // NOTE: Default texture is always activated as GL_TEXTURE0 + for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) + { + if (RLGL.State.activeTextureId[i] == 0) + { + glUniform1i(locIndex, 1 + i); // Activate new texture unit + RLGL.State.activeTextureId[i] = textureId; // Save texture id for binding on drawing + break; + } + } +#endif +} + +// Set shader currently active (id and locations) +void rlSetShader(unsigned int id, int *locs) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + if (RLGL.State.currentShaderId != id) + { + rlDrawRenderBatch(RLGL.currentBatch); + RLGL.State.currentShaderId = id; + RLGL.State.currentShaderLocs = locs; + } +#endif +} + +// Load compute shader program +unsigned int rlLoadComputeShaderProgram(unsigned int shaderId) +{ + unsigned int program = 0; + +#if defined(GRAPHICS_API_OPENGL_43) + GLint success = 0; + program = glCreateProgram(); + glAttachShader(program, shaderId); + glLinkProgram(program); + + // NOTE: All uniform variables are intitialised to 0 when a program links + + glGetProgramiv(program, GL_LINK_STATUS, &success); + + if (success == GL_FALSE) + { + TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to link compute shader program", program); + + int maxLength = 0; + glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); + + if (maxLength > 0) + { + int length = 0; + char *log = (char *)RL_CALLOC(maxLength, sizeof(char)); + glGetProgramInfoLog(program, maxLength, &length, log); + TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Link error: %s", program, log); + RL_FREE(log); + } + + glDeleteProgram(program); + + program = 0; + } + else + { + // Get the size of compiled shader program (not available on OpenGL ES 2.0) + // NOTE: If GL_LINK_STATUS is GL_FALSE, program binary length is zero. + //GLint binarySize = 0; + //glGetProgramiv(id, GL_PROGRAM_BINARY_LENGTH, &binarySize); + + TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Compute shader program loaded successfully", program); + } +#endif + + return program; +} + +// Dispatch compute shader (equivalent to *draw* for graphics pilepine) +void rlComputeShaderDispatch(unsigned int groupX, unsigned int groupY, unsigned int groupZ) +{ +#if defined(GRAPHICS_API_OPENGL_43) + glDispatchCompute(groupX, groupY, groupZ); +#endif +} + +// Load shader storage buffer object (SSBO) +unsigned int rlLoadShaderBuffer(unsigned int size, const void *data, int usageHint) +{ + unsigned int ssbo = 0; + +#if defined(GRAPHICS_API_OPENGL_43) + glGenBuffers(1, &ssbo); + glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo); + glBufferData(GL_SHADER_STORAGE_BUFFER, size, data, usageHint? usageHint : RL_STREAM_COPY); + if (data == NULL) glClearBufferData(GL_SHADER_STORAGE_BUFFER, GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE, NULL); // Clear buffer data to 0 + glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); +#endif + + return ssbo; +} + +// Unload shader storage buffer object (SSBO) +void rlUnloadShaderBuffer(unsigned int ssboId) +{ +#if defined(GRAPHICS_API_OPENGL_43) + glDeleteBuffers(1, &ssboId); +#endif +} + +// Update SSBO buffer data +void rlUpdateShaderBuffer(unsigned int id, const void *data, unsigned int dataSize, unsigned int offset) +{ +#if defined(GRAPHICS_API_OPENGL_43) + glBindBuffer(GL_SHADER_STORAGE_BUFFER, id); + glBufferSubData(GL_SHADER_STORAGE_BUFFER, offset, dataSize, data); +#endif +} + +// Get SSBO buffer size +unsigned int rlGetShaderBufferSize(unsigned int id) +{ + long long size = 0; + +#if defined(GRAPHICS_API_OPENGL_43) + glBindBuffer(GL_SHADER_STORAGE_BUFFER, id); + glGetInteger64v(GL_SHADER_STORAGE_BUFFER_SIZE, &size); +#endif + + return (size > 0)? (unsigned int)size : 0; +} + +// Read SSBO buffer data (GPU->CPU) +void rlReadShaderBuffer(unsigned int id, void *dest, unsigned int count, unsigned int offset) +{ +#if defined(GRAPHICS_API_OPENGL_43) + glBindBuffer(GL_SHADER_STORAGE_BUFFER, id); + glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, offset, count, dest); +#endif +} + +// Bind SSBO buffer +void rlBindShaderBuffer(unsigned int id, unsigned int index) +{ +#if defined(GRAPHICS_API_OPENGL_43) + glBindBufferBase(GL_SHADER_STORAGE_BUFFER, index, id); +#endif +} + +// Copy SSBO buffer data +void rlCopyShaderBuffer(unsigned int destId, unsigned int srcId, unsigned int destOffset, unsigned int srcOffset, unsigned int count) +{ +#if defined(GRAPHICS_API_OPENGL_43) + glBindBuffer(GL_COPY_READ_BUFFER, srcId); + glBindBuffer(GL_COPY_WRITE_BUFFER, destId); + glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, srcOffset, destOffset, count); +#endif +} + +// Bind image texture +void rlBindImageTexture(unsigned int id, unsigned int index, int format, bool readonly) +{ +#if defined(GRAPHICS_API_OPENGL_43) + unsigned int glInternalFormat = 0, glFormat = 0, glType = 0; + + rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); + glBindImageTexture(index, id, 0, 0, 0, readonly? GL_READ_ONLY : GL_READ_WRITE, glInternalFormat); +#endif +} + +// Matrix state management +//----------------------------------------------------------------------------------------- +// Get internal modelview matrix +Matrix rlGetMatrixModelview(void) +{ + Matrix matrix = rlMatrixIdentity(); +#if defined(GRAPHICS_API_OPENGL_11) + float mat[16]; + glGetFloatv(GL_MODELVIEW_MATRIX, mat); + matrix.m0 = mat[0]; + matrix.m1 = mat[1]; + matrix.m2 = mat[2]; + matrix.m3 = mat[3]; + matrix.m4 = mat[4]; + matrix.m5 = mat[5]; + matrix.m6 = mat[6]; + matrix.m7 = mat[7]; + matrix.m8 = mat[8]; + matrix.m9 = mat[9]; + matrix.m10 = mat[10]; + matrix.m11 = mat[11]; + matrix.m12 = mat[12]; + matrix.m13 = mat[13]; + matrix.m14 = mat[14]; + matrix.m15 = mat[15]; +#else + matrix = RLGL.State.modelview; +#endif + return matrix; +} + +// Get internal projection matrix +Matrix rlGetMatrixProjection(void) +{ +#if defined(GRAPHICS_API_OPENGL_11) + float mat[16]; + glGetFloatv(GL_PROJECTION_MATRIX,mat); + Matrix m; + m.m0 = mat[0]; + m.m1 = mat[1]; + m.m2 = mat[2]; + m.m3 = mat[3]; + m.m4 = mat[4]; + m.m5 = mat[5]; + m.m6 = mat[6]; + m.m7 = mat[7]; + m.m8 = mat[8]; + m.m9 = mat[9]; + m.m10 = mat[10]; + m.m11 = mat[11]; + m.m12 = mat[12]; + m.m13 = mat[13]; + m.m14 = mat[14]; + m.m15 = mat[15]; + return m; +#else + return RLGL.State.projection; +#endif +} + +// Get internal accumulated transform matrix +Matrix rlGetMatrixTransform(void) +{ + Matrix mat = rlMatrixIdentity(); +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + // TODO: Consider possible transform matrices in the RLGL.State.stack + // Is this the right order? or should we start with the first stored matrix instead of the last one? + //Matrix matStackTransform = rlMatrixIdentity(); + //for (int i = RLGL.State.stackCounter; i > 0; i--) matStackTransform = rlMatrixMultiply(RLGL.State.stack[i], matStackTransform); + mat = RLGL.State.transform; +#endif + return mat; +} + +// Get internal projection matrix for stereo render (selected eye) +RLAPI Matrix rlGetMatrixProjectionStereo(int eye) +{ + Matrix mat = rlMatrixIdentity(); +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + mat = RLGL.State.projectionStereo[eye]; +#endif + return mat; +} + +// Get internal view offset matrix for stereo render (selected eye) +RLAPI Matrix rlGetMatrixViewOffsetStereo(int eye) +{ + Matrix mat = rlMatrixIdentity(); +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + mat = RLGL.State.viewOffsetStereo[eye]; +#endif + return mat; +} + +// Set a custom modelview matrix (replaces internal modelview matrix) +void rlSetMatrixModelview(Matrix view) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + RLGL.State.modelview = view; +#endif +} + +// Set a custom projection matrix (replaces internal projection matrix) +void rlSetMatrixProjection(Matrix projection) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + RLGL.State.projection = projection; +#endif +} + +// Set eyes projection matrices for stereo rendering +void rlSetMatrixProjectionStereo(Matrix right, Matrix left) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + RLGL.State.projectionStereo[0] = right; + RLGL.State.projectionStereo[1] = left; +#endif +} + +// Set eyes view offsets matrices for stereo rendering +void rlSetMatrixViewOffsetStereo(Matrix right, Matrix left) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + RLGL.State.viewOffsetStereo[0] = right; + RLGL.State.viewOffsetStereo[1] = left; +#endif +} + +// Load and draw a quad in NDC +void rlLoadDrawQuad(void) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + unsigned int quadVAO = 0; + unsigned int quadVBO = 0; + + float vertices[] = { + // Positions Texcoords + -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, + -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, + 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, + 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, + }; + + // Gen VAO to contain VBO + glGenVertexArrays(1, &quadVAO); + glBindVertexArray(quadVAO); + + // Gen and fill vertex buffer (VBO) + glGenBuffers(1, &quadVBO); + glBindBuffer(GL_ARRAY_BUFFER, quadVBO); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW); + + // Bind vertex attributes (position, texcoords) + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)0); // Positions + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)(3*sizeof(float))); // Texcoords + + // Draw quad + glBindVertexArray(quadVAO); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + glBindVertexArray(0); + + // Delete buffers (VBO and VAO) + glDeleteBuffers(1, &quadVBO); + glDeleteVertexArrays(1, &quadVAO); +#endif +} + +// Load and draw a cube in NDC +void rlLoadDrawCube(void) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + unsigned int cubeVAO = 0; + unsigned int cubeVBO = 0; + + float vertices[] = { + // Positions Normals Texcoords + -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, + 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, + 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, + 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, + -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, + -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, + -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, + 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, + 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, + -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, + -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, + -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, + -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, + -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, + -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, + -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, + -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, + 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, + 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, + 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, + 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, + -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, + 1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, + 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, + 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, + -1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, + -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, + -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, + 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, + 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, + -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, + -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f + }; + + // Gen VAO to contain VBO + glGenVertexArrays(1, &cubeVAO); + glBindVertexArray(cubeVAO); + + // Gen and fill vertex buffer (VBO) + glGenBuffers(1, &cubeVBO); + glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); + + // Bind vertex attributes (position, normals, texcoords) + glBindVertexArray(cubeVAO); + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)0); // Positions + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(3*sizeof(float))); // Normals + glEnableVertexAttribArray(2); + glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(6*sizeof(float))); // Texcoords + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindVertexArray(0); + + // Draw cube + glBindVertexArray(cubeVAO); + glDrawArrays(GL_TRIANGLES, 0, 36); + glBindVertexArray(0); + + // Delete VBO and VAO + glDeleteBuffers(1, &cubeVBO); + glDeleteVertexArrays(1, &cubeVAO); +#endif +} + +// Get name string for pixel format +const char *rlGetPixelFormatName(unsigned int format) +{ + switch (format) + { + case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: return "GRAYSCALE"; break; // 8 bit per pixel (no alpha) + case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: return "GRAY_ALPHA"; break; // 8*2 bpp (2 channels) + case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: return "R5G6B5"; break; // 16 bpp + case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: return "R8G8B8"; break; // 24 bpp + case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: return "R5G5B5A1"; break; // 16 bpp (1 bit alpha) + case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: return "R4G4B4A4"; break; // 16 bpp (4 bit alpha) + case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: return "R8G8B8A8"; break; // 32 bpp + case RL_PIXELFORMAT_UNCOMPRESSED_R32: return "R32"; break; // 32 bpp (1 channel - float) + case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: return "R32G32B32"; break; // 32*3 bpp (3 channels - float) + case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: return "R32G32B32A32"; break; // 32*4 bpp (4 channels - float) + case RL_PIXELFORMAT_UNCOMPRESSED_R16: return "R16"; break; // 16 bpp (1 channel - half float) + case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: return "R16G16B16"; break; // 16*3 bpp (3 channels - half float) + case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: return "R16G16B16A16"; break; // 16*4 bpp (4 channels - half float) + case RL_PIXELFORMAT_COMPRESSED_DXT1_RGB: return "DXT1_RGB"; break; // 4 bpp (no alpha) + case RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA: return "DXT1_RGBA"; break; // 4 bpp (1 bit alpha) + case RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA: return "DXT3_RGBA"; break; // 8 bpp + case RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA: return "DXT5_RGBA"; break; // 8 bpp + case RL_PIXELFORMAT_COMPRESSED_ETC1_RGB: return "ETC1_RGB"; break; // 4 bpp + case RL_PIXELFORMAT_COMPRESSED_ETC2_RGB: return "ETC2_RGB"; break; // 4 bpp + case RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: return "ETC2_RGBA"; break; // 8 bpp + case RL_PIXELFORMAT_COMPRESSED_PVRT_RGB: return "PVRT_RGB"; break; // 4 bpp + case RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA: return "PVRT_RGBA"; break; // 4 bpp + case RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: return "ASTC_4x4_RGBA"; break; // 8 bpp + case RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: return "ASTC_8x8_RGBA"; break; // 2 bpp + default: return "UNKNOWN"; break; + } +} + +//---------------------------------------------------------------------------------- +// Module specific Functions Definition +//---------------------------------------------------------------------------------- +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) +// Load default shader (just vertex positioning and texture coloring) +// NOTE: This shader program is used for internal buffers +// NOTE: Loaded: RLGL.State.defaultShaderId, RLGL.State.defaultShaderLocs +static void rlLoadShaderDefault(void) +{ + RLGL.State.defaultShaderLocs = (int *)RL_CALLOC(RL_MAX_SHADER_LOCATIONS, sizeof(int)); + + // NOTE: All locations must be reseted to -1 (no location) + for (int i = 0; i < RL_MAX_SHADER_LOCATIONS; i++) RLGL.State.defaultShaderLocs[i] = -1; + + // Vertex shader directly defined, no external file required + const char *defaultVShaderCode = +#if defined(GRAPHICS_API_OPENGL_21) + "#version 120 \n" + "attribute vec3 vertexPosition; \n" + "attribute vec2 vertexTexCoord; \n" + "attribute vec4 vertexColor; \n" + "varying vec2 fragTexCoord; \n" + "varying vec4 fragColor; \n" +#elif defined(GRAPHICS_API_OPENGL_33) + "#version 330 \n" + "in vec3 vertexPosition; \n" + "in vec2 vertexTexCoord; \n" + "in vec4 vertexColor; \n" + "out vec2 fragTexCoord; \n" + "out vec4 fragColor; \n" +#endif +#if defined(GRAPHICS_API_OPENGL_ES2) + "#version 100 \n" + "precision mediump float; \n" // Precision required for OpenGL ES2 (WebGL) (on some browsers) + "attribute vec3 vertexPosition; \n" + "attribute vec2 vertexTexCoord; \n" + "attribute vec4 vertexColor; \n" + "varying vec2 fragTexCoord; \n" + "varying vec4 fragColor; \n" +#endif + "uniform mat4 mvp; \n" + "void main() \n" + "{ \n" + " fragTexCoord = vertexTexCoord; \n" + " fragColor = vertexColor; \n" + " gl_Position = mvp*vec4(vertexPosition, 1.0); \n" + "} \n"; + + // Fragment shader directly defined, no external file required + const char *defaultFShaderCode = +#if defined(GRAPHICS_API_OPENGL_21) + "#version 120 \n" + "varying vec2 fragTexCoord; \n" + "varying vec4 fragColor; \n" + "uniform sampler2D texture0; \n" + "uniform vec4 colDiffuse; \n" + "void main() \n" + "{ \n" + " vec4 texelColor = texture2D(texture0, fragTexCoord); \n" + " gl_FragColor = texelColor*colDiffuse*fragColor; \n" + "} \n"; +#elif defined(GRAPHICS_API_OPENGL_33) + "#version 330 \n" + "in vec2 fragTexCoord; \n" + "in vec4 fragColor; \n" + "out vec4 finalColor; \n" + "uniform sampler2D texture0; \n" + "uniform vec4 colDiffuse; \n" + "void main() \n" + "{ \n" + " vec4 texelColor = texture(texture0, fragTexCoord); \n" + " finalColor = texelColor*colDiffuse*fragColor; \n" + "} \n"; +#endif +#if defined(GRAPHICS_API_OPENGL_ES2) + "#version 100 \n" + "precision mediump float; \n" // Precision required for OpenGL ES2 (WebGL) + "varying vec2 fragTexCoord; \n" + "varying vec4 fragColor; \n" + "uniform sampler2D texture0; \n" + "uniform vec4 colDiffuse; \n" + "void main() \n" + "{ \n" + " vec4 texelColor = texture2D(texture0, fragTexCoord); \n" + " gl_FragColor = texelColor*colDiffuse*fragColor; \n" + "} \n"; +#endif + + // NOTE: Compiled vertex/fragment shaders are not deleted, + // they are kept for re-use as default shaders in case some shader loading fails + RLGL.State.defaultVShaderId = rlCompileShader(defaultVShaderCode, GL_VERTEX_SHADER); // Compile default vertex shader + RLGL.State.defaultFShaderId = rlCompileShader(defaultFShaderCode, GL_FRAGMENT_SHADER); // Compile default fragment shader + + RLGL.State.defaultShaderId = rlLoadShaderProgram(RLGL.State.defaultVShaderId, RLGL.State.defaultFShaderId); + + if (RLGL.State.defaultShaderId > 0) + { + TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Default shader loaded successfully", RLGL.State.defaultShaderId); + + // Set default shader locations: attributes locations + RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_POSITION] = glGetAttribLocation(RLGL.State.defaultShaderId, "vertexPosition"); + RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01] = glGetAttribLocation(RLGL.State.defaultShaderId, "vertexTexCoord"); + RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_COLOR] = glGetAttribLocation(RLGL.State.defaultShaderId, "vertexColor"); + + // Set default shader locations: uniform locations + RLGL.State.defaultShaderLocs[RL_SHADER_LOC_MATRIX_MVP] = glGetUniformLocation(RLGL.State.defaultShaderId, "mvp"); + RLGL.State.defaultShaderLocs[RL_SHADER_LOC_COLOR_DIFFUSE] = glGetUniformLocation(RLGL.State.defaultShaderId, "colDiffuse"); + RLGL.State.defaultShaderLocs[RL_SHADER_LOC_MAP_DIFFUSE] = glGetUniformLocation(RLGL.State.defaultShaderId, "texture0"); + } + else TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to load default shader", RLGL.State.defaultShaderId); +} + +// Unload default shader +// NOTE: Unloads: RLGL.State.defaultShaderId, RLGL.State.defaultShaderLocs +static void rlUnloadShaderDefault(void) +{ + glUseProgram(0); + + glDetachShader(RLGL.State.defaultShaderId, RLGL.State.defaultVShaderId); + glDetachShader(RLGL.State.defaultShaderId, RLGL.State.defaultFShaderId); + glDeleteShader(RLGL.State.defaultVShaderId); + glDeleteShader(RLGL.State.defaultFShaderId); + + glDeleteProgram(RLGL.State.defaultShaderId); + + RL_FREE(RLGL.State.defaultShaderLocs); + + TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Default shader unloaded successfully", RLGL.State.defaultShaderId); +} + +#if defined(RLGL_SHOW_GL_DETAILS_INFO) +// Get compressed format official GL identifier name +static const char *rlGetCompressedFormatName(int format) +{ + switch (format) + { + // GL_EXT_texture_compression_s3tc + case 0x83F0: return "GL_COMPRESSED_RGB_S3TC_DXT1_EXT"; break; + case 0x83F1: return "GL_COMPRESSED_RGBA_S3TC_DXT1_EXT"; break; + case 0x83F2: return "GL_COMPRESSED_RGBA_S3TC_DXT3_EXT"; break; + case 0x83F3: return "GL_COMPRESSED_RGBA_S3TC_DXT5_EXT"; break; + // GL_3DFX_texture_compression_FXT1 + case 0x86B0: return "GL_COMPRESSED_RGB_FXT1_3DFX"; break; + case 0x86B1: return "GL_COMPRESSED_RGBA_FXT1_3DFX"; break; + // GL_IMG_texture_compression_pvrtc + case 0x8C00: return "GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; break; + case 0x8C01: return "GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG"; break; + case 0x8C02: return "GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; break; + case 0x8C03: return "GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"; break; + // GL_OES_compressed_ETC1_RGB8_texture + case 0x8D64: return "GL_ETC1_RGB8_OES"; break; + // GL_ARB_texture_compression_rgtc + case 0x8DBB: return "GL_COMPRESSED_RED_RGTC1"; break; + case 0x8DBC: return "GL_COMPRESSED_SIGNED_RED_RGTC1"; break; + case 0x8DBD: return "GL_COMPRESSED_RG_RGTC2"; break; + case 0x8DBE: return "GL_COMPRESSED_SIGNED_RG_RGTC2"; break; + // GL_ARB_texture_compression_bptc + case 0x8E8C: return "GL_COMPRESSED_RGBA_BPTC_UNORM_ARB"; break; + case 0x8E8D: return "GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB"; break; + case 0x8E8E: return "GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB"; break; + case 0x8E8F: return "GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB"; break; + // GL_ARB_ES3_compatibility + case 0x9274: return "GL_COMPRESSED_RGB8_ETC2"; break; + case 0x9275: return "GL_COMPRESSED_SRGB8_ETC2"; break; + case 0x9276: return "GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"; break; + case 0x9277: return "GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"; break; + case 0x9278: return "GL_COMPRESSED_RGBA8_ETC2_EAC"; break; + case 0x9279: return "GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"; break; + case 0x9270: return "GL_COMPRESSED_R11_EAC"; break; + case 0x9271: return "GL_COMPRESSED_SIGNED_R11_EAC"; break; + case 0x9272: return "GL_COMPRESSED_RG11_EAC"; break; + case 0x9273: return "GL_COMPRESSED_SIGNED_RG11_EAC"; break; + // GL_KHR_texture_compression_astc_hdr + case 0x93B0: return "GL_COMPRESSED_RGBA_ASTC_4x4_KHR"; break; + case 0x93B1: return "GL_COMPRESSED_RGBA_ASTC_5x4_KHR"; break; + case 0x93B2: return "GL_COMPRESSED_RGBA_ASTC_5x5_KHR"; break; + case 0x93B3: return "GL_COMPRESSED_RGBA_ASTC_6x5_KHR"; break; + case 0x93B4: return "GL_COMPRESSED_RGBA_ASTC_6x6_KHR"; break; + case 0x93B5: return "GL_COMPRESSED_RGBA_ASTC_8x5_KHR"; break; + case 0x93B6: return "GL_COMPRESSED_RGBA_ASTC_8x6_KHR"; break; + case 0x93B7: return "GL_COMPRESSED_RGBA_ASTC_8x8_KHR"; break; + case 0x93B8: return "GL_COMPRESSED_RGBA_ASTC_10x5_KHR"; break; + case 0x93B9: return "GL_COMPRESSED_RGBA_ASTC_10x6_KHR"; break; + case 0x93BA: return "GL_COMPRESSED_RGBA_ASTC_10x8_KHR"; break; + case 0x93BB: return "GL_COMPRESSED_RGBA_ASTC_10x10_KHR"; break; + case 0x93BC: return "GL_COMPRESSED_RGBA_ASTC_12x10_KHR"; break; + case 0x93BD: return "GL_COMPRESSED_RGBA_ASTC_12x12_KHR"; break; + case 0x93D0: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR"; break; + case 0x93D1: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR"; break; + case 0x93D2: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR"; break; + case 0x93D3: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR"; break; + case 0x93D4: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR"; break; + case 0x93D5: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR"; break; + case 0x93D6: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR"; break; + case 0x93D7: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR"; break; + case 0x93D8: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR"; break; + case 0x93D9: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR"; break; + case 0x93DA: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR"; break; + case 0x93DB: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR"; break; + case 0x93DC: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR"; break; + case 0x93DD: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR"; break; + default: return "GL_COMPRESSED_UNKNOWN"; break; + } +} +#endif // RLGL_SHOW_GL_DETAILS_INFO + +#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 + +// Get pixel data size in bytes (image or texture) +// NOTE: Size depends on pixel format +static int rlGetPixelDataSize(int width, int height, int format) +{ + int dataSize = 0; // Size in bytes + int bpp = 0; // Bits per pixel + + switch (format) + { + case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: bpp = 8; break; + case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: + case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: + case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: + case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: bpp = 16; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: bpp = 32; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: bpp = 24; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R32: bpp = 32; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: bpp = 32*3; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: bpp = 32*4; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R16: bpp = 16; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: bpp = 16*3; break; + case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: bpp = 16*4; break; + case RL_PIXELFORMAT_COMPRESSED_DXT1_RGB: + case RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA: + case RL_PIXELFORMAT_COMPRESSED_ETC1_RGB: + case RL_PIXELFORMAT_COMPRESSED_ETC2_RGB: + case RL_PIXELFORMAT_COMPRESSED_PVRT_RGB: + case RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA: bpp = 4; break; + case RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA: + case RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA: + case RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: + case RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: bpp = 8; break; + case RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: bpp = 2; break; + default: break; + } + + dataSize = width*height*bpp/8; // Total data size in bytes + + // Most compressed formats works on 4x4 blocks, + // if texture is smaller, minimum dataSize is 8 or 16 + if ((width < 4) && (height < 4)) + { + if ((format >= RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) && (format < RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA)) dataSize = 8; + else if ((format >= RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA) && (format < RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA)) dataSize = 16; + } + + return dataSize; +} + +// Auxiliar math functions + +// Get identity matrix +static Matrix rlMatrixIdentity(void) +{ + Matrix result = { + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + }; + + return result; +} + +// Get two matrix multiplication +// NOTE: When multiplying matrices... the order matters! +static Matrix rlMatrixMultiply(Matrix left, Matrix right) +{ + Matrix result = { 0 }; + + result.m0 = left.m0*right.m0 + left.m1*right.m4 + left.m2*right.m8 + left.m3*right.m12; + result.m1 = left.m0*right.m1 + left.m1*right.m5 + left.m2*right.m9 + left.m3*right.m13; + result.m2 = left.m0*right.m2 + left.m1*right.m6 + left.m2*right.m10 + left.m3*right.m14; + result.m3 = left.m0*right.m3 + left.m1*right.m7 + left.m2*right.m11 + left.m3*right.m15; + result.m4 = left.m4*right.m0 + left.m5*right.m4 + left.m6*right.m8 + left.m7*right.m12; + result.m5 = left.m4*right.m1 + left.m5*right.m5 + left.m6*right.m9 + left.m7*right.m13; + result.m6 = left.m4*right.m2 + left.m5*right.m6 + left.m6*right.m10 + left.m7*right.m14; + result.m7 = left.m4*right.m3 + left.m5*right.m7 + left.m6*right.m11 + left.m7*right.m15; + result.m8 = left.m8*right.m0 + left.m9*right.m4 + left.m10*right.m8 + left.m11*right.m12; + result.m9 = left.m8*right.m1 + left.m9*right.m5 + left.m10*right.m9 + left.m11*right.m13; + result.m10 = left.m8*right.m2 + left.m9*right.m6 + left.m10*right.m10 + left.m11*right.m14; + result.m11 = left.m8*right.m3 + left.m9*right.m7 + left.m10*right.m11 + left.m11*right.m15; + result.m12 = left.m12*right.m0 + left.m13*right.m4 + left.m14*right.m8 + left.m15*right.m12; + result.m13 = left.m12*right.m1 + left.m13*right.m5 + left.m14*right.m9 + left.m15*right.m13; + result.m14 = left.m12*right.m2 + left.m13*right.m6 + left.m14*right.m10 + left.m15*right.m14; + result.m15 = left.m12*right.m3 + left.m13*right.m7 + left.m14*right.m11 + left.m15*right.m15; + + return result; +} + +#endif // RLGL_IMPLEMENTATION diff --git a/pkgs/raylib/raylib-5.0_win64_msvc16/lib/raylib.dll b/pkgs/raylib/raylib-5.0_win64_msvc16/lib/raylib.dll new file mode 100644 index 0000000..a9d218b Binary files /dev/null and b/pkgs/raylib/raylib-5.0_win64_msvc16/lib/raylib.dll differ diff --git a/pkgs/raylib/raylib-5.0_win64_msvc16/lib/raylib.lib b/pkgs/raylib/raylib-5.0_win64_msvc16/lib/raylib.lib new file mode 100644 index 0000000..7834a84 Binary files /dev/null and b/pkgs/raylib/raylib-5.0_win64_msvc16/lib/raylib.lib differ diff --git a/pkgs/raylib/raylib-5.0_win64_msvc16/lib/raylibdll.lib b/pkgs/raylib/raylib-5.0_win64_msvc16/lib/raylibdll.lib new file mode 100644 index 0000000..b264ea6 Binary files /dev/null and b/pkgs/raylib/raylib-5.0_win64_msvc16/lib/raylibdll.lib differ diff --git a/pkgs/raylib/raylib.lc b/pkgs/raylib/raylib.lc new file mode 100644 index 0000000..9128db9 --- /dev/null +++ b/pkgs/raylib/raylib.lc @@ -0,0 +1,1012 @@ +import "std_types"; + +Vector2 :: struct { + x: float; + y: float; +} + +Vector3 :: struct { + x: float; + y: float; + z: float; +} + +Vector4 :: struct { + x: float; + y: float; + z: float; + w: float; +} + +Matrix :: struct { + m0: float; + m4: float; + m8: float; + m12: float; + m1: float; + m5: float; + m9: float; + m13: float; + m2: float; + m6: float; + m10: float; + m14: float; + m3: float; + m7: float; + m11: float; + m15: float; +} + +Color :: struct { + r: uchar; + g: uchar; + b: uchar; + a: uchar; +} + +Rectangle :: struct { + x: float; + y: float; + width: float; + height: float; +} + +Image :: struct { + data: *void; + width: int; + height: int; + mipmaps: int; + format: int; +} + +Texture :: struct { + id: uint; + width: int; + height: int; + mipmaps: int; + format: int; +} + +RenderTexture :: struct { + id: uint; + texture: Texture; + depth: Texture; +} + +NPatchInfo :: struct { + source: Rectangle; + left: int; + top: int; + right: int; + bottom: int; + layout: int; +} + +GlyphInfo :: struct { + value: int; + offsetX: int; + offsetY: int; + advanceX: int; + image: Image; +} + +Font :: struct { + baseSize: int; + glyphCount: int; + glyphPadding: int; + texture: Texture2D; + recs: *Rectangle; + glyphs: *GlyphInfo; +} + +Camera3D :: struct { + position: Vector3; + target: Vector3; + up: Vector3; + fovy: float; + projection: int; +} + +Camera2D :: struct { + offset: Vector2; + target: Vector2; + rotation: float; + zoom: float; +} + +Mesh :: struct { + vertexCount: int; + triangleCount: int; + vertices: *float; + texcoords: *float; + texcoords2: *float; + normals: *float; + tangents: *float; + colors: *uchar; + indices: *ushort; + animVertices: *float; + animNormals: *float; + boneIds: *uchar; + boneWeights: *float; + vaoId: uint; + vboId: *uint; +} + +Shader :: struct { + id: uint; + locs: *int; +} + +MaterialMap :: struct { + texture: Texture2D; + color: Color; + value: float; +} + +Material :: struct { + shader: Shader; + maps: *MaterialMap; + params: [4]float; +} + +Transform :: struct { + translation: Vector3; + rotation: Quaternion; + scale: Vector3; +} + +BoneInfo :: struct { + name: [32]char; + parent: int; +} + +Model :: struct { + transform: Matrix; + meshCount: int; + materialCount: int; + meshes: *Mesh; + materials: *Material; + meshMaterial: *int; + boneCount: int; + bones: *BoneInfo; + bindPose: *Transform; +} + +ModelAnimation :: struct { + boneCount: int; + frameCount: int; + bones: *BoneInfo; + framePoses: **Transform; + name: [32]char; +} + +Ray :: struct { + position: Vector3; + direction: Vector3; +} + +RayCollision :: struct { + hit: bool; + distance: float; + point: Vector3; + normal: Vector3; +} + +BoundingBox :: struct { + min: Vector3; + max: Vector3; +} + +Wave :: struct { + frameCount: uint; + sampleRate: uint; + sampleSize: uint; + channels: uint; + data: *void; +} + +AudioStream :: struct { + buffer: *rAudioBuffer; + processor: *rAudioProcessor; + sampleRate: uint; + sampleSize: uint; + channels: uint; +} + +Sound :: struct { + stream: AudioStream; + frameCount: uint; +} + +Music :: struct { + stream: AudioStream; + frameCount: uint; + looping: bool; + ctxType: int; + ctxData: *void; +} + +VrDeviceInfo :: struct { + hResolution: int; + vResolution: int; + hScreenSize: float; + vScreenSize: float; + vScreenCenter: float; + eyeToScreenDistance: float; + lensSeparationDistance: float; + interpupillaryDistance: float; + lensDistortionValues: [4]float; + chromaAbCorrection: [4]float; +} + +VrStereoConfig :: struct { + projection: [2]Matrix; + viewOffset: [2]Matrix; + leftLensCenter: [2]float; + rightLensCenter: [2]float; + leftScreenCenter: [2]float; + rightScreenCenter: [2]float; + scale: [2]float; + scaleIn: [2]float; +} + +FilePathList :: struct { + capacity: uint; + count: uint; + paths: **char; +} + +AutomationEvent :: struct { + frame: uint; + type: uint; + params: [4]int; +} + +AutomationEventList :: struct { + capacity: uint; + count: uint; + events: *AutomationEvent; +} + +Quaternion :: typedef Vector4; +Texture2D :: typedef Texture; +TextureCubemap :: typedef Texture; +RenderTexture2D :: typedef RenderTexture; +Camera :: typedef Camera3D; +rAudioBuffer :: typedef void; +rAudioProcessor :: typedef void; +//TraceLogCallback :: typedef proc(a: int, b: *char, c: va_list): void; +LoadFileDataCallback :: typedef proc(a: *char, b: *int): *uchar; +SaveFileDataCallback :: typedef proc(a: *char, b: *void, c: int): bool; +LoadFileTextCallback :: typedef proc(a: *char): *char; +SaveFileTextCallback :: typedef proc(a: *char, b: *char): bool; +AudioCallback :: typedef proc(a: *void, b: uint): void; + +InitWindow :: proc(width: int, height: int, title: *char); @api +CloseWindow :: proc(); @api +WindowShouldClose :: proc(): bool; @api +IsWindowReady :: proc(): bool; @api +IsWindowFullscreen :: proc(): bool; @api +IsWindowHidden :: proc(): bool; @api +IsWindowMinimized :: proc(): bool; @api +IsWindowMaximized :: proc(): bool; @api +IsWindowFocused :: proc(): bool; @api +IsWindowResized :: proc(): bool; @api +IsWindowState :: proc(flag: uint): bool; @api +SetWindowState :: proc(flags: uint); @api +ClearWindowState :: proc(flags: uint); @api +ToggleFullscreen :: proc(); @api +ToggleBorderlessWindowed :: proc(); @api +MaximizeWindow :: proc(); @api +MinimizeWindow :: proc(); @api +RestoreWindow :: proc(); @api +SetWindowIcon :: proc(image: Image); @api +SetWindowIcons :: proc(images: *Image, count: int); @api +SetWindowTitle :: proc(title: *char); @api +SetWindowPosition :: proc(x: int, y: int); @api +SetWindowMonitor :: proc(monitor: int); @api +SetWindowMinSize :: proc(width: int, height: int); @api +SetWindowMaxSize :: proc(width: int, height: int); @api +SetWindowSize :: proc(width: int, height: int); @api +SetWindowOpacity :: proc(opacity: float); @api +SetWindowFocused :: proc(); @api +GetWindowHandle :: proc(): *void; @api +GetScreenWidth :: proc(): int; @api +GetScreenHeight :: proc(): int; @api +GetRenderWidth :: proc(): int; @api +GetRenderHeight :: proc(): int; @api +GetMonitorCount :: proc(): int; @api +GetCurrentMonitor :: proc(): int; @api +GetMonitorPosition :: proc(monitor: int): Vector2; @api +GetMonitorWidth :: proc(monitor: int): int; @api +GetMonitorHeight :: proc(monitor: int): int; @api +GetMonitorPhysicalWidth :: proc(monitor: int): int; @api +GetMonitorPhysicalHeight :: proc(monitor: int): int; @api +GetMonitorRefreshRate :: proc(monitor: int): int; @api +GetWindowPosition :: proc(): Vector2; @api +GetWindowScaleDPI :: proc(): Vector2; @api +GetMonitorName :: proc(monitor: int): *char; @api +SetClipboardText :: proc(text: *char); @api +GetClipboardText :: proc(): *char; @api +EnableEventWaiting :: proc(); @api +DisableEventWaiting :: proc(); @api +ShowCursor :: proc(); @api +HideCursor :: proc(); @api +IsCursorHidden :: proc(): bool; @api +EnableCursor :: proc(); @api +DisableCursor :: proc(); @api +IsCursorOnScreen :: proc(): bool; @api +ClearBackground :: proc(color: Color); @api +BeginDrawing :: proc(); @api +EndDrawing :: proc(); @api +BeginMode2D :: proc(camera: Camera2D); @api +EndMode2D :: proc(); @api +BeginMode3D :: proc(camera: Camera3D); @api +EndMode3D :: proc(); @api +BeginTextureMode :: proc(target: RenderTexture2D); @api +EndTextureMode :: proc(); @api +BeginShaderMode :: proc(shader: Shader); @api +EndShaderMode :: proc(); @api +BeginBlendMode :: proc(mode: int); @api +EndBlendMode :: proc(); @api +BeginScissorMode :: proc(x: int, y: int, width: int, height: int); @api +EndScissorMode :: proc(); @api +BeginVrStereoMode :: proc(config: VrStereoConfig); @api +EndVrStereoMode :: proc(); @api +LoadVrStereoConfig :: proc(device: VrDeviceInfo): VrStereoConfig; @api +UnloadVrStereoConfig :: proc(config: VrStereoConfig); @api +LoadShader :: proc(vsFileName: *char, fsFileName: *char): Shader; @api +LoadShaderFromMemory :: proc(vsCode: *char, fsCode: *char): Shader; @api +IsShaderReady :: proc(shader: Shader): bool; @api +GetShaderLocation :: proc(shader: Shader, uniformName: *char): int; @api +GetShaderLocationAttrib :: proc(shader: Shader, attribName: *char): int; @api +SetShaderValue :: proc(shader: Shader, locIndex: int, value: *void, uniformType: int); @api +SetShaderValueV :: proc(shader: Shader, locIndex: int, value: *void, uniformType: int, count: int); @api +SetShaderValueMatrix :: proc(shader: Shader, locIndex: int, mat: Matrix); @api +SetShaderValueTexture :: proc(shader: Shader, locIndex: int, texture: Texture2D); @api +UnloadShader :: proc(shader: Shader); @api +GetMouseRay :: proc(mousePosition: Vector2, camera: Camera): Ray; @api +GetCameraMatrix :: proc(camera: Camera): Matrix; @api +GetCameraMatrix2D :: proc(camera: Camera2D): Matrix; @api +GetWorldToScreen :: proc(position: Vector3, camera: Camera): Vector2; @api +GetScreenToWorld2D :: proc(position: Vector2, camera: Camera2D): Vector2; @api +GetWorldToScreenEx :: proc(position: Vector3, camera: Camera, width: int, height: int): Vector2; @api +GetWorldToScreen2D :: proc(position: Vector2, camera: Camera2D): Vector2; @api +SetTargetFPS :: proc(fps: int); @api +GetFrameTime :: proc(): float; @api +GetTime :: proc(): double; @api +GetFPS :: proc(): int; @api +SwapScreenBuffer :: proc(); @api +PollInputEvents :: proc(); @api +WaitTime :: proc(seconds: double); @api +SetRandomSeed :: proc(seed: uint); @api +GetRandomValue :: proc(min: int, max: int): int; @api +LoadRandomSequence :: proc(count: uint, min: int, max: int): *int; @api +UnloadRandomSequence :: proc(sequence: *int); @api +TakeScreenshot :: proc(fileName: *char); @api +SetConfigFlags :: proc(flags: uint); @api +OpenURL :: proc(url: *char); @api +TraceLog :: proc(logLevel: int, text: *char, ...); @api +SetTraceLogLevel :: proc(logLevel: int); @api +MemAlloc :: proc(size: uint): *void; @api +MemRealloc :: proc(ptr: *void, size: uint): *void; @api +MemFree :: proc(ptr: *void); @api +//SetTraceLogCallback :: proc(callback: TraceLogCallback); @api +SetLoadFileDataCallback :: proc(callback: LoadFileDataCallback); @api +SetSaveFileDataCallback :: proc(callback: SaveFileDataCallback); @api +SetLoadFileTextCallback :: proc(callback: LoadFileTextCallback); @api +SetSaveFileTextCallback :: proc(callback: SaveFileTextCallback); @api +LoadFileData :: proc(fileName: *char, dataSize: *int): *uchar; @api +UnloadFileData :: proc(data: *uchar); @api +SaveFileData :: proc(fileName: *char, data: *void, dataSize: int): bool; @api +ExportDataAsCode :: proc(data: *uchar, dataSize: int, fileName: *char): bool; @api +LoadFileText :: proc(fileName: *char): *char; @api +UnloadFileText :: proc(text: *char); @api +SaveFileText :: proc(fileName: *char, text: *char): bool; @api +FileExists :: proc(fileName: *char): bool; @api +DirectoryExists :: proc(dirPath: *char): bool; @api +IsFileExtension :: proc(fileName: *char, ext: *char): bool; @api +GetFileLength :: proc(fileName: *char): int; @api +GetFileExtension :: proc(fileName: *char): *char; @api +GetFileName :: proc(filePath: *char): *char; @api +GetFileNameWithoutExt :: proc(filePath: *char): *char; @api +GetDirectoryPath :: proc(filePath: *char): *char; @api +GetPrevDirectoryPath :: proc(dirPath: *char): *char; @api +GetWorkingDirectory :: proc(): *char; @api +GetApplicationDirectory :: proc(): *char; @api +ChangeDirectory :: proc(dir: *char): bool; @api +IsPathFile :: proc(path: *char): bool; @api +LoadDirectoryFiles :: proc(dirPath: *char): FilePathList; @api +LoadDirectoryFilesEx :: proc(basePath: *char, filter: *char, scanSubdirs: bool): FilePathList; @api +UnloadDirectoryFiles :: proc(files: FilePathList); @api +IsFileDropped :: proc(): bool; @api +LoadDroppedFiles :: proc(): FilePathList; @api +UnloadDroppedFiles :: proc(files: FilePathList); @api +GetFileModTime :: proc(fileName: *char): long; @api +CompressData :: proc(data: *uchar, dataSize: int, compDataSize: *int): *uchar; @api +DecompressData :: proc(compData: *uchar, compDataSize: int, dataSize: *int): *uchar; @api +EncodeDataBase64 :: proc(data: *uchar, dataSize: int, outputSize: *int): *char; @api +DecodeDataBase64 :: proc(data: *uchar, outputSize: *int): *uchar; @api +LoadAutomationEventList :: proc(fileName: *char): AutomationEventList; @api +UnloadAutomationEventList :: proc(list: *AutomationEventList); @api +ExportAutomationEventList :: proc(list: AutomationEventList, fileName: *char): bool; @api +SetAutomationEventList :: proc(list: *AutomationEventList); @api +SetAutomationEventBaseFrame :: proc(frame: int); @api +StartAutomationEventRecording :: proc(); @api +StopAutomationEventRecording :: proc(); @api +PlayAutomationEvent :: proc(event: AutomationEvent); @api +IsKeyPressed :: proc(key: int): bool; @api +IsKeyPressedRepeat :: proc(key: int): bool; @api +IsKeyDown :: proc(key: int): bool; @api +IsKeyReleased :: proc(key: int): bool; @api +IsKeyUp :: proc(key: int): bool; @api +GetKeyPressed :: proc(): int; @api +GetCharPressed :: proc(): int; @api +SetExitKey :: proc(key: int); @api +IsGamepadAvailable :: proc(gamepad: int): bool; @api +GetGamepadName :: proc(gamepad: int): *char; @api +IsGamepadButtonPressed :: proc(gamepad: int, button: int): bool; @api +IsGamepadButtonDown :: proc(gamepad: int, button: int): bool; @api +IsGamepadButtonReleased :: proc(gamepad: int, button: int): bool; @api +IsGamepadButtonUp :: proc(gamepad: int, button: int): bool; @api +GetGamepadButtonPressed :: proc(): int; @api +GetGamepadAxisCount :: proc(gamepad: int): int; @api +GetGamepadAxisMovement :: proc(gamepad: int, axis: int): float; @api +SetGamepadMappings :: proc(mappings: *char): int; @api +IsMouseButtonPressed :: proc(button: int): bool; @api +IsMouseButtonDown :: proc(button: int): bool; @api +IsMouseButtonReleased :: proc(button: int): bool; @api +IsMouseButtonUp :: proc(button: int): bool; @api +GetMouseX :: proc(): int; @api +GetMouseY :: proc(): int; @api +GetMousePosition :: proc(): Vector2; @api +GetMouseDelta :: proc(): Vector2; @api +SetMousePosition :: proc(x: int, y: int); @api +SetMouseOffset :: proc(offsetX: int, offsetY: int); @api +SetMouseScale :: proc(scaleX: float, scaleY: float); @api +GetMouseWheelMove :: proc(): float; @api +GetMouseWheelMoveV :: proc(): Vector2; @api +SetMouseCursor :: proc(cursor: int); @api +GetTouchX :: proc(): int; @api +GetTouchY :: proc(): int; @api +GetTouchPosition :: proc(index: int): Vector2; @api +GetTouchPointId :: proc(index: int): int; @api +GetTouchPointCount :: proc(): int; @api +SetGesturesEnabled :: proc(flags: uint); @api +IsGestureDetected :: proc(gesture: uint): bool; @api +GetGestureDetected :: proc(): int; @api +GetGestureHoldDuration :: proc(): float; @api +GetGestureDragVector :: proc(): Vector2; @api +GetGestureDragAngle :: proc(): float; @api +GetGesturePinchVector :: proc(): Vector2; @api +GetGesturePinchAngle :: proc(): float; @api +UpdateCamera :: proc(camera: *Camera, mode: int); @api +UpdateCameraPro :: proc(camera: *Camera, movement: Vector3, rotation: Vector3, zoom: float); @api +SetShapesTexture :: proc(texture: Texture2D, source: Rectangle); @api +DrawPixel :: proc(posX: int, posY: int, color: Color); @api +DrawPixelV :: proc(position: Vector2, color: Color); @api +DrawLine :: proc(startPosX: int, startPosY: int, endPosX: int, endPosY: int, color: Color); @api +DrawLineV :: proc(startPos: Vector2, endPos: Vector2, color: Color); @api +DrawLineEx :: proc(startPos: Vector2, endPos: Vector2, thick: float, color: Color); @api +DrawLineStrip :: proc(points: *Vector2, pointCount: int, color: Color); @api +DrawLineBezier :: proc(startPos: Vector2, endPos: Vector2, thick: float, color: Color); @api +DrawCircle :: proc(centerX: int, centerY: int, radius: float, color: Color); @api +DrawCircleSector :: proc(center: Vector2, radius: float, startAngle: float, endAngle: float, segments: int, color: Color); @api +DrawCircleSectorLines :: proc(center: Vector2, radius: float, startAngle: float, endAngle: float, segments: int, color: Color); @api +DrawCircleGradient :: proc(centerX: int, centerY: int, radius: float, color1: Color, color2: Color); @api +DrawCircleV :: proc(center: Vector2, radius: float, color: Color); @api +DrawCircleLines :: proc(centerX: int, centerY: int, radius: float, color: Color); @api +DrawCircleLinesV :: proc(center: Vector2, radius: float, color: Color); @api +DrawEllipse :: proc(centerX: int, centerY: int, radiusH: float, radiusV: float, color: Color); @api +DrawEllipseLines :: proc(centerX: int, centerY: int, radiusH: float, radiusV: float, color: Color); @api +DrawRing :: proc(center: Vector2, innerRadius: float, outerRadius: float, startAngle: float, endAngle: float, segments: int, color: Color); @api +DrawRingLines :: proc(center: Vector2, innerRadius: float, outerRadius: float, startAngle: float, endAngle: float, segments: int, color: Color); @api +DrawRectangle :: proc(posX: int, posY: int, width: int, height: int, color: Color); @api +DrawRectangleV :: proc(position: Vector2, size: Vector2, color: Color); @api +DrawRectangleRec :: proc(rec: Rectangle, color: Color); @api +DrawRectanglePro :: proc(rec: Rectangle, origin: Vector2, rotation: float, color: Color); @api +DrawRectangleGradientV :: proc(posX: int, posY: int, width: int, height: int, color1: Color, color2: Color); @api +DrawRectangleGradientH :: proc(posX: int, posY: int, width: int, height: int, color1: Color, color2: Color); @api +DrawRectangleGradientEx :: proc(rec: Rectangle, col1: Color, col2: Color, col3: Color, col4: Color); @api +DrawRectangleLines :: proc(posX: int, posY: int, width: int, height: int, color: Color); @api +DrawRectangleLinesEx :: proc(rec: Rectangle, lineThick: float, color: Color); @api +DrawRectangleRounded :: proc(rec: Rectangle, roundness: float, segments: int, color: Color); @api +DrawRectangleRoundedLines :: proc(rec: Rectangle, roundness: float, segments: int, lineThick: float, color: Color); @api +DrawTriangle :: proc(v1: Vector2, v2: Vector2, v3: Vector2, color: Color); @api +DrawTriangleLines :: proc(v1: Vector2, v2: Vector2, v3: Vector2, color: Color); @api +DrawTriangleFan :: proc(points: *Vector2, pointCount: int, color: Color); @api +DrawTriangleStrip :: proc(points: *Vector2, pointCount: int, color: Color); @api +DrawPoly :: proc(center: Vector2, sides: int, radius: float, rotation: float, color: Color); @api +DrawPolyLines :: proc(center: Vector2, sides: int, radius: float, rotation: float, color: Color); @api +DrawPolyLinesEx :: proc(center: Vector2, sides: int, radius: float, rotation: float, lineThick: float, color: Color); @api +DrawSplineLinear :: proc(points: *Vector2, pointCount: int, thick: float, color: Color); @api +DrawSplineBasis :: proc(points: *Vector2, pointCount: int, thick: float, color: Color); @api +DrawSplineCatmullRom :: proc(points: *Vector2, pointCount: int, thick: float, color: Color); @api +DrawSplineBezierQuadratic :: proc(points: *Vector2, pointCount: int, thick: float, color: Color); @api +DrawSplineBezierCubic :: proc(points: *Vector2, pointCount: int, thick: float, color: Color); @api +DrawSplineSegmentLinear :: proc(p1: Vector2, p2: Vector2, thick: float, color: Color); @api +DrawSplineSegmentBasis :: proc(p1: Vector2, p2: Vector2, p3: Vector2, p4: Vector2, thick: float, color: Color); @api +DrawSplineSegmentCatmullRom :: proc(p1: Vector2, p2: Vector2, p3: Vector2, p4: Vector2, thick: float, color: Color); @api +DrawSplineSegmentBezierQuadratic :: proc(p1: Vector2, c2: Vector2, p3: Vector2, thick: float, color: Color); @api +DrawSplineSegmentBezierCubic :: proc(p1: Vector2, c2: Vector2, c3: Vector2, p4: Vector2, thick: float, color: Color); @api +GetSplinePointLinear :: proc(startPos: Vector2, endPos: Vector2, t: float): Vector2; @api +GetSplinePointBasis :: proc(p1: Vector2, p2: Vector2, p3: Vector2, p4: Vector2, t: float): Vector2; @api +GetSplinePointCatmullRom :: proc(p1: Vector2, p2: Vector2, p3: Vector2, p4: Vector2, t: float): Vector2; @api +GetSplinePointBezierQuad :: proc(p1: Vector2, c2: Vector2, p3: Vector2, t: float): Vector2; @api +GetSplinePointBezierCubic :: proc(p1: Vector2, c2: Vector2, c3: Vector2, p4: Vector2, t: float): Vector2; @api +CheckCollisionRecs :: proc(rec1: Rectangle, rec2: Rectangle): bool; @api +CheckCollisionCircles :: proc(center1: Vector2, radius1: float, center2: Vector2, radius2: float): bool; @api +CheckCollisionCircleRec :: proc(center: Vector2, radius: float, rec: Rectangle): bool; @api +CheckCollisionPointRec :: proc(point: Vector2, rec: Rectangle): bool; @api +CheckCollisionPointCircle :: proc(point: Vector2, center: Vector2, radius: float): bool; @api +CheckCollisionPointTriangle :: proc(point: Vector2, p1: Vector2, p2: Vector2, p3: Vector2): bool; @api +CheckCollisionPointPoly :: proc(point: Vector2, points: *Vector2, pointCount: int): bool; @api +CheckCollisionLines :: proc(startPos1: Vector2, endPos1: Vector2, startPos2: Vector2, endPos2: Vector2, collisionPoint: *Vector2): bool; @api +CheckCollisionPointLine :: proc(point: Vector2, p1: Vector2, p2: Vector2, threshold: int): bool; @api +GetCollisionRec :: proc(rec1: Rectangle, rec2: Rectangle): Rectangle; @api +LoadImage :: proc(fileName: *char): Image; @api +LoadImageRaw :: proc(fileName: *char, width: int, height: int, format: int, headerSize: int): Image; @api +LoadImageSvg :: proc(fileNameOrString: *char, width: int, height: int): Image; @api +LoadImageAnim :: proc(fileName: *char, frames: *int): Image; @api +LoadImageFromMemory :: proc(fileType: *char, fileData: *uchar, dataSize: int): Image; @api +LoadImageFromTexture :: proc(texture: Texture2D): Image; @api +LoadImageFromScreen :: proc(): Image; @api +IsImageReady :: proc(image: Image): bool; @api +UnloadImage :: proc(image: Image); @api +ExportImage :: proc(image: Image, fileName: *char): bool; @api +ExportImageToMemory :: proc(image: Image, fileType: *char, fileSize: *int): *uchar; @api +ExportImageAsCode :: proc(image: Image, fileName: *char): bool; @api +GenImageColor :: proc(width: int, height: int, color: Color): Image; @api +GenImageGradientLinear :: proc(width: int, height: int, direction: int, start: Color, end: Color): Image; @api +GenImageGradientRadial :: proc(width: int, height: int, density: float, inner: Color, outer: Color): Image; @api +GenImageGradientSquare :: proc(width: int, height: int, density: float, inner: Color, outer: Color): Image; @api +GenImageChecked :: proc(width: int, height: int, checksX: int, checksY: int, col1: Color, col2: Color): Image; @api +GenImageWhiteNoise :: proc(width: int, height: int, factor: float): Image; @api +GenImagePerlinNoise :: proc(width: int, height: int, offsetX: int, offsetY: int, scale: float): Image; @api +GenImageCellular :: proc(width: int, height: int, tileSize: int): Image; @api +GenImageText :: proc(width: int, height: int, text: *char): Image; @api +ImageCopy :: proc(image: Image): Image; @api +ImageFromImage :: proc(image: Image, rec: Rectangle): Image; @api +ImageText :: proc(text: *char, fontSize: int, color: Color): Image; @api +ImageTextEx :: proc(font: Font, text: *char, fontSize: float, spacing: float, tint: Color): Image; @api +ImageFormat :: proc(image: *Image, newFormat: int); @api +ImageToPOT :: proc(image: *Image, fill: Color); @api +ImageCrop :: proc(image: *Image, crop: Rectangle); @api +ImageAlphaCrop :: proc(image: *Image, threshold: float); @api +ImageAlphaClear :: proc(image: *Image, color: Color, threshold: float); @api +ImageAlphaMask :: proc(image: *Image, alphaMask: Image); @api +ImageAlphaPremultiply :: proc(image: *Image); @api +ImageBlurGaussian :: proc(image: *Image, blurSize: int); @api +ImageResize :: proc(image: *Image, newWidth: int, newHeight: int); @api +ImageResizeNN :: proc(image: *Image, newWidth: int, newHeight: int); @api +ImageResizeCanvas :: proc(image: *Image, newWidth: int, newHeight: int, offsetX: int, offsetY: int, fill: Color); @api +ImageMipmaps :: proc(image: *Image); @api +ImageDither :: proc(image: *Image, rBpp: int, gBpp: int, bBpp: int, aBpp: int); @api +ImageFlipVertical :: proc(image: *Image); @api +ImageFlipHorizontal :: proc(image: *Image); @api +ImageRotate :: proc(image: *Image, degrees: int); @api +ImageRotateCW :: proc(image: *Image); @api +ImageRotateCCW :: proc(image: *Image); @api +ImageColorTint :: proc(image: *Image, color: Color); @api +ImageColorInvert :: proc(image: *Image); @api +ImageColorGrayscale :: proc(image: *Image); @api +ImageColorContrast :: proc(image: *Image, contrast: float); @api +ImageColorBrightness :: proc(image: *Image, brightness: int); @api +ImageColorReplace :: proc(image: *Image, color: Color, replace: Color); @api +LoadImageColors :: proc(image: Image): *Color; @api +LoadImagePalette :: proc(image: Image, maxPaletteSize: int, colorCount: *int): *Color; @api +UnloadImageColors :: proc(colors: *Color); @api +UnloadImagePalette :: proc(colors: *Color); @api +GetImageAlphaBorder :: proc(image: Image, threshold: float): Rectangle; @api +GetImageColor :: proc(image: Image, x: int, y: int): Color; @api +ImageClearBackground :: proc(dst: *Image, color: Color); @api +ImageDrawPixel :: proc(dst: *Image, posX: int, posY: int, color: Color); @api +ImageDrawPixelV :: proc(dst: *Image, position: Vector2, color: Color); @api +ImageDrawLine :: proc(dst: *Image, startPosX: int, startPosY: int, endPosX: int, endPosY: int, color: Color); @api +ImageDrawLineV :: proc(dst: *Image, start: Vector2, end: Vector2, color: Color); @api +ImageDrawCircle :: proc(dst: *Image, centerX: int, centerY: int, radius: int, color: Color); @api +ImageDrawCircleV :: proc(dst: *Image, center: Vector2, radius: int, color: Color); @api +ImageDrawCircleLines :: proc(dst: *Image, centerX: int, centerY: int, radius: int, color: Color); @api +ImageDrawCircleLinesV :: proc(dst: *Image, center: Vector2, radius: int, color: Color); @api +ImageDrawRectangle :: proc(dst: *Image, posX: int, posY: int, width: int, height: int, color: Color); @api +ImageDrawRectangleV :: proc(dst: *Image, position: Vector2, size: Vector2, color: Color); @api +ImageDrawRectangleRec :: proc(dst: *Image, rec: Rectangle, color: Color); @api +ImageDrawRectangleLines :: proc(dst: *Image, rec: Rectangle, thick: int, color: Color); @api +ImageDraw :: proc(dst: *Image, src: Image, srcRec: Rectangle, dstRec: Rectangle, tint: Color); @api +ImageDrawText :: proc(dst: *Image, text: *char, posX: int, posY: int, fontSize: int, color: Color); @api +ImageDrawTextEx :: proc(dst: *Image, font: Font, text: *char, position: Vector2, fontSize: float, spacing: float, tint: Color); @api +LoadTexture :: proc(fileName: *char): Texture2D; @api +LoadTextureFromImage :: proc(image: Image): Texture2D; @api +LoadTextureCubemap :: proc(image: Image, layout: int): TextureCubemap; @api +LoadRenderTexture :: proc(width: int, height: int): RenderTexture2D; @api +IsTextureReady :: proc(texture: Texture2D): bool; @api +UnloadTexture :: proc(texture: Texture2D); @api +IsRenderTextureReady :: proc(target: RenderTexture2D): bool; @api +UnloadRenderTexture :: proc(target: RenderTexture2D); @api +UpdateTexture :: proc(texture: Texture2D, pixels: *void); @api +UpdateTextureRec :: proc(texture: Texture2D, rec: Rectangle, pixels: *void); @api +GenTextureMipmaps :: proc(texture: *Texture2D); @api +SetTextureFilter :: proc(texture: Texture2D, filter: int); @api +SetTextureWrap :: proc(texture: Texture2D, wrap: int); @api +DrawTexture :: proc(texture: Texture2D, posX: int, posY: int, tint: Color); @api +DrawTextureV :: proc(texture: Texture2D, position: Vector2, tint: Color); @api +DrawTextureEx :: proc(texture: Texture2D, position: Vector2, rotation: float, scale: float, tint: Color); @api +DrawTextureRec :: proc(texture: Texture2D, source: Rectangle, position: Vector2, tint: Color); @api +DrawTexturePro :: proc(texture: Texture2D, source: Rectangle, dest: Rectangle, origin: Vector2, rotation: float, tint: Color); @api +DrawTextureNPatch :: proc(texture: Texture2D, nPatchInfo: NPatchInfo, dest: Rectangle, origin: Vector2, rotation: float, tint: Color); @api +Fade :: proc(color: Color, alpha: float): Color; @api +ColorToInt :: proc(color: Color): int; @api +ColorNormalize :: proc(color: Color): Vector4; @api +ColorFromNormalized :: proc(normalized: Vector4): Color; @api +ColorToHSV :: proc(color: Color): Vector3; @api +ColorFromHSV :: proc(hue: float, saturation: float, value: float): Color; @api +ColorTint :: proc(color: Color, tint: Color): Color; @api +ColorBrightness :: proc(color: Color, factor: float): Color; @api +ColorContrast :: proc(color: Color, contrast: float): Color; @api +ColorAlpha :: proc(color: Color, alpha: float): Color; @api +ColorAlphaBlend :: proc(dst: Color, src: Color, tint: Color): Color; @api +GetColor :: proc(hexValue: uint): Color; @api +GetPixelColor :: proc(srcPtr: *void, format: int): Color; @api +SetPixelColor :: proc(dstPtr: *void, color: Color, format: int); @api +GetPixelDataSize :: proc(width: int, height: int, format: int): int; @api +GetFontDefault :: proc(): Font; @api +LoadFont :: proc(fileName: *char): Font; @api +LoadFontEx :: proc(fileName: *char, fontSize: int, codepoints: *int, codepointCount: int): Font; @api +LoadFontFromImage :: proc(image: Image, key: Color, firstChar: int): Font; @api +LoadFontFromMemory :: proc(fileType: *char, fileData: *uchar, dataSize: int, fontSize: int, codepoints: *int, codepointCount: int): Font; @api +IsFontReady :: proc(font: Font): bool; @api +LoadFontData :: proc(fileData: *uchar, dataSize: int, fontSize: int, codepoints: *int, codepointCount: int, type: int): *GlyphInfo; @api +GenImageFontAtlas :: proc(glyphs: *GlyphInfo, glyphRecs: **Rectangle, glyphCount: int, fontSize: int, padding: int, packMethod: int): Image; @api +UnloadFontData :: proc(glyphs: *GlyphInfo, glyphCount: int); @api +UnloadFont :: proc(font: Font); @api +ExportFontAsCode :: proc(font: Font, fileName: *char): bool; @api +DrawFPS :: proc(posX: int, posY: int); @api +DrawText :: proc(text: *char, posX: int, posY: int, fontSize: int, color: Color); @api +DrawTextEx :: proc(font: Font, text: *char, position: Vector2, fontSize: float, spacing: float, tint: Color); @api +DrawTextPro :: proc(font: Font, text: *char, position: Vector2, origin: Vector2, rotation: float, fontSize: float, spacing: float, tint: Color); @api +DrawTextCodepoint :: proc(font: Font, codepoint: int, position: Vector2, fontSize: float, tint: Color); @api +DrawTextCodepoints :: proc(font: Font, codepoints: *int, codepointCount: int, position: Vector2, fontSize: float, spacing: float, tint: Color); @api +SetTextLineSpacing :: proc(spacing: int); @api +MeasureText :: proc(text: *char, fontSize: int): int; @api +MeasureTextEx :: proc(font: Font, text: *char, fontSize: float, spacing: float): Vector2; @api +GetGlyphIndex :: proc(font: Font, codepoint: int): int; @api +GetGlyphInfo :: proc(font: Font, codepoint: int): GlyphInfo; @api +GetGlyphAtlasRec :: proc(font: Font, codepoint: int): Rectangle; @api +LoadUTF8 :: proc(codepoints: *int, length: int): *char; @api +UnloadUTF8 :: proc(text: *char); @api +LoadCodepoints :: proc(text: *char, count: *int): *int; @api +UnloadCodepoints :: proc(codepoints: *int); @api +GetCodepointCount :: proc(text: *char): int; @api +GetCodepoint :: proc(text: *char, codepointSize: *int): int; @api +GetCodepointNext :: proc(text: *char, codepointSize: *int): int; @api +GetCodepointPrevious :: proc(text: *char, codepointSize: *int): int; @api +CodepointToUTF8 :: proc(codepoint: int, utf8Size: *int): *char; @api +TextCopy :: proc(dst: *char, src: *char): int; @api +TextIsEqual :: proc(text1: *char, text2: *char): bool; @api +TextLength :: proc(text: *char): uint; @api +TextFormat :: proc(text: *char, ...): *char; @api +TextSubtext :: proc(text: *char, position: int, length: int): *char; @api +TextReplace :: proc(text: *char, replace: *char, by: *char): *char; @api +TextInsert :: proc(text: *char, insert: *char, position: int): *char; @api +TextJoin :: proc(textList: **char, count: int, delimiter: *char): *char; @api +TextSplit :: proc(text: *char, delimiter: char, count: *int): **char; @api +TextAppend :: proc(text: *char, append: *char, position: *int); @api +TextFindIndex :: proc(text: *char, find: *char): int; @api +TextToUpper :: proc(text: *char): *char; @api +TextToLower :: proc(text: *char): *char; @api +TextToPascal :: proc(text: *char): *char; @api +TextToInteger :: proc(text: *char): int; @api +DrawLine3D :: proc(startPos: Vector3, endPos: Vector3, color: Color); @api +DrawPoint3D :: proc(position: Vector3, color: Color); @api +DrawCircle3D :: proc(center: Vector3, radius: float, rotationAxis: Vector3, rotationAngle: float, color: Color); @api +DrawTriangle3D :: proc(v1: Vector3, v2: Vector3, v3: Vector3, color: Color); @api +DrawTriangleStrip3D :: proc(points: *Vector3, pointCount: int, color: Color); @api +DrawCube :: proc(position: Vector3, width: float, height: float, length: float, color: Color); @api +DrawCubeV :: proc(position: Vector3, size: Vector3, color: Color); @api +DrawCubeWires :: proc(position: Vector3, width: float, height: float, length: float, color: Color); @api +DrawCubeWiresV :: proc(position: Vector3, size: Vector3, color: Color); @api +DrawSphere :: proc(centerPos: Vector3, radius: float, color: Color); @api +DrawSphereEx :: proc(centerPos: Vector3, radius: float, rings: int, slices: int, color: Color); @api +DrawSphereWires :: proc(centerPos: Vector3, radius: float, rings: int, slices: int, color: Color); @api +DrawCylinder :: proc(position: Vector3, radiusTop: float, radiusBottom: float, height: float, slices: int, color: Color); @api +DrawCylinderEx :: proc(startPos: Vector3, endPos: Vector3, startRadius: float, endRadius: float, sides: int, color: Color); @api +DrawCylinderWires :: proc(position: Vector3, radiusTop: float, radiusBottom: float, height: float, slices: int, color: Color); @api +DrawCylinderWiresEx :: proc(startPos: Vector3, endPos: Vector3, startRadius: float, endRadius: float, sides: int, color: Color); @api +DrawCapsule :: proc(startPos: Vector3, endPos: Vector3, radius: float, slices: int, rings: int, color: Color); @api +DrawCapsuleWires :: proc(startPos: Vector3, endPos: Vector3, radius: float, slices: int, rings: int, color: Color); @api +DrawPlane :: proc(centerPos: Vector3, size: Vector2, color: Color); @api +DrawRay :: proc(ray: Ray, color: Color); @api +DrawGrid :: proc(slices: int, spacing: float); @api +LoadModel :: proc(fileName: *char): Model; @api +LoadModelFromMesh :: proc(mesh: Mesh): Model; @api +IsModelReady :: proc(model: Model): bool; @api +UnloadModel :: proc(model: Model); @api +GetModelBoundingBox :: proc(model: Model): BoundingBox; @api +DrawModel :: proc(model: Model, position: Vector3, scale: float, tint: Color); @api +DrawModelEx :: proc(model: Model, position: Vector3, rotationAxis: Vector3, rotationAngle: float, scale: Vector3, tint: Color); @api +DrawModelWires :: proc(model: Model, position: Vector3, scale: float, tint: Color); @api +DrawModelWiresEx :: proc(model: Model, position: Vector3, rotationAxis: Vector3, rotationAngle: float, scale: Vector3, tint: Color); @api +DrawBoundingBox :: proc(box: BoundingBox, color: Color); @api +DrawBillboard :: proc(camera: Camera, texture: Texture2D, position: Vector3, size: float, tint: Color); @api +DrawBillboardRec :: proc(camera: Camera, texture: Texture2D, source: Rectangle, position: Vector3, size: Vector2, tint: Color); @api +DrawBillboardPro :: proc(camera: Camera, texture: Texture2D, source: Rectangle, position: Vector3, up: Vector3, size: Vector2, origin: Vector2, rotation: float, tint: Color); @api +UploadMesh :: proc(mesh: *Mesh, dynamic: bool); @api +UpdateMeshBuffer :: proc(mesh: Mesh, index: int, data: *void, dataSize: int, offset: int); @api +UnloadMesh :: proc(mesh: Mesh); @api +DrawMesh :: proc(mesh: Mesh, material: Material, transform: Matrix); @api +DrawMeshInstanced :: proc(mesh: Mesh, material: Material, transforms: *Matrix, instances: int); @api +ExportMesh :: proc(mesh: Mesh, fileName: *char): bool; @api +GetMeshBoundingBox :: proc(mesh: Mesh): BoundingBox; @api +GenMeshTangents :: proc(mesh: *Mesh); @api +GenMeshPoly :: proc(sides: int, radius: float): Mesh; @api +GenMeshPlane :: proc(width: float, length: float, resX: int, resZ: int): Mesh; @api +GenMeshCube :: proc(width: float, height: float, length: float): Mesh; @api +GenMeshSphere :: proc(radius: float, rings: int, slices: int): Mesh; @api +GenMeshHemiSphere :: proc(radius: float, rings: int, slices: int): Mesh; @api +GenMeshCylinder :: proc(radius: float, height: float, slices: int): Mesh; @api +GenMeshCone :: proc(radius: float, height: float, slices: int): Mesh; @api +GenMeshTorus :: proc(radius: float, size: float, radSeg: int, sides: int): Mesh; @api +GenMeshKnot :: proc(radius: float, size: float, radSeg: int, sides: int): Mesh; @api +GenMeshHeightmap :: proc(heightmap: Image, size: Vector3): Mesh; @api +GenMeshCubicmap :: proc(cubicmap: Image, cubeSize: Vector3): Mesh; @api +LoadMaterials :: proc(fileName: *char, materialCount: *int): *Material; @api +LoadMaterialDefault :: proc(): Material; @api +IsMaterialReady :: proc(material: Material): bool; @api +UnloadMaterial :: proc(material: Material); @api +SetMaterialTexture :: proc(material: *Material, mapType: int, texture: Texture2D); @api +SetModelMeshMaterial :: proc(model: *Model, meshId: int, materialId: int); @api +LoadModelAnimations :: proc(fileName: *char, animCount: *int): *ModelAnimation; @api +UpdateModelAnimation :: proc(model: Model, anim: ModelAnimation, frame: int); @api +UnloadModelAnimation :: proc(anim: ModelAnimation); @api +UnloadModelAnimations :: proc(animations: *ModelAnimation, animCount: int); @api +IsModelAnimationValid :: proc(model: Model, anim: ModelAnimation): bool; @api +CheckCollisionSpheres :: proc(center1: Vector3, radius1: float, center2: Vector3, radius2: float): bool; @api +CheckCollisionBoxes :: proc(box1: BoundingBox, box2: BoundingBox): bool; @api +CheckCollisionBoxSphere :: proc(box: BoundingBox, center: Vector3, radius: float): bool; @api +GetRayCollisionSphere :: proc(ray: Ray, center: Vector3, radius: float): RayCollision; @api +GetRayCollisionBox :: proc(ray: Ray, box: BoundingBox): RayCollision; @api +GetRayCollisionMesh :: proc(ray: Ray, mesh: Mesh, transform: Matrix): RayCollision; @api +GetRayCollisionTriangle :: proc(ray: Ray, p1: Vector3, p2: Vector3, p3: Vector3): RayCollision; @api +GetRayCollisionQuad :: proc(ray: Ray, p1: Vector3, p2: Vector3, p3: Vector3, p4: Vector3): RayCollision; @api +InitAudioDevice :: proc(); @api +CloseAudioDevice :: proc(); @api +IsAudioDeviceReady :: proc(): bool; @api +SetMasterVolume :: proc(volume: float); @api +GetMasterVolume :: proc(): float; @api +LoadWave :: proc(fileName: *char): Wave; @api +LoadWaveFromMemory :: proc(fileType: *char, fileData: *uchar, dataSize: int): Wave; @api +IsWaveReady :: proc(wave: Wave): bool; @api +LoadSound :: proc(fileName: *char): Sound; @api +LoadSoundFromWave :: proc(wave: Wave): Sound; @api +LoadSoundAlias :: proc(source: Sound): Sound; @api +IsSoundReady :: proc(sound: Sound): bool; @api +UpdateSound :: proc(sound: Sound, data: *void, sampleCount: int); @api +UnloadWave :: proc(wave: Wave); @api +UnloadSound :: proc(sound: Sound); @api +UnloadSoundAlias :: proc(alias: Sound); @api +ExportWave :: proc(wave: Wave, fileName: *char): bool; @api +ExportWaveAsCode :: proc(wave: Wave, fileName: *char): bool; @api +PlaySound :: proc(sound: Sound); @api +StopSound :: proc(sound: Sound); @api +PauseSound :: proc(sound: Sound); @api +ResumeSound :: proc(sound: Sound); @api +IsSoundPlaying :: proc(sound: Sound): bool; @api +SetSoundVolume :: proc(sound: Sound, volume: float); @api +SetSoundPitch :: proc(sound: Sound, pitch: float); @api +SetSoundPan :: proc(sound: Sound, pan: float); @api +WaveCopy :: proc(wave: Wave): Wave; @api +WaveCrop :: proc(wave: *Wave, initSample: int, finalSample: int); @api +WaveFormat :: proc(wave: *Wave, sampleRate: int, sampleSize: int, channels: int); @api +LoadWaveSamples :: proc(wave: Wave): *float; @api +UnloadWaveSamples :: proc(samples: *float); @api +LoadMusicStream :: proc(fileName: *char): Music; @api +LoadMusicStreamFromMemory :: proc(fileType: *char, data: *uchar, dataSize: int): Music; @api +IsMusicReady :: proc(music: Music): bool; @api +UnloadMusicStream :: proc(music: Music); @api +PlayMusicStream :: proc(music: Music); @api +IsMusicStreamPlaying :: proc(music: Music): bool; @api +UpdateMusicStream :: proc(music: Music); @api +StopMusicStream :: proc(music: Music); @api +PauseMusicStream :: proc(music: Music); @api +ResumeMusicStream :: proc(music: Music); @api +SeekMusicStream :: proc(music: Music, position: float); @api +SetMusicVolume :: proc(music: Music, volume: float); @api +SetMusicPitch :: proc(music: Music, pitch: float); @api +SetMusicPan :: proc(music: Music, pan: float); @api +GetMusicTimeLength :: proc(music: Music): float; @api +GetMusicTimePlayed :: proc(music: Music): float; @api +LoadAudioStream :: proc(sampleRate: uint, sampleSize: uint, channels: uint): AudioStream; @api +IsAudioStreamReady :: proc(stream: AudioStream): bool; @api +UnloadAudioStream :: proc(stream: AudioStream); @api +UpdateAudioStream :: proc(stream: AudioStream, data: *void, frameCount: int); @api +IsAudioStreamProcessed :: proc(stream: AudioStream): bool; @api +PlayAudioStream :: proc(stream: AudioStream); @api +PauseAudioStream :: proc(stream: AudioStream); @api +ResumeAudioStream :: proc(stream: AudioStream); @api +IsAudioStreamPlaying :: proc(stream: AudioStream): bool; @api +StopAudioStream :: proc(stream: AudioStream); @api +SetAudioStreamVolume :: proc(stream: AudioStream, volume: float); @api +SetAudioStreamPitch :: proc(stream: AudioStream, pitch: float); @api +SetAudioStreamPan :: proc(stream: AudioStream, pan: float); @api +SetAudioStreamBufferSizeDefault :: proc(size: int); @api +SetAudioStreamCallback :: proc(stream: AudioStream, callback: AudioCallback); @api +AttachAudioStreamProcessor :: proc(stream: AudioStream, processor: AudioCallback); @api +DetachAudioStreamProcessor :: proc(stream: AudioStream, processor: AudioCallback); @api +AttachAudioMixedProcessor :: proc(processor: AudioCallback); @api +DetachAudioMixedProcessor :: proc(processor: AudioCallback); @api + + +// Some Basic Colors +// NOTE: Custom raylib color palette for amazing visuals on WHITE background +LIGHTGRAY := :Color{ 200, 200, 200, 255 }; // Light Gray +GRAY := :Color{ 130, 130, 130, 255 }; // Gray +DARKGRAY := :Color{ 80, 80, 80, 255 }; // Dark Gray +YELLOW := :Color{ 253, 249, 0, 255 }; // Yellow +GOLD := :Color{ 255, 203, 0, 255 }; // Gold +ORANGE := :Color{ 255, 161, 0, 255 }; // Orange +PINK := :Color{ 255, 109, 194, 255 }; // Pink +RED := :Color{ 230, 41, 55, 255 }; // Red +MAROON := :Color{ 190, 33, 55, 255 }; // Maroon +GREEN := :Color{ 0, 228, 48, 255 }; // Green +LIME := :Color{ 0, 158, 47, 255 }; // Lime +DARKGREEN := :Color{ 0, 117, 44, 255 }; // Dark Green +SKYBLUE := :Color{ 102, 191, 255, 255 }; // Sky Blue +BLUE := :Color{ 0, 121, 241, 255 }; // Blue +DARKBLUE := :Color{ 0, 82, 172, 255 }; // Dark Blue +PURPLE := :Color{ 200, 122, 255, 255 }; // Purple +VIOLET := :Color{ 135, 60, 190, 255 }; // Violet +DARKPURPLE := :Color{ 112, 31, 126, 255 }; // Dark Purple +BEIGE := :Color{ 211, 176, 131, 255 }; // Beige +BROWN := :Color{ 127, 106, 79, 255 }; // Brown +DARKBROWN := :Color{ 76, 63, 47, 255 }; // Dark Brown +WHITE := :Color{ 255, 255, 255, 255 }; // White +BLACK := :Color{ 0, 0, 0, 255 }; // Black +BLANK := :Color{ 0, 0, 0, 0 }; // Blank (Transparent) +MAGENTA := :Color{ 255, 0, 255, 255 }; // Magenta +RAYWHITE := :Color{ 245, 245, 245, 255 }; // My own White (raylib logo) + + +// Keyboard keys (US keyboard layout) +// NOTE: Use GetKeyPressed() to allow redefining +// required keys for alternative layouts +KEY_NULL :: 0; // Key: NULL, used for no key pressed +// Alphanumeric keys +KEY_APOSTROPHE :: 39; // Key: ' +KEY_COMMA :: 44; // Key: , +KEY_MINUS :: 45; // Key: - +KEY_PERIOD :: 46; // Key: . +KEY_SLASH :: 47; // Key: / +KEY_ZERO :: 48; // Key: 0 +KEY_ONE :: 49; // Key: 1 +KEY_TWO :: 50; // Key: 2 +KEY_THREE :: 51; // Key: 3 +KEY_FOUR :: 52; // Key: 4 +KEY_FIVE :: 53; // Key: 5 +KEY_SIX :: 54; // Key: 6 +KEY_SEVEN :: 55; // Key: 7 +KEY_EIGHT :: 56; // Key: 8 +KEY_NINE :: 57; // Key: 9 +KEY_SEMICOLON :: 59; // Key: ; +KEY_EQUAL :: 61; // Key: = +KEY_A :: 65; // Key: A | a +KEY_B :: 66; // Key: B | b +KEY_C :: 67; // Key: C | c +KEY_D :: 68; // Key: D | d +KEY_E :: 69; // Key: E | e +KEY_F :: 70; // Key: F | f +KEY_G :: 71; // Key: G | g +KEY_H :: 72; // Key: H | h +KEY_I :: 73; // Key: I | i +KEY_J :: 74; // Key: J | j +KEY_K :: 75; // Key: K | k +KEY_L :: 76; // Key: L | l +KEY_M :: 77; // Key: M | m +KEY_N :: 78; // Key: N | n +KEY_O :: 79; // Key: O | o +KEY_P :: 80; // Key: P | p +KEY_Q :: 81; // Key: Q | q +KEY_R :: 82; // Key: R | r +KEY_S :: 83; // Key: S | s +KEY_T :: 84; // Key: T | t +KEY_U :: 85; // Key: U | u +KEY_V :: 86; // Key: V | v +KEY_W :: 87; // Key: W | w +KEY_X :: 88; // Key: X | x +KEY_Y :: 89; // Key: Y | y +KEY_Z :: 90; // Key: Z | z +KEY_LEFT_BRACKET :: 91; // Key: [ +KEY_BACKSLASH :: 92; // Key: '\' +KEY_RIGHT_BRACKET :: 93; // Key: ] +KEY_GRAVE :: 96; // Key: ` +// Function keys +KEY_SPACE :: 32; // Key: Space +KEY_ESCAPE :: 256; // Key: Esc +KEY_ENTER :: 257; // Key: Enter +KEY_TAB :: 258; // Key: Tab +KEY_BACKSPACE :: 259; // Key: Backspace +KEY_INSERT :: 260; // Key: Ins +KEY_DELETE :: 261; // Key: Del +KEY_RIGHT :: 262; // Key: Cursor right +KEY_LEFT :: 263; // Key: Cursor left +KEY_DOWN :: 264; // Key: Cursor down +KEY_UP :: 265; // Key: Cursor up +KEY_PAGE_UP :: 266; // Key: Page up +KEY_PAGE_DOWN :: 267; // Key: Page down +KEY_HOME :: 268; // Key: Home +KEY_END :: 269; // Key: End +KEY_CAPS_LOCK :: 280; // Key: Caps lock +KEY_SCROLL_LOCK :: 281; // Key: Scroll down +KEY_NUM_LOCK :: 282; // Key: Num lock +KEY_PRINT_SCREEN :: 283; // Key: Print screen +KEY_PAUSE :: 284; // Key: Pause +KEY_F1 :: 290; // Key: F1 +KEY_F2 :: 291; // Key: F2 +KEY_F3 :: 292; // Key: F3 +KEY_F4 :: 293; // Key: F4 +KEY_F5 :: 294; // Key: F5 +KEY_F6 :: 295; // Key: F6 +KEY_F7 :: 296; // Key: F7 +KEY_F8 :: 297; // Key: F8 +KEY_F9 :: 298; // Key: F9 +KEY_F10 :: 299; // Key: F10 +KEY_F11 :: 300; // Key: F11 +KEY_F12 :: 301; // Key: F12 +KEY_LEFT_SHIFT :: 340; // Key: Shift left +KEY_LEFT_CONTROL :: 341; // Key: Control left +KEY_LEFT_ALT :: 342; // Key: Alt left +KEY_LEFT_SUPER :: 343; // Key: Super left +KEY_RIGHT_SHIFT :: 344; // Key: Shift right +KEY_RIGHT_CONTROL :: 345; // Key: Control right +KEY_RIGHT_ALT :: 346; // Key: Alt right +KEY_RIGHT_SUPER :: 347; // Key: Super right +KEY_KB_MENU :: 348; // Key: KB menu +// Keypad keys +KEY_KP_0 :: 320; // Key: Keypad 0 +KEY_KP_1 :: 321; // Key: Keypad 1 +KEY_KP_2 :: 322; // Key: Keypad 2 +KEY_KP_3 :: 323; // Key: Keypad 3 +KEY_KP_4 :: 324; // Key: Keypad 4 +KEY_KP_5 :: 325; // Key: Keypad 5 +KEY_KP_6 :: 326; // Key: Keypad 6 +KEY_KP_7 :: 327; // Key: Keypad 7 +KEY_KP_8 :: 328; // Key: Keypad 8 +KEY_KP_9 :: 329; // Key: Keypad 9 +KEY_KP_DECIMAL :: 330; // Key: Keypad . +KEY_KP_DIVIDE :: 331; // Key: Keypad / +KEY_KP_MULTIPLY :: 332; // Key: Keypad * +KEY_KP_SUBTRACT :: 333; // Key: Keypad - +KEY_KP_ADD :: 334; // Key: Keypad + +KEY_KP_ENTER :: 335; // Key: Keypad Enter +KEY_KP_EQUAL :: 336; // Key: Keypad = +// Android key buttons +KEY_BACK :: 4; // Key: Android back button +KEY_MENU :: 82; // Key: Android menu button +KEY_VOLUME_UP :: 24; // Key: Android volume up button +KEY_VOLUME_DOWN :: 25; // Key: Android volume down button + +// Add backwards compatibility support for deprecated names +MOUSE_LEFT_BUTTON :: MOUSE_BUTTON_LEFT; +MOUSE_RIGHT_BUTTON :: MOUSE_BUTTON_RIGHT; +MOUSE_MIDDLE_BUTTON :: MOUSE_BUTTON_MIDDLE; + +// Mouse buttons +MOUSE_BUTTON_LEFT :: 0; // Mouse button left +MOUSE_BUTTON_RIGHT :: ^; // Mouse button right +MOUSE_BUTTON_MIDDLE :: ^; // Mouse button middle (pressed wheel) +MOUSE_BUTTON_SIDE :: ^; // Mouse button side (advanced mouse device) +MOUSE_BUTTON_EXTRA :: ^; // Mouse button extra (advanced mouse device) +MOUSE_BUTTON_FORWARD :: ^; // Mouse button forward (advanced mouse device) +MOUSE_BUTTON_BACK :: ^; // Mouse button back (advanced mouse device) + +MOUSE_CURSOR_DEFAULT :: 0; // Default pointer shape +MOUSE_CURSOR_ARROW :: ^; // Arrow shape +MOUSE_CURSOR_IBEAM :: ^; // Text writing cursor shape +MOUSE_CURSOR_CROSSHAIR :: ^; // Cross shape +MOUSE_CURSOR_POINTING_HAND :: ^; // Pointing hand cursor +MOUSE_CURSOR_RESIZE_EW :: ^; // Horizontal resize/move arrow shape +MOUSE_CURSOR_RESIZE_NS :: ^; // Vertical resize/move arrow shape +MOUSE_CURSOR_RESIZE_NWSE :: ^; // Top-left to bottom-right diagonal resize/move arrow shape +MOUSE_CURSOR_RESIZE_NESW :: ^; // The top-right to bottom-left diagonal resize/move arrow shape +MOUSE_CURSOR_RESIZE_ALL :: ^; // The omnidirectional resize/move cursor shape +MOUSE_CURSOR_NOT_ALLOWED :: ^; // The operation-not-allowed shape + diff --git a/pkgs/raylib/raymath.lc b/pkgs/raylib/raymath.lc new file mode 100644 index 0000000..4c2ad9b --- /dev/null +++ b/pkgs/raylib/raymath.lc @@ -0,0 +1,122 @@ +float3 :: struct { + v: [3]float; +} + +float16 :: struct { + v: [16]float; +} + +Clamp :: proc(value: float, min: float, max: float): float; @api +Lerp :: proc(start: float, end: float, amount: float): float; @api +Normalize :: proc(value: float, start: float, end: float): float; @api +Remap :: proc(value: float, inputStart: float, inputEnd: float, outputStart: float, outputEnd: float): float; @api +Wrap :: proc(value: float, min: float, max: float): float; @api +FloatEquals :: proc(x: float, y: float): int; @api +Vector2Zero :: proc(): Vector2; @api +Vector2One :: proc(): Vector2; @api +Vector2Add :: proc(v1: Vector2, v2: Vector2): Vector2; @api +Vector2AddValue :: proc(v: Vector2, add: float): Vector2; @api +Vector2Subtract :: proc(v1: Vector2, v2: Vector2): Vector2; @api +Vector2SubtractValue :: proc(v: Vector2, sub: float): Vector2; @api +Vector2Length :: proc(v: Vector2): float; @api +Vector2LengthSqr :: proc(v: Vector2): float; @api +Vector2DotProduct :: proc(v1: Vector2, v2: Vector2): float; @api +Vector2Distance :: proc(v1: Vector2, v2: Vector2): float; @api +Vector2DistanceSqr :: proc(v1: Vector2, v2: Vector2): float; @api +Vector2Angle :: proc(v1: Vector2, v2: Vector2): float; @api +Vector2LineAngle :: proc(start: Vector2, end: Vector2): float; @api +Vector2Scale :: proc(v: Vector2, scale: float): Vector2; @api +Vector2Multiply :: proc(v1: Vector2, v2: Vector2): Vector2; @api +Vector2Negate :: proc(v: Vector2): Vector2; @api +Vector2Divide :: proc(v1: Vector2, v2: Vector2): Vector2; @api +Vector2Normalize :: proc(v: Vector2): Vector2; @api +Vector2Transform :: proc(v: Vector2, mat: Matrix): Vector2; @api +Vector2Lerp :: proc(v1: Vector2, v2: Vector2, amount: float): Vector2; @api +Vector2Reflect :: proc(v: Vector2, normal: Vector2): Vector2; @api +Vector2Rotate :: proc(v: Vector2, angle: float): Vector2; @api +Vector2MoveTowards :: proc(v: Vector2, target: Vector2, maxDistance: float): Vector2; @api +Vector2Invert :: proc(v: Vector2): Vector2; @api +Vector2Clamp :: proc(v: Vector2, min: Vector2, max: Vector2): Vector2; @api +Vector2ClampValue :: proc(v: Vector2, min: float, max: float): Vector2; @api +Vector2Equals :: proc(p: Vector2, q: Vector2): int; @api +Vector3Zero :: proc(): Vector3; @api +Vector3One :: proc(): Vector3; @api +Vector3Add :: proc(v1: Vector3, v2: Vector3): Vector3; @api +Vector3AddValue :: proc(v: Vector3, add: float): Vector3; @api +Vector3Subtract :: proc(v1: Vector3, v2: Vector3): Vector3; @api +Vector3SubtractValue :: proc(v: Vector3, sub: float): Vector3; @api +Vector3Scale :: proc(v: Vector3, scalar: float): Vector3; @api +Vector3Multiply :: proc(v1: Vector3, v2: Vector3): Vector3; @api +Vector3CrossProduct :: proc(v1: Vector3, v2: Vector3): Vector3; @api +Vector3Perpendicular :: proc(v: Vector3): Vector3; @api +Vector3Length :: proc(v: Vector3): float; @api +Vector3LengthSqr :: proc(v: Vector3): float; @api +Vector3DotProduct :: proc(v1: Vector3, v2: Vector3): float; @api +Vector3Distance :: proc(v1: Vector3, v2: Vector3): float; @api +Vector3DistanceSqr :: proc(v1: Vector3, v2: Vector3): float; @api +Vector3Angle :: proc(v1: Vector3, v2: Vector3): float; @api +Vector3Negate :: proc(v: Vector3): Vector3; @api +Vector3Divide :: proc(v1: Vector3, v2: Vector3): Vector3; @api +Vector3Normalize :: proc(v: Vector3): Vector3; @api +Vector3Project :: proc(v1: Vector3, v2: Vector3): Vector3; @api +Vector3Reject :: proc(v1: Vector3, v2: Vector3): Vector3; @api +Vector3OrthoNormalize :: proc(v1: *Vector3, v2: *Vector3); @api +Vector3Transform :: proc(v: Vector3, mat: Matrix): Vector3; @api +Vector3RotateByQuaternion :: proc(v: Vector3, q: Quaternion): Vector3; @api +Vector3RotateByAxisAngle :: proc(v: Vector3, axis: Vector3, angle: float): Vector3; @api +Vector3Lerp :: proc(v1: Vector3, v2: Vector3, amount: float): Vector3; @api +Vector3Reflect :: proc(v: Vector3, normal: Vector3): Vector3; @api +Vector3Min :: proc(v1: Vector3, v2: Vector3): Vector3; @api +Vector3Max :: proc(v1: Vector3, v2: Vector3): Vector3; @api +Vector3Barycenter :: proc(p: Vector3, a: Vector3, b: Vector3, c: Vector3): Vector3; @api +Vector3Unproject :: proc(source: Vector3, projection: Matrix, view: Matrix): Vector3; @api +Vector3ToFloatV :: proc(v: Vector3): float3; @api +Vector3Invert :: proc(v: Vector3): Vector3; @api +Vector3Clamp :: proc(v: Vector3, min: Vector3, max: Vector3): Vector3; @api +Vector3ClampValue :: proc(v: Vector3, min: float, max: float): Vector3; @api +Vector3Equals :: proc(p: Vector3, q: Vector3): int; @api +Vector3Refract :: proc(v: Vector3, n: Vector3, r: float): Vector3; @api +MatrixDeterminant :: proc(mat: Matrix): float; @api +MatrixTrace :: proc(mat: Matrix): float; @api +MatrixTranspose :: proc(mat: Matrix): Matrix; @api +MatrixInvert :: proc(mat: Matrix): Matrix; @api +MatrixIdentity :: proc(): Matrix; @api +MatrixAdd :: proc(left: Matrix, right: Matrix): Matrix; @api +MatrixSubtract :: proc(left: Matrix, right: Matrix): Matrix; @api +MatrixMultiply :: proc(left: Matrix, right: Matrix): Matrix; @api +MatrixTranslate :: proc(x: float, y: float, z: float): Matrix; @api +MatrixRotate :: proc(axis: Vector3, angle: float): Matrix; @api +MatrixRotateX :: proc(angle: float): Matrix; @api +MatrixRotateY :: proc(angle: float): Matrix; @api +MatrixRotateZ :: proc(angle: float): Matrix; @api +MatrixRotateXYZ :: proc(angle: Vector3): Matrix; @api +MatrixRotateZYX :: proc(angle: Vector3): Matrix; @api +MatrixScale :: proc(x: float, y: float, z: float): Matrix; @api +MatrixFrustum :: proc(left: double, right: double, bottom: double, top: double, near: double, far: double): Matrix; @api +MatrixPerspective :: proc(fovY: double, aspect: double, nearPlane: double, farPlane: double): Matrix; @api +MatrixOrtho :: proc(left: double, right: double, bottom: double, top: double, nearPlane: double, farPlane: double): Matrix; @api +MatrixLookAt :: proc(eye: Vector3, target: Vector3, up: Vector3): Matrix; @api +MatrixToFloatV :: proc(mat: Matrix): float16; @api +QuaternionAdd :: proc(q1: Quaternion, q2: Quaternion): Quaternion; @api +QuaternionAddValue :: proc(q: Quaternion, add: float): Quaternion; @api +QuaternionSubtract :: proc(q1: Quaternion, q2: Quaternion): Quaternion; @api +QuaternionSubtractValue :: proc(q: Quaternion, sub: float): Quaternion; @api +QuaternionIdentity :: proc(): Quaternion; @api +QuaternionLength :: proc(q: Quaternion): float; @api +QuaternionNormalize :: proc(q: Quaternion): Quaternion; @api +QuaternionInvert :: proc(q: Quaternion): Quaternion; @api +QuaternionMultiply :: proc(q1: Quaternion, q2: Quaternion): Quaternion; @api +QuaternionScale :: proc(q: Quaternion, mul: float): Quaternion; @api +QuaternionDivide :: proc(q1: Quaternion, q2: Quaternion): Quaternion; @api +QuaternionLerp :: proc(q1: Quaternion, q2: Quaternion, amount: float): Quaternion; @api +QuaternionNlerp :: proc(q1: Quaternion, q2: Quaternion, amount: float): Quaternion; @api +QuaternionSlerp :: proc(q1: Quaternion, q2: Quaternion, amount: float): Quaternion; @api +QuaternionFromVector3ToVector3 :: proc(from: Vector3, to: Vector3): Quaternion; @api +QuaternionFromMatrix :: proc(mat: Matrix): Quaternion; @api +QuaternionToMatrix :: proc(q: Quaternion): Matrix; @api +QuaternionFromAxisAngle :: proc(axis: Vector3, angle: float): Quaternion; @api +QuaternionToAxisAngle :: proc(q: Quaternion, outAxis: *Vector3, outAngle: *float); @api +QuaternionFromEuler :: proc(pitch: float, yaw: float, roll: float): Quaternion; @api +QuaternionToEuler :: proc(q: Quaternion): Vector3; @api +QuaternionTransform :: proc(q: Quaternion, mat: Matrix): Quaternion; @api +QuaternionEquals :: proc(p: Quaternion, q: Quaternion): int; @api diff --git a/pkgs/raylib/rlgl.lc b/pkgs/raylib/rlgl.lc new file mode 100644 index 0000000..8552d20 --- /dev/null +++ b/pkgs/raylib/rlgl.lc @@ -0,0 +1,173 @@ +rlVertexBuffer :: struct { + elementCount: int; + vertices: *float; + texcoords: *float; + colors: *uchar; + indices: *uint; + vaoId: uint; + vboId: [4]uint; +} + +rlDrawCall :: struct { + mode: int; + vertexCount: int; + vertexAlignment: int; + textureId: uint; +} + +rlRenderBatch :: struct { + bufferCount: int; + currentBuffer: int; + vertexBuffer: *rlVertexBuffer; + draws: *rlDrawCall; + drawCounter: int; + currentDepth: float; +} + +rlMatrixMode :: proc(mode: int); @dont_mangle @api +rlPushMatrix :: proc(); @dont_mangle @api +rlPopMatrix :: proc(); @dont_mangle @api +rlLoadIdentity :: proc(); @dont_mangle @api +rlTranslatef :: proc(x: float, y: float, z: float); @dont_mangle @api +rlRotatef :: proc(angle: float, x: float, y: float, z: float); @dont_mangle @api +rlScalef :: proc(x: float, y: float, z: float); @dont_mangle @api +rlMultMatrixf :: proc(matf: *float); @dont_mangle @api +rlFrustum :: proc(left: double, right: double, bottom: double, top: double, znear: double, zfar: double); @dont_mangle @api +rlOrtho :: proc(left: double, right: double, bottom: double, top: double, znear: double, zfar: double); @dont_mangle @api +rlViewport :: proc(x: int, y: int, width: int, height: int); @dont_mangle @api +rlBegin :: proc(mode: int); @dont_mangle @api +rlEnd :: proc(); @dont_mangle @api +rlVertex2i :: proc(x: int, y: int); @dont_mangle @api +rlVertex2f :: proc(x: float, y: float); @dont_mangle @api +rlVertex3f :: proc(x: float, y: float, z: float); @dont_mangle @api +rlTexCoord2f :: proc(x: float, y: float); @dont_mangle @api +rlNormal3f :: proc(x: float, y: float, z: float); @dont_mangle @api +rlColor4ub :: proc(r: uchar, g: uchar, b: uchar, a: uchar); @dont_mangle @api +rlColor3f :: proc(x: float, y: float, z: float); @dont_mangle @api +rlColor4f :: proc(x: float, y: float, z: float, w: float); @dont_mangle @api +rlEnableVertexArray :: proc(vaoId: uint): bool; @dont_mangle @api +rlDisableVertexArray :: proc(); @dont_mangle @api +rlEnableVertexBuffer :: proc(id: uint); @dont_mangle @api +rlDisableVertexBuffer :: proc(); @dont_mangle @api +rlEnableVertexBufferElement :: proc(id: uint); @dont_mangle @api +rlDisableVertexBufferElement :: proc(); @dont_mangle @api +rlEnableVertexAttribute :: proc(index: uint); @dont_mangle @api +rlDisableVertexAttribute :: proc(index: uint); @dont_mangle @api +rlActiveTextureSlot :: proc(slot: int); @dont_mangle @api +rlEnableTexture :: proc(id: uint); @dont_mangle @api +rlDisableTexture :: proc(); @dont_mangle @api +rlEnableTextureCubemap :: proc(id: uint); @dont_mangle @api +rlDisableTextureCubemap :: proc(); @dont_mangle @api +rlTextureParameters :: proc(id: uint, param: int, value: int); @dont_mangle @api +rlCubemapParameters :: proc(id: uint, param: int, value: int); @dont_mangle @api +rlEnableShader :: proc(id: uint); @dont_mangle @api +rlDisableShader :: proc(); @dont_mangle @api +rlEnableFramebuffer :: proc(id: uint); @dont_mangle @api +rlDisableFramebuffer :: proc(); @dont_mangle @api +rlActiveDrawBuffers :: proc(count: int); @dont_mangle @api +rlBlitFramebuffer :: proc(srcX: int, srcY: int, srcWidth: int, srcHeight: int, dstX: int, dstY: int, dstWidth: int, dstHeight: int, bufferMask: int); @dont_mangle @api +rlEnableColorBlend :: proc(); @dont_mangle @api +rlDisableColorBlend :: proc(); @dont_mangle @api +rlEnableDepthTest :: proc(); @dont_mangle @api +rlDisableDepthTest :: proc(); @dont_mangle @api +rlEnableDepthMask :: proc(); @dont_mangle @api +rlDisableDepthMask :: proc(); @dont_mangle @api +rlEnableBackfaceCulling :: proc(); @dont_mangle @api +rlDisableBackfaceCulling :: proc(); @dont_mangle @api +rlSetCullFace :: proc(mode: int); @dont_mangle @api +rlEnableScissorTest :: proc(); @dont_mangle @api +rlDisableScissorTest :: proc(); @dont_mangle @api +rlScissor :: proc(x: int, y: int, width: int, height: int); @dont_mangle @api +rlEnableWireMode :: proc(); @dont_mangle @api +rlEnablePointMode :: proc(); @dont_mangle @api +rlDisableWireMode :: proc(); @dont_mangle @api +rlSetLineWidth :: proc(width: float); @dont_mangle @api +rlGetLineWidth :: proc(): float; @dont_mangle @api +rlEnableSmoothLines :: proc(); @dont_mangle @api +rlDisableSmoothLines :: proc(); @dont_mangle @api +rlEnableStereoRender :: proc(); @dont_mangle @api +rlDisableStereoRender :: proc(); @dont_mangle @api +rlIsStereoRenderEnabled :: proc(): bool; @dont_mangle @api +rlClearColor :: proc(r: uchar, g: uchar, b: uchar, a: uchar); @dont_mangle @api +rlClearScreenBuffers :: proc(); @dont_mangle @api +rlCheckErrors :: proc(); @dont_mangle @api +rlSetBlendMode :: proc(mode: int); @dont_mangle @api +rlSetBlendFactors :: proc(glSrcFactor: int, glDstFactor: int, glEquation: int); @dont_mangle @api +rlSetBlendFactorsSeparate :: proc(glSrcRGB: int, glDstRGB: int, glSrcAlpha: int, glDstAlpha: int, glEqRGB: int, glEqAlpha: int); @dont_mangle @api +rlglInit :: proc(width: int, height: int); @dont_mangle @api +rlglClose :: proc(); @dont_mangle @api +rlLoadExtensions :: proc(loader: *void); @dont_mangle @api +rlGetVersion :: proc(): int; @dont_mangle @api +rlSetFramebufferWidth :: proc(width: int); @dont_mangle @api +rlGetFramebufferWidth :: proc(): int; @dont_mangle @api +rlSetFramebufferHeight :: proc(height: int); @dont_mangle @api +rlGetFramebufferHeight :: proc(): int; @dont_mangle @api +rlGetTextureIdDefault :: proc(): uint; @dont_mangle @api +rlGetShaderIdDefault :: proc(): uint; @dont_mangle @api +rlGetShaderLocsDefault :: proc(): *int; @dont_mangle @api +rlLoadRenderBatch :: proc(numBuffers: int, bufferElements: int): rlRenderBatch; @dont_mangle @api +rlUnloadRenderBatch :: proc(batch: rlRenderBatch); @dont_mangle @api +rlDrawRenderBatch :: proc(batch: *rlRenderBatch); @dont_mangle @api +rlSetRenderBatchActive :: proc(batch: *rlRenderBatch); @dont_mangle @api +rlDrawRenderBatchActive :: proc(); @dont_mangle @api +rlCheckRenderBatchLimit :: proc(vCount: int): bool; @dont_mangle @api +rlSetTexture :: proc(id: uint); @dont_mangle @api +rlLoadVertexArray :: proc(): uint; @dont_mangle @api +rlLoadVertexBuffer :: proc(buffer: *void, size: int, dynamic: bool): uint; @dont_mangle @api +rlLoadVertexBufferElement :: proc(buffer: *void, size: int, dynamic: bool): uint; @dont_mangle @api +rlUpdateVertexBuffer :: proc(bufferId: uint, data: *void, dataSize: int, offset: int); @dont_mangle @api +rlUpdateVertexBufferElements :: proc(id: uint, data: *void, dataSize: int, offset: int); @dont_mangle @api +rlUnloadVertexArray :: proc(vaoId: uint); @dont_mangle @api +rlUnloadVertexBuffer :: proc(vboId: uint); @dont_mangle @api +rlSetVertexAttribute :: proc(index: uint, compSize: int, type: int, normalized: bool, stride: int, pointer: *void); @dont_mangle @api +rlSetVertexAttributeDivisor :: proc(index: uint, divisor: int); @dont_mangle @api +rlSetVertexAttributeDefault :: proc(locIndex: int, value: *void, attribType: int, count: int); @dont_mangle @api +rlDrawVertexArray :: proc(offset: int, count: int); @dont_mangle @api +rlDrawVertexArrayElements :: proc(offset: int, count: int, buffer: *void); @dont_mangle @api +rlDrawVertexArrayInstanced :: proc(offset: int, count: int, instances: int); @dont_mangle @api +rlDrawVertexArrayElementsInstanced :: proc(offset: int, count: int, buffer: *void, instances: int); @dont_mangle @api +rlLoadTexture :: proc(data: *void, width: int, height: int, format: int, mipmapCount: int): uint; @dont_mangle @api +rlLoadTextureDepth :: proc(width: int, height: int, useRenderBuffer: bool): uint; @dont_mangle @api +rlLoadTextureCubemap :: proc(data: *void, size: int, format: int): uint; @dont_mangle @api +rlUpdateTexture :: proc(id: uint, offsetX: int, offsetY: int, width: int, height: int, format: int, data: *void); @dont_mangle @api +rlGetGlTextureFormats :: proc(format: int, glInternalFormat: *uint, glFormat: *uint, glType: *uint); @dont_mangle @api +rlGetPixelFormatName :: proc(format: uint): *char; @dont_mangle @api +rlUnloadTexture :: proc(id: uint); @dont_mangle @api +rlGenTextureMipmaps :: proc(id: uint, width: int, height: int, format: int, mipmaps: *int); @dont_mangle @api +rlReadTexturePixels :: proc(id: uint, width: int, height: int, format: int): *void; @dont_mangle @api +rlReadScreenPixels :: proc(width: int, height: int): *uchar; @dont_mangle @api +rlLoadFramebuffer :: proc(width: int, height: int): uint; @dont_mangle @api +rlFramebufferAttach :: proc(fboId: uint, texId: uint, attachType: int, texType: int, mipLevel: int); @dont_mangle @api +rlFramebufferComplete :: proc(id: uint): bool; @dont_mangle @api +rlUnloadFramebuffer :: proc(id: uint); @dont_mangle @api +rlLoadShaderCode :: proc(vsCode: *char, fsCode: *char): uint; @dont_mangle @api +rlCompileShader :: proc(shaderCode: *char, type: int): uint; @dont_mangle @api +rlLoadShaderProgram :: proc(vShaderId: uint, fShaderId: uint): uint; @dont_mangle @api +rlUnloadShaderProgram :: proc(id: uint); @dont_mangle @api +rlGetLocationUniform :: proc(shaderId: uint, uniformName: *char): int; @dont_mangle @api +rlGetLocationAttrib :: proc(shaderId: uint, attribName: *char): int; @dont_mangle @api +rlSetUniform :: proc(locIndex: int, value: *void, uniformType: int, count: int); @dont_mangle @api +rlSetUniformMatrix :: proc(locIndex: int, mat: Matrix); @dont_mangle @api +rlSetUniformSampler :: proc(locIndex: int, textureId: uint); @dont_mangle @api +rlSetShader :: proc(id: uint, locs: *int); @dont_mangle @api +rlLoadComputeShaderProgram :: proc(shaderId: uint): uint; @dont_mangle @api +rlComputeShaderDispatch :: proc(groupX: uint, groupY: uint, groupZ: uint); @dont_mangle @api +rlLoadShaderBuffer :: proc(size: uint, data: *void, usageHint: int): uint; @dont_mangle @api +rlUnloadShaderBuffer :: proc(ssboId: uint); @dont_mangle @api +rlUpdateShaderBuffer :: proc(id: uint, data: *void, dataSize: uint, offset: uint); @dont_mangle @api +rlBindShaderBuffer :: proc(id: uint, index: uint); @dont_mangle @api +rlReadShaderBuffer :: proc(id: uint, dest: *void, count: uint, offset: uint); @dont_mangle @api +rlCopyShaderBuffer :: proc(destId: uint, srcId: uint, destOffset: uint, srcOffset: uint, count: uint); @dont_mangle @api +rlGetShaderBufferSize :: proc(id: uint): uint; @dont_mangle @api +rlBindImageTexture :: proc(id: uint, index: uint, format: int, readonly: bool); @dont_mangle @api +rlGetMatrixModelview :: proc(): Matrix; @dont_mangle @api +rlGetMatrixProjection :: proc(): Matrix; @dont_mangle @api +rlGetMatrixTransform :: proc(): Matrix; @dont_mangle @api +rlGetMatrixProjectionStereo :: proc(eye: int): Matrix; @dont_mangle @api +rlGetMatrixViewOffsetStereo :: proc(eye: int): Matrix; @dont_mangle @api +rlSetMatrixProjection :: proc(proj: Matrix); @dont_mangle @api +rlSetMatrixModelview :: proc(view: Matrix); @dont_mangle @api +rlSetMatrixProjectionStereo :: proc(right: Matrix, left: Matrix); @dont_mangle @api +rlSetMatrixViewOffsetStereo :: proc(right: Matrix, left: Matrix); @dont_mangle @api +rlLoadDrawCube :: proc(); @dont_mangle @api +rlLoadDrawQuad :: proc(); @dont_mangle @api diff --git a/pkgs/std_types/c_types.lc b/pkgs/std_types/c_types.lc new file mode 100644 index 0000000..051c505 --- /dev/null +++ b/pkgs/std_types/c_types.lc @@ -0,0 +1,12 @@ +#build_if(LC_GEN == GEN_C); +#`#include `; + +i8 :: typedef char; @foreign(int8_t) +i16 :: typedef short; @foreign(int16_t) +i32 :: typedef int; @foreign(int32_t) +i64 :: typedef llong; @foreign(int64_t) + +u8 :: typedef uchar; @foreign(uint8_t) +u16 :: typedef ushort; @foreign(uint16_t) +u32 :: typedef uint; @foreign(uint32_t) +u64 :: typedef ullong; @foreign(uint64_t) diff --git a/pkgs/std_types/non_c_types.lc b/pkgs/std_types/non_c_types.lc new file mode 100644 index 0000000..d5c1161 --- /dev/null +++ b/pkgs/std_types/non_c_types.lc @@ -0,0 +1,11 @@ +#build_if(LC_GEN != GEN_C); + +i8 :: typedef char; +i16 :: typedef short; +i32 :: typedef int; +i64 :: typedef llong; + +u8 :: typedef uchar; +u16 :: typedef ushort; +u32 :: typedef uint; +u64 :: typedef ullong; diff --git a/pkgs/std_types/types.lc b/pkgs/std_types/types.lc new file mode 100644 index 0000000..fd4101a --- /dev/null +++ b/pkgs/std_types/types.lc @@ -0,0 +1,44 @@ +#static_assert(sizeof(:i8) == 1); +#static_assert(sizeof(:i16) == 2); +#static_assert(sizeof(:i32) == 4); +#static_assert(sizeof(:i64) == 8); +#static_assert(sizeof(:u8) == 1); +#static_assert(sizeof(:u16) == 2); +#static_assert(sizeof(:u32) == 4); +#static_assert(sizeof(:u64) == 8); + +f32 :: typedef float; @weak @foreign +f64 :: typedef double; @weak @foreign + +UINT64_MAX :: 0xffffffffffffffff; +UINT64_MIN :: 0; +UINT32_MAX :: 0xffffffff; +UINT32_MIN :: 0; +UINT16_MAX :: 0xffff; +UINT16_MIN :: 0; +UINT8_MAX :: 0xff; +UINT8_MIN :: 0; +INT64_MAX :: 9223372036854775807; +INT64_MIN :: -9223372036854775808; +INT32_MAX :: 2147483647; +INT32_MIN :: -2147483648; +INT16_MAX :: 32767; +INT16_MIN :: -32768; +INT8_MAX :: 127; +INT8_MIN :: -128; +CHAR_MAX :: INT8_MAX; +CHAR_MIN :: INT8_MIN; +UCHAR_MAX :: UINT8_MAX; +UCHAR_MIN :: UINT8_MIN; +SHORT_MAX :: INT16_MAX; +SHORT_MIN :: INT16_MIN; +USHORT_MAX :: UINT16_MAX; +USHORT_MIN :: UINT16_MIN; +INT_MAX :: INT32_MAX; +INT_MIN :: INT32_MIN; +UINT_MAX :: UINT32_MAX; +UINT_MIN :: UINT32_MIN; +LLONG_MAX :: INT64_MAX; +LLONG_MIN :: INT64_MIN; +ULLONG_MAX :: UINT64_MAX; +ULLONG_MIN :: UINT64_MIN; diff --git a/pkgs/std_types/windows_types.lc b/pkgs/std_types/windows_types.lc new file mode 100644 index 0000000..f1e4f1b --- /dev/null +++ b/pkgs/std_types/windows_types.lc @@ -0,0 +1,9 @@ +#build_if(LC_OS == OS_WINDOWS); + +#static_assert(sizeof(:long) == 4); + +LONG_MAX :: INT32_MAX; +LONG_MIN :: INT32_MIN; +ULONG_MAX :: UINT32_MAX; +ULONG_MIN :: UINT32_MIN; + diff --git a/pkgs/std_types/x64_linux_types.lc b/pkgs/std_types/x64_linux_types.lc new file mode 100644 index 0000000..fcdd2fc --- /dev/null +++ b/pkgs/std_types/x64_linux_types.lc @@ -0,0 +1,8 @@ +#build_if((LC_OS == OS_MAC || LC_OS == OS_LINUX) && LC_ARCH == ARCH_X64); + +#static_assert(sizeof(:long) == 8); + +LONG_MAX :: INT64_MAX; +LONG_MIN :: INT64_MIN; +ULONG_MAX :: UINT64_MAX; +ULONG_MIN :: UINT64_MIN; diff --git a/pkgs/std_types/x64_types.lc b/pkgs/std_types/x64_types.lc new file mode 100644 index 0000000..edf210a --- /dev/null +++ b/pkgs/std_types/x64_types.lc @@ -0,0 +1,15 @@ +#build_if(LC_ARCH == ARCH_X64); + +usize :: typedef u64; @foreign(size_t) +isize :: typedef i64; @foreign(intptr_t) +intptr :: typedef i64; @foreign(intptr_t) +uintptr :: typedef u64; @foreign(uintptr_t) + +INTPTR_MAX :: INT64_MAX; +INTPTR_MIN :: INT64_MIN; +UINTPTR_MAX :: UINT64_MAX; +UINTPTR_MIN :: UINT64_MIN; +ISIZE_MAX :: INT64_MAX; +ISIZE_MIN :: INT64_MIN; +USIZE_MAX :: UINT64_MAX; +USIZE_MIN :: UINT64_MIN; \ No newline at end of file diff --git a/pkgs/std_types/x86_types.lc b/pkgs/std_types/x86_types.lc new file mode 100644 index 0000000..5e6c249 --- /dev/null +++ b/pkgs/std_types/x86_types.lc @@ -0,0 +1,22 @@ +#build_if(LC_ARCH == ARCH_X86); + +#static_assert(sizeof(:long) == 4); + +LONG_MAX :: INT32_MAX; +LONG_MIN :: INT32_MIN; +ULONG_MAX :: UINT32_MAX; +ULONG_MIN :: UINT32_MIN; + +usize :: typedef u32; @foreign(size_t) +isize :: typedef i32; @foreign(intptr_t) +intptr :: typedef i32; @foreign(intptr_t) +uintptr :: typedef u32; @foreign(uintptr_t) + +INTPTR_MAX :: INT32_MAX; +INTPTR_MIN :: INT32_MIN; +UINTPTR_MAX :: UINT32_MAX; +UINTPTR_MIN :: UINT32_MIN; +ISIZE_MAX :: INT32_MAX; +ISIZE_MIN :: INT32_MIN; +USIZE_MAX :: UINT32_MAX; +USIZE_MIN :: UINT32_MIN; \ No newline at end of file diff --git a/src/build_file/ast_verify.cpp b/src/build_file/ast_verify.cpp new file mode 100644 index 0000000..5f219d6 --- /dev/null +++ b/src/build_file/ast_verify.cpp @@ -0,0 +1,125 @@ +thread_local LC_Map DebugASTMap; + +void DebugVerify_WalkAST(LC_ASTWalker *ctx, LC_AST *n) { + bool created = LC_InsertWithoutReplace(&DebugASTMap, n, (void *)(intptr_t)100); + if (!created) LC_ReportASTError(n, "we got to the same ast node twice using ast walker"); + // AST_Decl doesn't need to hold types, it's just a standin for LC_Decl + if (LC_IsDecl(n)) { + if (n->type) { + LC_ReportASTError(n, "decl holds type"); + } + } + + if (LC_IsStmt(n)) { + // These might pop up in a for loop as expressions + if (n->kind == LC_ASTKind_StmtVar || n->kind == LC_ASTKind_StmtConst || n->kind == LC_ASTKind_StmtAssign || n->kind == LC_ASTKind_StmtExpr) { + if (!n->type) { + LC_ReportASTError(n, "typed stmt doesn't hold type"); + } + } else { + if (n->type) { + LC_ReportASTError(n, "stmt holds type"); + } + } + } + + if (LC_IsType(n) && ctx->inside_discarded == 0) { + if (!n->type) { + LC_ReportASTError(n, "typespec doesn't hold type"); + } + } + + if (LC_IsExpr(n)) { + bool parent_is_const = false; + bool parent_is_builtin = false; + for (int i = ctx->stack.len - 1; i >= 0; i -= 1) { + LC_AST *parent = ctx->stack.data[i]; + if (parent->kind == LC_ASTKind_DeclConst || parent->kind == LC_ASTKind_StmtConst || parent->const_val.type) { + parent_is_const = true; + } + if (parent->kind == LC_ASTKind_ExprBuiltin) { + parent_is_builtin = true; + } + } + + bool should_have_type = parent_is_builtin == false && ctx->inside_note == 0 && ctx->inside_discarded == 0; + if (should_have_type && !n->type) { + LC_ReportASTError(n, "expression doesn't have type"); + } + + if (should_have_type && !parent_is_const) { + bool type_is_ok = !LC_IsUntyped(n->type) || n->type == L->tuntypedbool; + if (!type_is_ok) { + LC_ReportASTError(n, "expression is still untyped"); + } + } + + if (should_have_type && n->kind == LC_ASTKind_ExprIdent) { + if (n->eident.resolved_decl == NULL) { + LC_ReportASTError(n, "identifier doesn't hold resolved declaration"); + } + } + } +} + +void VerifyCopy_Walk(LC_ASTWalker *ctx, LC_AST *n) { + int *counter = (int *)ctx->user_data; + counter[0] += 1; +} + +void VerifyASTCopy(LC_ASTRefList packages) { + for (LC_ASTRef *it = packages.first; it; it = it->next) { + LC_ASTFor(file, it->ast->apackage.ffile) { + LC_TempArena c = LC_BeginTemp(L->arena); + LC_AST *copy = LC_CopyAST(L->arena, file); + + int copy_counter = 0; + int original_counter = 0; + + { + LC_ASTWalker walker = LC_GetDefaultWalker(L->arena, VerifyCopy_Walk); + walker.visit_notes = walker.visit_discarded = true; + walker.user_data = (void *)©_counter; + LC_WalkAST(&walker, copy); + walker.user_data = (void *)&original_counter; + LC_WalkAST(&walker, copy); + } + + IO_Assert(copy_counter == original_counter); + IO_Assert(copy_counter > 1); + IO_Assert(original_counter > 1); + + LC_EndTemp(c); + } + } +} + +void DebugVerifyAST(LC_ASTRefList packages) { + LC_TempArena checkpoint = LC_BeginTemp(L->arena); + + DebugASTMap = {L->arena}; + LC_MapReserve(&DebugASTMap, 4096); + + LC_ASTWalker walker = LC_GetDefaultWalker(L->arena, DebugVerify_WalkAST); + walker.visit_notes = walker.visit_discarded = true; + for (LC_ASTRef *it = packages.first; it; it = it->next) { + LC_WalkAST(&walker, it->ast); + } + LC_WalkAST(&walker, L->tstring->decl->ast); + LC_WalkAST(&walker, L->tany->decl->ast); + + for (int i = 0; i < L->ast_count; i += 1) { + LC_AST *it = (LC_AST *)L->ast_arena->memory.data + i; + if (it == L->builtin_package) continue; + if (it->kind == LC_ASTKind_Ignore) continue; + intptr_t value = (intptr_t)LC_MapGetP(&DebugASTMap, it); + + if (value != 100) { + LC_ReportASTError(it, "marking verification failed!"); + } + } + LC_MapClear(&DebugASTMap); + + VerifyASTCopy(packages); + LC_EndTemp(checkpoint); +} diff --git a/src/build_file/package_compiler.cpp b/src/build_file/package_compiler.cpp new file mode 100644 index 0000000..a51f7b4 --- /dev/null +++ b/src/build_file/package_compiler.cpp @@ -0,0 +1,166 @@ +bool Expand(MA_Arena *arena, S8_List *out, S8_String filepath) { + S8_String c = OS_ReadFile(arena, filepath); + if (c.str == 0) return false; + // S8_String name = S8_SkipToLastSlash(filepath); + // S8_AddF(arena, out, "// %.*s\n", S8_Expand(name)); + + S8_String path = S8_ChopLastSlash(filepath); + S8_String include = S8_Lit("#include \""); + for (;;) { + int64_t idx = -1; + if (S8_Seek(c, include, 0, &idx)) { + S8_String str_to_add = S8_GetPrefix(c, idx); + S8_AddNode(arena, out, str_to_add); + S8_String save = c; + c = S8_Skip(c, idx + include.len); + + S8_String filename = c; + filename.len = 0; + while (filename.str[filename.len] != '"' && filename.len < c.len) { + filename.len += 1; + } + + c = S8_Skip(c, filename.len + 1); + S8_String inc_path = S8_Format(arena, "%.*s/%.*s", S8_Expand(path), S8_Expand(filename)); + + bool dont_expand_and_remove_include = false; + if (S8_EndsWith(inc_path, "lib_compiler.h")) dont_expand_and_remove_include = true; + + if (!dont_expand_and_remove_include) { + if (!Expand(arena, out, inc_path)) { + S8_String s = S8_GetPrefix(save, save.len - c.len); + S8_AddNode(arena, out, s); + } + } + } else { + S8_AddNode(arena, out, c); + break; + } + } + + return true; +} + +S8_String ExpandIncludes(MA_Arena *arena, S8_String filepath) { + S8_List out = S8_MakeEmptyList(); + S8_String result = S8_MakeEmpty(); + Expand(arena, &out, filepath); + result = S8_Merge(arena, out); + return result; +} + +void PackageCompiler() { + MA_Scratch scratch; + S8_String header = ExpandIncludes(scratch, S8_Lit("../src/compiler/lib_compiler.h")); + S8_String impl = ExpandIncludes(scratch, S8_Lit("../src/compiler/lib_compiler.c")); + + S8_List list = {0}; + S8_AddF(scratch, &list, R"FOO(/* +This is a compiler frontend in a single-header-file library form. +This is a **beta** so things may change between versions! + +# How to use + +In *one* of your C or C++ files to create the implementation: + +``` +#define LIB_COMPILER_IMPLEMENTATION +#include "lib_compiler.h" +``` + +In the rest of your files you can just include it like a regular +header. + +# Examples + +See online repository for code examples + +# Overrides + +You can override libc calls, the arena implementation using +preprocessor at compile time, here is an example of how you +would go about it: + +``` +#define LC_vsnprintf stbsp_vsnprintf +#define LC_MemoryZero(p, size) __builtin_memset(p, 0, size); +#define LC_MemoryCopy(dst, src, size) __builtin_memcpy(dst, src, size) + +#define LIB_COMPILER_IMPLEMENTATION +#include "lib_compiler.h" +``` + +Look for '@override' to find things that can be overridden using macro preprocessor +Look for '@api' to find the main functions that you are supposed to use +Look for '@configurable' to find runtime callbacks you can register and other settings + +# License (MIT) + +See end of file + +*/ +)FOO"); + S8_AddNode(scratch, &list, header); + S8_AddF(scratch, &list, "\n#ifdef LIB_COMPILER_IMPLEMENTATION\n"); + S8_AddNode(scratch, &list, impl); + S8_AddF(scratch, &list, "\n#endif // LIB_COMPILER_IMPLEMENTATION\n"); + S8_AddF(scratch, &list, R"FOO( +/* +Copyright (c) 2024 Krzosa Karol + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +)FOO"); + S8_String result = S8_Merge(scratch, list); + + if (PrintAllFunctions) { + S8_List lines = S8_Split(Perm, result, S8_Lit("\n"), 0); + S8_For(_line, lines) { + S8_String line = _line->string; + + if (!S8_Seek(line, "{", S8_FindFlag_MatchFindLast)) { + continue; + } + + int64_t idx = 0; + if (S8_Seek(line, ")", 0, &idx)) { + line.len = idx + 1; + } + + S8_String proc_name = line; + if (S8_Seek(line, "(", 0, &idx)) { + proc_name.len = idx; + for (int64_t i = proc_name.len - 1; i > 0; i -= 1) { + bool is_ident = CHAR_IsIdent(proc_name.str[i]) || CHAR_IsDigit(proc_name.str[i]); + if (!is_ident) { + proc_name = S8_Skip(proc_name, i + 1); + break; + } + } + } + + if (S8_StartsWith(line, "LC_FUNCTION", false)) { + if (PrintAllFunctions) IO_Printf("%.*s;\n", S8_Expand(line)); + } + } + } + + OS_WriteFile(S8_Lit("../lib_compiler.h"), result); +} diff --git a/src/build_file/test_readme.cpp b/src/build_file/test_readme.cpp new file mode 100644 index 0000000..53e23f3 --- /dev/null +++ b/src/build_file/test_readme.cpp @@ -0,0 +1,37 @@ +void ReadmeReadFile(LC_AST *package, LoadedFile *file) { + S8_String result = {}; + if (package->apackage.name == LC_ILit("readme_test")) { + S8_String code = *(S8_String *)L->user_data; + file->content = S8_Copy(L->arena, code); + } else { + file->content = OS_ReadFile(L->arena, file->path); + } +} + +void TestReadme() { + MA_Scratch scratch; + + S8_String readme_path = OS_GetAbsolutePath(scratch, "../README.md"); + S8_String readme = OS_ReadFile(scratch, readme_path); + S8_List split = S8_Split(scratch, readme, "```"); + S8_For(it, split) { + if (S8_StartsWith(it->string, " odin", S8_IgnoreCase)) { + S8_String code = S8_Skip(it->string, 5); + + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + lang->user_data = (void *)&code; + lang->on_file_load = ReadmeReadFile; + LC_LangBegin(lang); + LC_DeclareNote(LC_ILit("do_something")); + LC_DeclareNote(LC_ILit("serialize")); + defer { LC_LangEnd(lang); }; + + LC_RegisterPackageDir("../pkgs"); + LC_Intern name = LC_ILit("readme_test"); + LC_AddSingleFilePackage(name, readme_path); + LC_ResolvePackageByName(name); + // LC_FindUnusedLocalsAndRemoveUnusedGlobalDecls(); + } + } +} diff --git a/src/build_file/testsuite.cpp b/src/build_file/testsuite.cpp new file mode 100644 index 0000000..503d023 --- /dev/null +++ b/src/build_file/testsuite.cpp @@ -0,0 +1,463 @@ + +enum TestResult { + OK, + Failed_Lex, + Failed_Parse, + Failed_Resolve, + Failed_CCompile, + Failed_Run, + Failed_Condition, + Failed_Package, +}; + +const char *TestResultString[] = { + "OK", + "Failed_Lex", + "Failed_Parse", + "Failed_Resolve", + "Failed_CCompile", + "Failed_Run", + "Failed_Condition", + "Failed_Package", +}; + +struct Test { + char *path; + bool msg_found[256]; + char *msg_expected[256]; + int msg_count; + TestResult expected_result; + bool dont_run; +}; + +struct Task { + bool do_run; + S8_String exe; + S8_String cmd; + Process process; +}; + +enum TestKind { + TestKind_File, + TestKind_Dir, +}; + +struct TestDesc { + TestKind kind; + S8_String absolute_path; + S8_String filename; + S8_String package_name; + bool dont_run; +}; + +TestResult Compile(S8_String name, S8_String file_to_compile) { + TestResult result = OK; + int errcode = 0; + Array tasks = {MA_GetAllocator(Perm)}; + + { + Task tcc = {}; + tcc.do_run = UseTCC; + tcc.exe = Fmt("%.*s/tcc_%.*s.exe", S8_Expand(name), S8_Expand(name)); + tcc.cmd = Fmt("tcc -std=c99 %.*s " IF_MAC("-lm") IF_LINUX("-lm") " -o %.*s", S8_Expand(file_to_compile), S8_Expand(tcc.exe)); + tasks.add(tcc); + + Task clang = {}; + clang.do_run = UseClang; + clang.exe = Fmt("%.*s/clang_%.*s.exe", S8_Expand(name), S8_Expand(name)); + clang.cmd = Fmt("clang -Wno-string-plus-int -g -std=c99 " IF_MAC("-lm") IF_LINUX("-lm") " %.*s -o %.*s", S8_Expand(file_to_compile), S8_Expand(clang.exe)); + tasks.add(clang); + + Task cl = {}; + cl.do_run = UseCL; + cl.exe = Fmt("%.*s/cl_%.*s.exe", S8_Expand(name), S8_Expand(name)); + cl.cmd = Fmt("cl %.*s -Zi -std:c11 -nologo /Fd:%.*s.pdb -FC -Fe:%.*s", S8_Expand(file_to_compile), S8_Expand(file_to_compile), S8_Expand(cl.exe)); + tasks.add(cl); + + Task gcc = {}; + gcc.do_run = UseGCC; + gcc.exe = Fmt("%.*s/gcc_%.*s.exe", S8_Expand(name), S8_Expand(name)); + gcc.cmd = Fmt("gcc -Wno-string-plus-int -g -std=c99 " IF_MAC("-lm") IF_LINUX("-lm") " %.*s -o %.*s", S8_Expand(file_to_compile), S8_Expand(gcc.exe)); + tasks.add(gcc); + } + + For(tasks) { + if (!it.do_run) continue; + errcode = Run(it.cmd); + if (errcode != 0) { + result = Failed_CCompile; + goto end_of_test; + } + it.exe = OS_GetAbsolutePath(Perm, it.exe); + } + + For(tasks) { + if (!it.do_run) continue; + it.process = RunEx(it.exe); + } + + For(tasks) { + if (!it.do_run) continue; + errcode += Wait(&it.process); + } + + if (errcode != 0) { + result = Failed_Run; + goto end_of_test; + } +end_of_test: + return result; +} + +thread_local Test *T; +thread_local Array Messages; + +void HandleOutputMessageGlobalTest(LC_Token *pos, char *str, int len) { + S8_String s = S8_Make(str, len); + s = S8_Trim(s); + + if (S8_StartsWith(s, S8_Lit("Executing: "), 0)) return; + if (S8_StartsWith(s, S8_Lit("> "), 0)) return; + if (T && T->msg_expected[0]) { + for (int i = 0; i < 256; i += 1) { + if (T->msg_expected[i] == 0) break; + + char *str = T->msg_expected[i]; + bool *found = T->msg_found + i; + if (!found[0]) { + S8_String expected = S8_MakeFromChar(str); + if (S8_Seek(s, expected, S8_FindFlag_IgnoreCase, NULL)) { + found[0] = true; + break; + } + } + } + } + + if (pos) s = S8_Format(Perm, "%s(%d,%d): error: %.*s\n", (char *)pos->lex->file, pos->line, pos->column, len, str); + Messages.add(S8_Copy(Perm, s)); +} + +TestResult PrintGlobalTestResult(char *path, TestResult result) { + const char *red = "\033[31m"; + const char *reset = "\033[0m"; + const char *green = "\033[32m"; + if (!UseColoredIO) { + red = ""; + reset = ""; + green = ""; + } + + TestResult actual_result = result; + if (result == T->expected_result) { + result = OK; + } else { + result = Failed_Condition; + } + + if (T->msg_expected[0]) { + bool all_found = true; + for (int i = 0; i < T->msg_count; i += 1) { + if (T->msg_expected[i] == 0) { + IO_Printf("%sCount of expected messages doesn't match expected messages%s\n", red, reset); + all_found = false; + break; + } + + if (!T->msg_found[i]) { + all_found = false; + } + } + + if (!all_found) { + result = Failed_Condition; + + for (int i = 0; i < 256; i += 1) { + char *str = T->msg_expected[i]; + if (str == 0) break; + + const char *color = green; + if (!T->msg_found[i]) color = red; + IO_Printf("%sMessage not found - %s%s\n", color, T->msg_expected[i], reset); + } + } + } + + if (T->msg_count != Messages.len) { + IO_Printf("%sCount of expected messages: %d doesn't match actual message count: %d%s\n", red, T->msg_count, Messages.len, reset); + result = Failed_Condition; + } + + const char *color = green; + if (result != OK) { + color = red; + IO_Printf("%-50s - %s Expected result: %s, got instead: %s%s\n", path, color, TestResultString[T->expected_result], TestResultString[actual_result], reset); + } else { + IO_Printf("%-50s - %s%s%s\n", path, color, TestResultString[result], reset); + } + + if (result != OK) { + For(Messages) IO_Printf("%.*s", S8_Expand(it)); + } + Messages.reset(); + return result; +} + +void ParseErrorNotationAndFillGlobalTest(S8_String s) { + S8_String count_lit = S8_Lit("// #expected_error_count: "); + S8_String errlit = S8_Lit("// #error: "); + S8_String resultlit = S8_Lit("// #failed: "); + S8_String dont_run_lit = S8_Lit("// #dont_run"); + S8_List errors = S8_Split(Perm, s, S8_Lit("\n"), 0); + S8_For(it, errors) { + if (S8_StartsWith(it->string, errlit, 0)) { + S8_String error = S8_Skip(it->string, errlit.len); + error = S8_Trim(error); + error = S8_Copy(Perm, error); + T->msg_expected[T->msg_count++] = error.str; + } + if (S8_StartsWith(it->string, resultlit, 0)) { + if (S8_Seek(it->string, S8_Lit("parse"), 0, 0)) { + T->expected_result = Failed_Parse; + } + if (S8_Seek(it->string, S8_Lit("resolve"), 0, 0)) { + T->expected_result = Failed_Resolve; + } + if (S8_Seek(it->string, S8_Lit("lex"), 0, 0)) { + T->expected_result = Failed_Lex; + } + if (S8_Seek(it->string, S8_Lit("package"), 0, 0)) { + T->expected_result = Failed_Package; + } + } + if (S8_StartsWith(it->string, count_lit, 0)) { + S8_String count = S8_Skip(it->string, count_lit.len); + count = S8_Copy(Perm, count); + T->msg_count = atoi(count.str); + } + if (S8_StartsWith(it->string, dont_run_lit, 0)) { + T->dont_run = true; + } + } +} + +S8_String PushDir(S8_String dir_name) { + S8_String prev = OS_GetWorkingDir(Perm); + OS_MakeDir(dir_name); + OS_SetWorkingDir(dir_name); + return prev; +} + +void RunTestFile(TestDesc it) { + LC_Lang *lang = LC_LangAlloc(); + lang->on_message = HandleOutputMessageGlobalTest; + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + LC_LangBegin(lang); + + Test test = {}; + test.dont_run = it.dont_run; + T = &test; + TestResult result = OK; + + S8_String s = OS_ReadFile(L->arena, it.absolute_path); + if (s.len == 0) { + IO_FatalErrorf("Failed to open file %.*s", S8_Expand(it.absolute_path)); + } + + ParseErrorNotationAndFillGlobalTest(s); + + S8_String code = {}; + S8_String out_path = {}; + + LC_RegisterPackageDir("../../pkgs"); + + LC_Intern name = LC_ILit("testing"); + LC_AddSingleFilePackage(name, it.absolute_path); + + L->first_package = name; + LC_ParsePackagesUsingRegistry(name); + if (L->errors) { + result = Failed_Parse; + goto end_of_test; + } + + LC_OrderAndResolveTopLevelDecls(name); + LC_ResolveAllProcBodies(); + LC_FindUnusedLocalsAndRemoveUnusedGlobalDecls(); + if (L->errors) { + result = Failed_Resolve; + goto end_of_test; + } + + DebugVerifyAST(L->ordered_packages); + + OS_MakeDir(it.filename); + code = LC_GenerateUnityBuild(L->ordered_packages); + out_path = S8_Format(L->arena, "%.*s/%.*s.c", S8_Expand(it.filename), S8_Expand(it.filename)); + OS_WriteFile(out_path, code); + + { + LC_BeginStringGen(L->arena); + LC_GenLCNode(L->ordered_packages.first->ast); + S8_String c = LC_EndStringGen(L->arena); + S8_String p = S8_Format(L->arena, "%.*s/%.*s.generated.lc", S8_Expand(it.filename), S8_Expand(it.filename)); + p = OS_GetAbsolutePath(L->arena, p); + OS_WriteFile(p, c); + LC_ParseFile(NULL, p.str, c.str, 0); + } + + if (!T->dont_run) result = Compile(it.filename, out_path); + +end_of_test: + result = PrintGlobalTestResult(it.filename.str, result); + LC_LangEnd(lang); +} + +void RunTestDir(TestDesc it, S8_String package_name) { + LC_Lang *lang = LC_LangAlloc(); + lang->on_message = HandleOutputMessageGlobalTest; + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + LC_LangBegin(lang); + + Test test = {}; + T = &test; + TestResult result = OK; + + S8_String path_to_test_file = S8_Format(L->arena, "%.*s/test.txt", S8_Expand(it.absolute_path)); + S8_String error_notation = OS_ReadFile(L->arena, path_to_test_file); + if (error_notation.str) ParseErrorNotationAndFillGlobalTest(error_notation); + + LC_Intern first_package = LC_ILit(package_name.str); + LC_RegisterPackageDir(it.absolute_path.str); + LC_RegisterPackageDir("../../pkgs"); + LC_ASTRefList packages = LC_ResolvePackageByName(first_package); + LC_FindUnusedLocalsAndRemoveUnusedGlobalDecls(); + if (L->errors != 0) result = Failed_Package; + + if (result == OK && T->expected_result == OK) { + DebugVerifyAST(packages); + + OS_MakeDir(it.filename); + S8_String code = LC_GenerateUnityBuild(packages); + S8_String out_path = S8_Format(L->arena, "%.*s/%.*s.c", S8_Expand(it.filename), S8_Expand(it.filename)); + OS_WriteFile(out_path, code); + if (!T->dont_run) result = Compile(it.filename, out_path); + } + + result = PrintGlobalTestResult(it.filename.str, result); + LC_LangEnd(lang); +} + +void TestThread(Array tests) { + MA_InitScratch(); + For(tests) { + if (it.kind == TestKind_Dir) { + RunTestDir(it, it.package_name); + } else if (it.kind == TestKind_File) { + RunTestFile(it); + } + } +} + +bool ShouldSkip(S8_String filename, bool is_directory = false) { + if (TestsToRun.first) { + bool found = false; + S8_For(match, TestsToRun) { + if (match->string == filename) { + found = true; + break; + } + } + if (!found) { + return true; + } + } + + if (is_directory) { + if (S8_StartsWith(filename, "example_", true) || S8_StartsWith(filename, "compilation", true)) + return true; + } + + return false; +} + +bool ShouldRun(S8_String filename) { + bool result = !ShouldSkip(filename, false); + return result; +} + +void RunTests() { + MA_Scratch scratch; + int test_count = 0; + S8_String working_dir = PushDir("test_result"); + + Array tests = {MA_GetAllocator(scratch)}; + + for (OS_FileIter it = OS_IterateFiles(scratch, S8_Lit("../../tests")); OS_IsValid(it); OS_Advance(&it)) { + if (ShouldSkip(it.filename, it.is_directory)) continue; + TestDesc desc = {it.is_directory ? TestKind_Dir : TestKind_File, it.absolute_path, it.filename, "main"}; + tests.add(desc); + } + + test_count = tests.len; + const int thread_count = ThreadCount; + Array> work = {MA_GetAllocator(scratch)}; + Array threads = {MA_GetAllocator(scratch)}; + + for (int i = 0; i < thread_count; i += 1) { + work.add({MA_GetAllocator(scratch)}); + } + + int i = 0; + For(tests) { + work[i].add(it); + i = (i + 1) % thread_count; + } + + For(work) threads.add(new std::thread(TestThread, it)); + For(threads) it->join(); + + // + // Non automated tests + // + if (ShouldRun("example_ui_and_hot_reloading")) { + test_count += 1; + TestResult result = OK; + Test t = {}; + t.path = OS_GetAbsolutePath(scratch, "../../tests/example_ui_and_hot_reloading/").str; + t.expected_result = OK; + T = &t; + + LC_Lang *lang = LC_LangAlloc(); + lang->on_message = HandleOutputMessageGlobalTest; + lang->use_colored_terminal_output = UseColoredIO; + lang->breakpoint_on_error = BreakpointOnError; + LC_LangBegin(lang); + LC_RegisterPackageDir(T->path); + LC_ASTRefList dll_packages = LC_ResolvePackageByName(LC_ILit("dll")); + LC_ASTRefList exe_packages = LC_ResolvePackageByName(LC_ILit("exe")); + result = L->errors >= 1 ? Failed_Package : OK; + + if (result == OK) { + DebugVerifyAST(dll_packages); + // DebugVerifyAST(exe_packages); + + S8_String prev = PushDir("example_ui_and_hot_reloading"); + S8_String code = LC_GenerateUnityBuild(exe_packages); + OS_WriteFile("example_ui_and_hot_reloading", code); + OS_SetWorkingDir(prev); + } + + LC_LangEnd(lang); + PrintGlobalTestResult("example_ui_and_hot_reloading", result); +#if 0 + OS_SystemF("clang unity_exe.c -o platform.exe -g -O0 -I\"../..\""); + OS_SystemF("clang unity_dll.c -o game.dll -O0 -shared -g -I\"../..\" -Wl,-export:APP_Update"); +#endif + } + + OS_SetWorkingDir(working_dir); + IO_Printf("Total test count = %d\n", test_count); +} diff --git a/src/build_tool/cache.cpp b/src/build_tool/cache.cpp new file mode 100644 index 0000000..0902057 --- /dev/null +++ b/src/build_tool/cache.cpp @@ -0,0 +1,127 @@ +#define SRC_CACHE_ENTRY_COUNT 1024 + +struct SRC_CacheEntry { + uint64_t filepath_hash; + uint64_t file_hash; + uint64_t includes_hash; + uint64_t total_hash; +}; + +struct SRC_Cache { + int entry_cap; + int entry_len; + SRC_CacheEntry entries[SRC_CACHE_ENTRY_COUNT]; +}; + +double SRC_Time; +SRC_Cache *SRC_InMemoryCache; +SRC_Cache *SRC_FromFileCache; +S8_String SRC_CacheFilename; +CL_SearchPaths SRC_SearchPaths = {}; // @todo; + +void SRC_InitCache(MA_Arena *arena, S8_String cachefilename) { + SRC_CacheFilename = cachefilename; + + SRC_InMemoryCache = MA_PushStruct(arena, SRC_Cache); + SRC_InMemoryCache->entry_cap = SRC_CACHE_ENTRY_COUNT; + + SRC_FromFileCache = MA_PushStruct(arena, SRC_Cache); + SRC_FromFileCache->entry_cap = SRC_CACHE_ENTRY_COUNT; + + S8_String cache = OS_ReadFile(arena, SRC_CacheFilename); + if (cache.len) MA_MemoryCopy(SRC_FromFileCache, cache.str, cache.len); +} + +void SRC_SaveCache() { + S8_String dump = S8_Make((char *)SRC_InMemoryCache, sizeof(SRC_Cache)); + OS_WriteFile(SRC_CacheFilename, dump); +} + +SRC_CacheEntry *SRC_AddHash(uint64_t filepath, uint64_t file, uint64_t includes) { + IO_Assert(SRC_InMemoryCache->entry_len + 1 < SRC_InMemoryCache->entry_cap); + SRC_CacheEntry *result = SRC_InMemoryCache->entries + SRC_InMemoryCache->entry_len++; + result->filepath_hash = filepath; + result->file_hash = file; + result->includes_hash = includes; + result->total_hash = HashBytes(result, sizeof(uint64_t) * 3); + return result; +} + +SRC_CacheEntry *SRC_FindCache(SRC_Cache *cache, uint64_t filepath_hash) { + for (int cache_i = 0; cache_i < cache->entry_len; cache_i += 1) { + SRC_CacheEntry *it = cache->entries + cache_i; + if (it->filepath_hash == filepath_hash) { + return it; + } + } + return 0; +} + +SRC_CacheEntry *SRC_HashFile(S8_String file, char *parent_file) { + char *resolved_file = CL_ResolveFilepath(Perm, &SRC_SearchPaths, file.str, parent_file, false); + if (!resolved_file) { + IO_Printf("Failed to resolve file: %.*s\n", S8_Expand(file)); + return 0; + } + + uint64_t filepath_hash = HashBytes(resolved_file, S8_Length(resolved_file)); + SRC_CacheEntry *entry = SRC_FindCache(SRC_InMemoryCache, filepath_hash); + if (entry) return entry; + + S8_String filecontent = OS_ReadFile(Perm, S8_MakeFromChar(resolved_file)); + IO_Assert(filecontent.str); + + uint64_t file_hash = HashBytes(filecontent.str, filecontent.len); + uint64_t includes_hash = 13; + + CL_Lexer lexer = CL_Begin(Perm, filecontent.str, resolved_file); + lexer.select_includes = true; + + for (CL_Token token = CL_Next(&lexer); token.kind != CL_EOF; token = CL_Next(&lexer)) { + if (token.is_system_include) continue; + + S8_String file_it = S8_MakeFromChar(token.string_literal); + SRC_CacheEntry *cache = SRC_HashFile(file_it, resolved_file); + if (!cache) { + // error was reported already IO_Printf("Missing cache for: %.*s\n", S8_Expand(file_it)); + continue; + } + + includes_hash = HashMix(includes_hash, cache->total_hash); + } + + SRC_CacheEntry *result = SRC_AddHash(filepath_hash, file_hash, includes_hash); + return result; +} + +bool SRC_WasModified(S8_String file, S8_String artifact_path) { + double time_start = OS_GetTime(); + + if (OS_FileExists(file) == false) { + IO_Printf("FAILED File doesnt exist: %.*s\n", S8_Expand(file)); + exit(0); + } + if (OS_IsAbsolute(file) == false) { + file = OS_GetAbsolutePath(Perm, file); + } + + S8_String without_ext = S8_ChopLastPeriod(file); + S8_String name_only = S8_SkipToLastSlash(without_ext); + + if (artifact_path.len == 0) artifact_path = S8_Format(Perm, "%.*s.%s", S8_Expand(name_only), IF_WINDOWS_ELSE("obj", "o")); + bool modified = OS_FileExists(artifact_path) == false; + + SRC_CacheEntry *in_memory = SRC_HashFile(file, 0); + IO_Assert(in_memory); + + if (modified == false) { + SRC_CacheEntry *from_file = SRC_FindCache(SRC_FromFileCache, in_memory->filepath_hash); + if (from_file == 0 || (in_memory->total_hash != from_file->total_hash)) { + modified = true; + } + } + + SRC_Time = SRC_Time + (OS_GetTime() - time_start); + + return modified; +} \ No newline at end of file diff --git a/src/build_tool/easy_strings.cpp b/src/build_tool/easy_strings.cpp new file mode 100644 index 0000000..12a698e --- /dev/null +++ b/src/build_tool/easy_strings.cpp @@ -0,0 +1,116 @@ +S8_String Fmt(const char *str, ...) S8__PrintfFormat(1, 2); + +Array operator+(Array a, Array b) { + Array c = a.copy(MA_GetAllocator(Perm)); + c.add_array(b); + return c; +} + +Array operator+(Array a, S8_String b) { + Array c = a.copy(MA_GetAllocator(Perm)); + c.add(b); + return c; +} + +Array operator+(S8_String a, Array b) { + Array c = b.copy(MA_GetAllocator(Perm)); + c.insert(a, 0); + return c; +} + +Array operator+(S8_String a, S8_String b) { + Array c = {MA_GetAllocator(Perm)}; + c.add(a); + c.add(b); + return c; +} + +Array &operator+=(Array &a, Array b) { + a.add_array(b); + return a; +} + +Array &operator+=(Array &a, S8_String s) { + a.add(s); + return a; +} + +//@todo: split on any whitespace instead! +Array Split(S8_String s, S8_String sep = " ") { + S8_List list = S8_Split(Perm, s, sep, 0); + Array result = {MA_GetAllocator(Perm)}; + S8_For(it, list) result.add(it->string); + return result; +} + +S8_String Merge(MA_Arena *arena, Array list, S8_String separator = " "_s) { + int64_t char_count = 0; + For(list) char_count += it.len; + if (char_count == 0) return {}; + int64_t node_count = list.len; + + int64_t base_size = (char_count + 1); + int64_t sep_size = (node_count - 1) * separator.len; + int64_t size = base_size + sep_size; + char *buff = (char *)MA_PushSize(arena, sizeof(char) * (size + 1)); + S8_String string = S8_Make(buff, 0); + For(list) { + IO_Assert(string.len + it.len <= size); + MA_MemoryCopy(string.str + string.len, it.str, it.len); + string.len += it.len; + if (!list.is_last(it)) { + MA_MemoryCopy(string.str + string.len, separator.str, separator.len); + string.len += separator.len; + } + } + IO_Assert(string.len == size - 1); + string.str[size] = 0; + return string; +} + +S8_String Merge(Array list, S8_String separator = " ") { + return Merge(Perm, list, separator); +} + +S8_String Fmt(const char *str, ...) { + S8_FORMAT(Perm, str, str_fmt); + return str_fmt; +} + +Array ListDir(char *dir) { + Array result = {MA_GetAllocator(Perm)}; + for (OS_FileIter it = OS_IterateFiles(Perm, S8_MakeFromChar(dir)); OS_IsValid(it); OS_Advance(&it)) { + result.add(S8_Copy(Perm, it.absolute_path)); + } + return result; +} + +Array CMD_Make(char **argv, int argc) { + Array result = {MA_GetAllocator(Perm)}; + for (int i = 1; i < argc; i += 1) { + S8_String it = S8_MakeFromChar(argv[i]); + result.add(it); + } + return result; +} + +S8_String CMD_Get(Array &cmd, S8_String name, S8_String default_value = "") { + For(cmd) { + int64_t idx = 0; + if (S8_Seek(it, "="_s, 0, &idx)) { + S8_String key = S8_GetPrefix(it, idx); + S8_String value = S8_Skip(it, idx + 1); + if (key == name) { + return value; + } + } + } + return default_value; +} + +bool CMD_Match(Array &cmd, S8_String name) { + For(cmd) { + if (it == name) return true; + } + return false; +} \ No newline at end of file diff --git a/src/build_tool/library.cpp b/src/build_tool/library.cpp new file mode 100644 index 0000000..061a41c --- /dev/null +++ b/src/build_tool/library.cpp @@ -0,0 +1,55 @@ +#ifndef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS +#endif + +#include "../core/core.c" + +#define CL_Allocator MA_Arena * +#define CL_Allocate(a, s) MA_PushSizeNonZeroed(a, s) +#define CL_ASSERT IO_Assert +#define CL_VSNPRINTF stbsp_vsnprintf +#define CL_SNPRINTF stbsp_snprintf +#define AND_CL_STRING_TERMINATE_ON_NEW_LINE +#include "../standalone_libraries/clexer.c" + +thread_local MA_Arena PernamentArena; +thread_local MA_Arena *Perm = &PernamentArena; + +#include "cache.cpp" +#include "easy_strings.cpp" +#include "process.cpp" + +S8_String CL_Flags = "/MP /Zi /FC /WX /W3 /wd4200 /diagnostics:column /nologo -D_CRT_SECURE_NO_WARNINGS /GF /Gm- /Oi"; +S8_String CL_Link = "/link /incremental:no"; +S8_String CL_StdOff = "/GR- /EHa-"; +S8_String CL_StdOn = "/EHsc"; +S8_String CL_Debug = "-Od -D_DEBUG -fsanitize=address -RTC1"; +S8_String CL_Release = "-O2 -MT -DNDEBUG -GL"; +S8_String CL_ReleaseLink = "-opt:ref -opt:icf"; +/* +/FC = Print full paths in diagnostics +/Gm- = Old feature, 'minimal compilation', in case it's not off by default +/GF = Pools strings as read-only. If you try to modify strings under /GF, an application error occurs. +/Oi = Replaces some function calls with intrinsic +/MP = Multithreaded compilation +/GR- = Disable runtime type information +/EHa- = Disable exceptions +/EHsc = Enable exceptions +/MT = Link static libc. The 'd' means debug version +/MD = Link dynamic libc. The 'd' means debug version +/GL = Whole program optimization +/RTC1 = runtime error checks +/opt:ref = eliminates functions and data that are never referenced +/opt:icf = eliminates redundant 'COMDAT's +*/ + +S8_String Clang_Flags = "-fdiagnostics-absolute-paths -Wno-writable-strings"; +S8_String Clang_NoStd = "-fno-exceptions"; +S8_String Clang_Debug = "-fsanitize=address -g"; +/* +-std=c++11 + */ + +S8_String GCC_Flags = "-Wno-write-strings"; +S8_String GCC_NoStd = "-fno-exceptions"; +S8_String GCC_Debug = "-fsanitize=address -g"; diff --git a/src/build_tool/main.cpp b/src/build_tool/main.cpp new file mode 100644 index 0000000..2d4b286 --- /dev/null +++ b/src/build_tool/main.cpp @@ -0,0 +1,90 @@ +#include "library.cpp" + +int main(int argument_count, char **arguments) { + MA_InitScratch(); + OS_MakeDir(S8_Lit("build")); + OS_SetWorkingDir(S8_Lit("build")); + S8_String working_dir = OS_GetWorkingDir(Perm); + IO_Printf("WORKING DIR: %.*s\n", S8_Expand(working_dir)); + + Array cmd = CMD_Make(arguments, argument_count); + S8_String cc = CMD_Get(cmd, "cc", IF_WINDOWS("cl") IF_MAC("clang") IF_LINUX("gcc")); + + // Search for build file in the project directory + S8_String build_file = {}; + { + for (OS_FileIter it = OS_IterateFiles(Perm, S8_Lit("..")); OS_IsValid(it); OS_Advance(&it)) { + if (S8_Seek(it.filename, S8_Lit("build_file.c"), S8_IgnoreCase)) { + build_file = it.absolute_path; + } + } + + if (build_file.str == 0) { + IO_Printf("Couldnt find build file in current dir: %.*s, exiting ... \n", S8_Expand(working_dir)); + IO_Printf("- Proper build file contains 'build_file.c' in it's name\n"); + IO_Printf("- Alternative compiler can be chosen like this: bld cc=clang\n"); + return 0; + } + } + + SRC_InitCache(Perm, "build_tool.cache"); + S8_String name_no_ext = S8_GetNameNoExt(build_file); + S8_String exe_name = S8_Format(Perm, "%.*s.exe", S8_Expand(name_no_ext)); + + // Compile the build file only if code changed + if (SRC_WasModified(build_file, exe_name)) { + double time = OS_GetTime(); + int result = 0; + if (cc == "cl") { + Array flags = {MA_GetAllocator(Perm)}; + flags += "-nologo -Zi"; + flags += "-WX -W3 -wd4200 -diagnostics:column"; + flags += Fmt("/Fe:%.*s /Fd:%.*s.pdb", S8_Expand(exe_name), S8_Expand(exe_name)); + result = Run(cc + build_file + flags); + } else if (cc == "clang") { + Array flags = {MA_GetAllocator(Perm)}; + cc = "clang++"; + + flags += "-std=c++11 -g"; + flags += "-fdiagnostics-absolute-paths"; + flags += "-Wno-writable-strings"; + flags += "-lm"; + flags += Fmt("-o %.*s", S8_Expand(exe_name)); + result = Run(cc + build_file + flags); + } else { + IO_Assert(cc == "gcc"); + cc = "g++"; + + Array flags = {MA_GetAllocator(Perm)}; + flags += "-std=c++11 -g"; + flags += "-Wno-write-strings"; + flags += "-lm"; + flags += Fmt("-o %.*s", S8_Expand(exe_name)); + result = Run(cc + build_file + flags); + } + + if (result != 0) { + IO_Printf("FAILED compilation of the build file!\n"); + OS_DeleteFile("build_tool.cache"); + return 1; + } + time = OS_GetTime() - time; + IO_Printf("TIME Build file compilation: %f\n", time); + } + + // Run the build file + double time = OS_GetTime(); + if (build_file.str) { + exe_name = OS_GetAbsolutePath(Perm, exe_name); + int result = Run(exe_name + cmd); + if (result != 0) { + IO_Printf("FAILED execution of the build file!\n"); + OS_DeleteFile("build_tool.cache"); + return 1; + } + } + + SRC_SaveCache(); + time = OS_GetTime() - time; + IO_Printf("TIME total build file execution: %f\n", time); +} diff --git a/src/build_tool/process.cpp b/src/build_tool/process.cpp new file mode 100644 index 0000000..47afcbf --- /dev/null +++ b/src/build_tool/process.cpp @@ -0,0 +1,153 @@ +struct Process { + bool is_valid; + char platform[32]; +}; + +#if OS_WINDOWS +Process RunEx(S8_String in_cmd) { + MA_Scratch scratch; + wchar_t *application_name = NULL; + wchar_t *cmd = S8_ToWidechar(scratch, in_cmd); + BOOL inherit_handles = FALSE; + DWORD creation_flags = 0; + void *enviroment = NULL; + wchar_t *working_dir = NULL; + STARTUPINFOW startup_info = {}; + startup_info.cb = sizeof(STARTUPINFOW); + Process result = {}; + IO_Assert(sizeof(result.platform) >= sizeof(PROCESS_INFORMATION)); + PROCESS_INFORMATION *process_info = (PROCESS_INFORMATION *)result.platform; + BOOL success = CreateProcessW(application_name, cmd, NULL, NULL, inherit_handles, creation_flags, enviroment, working_dir, &startup_info, process_info); + result.is_valid = true; + if (!success) { + result.is_valid = false; + + LPVOID lpMsgBuf; + DWORD dw = GetLastError(); + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); + LocalFree(lpMsgBuf); + + IO_FatalErrorf("Failed to create process \ncmd: %.*s\nwindows_message: %s", S8_Expand(in_cmd), lpMsgBuf); + } + return result; +} + +int Wait(Process *process) { + IO_Assert(process->is_valid); + PROCESS_INFORMATION *pi = (PROCESS_INFORMATION *)process->platform; + WaitForSingleObject(pi->hProcess, INFINITE); + + DWORD exit_code; + BOOL err = GetExitCodeProcess(pi->hProcess, &exit_code); + IO_Assert(err != 0); + + CloseHandle(pi->hProcess); + CloseHandle(pi->hThread); + process[0] = {}; + return (int)exit_code; +} +#else + #include + #include + +struct TH_UnixProcess { + pid_t pid; +}; + +extern char **environ; + +Process RunEx(S8_String cmd) { + MA_Scratch scratch; + Process result = {}; + IO_Assert(sizeof(result.platform) >= sizeof(TH_UnixProcess)); + TH_UnixProcess *u = (TH_UnixProcess *)result.platform; + + S8_String exec_file = cmd; + S8_String argv = ""; + int64_t pos; + if (S8_Seek(cmd, S8_Lit(" "), 0, &pos)) { + exec_file = S8_GetPrefix(cmd, pos); + argv = S8_Skip(cmd, pos + 1); + } + + exec_file = S8_Copy(scratch, exec_file); + + // Split string on whitespace and conform with argv format + Array args = {MA_GetAllocator(scratch)}; + { + args.add(exec_file.str); + for (int64_t i = 0; i < argv.len;) { + while (i < argv.len && CHAR_IsWhitespace(argv.str[i])) { + i += 1; + } + + S8_String word = {argv.str + i, 0}; + while (i < argv.len && !CHAR_IsWhitespace(argv.str[i])) { + word.len += 1; + i += 1; + } + word = S8_Copy(scratch, word); + args.add(word.str); + } + args.add(NULL); + } + + int err = posix_spawnp(&u->pid, exec_file.str, NULL, NULL, args.data, environ); + if (err == 0) { + result.is_valid = true; + } else { + perror("posix_spawnp error"); + IO_FatalErrorf("Failed to create process, cmd: %.*s", S8_Expand(cmd)); + } + + return result; +} + +int Wait(Process *process) { + if (!process->is_valid) return 1; + TH_UnixProcess *u = (TH_UnixProcess *)process->platform; + + int status = 0; + int pid = waitpid(u->pid, &status, 0); + IO_Assert(pid != -1); + + int result = 0; + if (WIFEXITED(status)) { + result = WEXITSTATUS(status); + } else { + result = 1; + } + + process[0] = {}; + return result; +} +#endif + +Process RunEx(Array s) { + S8_String cmd = Merge(s); + Process proc = RunEx(cmd); + return proc; +} + +Process RunEx(Array s, S8_String process_start_dir) { + OS_MakeDir(process_start_dir); + S8_String working_dir = OS_GetWorkingDir(Perm); + OS_SetWorkingDir(process_start_dir); + S8_String cmd = Merge(s); + Process proc = RunEx(cmd); + OS_SetWorkingDir(working_dir); + return proc; +} + +int Run(S8_String cmd) { + Process process = RunEx(cmd); + int result = Wait(&process); + return result; +} + +int Run(Array cmd) { + S8_String cmds = Merge(cmd); + int result = Run(cmds); + return result; +} diff --git a/src/compiler/arena.c b/src/compiler/arena.c new file mode 100644 index 0000000..33683ca --- /dev/null +++ b/src/compiler/arena.c @@ -0,0 +1,138 @@ +#if defined(LC_USE_ADDRESS_SANITIZER) + #include +#endif + +#if !defined(ASAN_POISON_MEMORY_REGION) + #define LC_ASAN_POISON_MEMORY_REGION(addr, size) ((void)(addr), (void)(size)) + #define LC_ASAN_UNPOISON_MEMORY_REGION(addr, size) ((void)(addr), (void)(size)) +#else + #define LC_ASAN_POISON_MEMORY_REGION(addr, size) ASAN_POISON_MEMORY_REGION(addr, size) + #define LC_ASAN_UNPOISON_MEMORY_REGION(addr, size) ASAN_UNPOISON_MEMORY_REGION(addr, size) +#endif + +#define LC_DEFAULT_RESERVE_SIZE LC_GIB(1) +#define LC_DEFAULT_ALIGNMENT 8 +#define LC_COMMIT_ADD_SIZE LC_MIB(4) + +LC_FUNCTION uint8_t *LC_V_AdvanceCommit(LC_VMemory *m, size_t *commit_size, size_t page_size) { + size_t aligned_up_commit = LC_AlignUp(*commit_size, page_size); + size_t to_be_total_commited_size = aligned_up_commit + m->commit; + size_t to_be_total_commited_size_clamped_to_reserve = LC_CLAMP_TOP(to_be_total_commited_size, m->reserve); + size_t adjusted_to_boundary_commit = to_be_total_commited_size_clamped_to_reserve - m->commit; + LC_Assertf(adjusted_to_boundary_commit, "Reached the virtual memory reserved boundary"); + *commit_size = adjusted_to_boundary_commit; + + if (adjusted_to_boundary_commit == 0) { + return 0; + } + uint8_t *result = m->data + m->commit; + return result; +} + +LC_FUNCTION void LC_PopToPos(LC_Arena *arena, size_t pos) { + LC_Assertf(arena->len >= arena->base_len, "Bug: arena->len shouldn't ever be smaller then arena->base_len"); + pos = LC_CLAMP(pos, arena->base_len, arena->len); + size_t size = arena->len - pos; + arena->len = pos; + LC_ASAN_POISON_MEMORY_REGION(arena->memory.data + arena->len, size); +} + +LC_FUNCTION void LC_PopSize(LC_Arena *arena, size_t size) { + LC_PopToPos(arena, arena->len - size); +} + +LC_FUNCTION void LC_DeallocateArena(LC_Arena *arena) { + LC_VDeallocate(&arena->memory); +} + +LC_FUNCTION void LC_ResetArena(LC_Arena *arena) { + LC_PopToPos(arena, 0); +} + +LC_FUNCTION size_t LC__AlignLen(LC_Arena *a) { + size_t align_offset = a->alignment ? LC_GetAlignOffset((uintptr_t)a->memory.data + (uintptr_t)a->len, a->alignment) : 0; + size_t aligned = a->len + align_offset; + return aligned; +} + +LC_FUNCTION void *LC__PushSizeNonZeroed(LC_Arena *a, size_t size) { + size_t align_offset = a->alignment ? LC_GetAlignOffset((uintptr_t)a->memory.data + (uintptr_t)a->len, a->alignment) : 0; + size_t aligned_len = a->len + align_offset; + size_t size_with_alignment = size + align_offset; + + if (a->len + size_with_alignment > a->memory.commit) { + if (a->memory.reserve == 0) { + LC_Assertf(0, "Pushing on uninitialized arena with zero initialization turned off"); + } + bool result = LC_VCommit(&a->memory, size_with_alignment + LC_COMMIT_ADD_SIZE); + LC_Assertf(result, "%s(%d): Failed to commit memory more memory! reserve: %zu commit: %zu len: %zu size_with_alignment: %zu", LC_BeginTempdSourceLoc.file, LC_BeginTempdSourceLoc.line, a->memory.reserve, a->memory.commit, a->len, size_with_alignment); + (void)result; + } + + uint8_t *result = a->memory.data + aligned_len; + a->len += size_with_alignment; + LC_Assertf(a->len <= a->memory.commit, "%s(%d): Reached commit boundary! reserve: %zu commit: %zu len: %zu base_len: %zu alignment: %d size_with_alignment: %zu", LC_BeginTempdSourceLoc.file, LC_BeginTempdSourceLoc.line, a->memory.reserve, a->memory.commit, a->len, a->base_len, a->alignment, size_with_alignment); + LC_ASAN_UNPOISON_MEMORY_REGION(result, size); + return (void *)result; +} + +LC_FUNCTION void *LC__PushSize(LC_Arena *arena, size_t size) { + void *result = LC__PushSizeNonZeroed(arena, size); + LC_MemoryZero(result, size); + return result; +} + +LC_FUNCTION LC_Arena LC_PushArena(LC_Arena *arena, size_t size) { + LC_Arena result; + LC_MemoryZero(&result, sizeof(result)); + result.memory.data = LC_PushArrayNonZeroed(arena, uint8_t, size); + result.memory.commit = size; + result.memory.reserve = size; + result.alignment = arena->alignment; + return result; +} + +LC_FUNCTION LC_Arena *LC_PushArenaP(LC_Arena *arena, size_t size) { + LC_Arena *result = LC_PushStruct(arena, LC_Arena); + *result = LC_PushArena(arena, size); + return result; +} + +LC_FUNCTION void LC_InitArenaEx(LC_Arena *a, size_t reserve) { + a->memory = LC_VReserve(reserve); + LC_ASAN_POISON_MEMORY_REGION(a->memory.data, a->memory.reserve); + a->alignment = LC_DEFAULT_ALIGNMENT; +} + +LC_FUNCTION void LC_InitArena(LC_Arena *a) { + LC_InitArenaEx(a, LC_DEFAULT_RESERVE_SIZE); +} + +LC_FUNCTION LC_Arena *LC_BootstrapArena(void) { + LC_Arena bootstrap_arena = {0}; + LC_InitArena(&bootstrap_arena); + + LC_Arena *arena = LC_PushStruct(&bootstrap_arena, LC_Arena); + *arena = bootstrap_arena; + arena->base_len = arena->len; + return arena; +} + +LC_FUNCTION void LC_InitArenaFromBuffer(LC_Arena *arena, void *buffer, size_t size) { + arena->memory.data = (uint8_t *)buffer; + arena->memory.commit = size; + arena->memory.reserve = size; + arena->alignment = LC_DEFAULT_ALIGNMENT; + LC_ASAN_POISON_MEMORY_REGION(arena->memory.data, arena->memory.reserve); +} + +LC_FUNCTION LC_TempArena LC_BeginTemp(LC_Arena *arena) { + LC_TempArena result; + result.pos = arena->len; + result.arena = arena; + return result; +} + +LC_FUNCTION void LC_EndTemp(LC_TempArena checkpoint) { + LC_PopToPos(checkpoint.arena, checkpoint.pos); +} \ No newline at end of file diff --git a/src/compiler/ast.c b/src/compiler/ast.c new file mode 100644 index 0000000..e3a59e1 --- /dev/null +++ b/src/compiler/ast.c @@ -0,0 +1,167 @@ +LC_FUNCTION LC_AST *LC_CreateAST(LC_Token *pos, LC_ASTKind kind) { + LC_AST *n = LC_PushStruct(L->ast_arena, LC_AST); + n->id = ++L->ast_count; + n->kind = kind; + n->pos = pos; + if (L->parser == &L->quick_parser) n->pos = &L->BuiltinToken; + return n; +} + +LC_FUNCTION LC_AST *LC_CreateUnary(LC_Token *pos, LC_TokenKind op, LC_AST *expr) { + LC_AST *r = LC_CreateAST(pos, LC_ASTKind_ExprUnary); + r->eunary.op = op; + r->eunary.expr = expr; + return r; +} + +LC_FUNCTION LC_AST *LC_CreateBinary(LC_Token *pos, LC_AST *left, LC_AST *right, LC_TokenKind op) { + LC_AST *r = LC_CreateAST(pos, LC_ASTKind_ExprBinary); + r->ebinary.op = op; + r->ebinary.left = left; + r->ebinary.right = right; + return r; +} + +LC_FUNCTION LC_AST *LC_CreateIndex(LC_Token *pos, LC_AST *left, LC_AST *index) { + LC_AST *r = LC_CreateAST(pos, LC_ASTKind_ExprIndex); + r->eindex.index = index; + r->eindex.base = left; + return r; +} + +LC_FUNCTION void LC_SetPointerSizeAndAlign(int size, int align) { + L->pointer_align = align; + L->pointer_size = size; + if (L->tpvoid) { + L->tpvoid->size = size; + L->tpvoid->align = align; + } + if (L->tpchar) { + L->tpchar->size = size; + L->tpchar->align = align; + } +} + +LC_FUNCTION LC_Type *LC_CreateType(LC_TypeKind kind) { + LC_Type *r = LC_PushStruct(L->type_arena, LC_Type); + L->type_count += 1; + r->kind = kind; + r->id = ++L->typeids; + if (r->kind == LC_TypeKind_Proc || r->kind == LC_TypeKind_Pointer) { + r->size = L->pointer_size; + r->align = L->pointer_align; + r->is_unsigned = true; + } + return r; +} + +LC_FUNCTION LC_Type *LC_CreateTypedef(LC_Decl *decl, LC_Type *base) { + LC_Type *n = LC_CreateType(base->kind); + *n = *base; + decl->typedef_renamed_type_decl = base->decl; + n->decl = decl; + return n; +} + +LC_FUNCTION LC_Type *LC_CreatePointerType(LC_Type *type) { + uint64_t key = (uint64_t)type; + LC_Type *entry = (LC_Type *)LC_MapGetU64(&L->type_map, key); + if (entry) { + return entry; + } + LC_Type *n = LC_CreateType(LC_TypeKind_Pointer); + n->tbase = type; + LC_MapInsertU64(&L->type_map, key, n); + return n; +} + +LC_FUNCTION LC_Type *LC_CreateArrayType(LC_Type *type, int size) { + uint64_t size_key = LC_HashBytes(&size, sizeof(size)); + uint64_t type_key = LC_HashBytes(type, sizeof(*type)); + uint64_t key = LC_HashMix(size_key, type_key); + LC_Type *entry = (LC_Type *)LC_MapGetU64(&L->type_map, key); + if (entry) { + return entry; + } + LC_Type *n = LC_CreateType(LC_TypeKind_Array); + n->tbase = type; + n->tarray.size = size; + n->size = type->size * size; + n->align = type->align; + LC_MapInsertU64(&L->type_map, key, n); + return n; +} + +LC_FUNCTION LC_Type *LC_CreateProcType(LC_TypeMemberList args, LC_Type *ret, bool has_vargs, bool has_vargs_any_promotion) { + LC_ASSERT(NULL, ret); + uint64_t key = LC_HashBytes(ret, sizeof(*ret)); + key = LC_HashMix(key, LC_HashBytes(&has_vargs, sizeof(has_vargs))); + key = LC_HashMix(key, LC_HashBytes(&has_vargs_any_promotion, sizeof(has_vargs_any_promotion))); + int procarg_count = 0; + LC_TypeFor(it, args.first) { + key = LC_HashMix(LC_HashBytes(it->type, sizeof(it->type[0])), key); + key = LC_HashMix(LC_HashBytes((char *)it->name, LC_StrLen((char *)it->name)), key); + if (it->default_value_expr) { + key = LC_HashMix(LC_HashBytes(&it->default_value_expr, sizeof(LC_AST *)), key); + } + procarg_count += 1; + } + LC_Type *n = (LC_Type *)LC_MapGetU64(&L->type_map, key); + if (n) return n; + + n = LC_CreateType(LC_TypeKind_Proc); + n->tproc.args = args; + n->tproc.vargs = has_vargs; + n->tproc.vargs_any_promotion = has_vargs_any_promotion; + n->tproc.ret = ret; + LC_MapInsertU64(&L->type_map, key, n); + return n; +} + +LC_FUNCTION LC_Type *LC_CreateIncompleteType(LC_Decl *decl) { + LC_Type *n = LC_CreateType(LC_TypeKind_Incomplete); + n->decl = decl; + return n; +} + +LC_FUNCTION LC_Type *LC_CreateUntypedIntEx(LC_Type *base, LC_Decl *decl) { + uint64_t hash_base = LC_HashBytes(base, sizeof(*base)); + uint64_t untyped_int = LC_TypeKind_UntypedInt; + uint64_t key = LC_HashMix(hash_base, untyped_int); + LC_Type *n = (LC_Type *)LC_MapGetU64(&L->type_map, key); + if (n) return n; + + n = LC_CreateType(LC_TypeKind_UntypedInt); + n->tbase = base; + n->decl = decl; + return n; +} + +LC_FUNCTION LC_Type *LC_CreateUntypedInt(LC_Type *base) { + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Type, LC_ILit("UntypedInt"), &L->NullAST); + LC_Type *n = LC_CreateUntypedIntEx(base, decl); + return n; +} + +LC_FUNCTION LC_TypeMember *LC_AddTypeToList(LC_TypeMemberList *list, LC_Intern name, LC_Type *type, LC_AST *ast) { + LC_TypeFor(it, list->first) { + if (name == it->name) { + return NULL; + } + } + + LC_TypeMember *r = LC_PushStruct(L->arena, LC_TypeMember); + r->name = name; + r->type = type; + r->ast = ast; + LC_DLLAdd(list->first, list->last, r); + list->count += 1; + return r; +} + +LC_FUNCTION LC_Type *LC_StripPointer(LC_Type *type) { + if (type->kind == LC_TypeKind_Pointer) { + return type->tbase; + } + return type; +} diff --git a/src/compiler/ast_copy.c b/src/compiler/ast_copy.c new file mode 100644 index 0000000..5bd804e --- /dev/null +++ b/src/compiler/ast_copy.c @@ -0,0 +1,283 @@ +LC_FUNCTION LC_AST *LC_CopyAST(LC_Arena *arena, LC_AST *n) { + if (n == NULL) return NULL; + + LC_AST *result = LC_PushStruct(arena, LC_AST); + result->kind = n->kind; + result->id = ++L->ast_count; + result->notes = LC_CopyAST(arena, n->notes); + result->pos = n->pos; + + switch (n->kind) { + case LC_ASTKind_File: { + result->afile.x = n->afile.x; + + LC_ASTFor(it, n->afile.fimport) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->afile.fimport, result->afile.limport, it_copy); + } + LC_ASTFor(it, n->afile.fdecl) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->afile.fdecl, result->afile.ldecl, it_copy); + } + LC_ASTFor(it, n->afile.fdiscarded) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->afile.fdiscarded, result->afile.ldiscarded, it_copy); + } + + result->afile.build_if = n->afile.build_if; + } break; + + case LC_ASTKind_DeclProc: { + result->dbase.name = n->dbase.name; + result->dproc.body = LC_CopyAST(arena, n->dproc.body); + result->dproc.type = LC_CopyAST(arena, n->dproc.type); + } break; + + case LC_ASTKind_NoteList: { + LC_ASTFor(it, n->anote_list.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->anote_list.first, result->anote_list.last, it_copy); + } + } break; + + case LC_ASTKind_TypespecAggMem: + case LC_ASTKind_TypespecProcArg: { + result->tproc_arg.name = n->tproc_arg.name; + result->tproc_arg.type = LC_CopyAST(arena, n->tproc_arg.type); + result->tproc_arg.expr = LC_CopyAST(arena, n->tproc_arg.expr); + } break; + + case LC_ASTKind_ExprNote: { + result->enote.expr = LC_CopyAST(arena, n->enote.expr); + } break; + + case LC_ASTKind_StmtSwitch: { + LC_ASTFor(it, n->sswitch.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->sswitch.first, result->sswitch.last, it_copy); + } + result->sswitch.total_switch_case_count = n->sswitch.total_switch_case_count; + result->sswitch.expr = LC_CopyAST(arena, n->sswitch.expr); + } break; + + case LC_ASTKind_StmtSwitchCase: { + LC_ASTFor(it, n->scase.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->scase.first, result->scase.last, it_copy); + } + result->scase.body = LC_CopyAST(arena, n->scase.body); + } break; + + case LC_ASTKind_StmtSwitchDefault: { + LC_ASTFor(it, n->scase.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->scase.first, result->scase.last, it_copy); + } + result->scase.body = LC_CopyAST(arena, n->scase.body); + } break; + + case LC_ASTKind_StmtIf: { + LC_ASTFor(it, n->sif.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->sswitch.first, result->sswitch.last, it_copy); + } + result->sif.expr = LC_CopyAST(arena, n->sif.expr); + result->sif.body = LC_CopyAST(arena, n->sif.body); + } break; + + case LC_ASTKind_StmtElse: + case LC_ASTKind_StmtElseIf: { + result->sif.expr = LC_CopyAST(arena, n->sif.expr); + result->sif.body = LC_CopyAST(arena, n->sif.body); + } break; + + case LC_ASTKind_GlobImport: { + result->gimport.name = n->gimport.name; + result->gimport.path = n->gimport.path; + } break; + + case LC_ASTKind_DeclNote: { + result->dnote.expr = LC_CopyAST(arena, n->dnote.expr); + } break; + + case LC_ASTKind_DeclUnion: + case LC_ASTKind_DeclStruct: { + result->dbase.name = n->dbase.name; + LC_ASTFor(it, n->dagg.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->dagg.first, result->dagg.last, it_copy); + } + } break; + + case LC_ASTKind_DeclVar: { + result->dbase.name = n->dbase.name; + result->dvar.type = LC_CopyAST(arena, n->dvar.type); + result->dvar.expr = LC_CopyAST(arena, n->dvar.expr); + } break; + + case LC_ASTKind_DeclConst: { + result->dbase.name = n->dbase.name; + result->dconst.expr = LC_CopyAST(arena, n->dconst.expr); + } break; + + case LC_ASTKind_DeclTypedef: { + result->dbase.name = n->dbase.name; + result->dtypedef.type = LC_CopyAST(arena, n->dtypedef.type); + } break; + + case LC_ASTKind_ExprField: + case LC_ASTKind_TypespecField: { + result->efield.left = LC_CopyAST(arena, n->efield.left); + result->efield.right = n->efield.right; + } break; + + case LC_ASTKind_TypespecIdent: { + result->eident.name = n->eident.name; + } break; + + case LC_ASTKind_TypespecPointer: { + result->tpointer.base = LC_CopyAST(arena, n->tpointer.base); + } break; + + case LC_ASTKind_TypespecArray: { + result->tarray.base = LC_CopyAST(arena, n->tarray.base); + result->tarray.index = LC_CopyAST(arena, n->tarray.index); + } break; + + case LC_ASTKind_TypespecProc: { + LC_ASTFor(it, n->tproc.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->tproc.first, result->tproc.last, it_copy); + } + result->tproc.ret = LC_CopyAST(arena, n->tproc.ret); + result->tproc.vargs = n->tproc.vargs; + } break; + + case LC_ASTKind_StmtBlock: { + LC_ASTFor(it, n->sblock.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->sblock.first, result->sblock.last, it_copy); + + if (it_copy->kind == LC_ASTKind_StmtDefer) { + LC_SLLStackAddMod(result->sblock.first_defer, it_copy, sdefer.next); + } + } + if (n->sblock.first_defer) { + LC_ASSERT(result, result->sblock.first_defer); + } + result->sblock.kind = n->sblock.kind; + result->sblock.name = n->sblock.name; + } break; + + case LC_ASTKind_StmtNote: { + result->snote.expr = LC_CopyAST(arena, n->snote.expr); + } break; + + case LC_ASTKind_StmtReturn: { + result->sreturn.expr = LC_CopyAST(arena, n->sreturn.expr); + } break; + + case LC_ASTKind_StmtBreak: { + result->sbreak.name = n->sbreak.name; + } break; + + case LC_ASTKind_StmtContinue: { + result->scontinue.name = n->scontinue.name; + } break; + + case LC_ASTKind_StmtDefer: { + result->sdefer.body = LC_CopyAST(arena, n->sdefer.body); + } break; + + case LC_ASTKind_StmtFor: { + result->sfor.init = LC_CopyAST(arena, n->sfor.init); + result->sfor.cond = LC_CopyAST(arena, n->sfor.cond); + result->sfor.inc = LC_CopyAST(arena, n->sfor.inc); + result->sfor.body = LC_CopyAST(arena, n->sfor.body); + } break; + + case LC_ASTKind_StmtAssign: { + result->sassign.op = n->sassign.op; + result->sassign.left = LC_CopyAST(arena, n->sassign.left); + result->sassign.right = LC_CopyAST(arena, n->sassign.right); + } break; + + case LC_ASTKind_StmtExpr: { + result->sexpr.expr = LC_CopyAST(arena, n->sexpr.expr); + } break; + + case LC_ASTKind_StmtVar: { + result->svar.type = LC_CopyAST(arena, n->svar.type); + result->svar.expr = LC_CopyAST(arena, n->svar.expr); + result->svar.name = n->svar.name; + } break; + + case LC_ASTKind_StmtConst: { + result->sconst.expr = LC_CopyAST(arena, n->sconst.expr); + result->sconst.name = n->sconst.name; + } break; + + case LC_ASTKind_ExprIdent: { + result->eident.name = n->eident.name; + } break; + + case LC_ASTKind_ExprBool: + case LC_ASTKind_ExprFloat: + case LC_ASTKind_ExprInt: + case LC_ASTKind_ExprString: { + result->eatom = n->eatom; + } break; + + case LC_ASTKind_ExprType: { + result->etype.type = LC_CopyAST(arena, n->etype.type); + } break; + + case LC_ASTKind_ExprAddPtr: + case LC_ASTKind_ExprBinary: { + result->ebinary.op = n->ebinary.op; + result->ebinary.left = LC_CopyAST(arena, n->ebinary.left); + result->ebinary.right = LC_CopyAST(arena, n->ebinary.right); + } break; + + case LC_ASTKind_ExprGetPointerOfValue: + case LC_ASTKind_ExprGetValueOfPointer: + case LC_ASTKind_ExprUnary: { + result->eunary.op = n->eunary.op; + result->eunary.expr = LC_CopyAST(arena, n->eunary.expr); + } break; + + case LC_ASTKind_ExprCompoundItem: + case LC_ASTKind_ExprCallItem: { + result->ecompo_item.name = n->ecompo_item.name; + result->ecompo_item.index = LC_CopyAST(arena, n->ecompo_item.index); + result->ecompo_item.expr = LC_CopyAST(arena, n->ecompo_item.expr); + } break; + + case LC_ASTKind_ExprBuiltin: + case LC_ASTKind_Note: + case LC_ASTKind_ExprCall: + case LC_ASTKind_ExprCompound: { + LC_ASTFor(it, n->ecompo.first) { + LC_AST *it_copy = LC_CopyAST(arena, it); + LC_DLLAdd(result->ecompo.first, result->ecompo.last, it_copy); + } + + result->ecompo.size = n->ecompo.size; + result->ecompo.name = LC_CopyAST(arena, n->ecompo.name); + } break; + + case LC_ASTKind_ExprCast: { + result->ecast.type = LC_CopyAST(arena, n->ecast.type); + result->ecast.expr = LC_CopyAST(arena, n->ecast.expr); + } break; + + case LC_ASTKind_ExprIndex: { + result->eindex.index = LC_CopyAST(arena, n->eindex.index); + result->eindex.base = LC_CopyAST(arena, n->eindex.base); + } break; + + default: LC_ReportASTError(n, "internal compiler error: failed to LC_CopyAST, got invalid ast kind: %s", LC_ASTKindToString(n->kind)); + } + + return result; +} diff --git a/src/compiler/ast_walk.c b/src/compiler/ast_walk.c new file mode 100644 index 0000000..3fe01ce --- /dev/null +++ b/src/compiler/ast_walk.c @@ -0,0 +1,316 @@ +LC_FUNCTION void LC_ReserveAST(LC_ASTArray *stack, int size) { + if (size > stack->cap) { + LC_AST **new_stack = LC_PushArray(stack->arena, LC_AST *, size); + + LC_MemoryCopy(new_stack, stack->data, stack->len * sizeof(LC_AST *)); + stack->data = new_stack; + stack->cap = size; + } +} + +LC_FUNCTION void LC_PushAST(LC_ASTArray *stack, LC_AST *ast) { + LC_ASSERT(NULL, stack->len <= stack->cap); + LC_ASSERT(NULL, stack->arena); + if (stack->len == stack->cap) { + int new_cap = stack->cap < 16 ? 16 : stack->cap * 2; + LC_AST **new_stack = LC_PushArray(stack->arena, LC_AST *, new_cap); + + LC_MemoryCopy(new_stack, stack->data, stack->len * sizeof(LC_AST *)); + stack->data = new_stack; + stack->cap = new_cap; + } + stack->data[stack->len++] = ast; +} + +LC_FUNCTION void LC_PopAST(LC_ASTArray *stack) { + LC_ASSERT(NULL, stack->arena); + LC_ASSERT(NULL, stack->len > 0); + stack->len -= 1; +} + +LC_FUNCTION LC_AST *LC_GetLastAST(LC_ASTArray *arr) { + LC_ASSERT(NULL, arr->len > 0); + LC_AST *result = arr->data[arr->len - 1]; + return result; +} + +LC_FUNCTION void LC_WalkAST(LC_ASTWalker *ctx, LC_AST *n) { + if (!ctx->depth_first) { + ctx->proc(ctx, n); + } + + if (ctx->dont_recurse) { + ctx->dont_recurse = false; + return; + } + + LC_PushAST(&ctx->stack, n); + switch (n->kind) { + case LC_ASTKind_TypespecIdent: + case LC_ASTKind_ExprIdent: + case LC_ASTKind_ExprString: + case LC_ASTKind_ExprInt: + case LC_ASTKind_ExprFloat: + case LC_ASTKind_GlobImport: + case LC_ASTKind_ExprBool: + case LC_ASTKind_StmtBreak: + case LC_ASTKind_StmtContinue: break; + + case LC_ASTKind_Package: { + LC_ASTFor(it, n->apackage.ffile) LC_WalkAST(ctx, it); + + ctx->inside_discarded += 1; + if (ctx->visit_discarded) LC_ASTFor(it, n->apackage.fdiscarded) LC_WalkAST(ctx, it); + ctx->inside_discarded -= 1; + } break; + + case LC_ASTKind_File: { + LC_ASTFor(it, n->afile.fimport) LC_WalkAST(ctx, it); + LC_ASTFor(it, n->afile.fdecl) { + if (ctx->visit_notes == false && it->kind == LC_ASTKind_DeclNote) continue; + LC_WalkAST(ctx, it); + } + + ctx->inside_discarded += 1; + if (ctx->visit_discarded) LC_ASTFor(it, n->afile.fdiscarded) LC_WalkAST(ctx, it); + ctx->inside_discarded -= 1; + } break; + + case LC_ASTKind_DeclProc: { + LC_WalkAST(ctx, n->dproc.type); + if (n->dproc.body) LC_WalkAST(ctx, n->dproc.body); + } break; + case LC_ASTKind_NoteList: { + if (ctx->visit_notes) LC_ASTFor(it, n->anote_list.first) LC_WalkAST(ctx, it); + } break; + case LC_ASTKind_TypespecProcArg: { + LC_WalkAST(ctx, n->tproc_arg.type); + if (n->tproc_arg.expr) LC_WalkAST(ctx, n->tproc_arg.expr); + } break; + case LC_ASTKind_TypespecAggMem: { + LC_WalkAST(ctx, n->tproc_arg.type); + } break; + + case LC_ASTKind_ExprNote: { + ctx->inside_note += 1; + if (ctx->visit_notes) LC_WalkAST(ctx, n->enote.expr); + ctx->inside_note -= 1; + } break; + + case LC_ASTKind_StmtSwitch: { + LC_WalkAST(ctx, n->sswitch.expr); + LC_ASTFor(it, n->sswitch.first) LC_WalkAST(ctx, it); + } break; + + case LC_ASTKind_StmtSwitchCase: { + LC_ASTFor(it, n->scase.first) LC_WalkAST(ctx, it); + LC_WalkAST(ctx, n->scase.body); + } break; + case LC_ASTKind_StmtSwitchDefault: { + LC_ASTFor(it, n->scase.first) LC_WalkAST(ctx, it); + LC_WalkAST(ctx, n->scase.body); + } break; + + case LC_ASTKind_StmtIf: { + LC_WalkAST(ctx, n->sif.expr); + LC_WalkAST(ctx, n->sif.body); + LC_ASTFor(it, n->sif.first) LC_WalkAST(ctx, it); + } break; + case LC_ASTKind_StmtElse: + case LC_ASTKind_StmtElseIf: { + if (n->sif.expr) LC_WalkAST(ctx, n->sif.expr); + LC_WalkAST(ctx, n->sif.body); + } break; + + case LC_ASTKind_DeclNote: { + ctx->inside_note += 1; + if (ctx->visit_notes) LC_WalkAST(ctx, n->dnote.expr); + ctx->inside_note -= 1; + } break; + case LC_ASTKind_DeclUnion: + case LC_ASTKind_DeclStruct: { + LC_ASTFor(it, n->dagg.first) LC_WalkAST(ctx, it); + } break; + + case LC_ASTKind_DeclVar: { + if (n->dvar.type) LC_WalkAST(ctx, n->dvar.type); + if (n->dvar.expr) LC_WalkAST(ctx, n->dvar.expr); + } break; + case LC_ASTKind_DeclConst: { + if (n->dconst.expr) LC_WalkAST(ctx, n->dconst.expr); + } break; + case LC_ASTKind_DeclTypedef: { + LC_WalkAST(ctx, n->dtypedef.type); + } break; + case LC_ASTKind_TypespecField: { + LC_WalkAST(ctx, n->efield.left); + } break; + + case LC_ASTKind_TypespecPointer: { + LC_WalkAST(ctx, n->tpointer.base); + } break; + case LC_ASTKind_TypespecArray: { + LC_WalkAST(ctx, n->tarray.base); + if (n->tarray.index) LC_WalkAST(ctx, n->tarray.index); + } break; + case LC_ASTKind_TypespecProc: { + LC_ASTFor(it, n->tproc.first) LC_WalkAST(ctx, it); + if (n->tproc.ret) LC_WalkAST(ctx, n->tproc.ret); + } break; + case LC_ASTKind_StmtBlock: { + LC_ASTFor(it, n->sblock.first) LC_WalkAST(ctx, it); + // hmm should we inline defers or maybe remove them from + // the stmt list? + // LC_ASTFor(it, n->sblock.first_defer) LC_WalkAST(ctx, it); + } break; + + case LC_ASTKind_StmtNote: { + ctx->inside_note += 1; + if (ctx->visit_notes) LC_WalkAST(ctx, n->snote.expr); + ctx->inside_note -= 1; + } break; + case LC_ASTKind_StmtReturn: { + if (n->sreturn.expr) LC_WalkAST(ctx, n->sreturn.expr); + } break; + + case LC_ASTKind_StmtDefer: { + LC_WalkAST(ctx, n->sdefer.body); + } break; + case LC_ASTKind_StmtFor: { + if (n->sfor.init) LC_WalkAST(ctx, n->sfor.init); + if (n->sfor.cond) LC_WalkAST(ctx, n->sfor.cond); + if (n->sfor.inc) LC_WalkAST(ctx, n->sfor.inc); + LC_WalkAST(ctx, n->sfor.body); + } break; + + case LC_ASTKind_StmtAssign: { + LC_WalkAST(ctx, n->sassign.left); + LC_WalkAST(ctx, n->sassign.right); + } break; + case LC_ASTKind_StmtExpr: { + LC_WalkAST(ctx, n->sexpr.expr); + } break; + case LC_ASTKind_StmtVar: { + if (n->svar.type) LC_WalkAST(ctx, n->svar.type); + if (n->svar.expr) LC_WalkAST(ctx, n->svar.expr); + } break; + case LC_ASTKind_StmtConst: { + LC_WalkAST(ctx, n->sconst.expr); + } break; + + case LC_ASTKind_ExprType: { + LC_WalkAST(ctx, n->etype.type); + } break; + case LC_ASTKind_ExprAddPtr: + case LC_ASTKind_ExprBinary: { + LC_WalkAST(ctx, n->ebinary.left); + LC_WalkAST(ctx, n->ebinary.right); + } break; + case LC_ASTKind_ExprGetPointerOfValue: + case LC_ASTKind_ExprGetValueOfPointer: + case LC_ASTKind_ExprUnary: { + LC_WalkAST(ctx, n->eunary.expr); + } break; + case LC_ASTKind_ExprCompoundItem: + case LC_ASTKind_ExprCallItem: { + if (n->ecompo_item.index) LC_WalkAST(ctx, n->ecompo_item.index); + LC_WalkAST(ctx, n->ecompo_item.expr); + } break; + case LC_ASTKind_Note: { + ctx->inside_note += 1; + if (n->ecompo.name) LC_WalkAST(ctx, n->ecompo.name); + LC_ASTFor(it, n->ecompo.first) LC_WalkAST(ctx, it); + ctx->inside_note -= 1; + } break; + case LC_ASTKind_ExprBuiltin: { + ctx->inside_builtin += 1; + if (n->ecompo.name) LC_WalkAST(ctx, n->ecompo.name); + LC_ASTFor(it, n->ecompo.first) LC_WalkAST(ctx, it); + ctx->inside_builtin -= 1; + } break; + case LC_ASTKind_ExprCall: + case LC_ASTKind_ExprCompound: { + if (n->ecompo.name) LC_WalkAST(ctx, n->ecompo.name); + LC_ASTFor(it, n->ecompo.first) LC_WalkAST(ctx, it); + } break; + case LC_ASTKind_ExprCast: { + LC_WalkAST(ctx, n->ecast.type); + LC_WalkAST(ctx, n->ecast.expr); + } break; + case LC_ASTKind_ExprField: { + LC_WalkAST(ctx, n->efield.left); + } break; + case LC_ASTKind_ExprIndex: { + LC_WalkAST(ctx, n->eindex.index); + LC_WalkAST(ctx, n->eindex.base); + } break; + + case LC_ASTKind_Ignore: + case LC_ASTKind_Error: + default: LC_ReportASTError(n, "internal compiler error: got invalid ast kind during ast walk: %s", LC_ASTKindToString(n->kind)); + } + + if (ctx->visit_notes && n->notes) { + LC_WalkAST(ctx, n->notes); + } + LC_PopAST(&ctx->stack); + + if (ctx->depth_first) { + ctx->proc(ctx, n); + } +} + +LC_FUNCTION LC_ASTWalker LC_GetDefaultWalker(LC_Arena *arena, LC_ASTWalkProc *proc) { + LC_ASTWalker result = {0}; + result.stack.arena = arena; + result.proc = proc; + result.depth_first = true; + return result; +} + +LC_FUNCTION void WalkAndFlattenAST(LC_ASTWalker *ctx, LC_AST *n) { + LC_ASTArray *array = (LC_ASTArray *)ctx->user_data; + LC_PushAST(array, n); +} + +LC_FUNCTION LC_ASTArray LC_FlattenAST(LC_Arena *arena, LC_AST *n) { + LC_ASTArray array = {arena}; + LC_ASTWalker walker = LC_GetDefaultWalker(arena, WalkAndFlattenAST); + walker.user_data = (void *)&array; + LC_WalkAST(&walker, n); + return array; +} + +LC_FUNCTION void WalkToFindSizeofLike(LC_ASTWalker *w, LC_AST *n) { + if (n->kind == LC_ASTKind_ExprBuiltin) { + LC_ASSERT(n, n->ecompo.name->kind == LC_ASTKind_ExprIdent); + if (n->ecompo.name->eident.name == L->isizeof || n->ecompo.name->eident.name == L->ialignof || n->ecompo.name->eident.name == L->ioffsetof) { + ((bool *)w->user_data)[0] = true; + } + } +} + +LC_FUNCTION bool LC_ContainsCBuiltin(LC_AST *n) { + LC_TempArena checkpoint = LC_BeginTemp(L->arena); + bool found = false; + { + LC_ASTWalker walker = LC_GetDefaultWalker(L->arena, WalkToFindSizeofLike); + walker.depth_first = false; + walker.user_data = (void *)&found; + LC_WalkAST(&walker, n); + } + LC_EndTemp(checkpoint); + return found; +} + +LC_FUNCTION void SetASTPosOnAll_Walk(LC_ASTWalker *ctx, LC_AST *n) { + n->pos = (LC_Token *)ctx->user_data; +} + +LC_FUNCTION void LC_SetASTPosOnAll(LC_AST *n, LC_Token *pos) { + LC_TempArena check = LC_BeginTemp(L->arena); + LC_ASTWalker walker = LC_GetDefaultWalker(L->arena, SetASTPosOnAll_Walk); + walker.user_data = (void *)pos; + LC_WalkAST(&walker, n); + LC_EndTemp(check); +} \ No newline at end of file diff --git a/src/compiler/bigint.c b/src/compiler/bigint.c new file mode 100644 index 0000000..c439c89 --- /dev/null +++ b/src/compiler/bigint.c @@ -0,0 +1,1471 @@ +/* +The bigint code was written by Christoffer Lerno, he is the programmer +behind C3. He allowed me to use this code without any restrictions. Great guy! +You can check out C3 compiler: https://github.com/c3lang/c3c +He also writes very helpful blogs about compilers: https://c3.handmade.network/blog +*/ + +#ifndef malloc_arena + #define malloc_arena(size) LC_PushSize(L->arena, size) +#endif +#define ALLOC_DIGITS(_digits) ((_digits) ? (uint64_t *)malloc_arena(sizeof(uint64_t) * (_digits)) : NULL) + +LC_FUNCTION uint32_t LC_u32_min(uint32_t a, uint32_t b) { + return a < b ? a : b; +} + +LC_FUNCTION size_t LC_size_max(size_t a, size_t b) { + return a > b ? a : b; +} + +LC_FUNCTION unsigned LC_unsigned_max(unsigned a, unsigned b) { + return a > b ? a : b; +} + +LC_FUNCTION uint64_t *LC_Bigint_ptr(LC_BigInt *big_int) { + return big_int->digit_count == 1 ? &big_int->digit : big_int->digits; +} + +LC_FUNCTION LC_BigInt LC_Bigint_u64(uint64_t val) { + LC_BigInt result = {0}; + LC_Bigint_init_unsigned(&result, val); + return result; +} + +LC_FUNCTION void LC_normalize(LC_BigInt *big_int) { + uint64_t *digits = LC_Bigint_ptr(big_int); + unsigned last_non_zero = UINT32_MAX; + for (unsigned i = 0; i < big_int->digit_count; i++) { + if (digits[i] != 0) { + last_non_zero = i; + } + } + if (last_non_zero == UINT32_MAX) { + big_int->is_negative = false; + big_int->digit_count = 0; + return; + } + big_int->digit_count = last_non_zero + 1; + if (!last_non_zero) { + big_int->digit = digits[0]; + } +} + +LC_FUNCTION char LC_digit_to_char(uint8_t digit, bool upper) { + if (digit <= 9) { + return (char)(digit + '0'); + } + if (digit <= 35) { + return (char)(digit + (upper ? 'A' : 'a') - 10); + } + LC_ASSERT(NULL, !"Can't reach"); + return 0; +} + +LC_FUNCTION bool LC_bit_at_index(LC_BigInt *big_int, size_t index) { + size_t digit_index = index / 64; + if (digit_index >= big_int->digit_count) { + return false; + } + size_t digit_bit_index = index % 64; + uint64_t *digits = LC_Bigint_ptr(big_int); + uint64_t digit = digits[digit_index]; + return ((digit >> digit_bit_index) & 0x1U) == 0x1U; +} + +LC_FUNCTION size_t LC_Bigint_bits_needed(LC_BigInt *big_int) { + size_t full_bits = big_int->digit_count * 64; + size_t leading_zero_count = LC_Bigint_clz(big_int, full_bits); + size_t bits_needed = full_bits - leading_zero_count; + return bits_needed + big_int->is_negative; +} + +LC_FUNCTION void LC_Bigint_init_unsigned(LC_BigInt *big_int, uint64_t value) { + if (value == 0) { + big_int->digit_count = 0; + big_int->is_negative = false; + return; + } + big_int->digit_count = 1; + big_int->digit = value; + big_int->is_negative = false; +} + +LC_FUNCTION void LC_Bigint_init_signed(LC_BigInt *dest, int64_t value) { + if (value >= 0) { + LC_Bigint_init_unsigned(dest, (uint64_t)value); + return; + } + dest->is_negative = true; + dest->digit_count = 1; + dest->digit = ((uint64_t)(-(value + 1))) + 1; +} + +LC_FUNCTION void LC_Bigint_init_bigint(LC_BigInt *dest, LC_BigInt *src) { + if (src->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + if (src->digit_count == 1) { + dest->digit_count = 1; + dest->digit = src->digit; + dest->is_negative = src->is_negative; + return; + } + dest->is_negative = src->is_negative; + dest->digit_count = src->digit_count; + dest->digits = ALLOC_DIGITS(dest->digit_count); + LC_MemoryCopy(dest->digits, src->digits, sizeof(uint64_t) * dest->digit_count); +} + +LC_FUNCTION void LC_Bigint_negate(LC_BigInt *dest, LC_BigInt *source) { + LC_Bigint_init_bigint(dest, source); + dest->is_negative = !dest->is_negative; + LC_normalize(dest); +} + +LC_FUNCTION void LC_to_twos_complement(LC_BigInt *dest, LC_BigInt *source, size_t bit_count) { + if (bit_count == 0 || source->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + if (source->is_negative) { + LC_BigInt negated = {0}; + LC_Bigint_negate(&negated, source); + + LC_BigInt inverted = {0}; + LC_Bigint_not(&inverted, &negated, bit_count, false); + + LC_BigInt one = {0}; + LC_Bigint_init_unsigned(&one, 1); + + LC_Bigint_add(dest, &inverted, &one); + return; + } + + dest->is_negative = false; + uint64_t *source_digits = LC_Bigint_ptr(source); + if (source->digit_count == 1) { + dest->digit = source_digits[0]; + if (bit_count < 64) { + dest->digit &= (1ULL << bit_count) - 1; + } + dest->digit_count = 1; + LC_normalize(dest); + return; + } + unsigned digits_to_copy = (unsigned int)(bit_count / 64); + unsigned leftover_bits = (unsigned int)(bit_count % 64); + dest->digit_count = digits_to_copy + ((leftover_bits == 0) ? 0 : 1); + if (dest->digit_count == 1 && leftover_bits == 0) { + dest->digit = source_digits[0]; + if (dest->digit == 0) dest->digit_count = 0; + return; + } + dest->digits = (uint64_t *)malloc_arena(dest->digit_count * sizeof(uint64_t)); + for (size_t i = 0; i < digits_to_copy; i += 1) { + uint64_t digit = (i < source->digit_count) ? source_digits[i] : 0; + dest->digits[i] = digit; + } + if (leftover_bits != 0) { + uint64_t digit = (digits_to_copy < source->digit_count) ? source_digits[digits_to_copy] : 0; + dest->digits[digits_to_copy] = digit & ((1ULL << leftover_bits) - 1); + } + LC_normalize(dest); +} + +LC_FUNCTION size_t LC_Bigint_clz(LC_BigInt *big_int, size_t bit_count) { + if (big_int->is_negative || bit_count == 0) { + return 0; + } + if (big_int->digit_count == 0) { + return bit_count; + } + size_t count = 0; + for (size_t i = bit_count - 1;;) { + if (LC_bit_at_index(big_int, i)) { + return count; + } + count++; + if (i == 0) break; + i--; + } + return count; +} + +LC_FUNCTION bool LC_Bigint_eql(LC_BigInt a, LC_BigInt b) { + return LC_Bigint_cmp(&a, &b) == LC_CmpRes_EQ; +} + +LC_FUNCTION void LC_from_twos_complement(LC_BigInt *dest, LC_BigInt *src, size_t bit_count, bool is_signed) { + LC_ASSERT(NULL, !src->is_negative); + + if (bit_count == 0 || src->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + + if (is_signed && LC_bit_at_index(src, bit_count - 1)) { + LC_BigInt negative_one = {0}; + LC_Bigint_init_signed(&negative_one, -1); + + LC_BigInt minus_one = {0}; + LC_Bigint_add(&minus_one, src, &negative_one); + + LC_BigInt inverted = {0}; + LC_Bigint_not(&inverted, &minus_one, bit_count, false); + + LC_Bigint_negate(dest, &inverted); + return; + } + + LC_Bigint_init_bigint(dest, src); +} + +void LC_Bigint_init_data(LC_BigInt *dest, uint64_t *digits, unsigned int digit_count, bool is_negative) { + if (digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + + if (digit_count == 1) { + dest->digit_count = 1; + dest->digit = digits[0]; + dest->is_negative = is_negative; + LC_normalize(dest); + return; + } + + dest->digit_count = digit_count; + dest->is_negative = is_negative; + dest->digits = ALLOC_DIGITS(digit_count); + LC_MemoryCopy(dest->digits, digits, sizeof(uint64_t) * digit_count); + + LC_normalize(dest); +} + +LC_FUNCTION bool LC_Bigint_fits_in_bits(LC_BigInt *big_int, size_t bit_count, bool is_signed) { + LC_ASSERT(NULL, big_int->digit_count != 1 || big_int->digit != 0); + if (bit_count == 0) { + return LC_Bigint_cmp_zero(big_int) == LC_CmpRes_EQ; + } + if (big_int->digit_count == 0) { + return true; + } + + if (!is_signed) { + size_t full_bits = big_int->digit_count * 64; + size_t leading_zero_count = LC_Bigint_clz(big_int, full_bits); + return bit_count >= full_bits - leading_zero_count; + } + + LC_BigInt one = {0}; + LC_Bigint_init_unsigned(&one, 1); + + LC_BigInt shl_amt = {0}; + LC_Bigint_init_unsigned(&shl_amt, bit_count - 1); + + LC_BigInt max_value_plus_one = {0}; + LC_Bigint_shl(&max_value_plus_one, &one, &shl_amt); + + LC_BigInt max_value = {0}; + LC_Bigint_sub(&max_value, &max_value_plus_one, &one); + + LC_BigInt min_value = {0}; + LC_Bigint_negate(&min_value, &max_value_plus_one); + + LC_CmpRes min_cmp = LC_Bigint_cmp(big_int, &min_value); + LC_CmpRes max_cmp = LC_Bigint_cmp(big_int, &max_value); + + return (min_cmp == LC_CmpRes_GT || min_cmp == LC_CmpRes_EQ) && (max_cmp == LC_CmpRes_LT || max_cmp == LC_CmpRes_EQ); +} + +LC_FUNCTION uint64_t LC_Bigint_as_unsigned(LC_BigInt *bigint) { + LC_ASSERT(NULL, !bigint->is_negative); + if (bigint->digit_count == 0) { + return 0; + } + if (bigint->digit_count != 1) { + LC_ASSERT(NULL, !"Bigint exceeds u64"); + } + return bigint->digit; +} + +#if defined(_MSC_VER) + +LC_FUNCTION bool LC_add_u64_overflow(uint64_t op1, uint64_t op2, uint64_t *result) { + *result = op1 + op2; + return *result < op1 || *result < op2; +} + +LC_FUNCTION bool LC_sub_u64_overflow(uint64_t op1, uint64_t op2, uint64_t *result) { + *result = op1 - op2; + return *result > op1; +} + +LC_FUNCTION bool LC_mul_u64_overflow(uint64_t op1, uint64_t op2, uint64_t *result) { + *result = op1 * op2; + + if (op1 == 0 || op2 == 0) return false; + if (op1 > UINT64_MAX / op2) return true; + if (op2 > UINT64_MAX / op1) return true; + return false; +} + +#else + +LC_FUNCTION bool LC_add_u64_overflow(uint64_t op1, uint64_t op2, uint64_t *result) { + return __builtin_uaddll_overflow((unsigned long long)op1, (unsigned long long)op2, + (unsigned long long *)result); +} + +LC_FUNCTION bool LC_sub_u64_overflow(uint64_t op1, uint64_t op2, uint64_t *result) { + return __builtin_usubll_overflow((unsigned long long)op1, (unsigned long long)op2, + (unsigned long long *)result); +} + +LC_FUNCTION bool LC_mul_u64_overflow(uint64_t op1, uint64_t op2, uint64_t *result) { + return __builtin_umulll_overflow((unsigned long long)op1, (unsigned long long)op2, + (unsigned long long *)result); +} + +#endif + +LC_FUNCTION void LC_Bigint_add(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->digit_count == 0) { + LC_Bigint_init_bigint(dest, op2); + return; + } + if (op2->digit_count == 0) { + LC_Bigint_init_bigint(dest, op1); + return; + } + if (op1->is_negative == op2->is_negative) { + dest->is_negative = op1->is_negative; + + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + uint64_t overflow = LC_add_u64_overflow(op1_digits[0], op2_digits[0], &dest->digit); + if (overflow == 0 && op1->digit_count == 1 && op2->digit_count == 1) { + dest->digit_count = 1; + LC_normalize(dest); + return; + } + unsigned i = 1; + uint64_t first_digit = dest->digit; + dest->digits = ALLOC_DIGITS(LC_unsigned_max(op1->digit_count, op2->digit_count) + 1); + dest->digits[0] = first_digit; + + for (;;) { + bool found_digit = false; + uint64_t x = (uint64_t)overflow; + overflow = 0; + + if (i < op1->digit_count) { + found_digit = true; + uint64_t digit = op1_digits[i]; + overflow += LC_add_u64_overflow(x, digit, &x); + } + + if (i < op2->digit_count) { + found_digit = true; + uint64_t digit = op2_digits[i]; + overflow += LC_add_u64_overflow(x, digit, &x); + } + + dest->digits[i] = x; + i += 1; + + if (!found_digit) { + dest->digit_count = i; + LC_normalize(dest); + return; + } + } + } + LC_BigInt *op_pos; + LC_BigInt *op_neg; + if (op1->is_negative) { + op_neg = op1; + op_pos = op2; + } else { + op_pos = op1; + op_neg = op2; + } + + LC_BigInt op_neg_abs = {0}; + LC_Bigint_negate(&op_neg_abs, op_neg); + LC_BigInt *bigger_op; + LC_BigInt *smaller_op; + switch (LC_Bigint_cmp(op_pos, &op_neg_abs)) { + case LC_CmpRes_EQ: + LC_Bigint_init_unsigned(dest, 0); + return; + case LC_CmpRes_LT: + bigger_op = &op_neg_abs; + smaller_op = op_pos; + dest->is_negative = true; + break; + case LC_CmpRes_GT: + bigger_op = op_pos; + smaller_op = &op_neg_abs; + dest->is_negative = false; + break; + default: + LC_ASSERT(NULL, !"UNREACHABLE"); + } + uint64_t *bigger_op_digits = LC_Bigint_ptr(bigger_op); + uint64_t *smaller_op_digits = LC_Bigint_ptr(smaller_op); + uint64_t overflow = (uint64_t)LC_sub_u64_overflow(bigger_op_digits[0], smaller_op_digits[0], &dest->digit); + if (overflow == 0 && bigger_op->digit_count == 1 && smaller_op->digit_count == 1) { + dest->digit_count = 1; + LC_normalize(dest); + return; + } + uint64_t first_digit = dest->digit; + dest->digits = ALLOC_DIGITS(bigger_op->digit_count); + dest->digits[0] = first_digit; + unsigned i = 1; + + for (;;) { + bool found_digit = false; + uint64_t x = bigger_op_digits[i]; + uint64_t prev_overflow = overflow; + overflow = 0; + + if (i < smaller_op->digit_count) { + found_digit = true; + uint64_t digit = smaller_op_digits[i]; + overflow += LC_sub_u64_overflow(x, digit, &x); + } + if (LC_sub_u64_overflow(x, prev_overflow, &x)) { + found_digit = true; + overflow += 1; + } + dest->digits[i] = x; + i += 1; + + if (!found_digit || i >= bigger_op->digit_count) { + break; + } + } + LC_ASSERT(NULL, overflow == 0); + dest->digit_count = i; + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_add_wrap(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed) { + LC_BigInt unwrapped = {0}; + LC_Bigint_add(&unwrapped, op1, op2); + LC_Bigint_truncate(dest, &unwrapped, bit_count, is_signed); +} + +LC_FUNCTION void LC_Bigint_sub(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + LC_BigInt op2_negated = {0}; + LC_Bigint_negate(&op2_negated, op2); + LC_Bigint_add(dest, op1, &op2_negated); + return; +} + +LC_FUNCTION void LC_Bigint_sub_wrap(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed) { + LC_BigInt op2_negated = {0}; + LC_Bigint_negate(&op2_negated, op2); + LC_Bigint_add_wrap(dest, op1, &op2_negated, bit_count, is_signed); + return; +} + +LC_FUNCTION void mul_overflow(uint64_t op1, uint64_t op2, uint64_t *lo, uint64_t *hi) { + uint64_t u1 = (op1 & 0xffffffff); + uint64_t v1 = (op2 & 0xffffffff); + uint64_t t = (u1 * v1); + uint64_t w3 = (t & 0xffffffff); + uint64_t k = (t >> 32); + + op1 >>= 32; + t = (op1 * v1) + k; + k = (t & 0xffffffff); + uint64_t w1 = (t >> 32); + + op2 >>= 32; + t = (u1 * op2) + k; + k = (t >> 32); + + *hi = (op1 * op2) + w1 + k; + *lo = (t << 32) + w3; +} + +LC_FUNCTION void LC_mul_scalar(LC_BigInt *dest, LC_BigInt *op, uint64_t scalar) { + LC_Bigint_init_unsigned(dest, 0); + + LC_BigInt bi_64; + LC_Bigint_init_unsigned(&bi_64, 64); + + uint64_t *op_digits = LC_Bigint_ptr(op); + size_t i = op->digit_count - 1; + + while (1) { + LC_BigInt shifted; + LC_Bigint_shl(&shifted, dest, &bi_64); + + uint64_t result_scalar; + uint64_t carry_scalar; + mul_overflow(scalar, op_digits[i], &result_scalar, &carry_scalar); + + LC_BigInt result; + LC_Bigint_init_unsigned(&result, result_scalar); + + LC_BigInt carry; + LC_Bigint_init_unsigned(&carry, carry_scalar); + + LC_BigInt carry_shifted; + LC_Bigint_shl(&carry_shifted, &carry, &bi_64); + + LC_BigInt tmp; + LC_Bigint_add(&tmp, &shifted, &carry_shifted); + + LC_Bigint_add(dest, &tmp, &result); + + if (i == 0) { + break; + } + i -= 1; + } +} + +LC_FUNCTION void LC_Bigint_mul(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->digit_count == 0 || op2->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + + uint64_t carry; + mul_overflow(op1_digits[0], op2_digits[0], &dest->digit, &carry); + if (carry == 0 && op1->digit_count == 1 && op2->digit_count == 1) { + dest->is_negative = (op1->is_negative != op2->is_negative); + dest->digit_count = 1; + LC_normalize(dest); + return; + } + + LC_Bigint_init_unsigned(dest, 0); + + LC_BigInt bi_64; + LC_Bigint_init_unsigned(&bi_64, 64); + + size_t i = op2->digit_count - 1; + for (;;) { + LC_BigInt shifted; + LC_Bigint_shl(&shifted, dest, &bi_64); + + LC_BigInt scalar_result; + LC_mul_scalar(&scalar_result, op1, op2_digits[i]); + + LC_Bigint_add(dest, &scalar_result, &shifted); + + if (i == 0) { + break; + } + i -= 1; + } + + dest->is_negative = (op1->is_negative != op2->is_negative); + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_mul_wrap(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed) { + LC_BigInt unwrapped = {0}; + LC_Bigint_mul(&unwrapped, op1, op2); + LC_Bigint_truncate(dest, &unwrapped, bit_count, is_signed); +} + +LC_FUNCTION unsigned LC_count_leading_zeros(uint32_t val) { + if (val == 0) return 32; + +#if _MSC_VER + unsigned long Index; + _BitScanReverse(&Index, val); + return Index ^ 31; +#else + return __builtin_clz(val); +#endif +} + +// Make a 64-bit integer from a high / low pair of 32-bit integers. +LC_FUNCTION uint64_t LC_make_64(uint32_t hi, uint32_t lo) { + return (((uint64_t)hi) << 32) | ((uint64_t)lo); +} + +// Return the high 32 bits of a 64 bit value. +LC_FUNCTION uint32_t LC_hi_32(uint64_t value) { + return (uint32_t)(value >> 32); +} + +// Return the low 32 bits of a 64 bit value. +LC_FUNCTION uint32_t LC_lo_32(uint64_t val) { + return (uint32_t)val; +} + +// Implementation of Knuth's Algorithm D (Division of nonnegative integers) +// from "Art of Computer Programming, Volume 2", section 4.3.1, p. 272. The +// variables here have the same names as in the algorithm. Comments explain +// the algorithm and any deviation from it. +LC_FUNCTION void LC_knuth_div(uint32_t *u, uint32_t *v, uint32_t *q, uint32_t *r, unsigned m, unsigned n) { + LC_ASSERT(NULL, u && "Must provide dividend"); + LC_ASSERT(NULL, v && "Must provide divisor"); + LC_ASSERT(NULL, q && "Must provide quotient"); + LC_ASSERT(NULL, u != v && u != q && v != q && "Must use different memory"); + LC_ASSERT(NULL, n > 1 && "n must be > 1"); + + // b denotes the base of the number system. In our case b is 2^32. + uint64_t b = ((uint64_t)1) << 32; + + // D1. [Normalize.] Set d = b / (v[n-1] + 1) and multiply all the digits of + // u and v by d. Note that we have taken Knuth's advice here to use a power + // of 2 value for d such that d * v[n-1] >= b/2 (b is the base). A power of + // 2 allows us to shift instead of multiply and it is easy to determine the + // shift amount from the leading zeros. We are basically normalizing the u + // and v so that its high bits are shifted to the top of v's range without + // overflow. Note that this can require an extra word in u so that u must + // be of length m+n+1. + unsigned shift = LC_count_leading_zeros(v[n - 1]); + uint32_t v_carry = 0; + uint32_t u_carry = 0; + if (shift) { + for (unsigned i = 0; i < m + n; ++i) { + uint32_t u_tmp = u[i] >> (32 - shift); + u[i] = (u[i] << shift) | u_carry; + u_carry = u_tmp; + } + for (unsigned i = 0; i < n; ++i) { + uint32_t v_tmp = v[i] >> (32 - shift); + v[i] = (v[i] << shift) | v_carry; + v_carry = v_tmp; + } + } + u[m + n] = u_carry; + + // D2. [Initialize j.] Set j to m. This is the loop counter over the places. + int j = (int)m; + do { + // D3. [Calculate q'.]. + // Set qp = (u[j+n]*b + u[j+n-1]) / v[n-1]. (qp=qprime=q') + // Set rp = (u[j+n]*b + u[j+n-1]) % v[n-1]. (rp=rprime=r') + // Now test if qp == b or qp*v[n-2] > b*rp + u[j+n-2]; if so, decrease + // qp by 1, increase rp by v[n-1], and repeat this test if rp < b. The test + // on v[n-2] determines at high speed most of the cases in which the trial + // value qp is one too large, and it eliminates all cases where qp is two + // too large. + uint64_t dividend = LC_make_64(u[j + n], u[j + n - 1]); + uint64_t qp = dividend / v[n - 1]; + uint64_t rp = dividend % v[n - 1]; + if (qp == b || qp * v[n - 2] > b * rp + u[j + n - 2]) { + qp--; + rp += v[n - 1]; + if (rp < b && (qp == b || qp * v[n - 2] > b * rp + u[j + n - 2])) { + qp--; + } + } + + // D4. [Multiply and subtract.] Replace (u[j+n]u[j+n-1]...u[j]) with + // (u[j+n]u[j+n-1]..u[j]) - qp * (v[n-1]...v[1]v[0]). This computation + // consists of a simple multiplication by a one-place number, combined with + // a subtraction. + // The digits (u[j+n]...u[j]) should be kept positive; if the result of + // this step is actually negative, (u[j+n]...u[j]) should be left as the + // true value plus b**(n+1), namely as the b's complement of + // the true value, and a "borrow" to the left should be remembered. + int64_t borrow = 0; + for (unsigned i = 0; i < n; ++i) { + uint64_t p = ((uint64_t)qp) * ((uint64_t)(v[i])); + int64_t subres = ((int64_t)(u[j + i])) - borrow - LC_lo_32(p); + u[j + i] = LC_lo_32((uint64_t)subres); + borrow = LC_hi_32(p) - LC_hi_32((uint64_t)subres); + } + bool is_neg = u[j + n] < borrow; + u[j + n] -= LC_lo_32((uint64_t)borrow); + + // D5. [Test remainder.] Set q[j] = qp. If the result of step D4 was + // negative, go to step D6; otherwise go on to step D7. + q[j] = LC_lo_32(qp); + if (is_neg) { + // D6. [Add back]. The probability that this step is necessary is very + // small, on the order of only 2/b. Make sure that test data accounts for + // this possibility. Decrease q[j] by 1 + q[j]--; + // and add (0v[n-1]...v[1]v[0]) to (u[j+n]u[j+n-1]...u[j+1]u[j]). + // A carry will occur to the left of u[j+n], and it should be ignored + // since it cancels with the borrow that occurred in D4. + bool carry = false; + for (unsigned i = 0; i < n; i++) { + uint32_t limit = LC_u32_min(u[j + i], v[i]); + u[j + i] += v[i] + carry; + carry = u[j + i] < limit || (carry && u[j + i] == limit); + } + u[j + n] += carry; + } + + // D7. [Loop on j.] Decrease j by one. Now if j >= 0, go back to D3. + } while (--j >= 0); + + // D8. [Unnormalize]. Now q[...] is the desired quotient, and the desired + // remainder may be obtained by dividing u[...] by d. If r is non-null we + // compute the remainder (urem uses this). + if (r) { + // The value d is expressed by the "shift" value above since we avoided + // multiplication by d by using a shift left. So, all we have to do is + // shift right here. + if (shift) { + uint32_t carry = 0; + for (int i = (int)n - 1; i >= 0; i--) { + r[i] = (u[i] >> shift) | carry; + carry = u[i] << (32 - shift); + } + } else { + for (int i = (int)n - 1; i >= 0; i--) { + r[i] = u[i]; + } + } + } +} + +LC_FUNCTION void LC_Bigint_unsigned_division(LC_BigInt *op1, LC_BigInt *op2, LC_BigInt *Quotient, LC_BigInt *Remainder) { + LC_CmpRes cmp = LC_Bigint_cmp(op1, op2); + if (cmp == LC_CmpRes_LT) { + if (!Quotient) { + LC_Bigint_init_unsigned(Quotient, 0); + } + if (!Remainder) { + LC_Bigint_init_bigint(Remainder, op1); + } + return; + } + if (cmp == LC_CmpRes_EQ) { + if (!Quotient) { + LC_Bigint_init_unsigned(Quotient, 1); + } + if (!Remainder) { + LC_Bigint_init_unsigned(Remainder, 0); + } + return; + } + + uint64_t *lhs = LC_Bigint_ptr(op1); + uint64_t *rhs = LC_Bigint_ptr(op2); + unsigned lhsWords = op1->digit_count; + unsigned rhsWords = op2->digit_count; + + // First, compose the values into an array of 32-bit words instead of + // 64-bit words. This is a necessity of both the "short division" algorithm + // and the Knuth "classical algorithm" which requires there to be native + // operations for +, -, and * on an m bit value with an m*2 bit result. We + // can't use 64-bit operands here because we don't have native results of + // 128-bits. Furthermore, casting the 64-bit values to 32-bit values won't + // work on large-endian machines. + unsigned n = rhsWords * 2; + unsigned m = (lhsWords * 2) - n; + + // Allocate space for the temporary values we need either on the stack, if + // it will fit, or on the heap if it won't. + uint32_t space[128]; + uint32_t *U = NULL; + uint32_t *V = NULL; + uint32_t *Q = NULL; + uint32_t *R = NULL; + if ((Remainder ? 4 : 3) * n + 2 * m + 1 <= 128) { + U = &space[0]; + V = &space[m + n + 1]; + Q = &space[(m + n + 1) + n]; + if (Remainder) { + R = &space[(m + n + 1) + n + (m + n)]; + } + } else { + U = (uint32_t *)malloc_arena(sizeof(uint32_t) * (m + n + 1)); + V = (uint32_t *)malloc_arena(sizeof(uint32_t) * n); + Q = (uint32_t *)malloc_arena(sizeof(uint32_t) * (m + n)); + if (Remainder) { + R = (uint32_t *)malloc_arena(sizeof(uint32_t) * n); + } + } + + // Initialize the dividend + LC_MemoryZero(U, (m + n + 1) * sizeof(uint32_t)); + for (unsigned i = 0; i < lhsWords; ++i) { + uint64_t tmp = lhs[i]; + U[i * 2] = LC_lo_32(tmp); + U[i * 2 + 1] = LC_hi_32(tmp); + } + U[m + n] = 0; // this extra word is for "spill" in the Knuth algorithm. + + // Initialize the divisor + LC_MemoryZero(V, (n) * sizeof(uint32_t)); + for (unsigned i = 0; i < rhsWords; ++i) { + uint64_t tmp = rhs[i]; + V[i * 2] = LC_lo_32(tmp); + V[i * 2 + 1] = LC_hi_32(tmp); + } + + // initialize the quotient and remainder + LC_MemoryZero(Q, (m + n) * sizeof(uint32_t)); + if (Remainder) LC_MemoryZero(R, n * sizeof(uint32_t)); + + // Now, adjust m and n for the Knuth division. n is the number of words in + // the divisor. m is the number of words by which the dividend exceeds the + // divisor (i.e. m+n is the length of the dividend). These sizes must not + // contain any zero words or the Knuth algorithm fails. + for (unsigned i = n; i > 0 && V[i - 1] == 0; i--) { + n--; + m++; + } + for (unsigned i = m + n; i > 0 && U[i - 1] == 0; i--) { + m--; + } + + // If we're left with only a single word for the divisor, Knuth doesn't work + // so we implement the short division algorithm here. This is much simpler + // and faster because we are certain that we can divide a 64-bit quantity + // by a 32-bit quantity at hardware speed and short division is simply a + // series of such operations. This is just like doing short division but we + // are using base 2^32 instead of base 10. + LC_ASSERT(NULL, n != 0 && "Divide by zero?"); + if (n == 1) { + uint32_t divisor = V[0]; + uint32_t rem = 0; + for (int i = (int)m; i >= 0; i--) { + uint64_t partial_dividend = LC_make_64(rem, U[i]); + if (partial_dividend == 0) { + Q[i] = 0; + rem = 0; + } else if (partial_dividend < divisor) { + Q[i] = 0; + rem = LC_lo_32(partial_dividend); + } else if (partial_dividend == divisor) { + Q[i] = 1; + rem = 0; + } else { + Q[i] = LC_lo_32(partial_dividend / divisor); + rem = LC_lo_32(partial_dividend - (Q[i] * divisor)); + } + } + if (R) { + R[0] = rem; + } + } else { + // Now we're ready to invoke the Knuth classical divide algorithm. In this + // case n > 1. + LC_knuth_div(U, V, Q, R, m, n); + } + + // If the caller wants the quotient + if (Quotient) { + Quotient->is_negative = false; + Quotient->digit_count = lhsWords; + if (lhsWords == 1) { + Quotient->digit = LC_make_64(Q[1], Q[0]); + } else { + Quotient->digits = ALLOC_DIGITS(lhsWords); + for (size_t i = 0; i < lhsWords; i += 1) { + Quotient->digits[i] = LC_make_64(Q[i * 2 + 1], Q[i * 2]); + } + } + } + + // If the caller wants the remainder + if (Remainder) { + Remainder->is_negative = false; + Remainder->digit_count = rhsWords; + if (rhsWords == 1) { + Remainder->digit = LC_make_64(R[1], R[0]); + } else { + Remainder->digits = ALLOC_DIGITS(rhsWords); + for (size_t i = 0; i < rhsWords; i += 1) { + Remainder->digits[i] = LC_make_64(R[i * 2 + 1], R[i * 2]); + } + } + } +} + +LC_FUNCTION void LC_Bigint_div_trunc(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + LC_ASSERT(NULL, op2->digit_count != 0); // division by zero + if (op1->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + if (op1->digit_count == 1 && op2->digit_count == 1) { + dest->digit = op1_digits[0] / op2_digits[0]; + dest->digit_count = 1; + dest->is_negative = op1->is_negative != op2->is_negative; + LC_normalize(dest); + return; + } + if (op2->digit_count == 1 && op2_digits[0] == 1) { + // X / 1 == X + LC_Bigint_init_bigint(dest, op1); + dest->is_negative = op1->is_negative != op2->is_negative; + LC_normalize(dest); + return; + } + + LC_BigInt *op1_positive; + LC_BigInt op1_positive_data; + if (op1->is_negative) { + LC_Bigint_negate(&op1_positive_data, op1); + op1_positive = &op1_positive_data; + } else { + op1_positive = op1; + } + + LC_BigInt *op2_positive; + LC_BigInt op2_positive_data; + if (op2->is_negative) { + LC_Bigint_negate(&op2_positive_data, op2); + op2_positive = &op2_positive_data; + } else { + op2_positive = op2; + } + + LC_Bigint_unsigned_division(op1_positive, op2_positive, dest, NULL); + dest->is_negative = op1->is_negative != op2->is_negative; + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_div_floor(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->is_negative != op2->is_negative) { + LC_Bigint_div_trunc(dest, op1, op2); + LC_BigInt mult_again = {0}; + LC_Bigint_mul(&mult_again, dest, op2); + mult_again.is_negative = op1->is_negative; + if (LC_Bigint_cmp(&mult_again, op1) != LC_CmpRes_EQ) { + LC_BigInt tmp = {0}; + LC_Bigint_init_bigint(&tmp, dest); + LC_BigInt neg_one = {0}; + LC_Bigint_init_signed(&neg_one, -1); + LC_Bigint_add(dest, &tmp, &neg_one); + } + LC_normalize(dest); + } else { + LC_Bigint_div_trunc(dest, op1, op2); + } +} + +LC_FUNCTION void LC_Bigint_rem(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + LC_ASSERT(NULL, op2->digit_count != 0); // division by zero + if (op1->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + + if (op1->digit_count == 1 && op2->digit_count == 1) { + dest->digit = op1_digits[0] % op2_digits[0]; + dest->digit_count = 1; + dest->is_negative = op1->is_negative; + LC_normalize(dest); + return; + } + if (op2->digit_count == 2 && op2_digits[0] == 0 && op2_digits[1] == 1) { + // special case this divisor + LC_Bigint_init_unsigned(dest, op1_digits[0]); + dest->is_negative = op1->is_negative; + LC_normalize(dest); + return; + } + + if (op2->digit_count == 1 && op2_digits[0] == 1) { + // X % 1 == 0 + LC_Bigint_init_unsigned(dest, 0); + return; + } + + LC_BigInt *op1_positive; + LC_BigInt op1_positive_data; + if (op1->is_negative) { + LC_Bigint_negate(&op1_positive_data, op1); + op1_positive = &op1_positive_data; + } else { + op1_positive = op1; + } + + LC_BigInt *op2_positive; + LC_BigInt op2_positive_data; + if (op2->is_negative) { + LC_Bigint_negate(&op2_positive_data, op2); + op2_positive = &op2_positive_data; + } else { + op2_positive = op2; + } + + LC_Bigint_unsigned_division(op1_positive, op2_positive, NULL, dest); + dest->is_negative = op1->is_negative; + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_mod(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->is_negative) { + LC_BigInt first_rem; + LC_Bigint_rem(&first_rem, op1, op2); + first_rem.is_negative = !op2->is_negative; + LC_BigInt op2_minus_rem; + LC_Bigint_add(&op2_minus_rem, op2, &first_rem); + LC_Bigint_rem(dest, &op2_minus_rem, op2); + dest->is_negative = false; + } else { + LC_Bigint_rem(dest, op1, op2); + dest->is_negative = false; + } +} + +LC_FUNCTION void LC_Bigint_or(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->digit_count == 0) { + LC_Bigint_init_bigint(dest, op2); + return; + } + if (op2->digit_count == 0) { + LC_Bigint_init_bigint(dest, op1); + return; + } + if (op1->is_negative || op2->is_negative) { + size_t big_bit_count = LC_size_max(LC_Bigint_bits_needed(op1), LC_Bigint_bits_needed(op2)); + + LC_BigInt twos_comp_op1 = {0}; + LC_to_twos_complement(&twos_comp_op1, op1, big_bit_count); + + LC_BigInt twos_comp_op2 = {0}; + LC_to_twos_complement(&twos_comp_op2, op2, big_bit_count); + + LC_BigInt twos_comp_dest = {0}; + LC_Bigint_or(&twos_comp_dest, &twos_comp_op1, &twos_comp_op2); + + LC_from_twos_complement(dest, &twos_comp_dest, big_bit_count, true); + } else { + dest->is_negative = false; + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + if (op1->digit_count == 1 && op2->digit_count == 1) { + dest->digit_count = 1; + dest->digit = op1_digits[0] | op2_digits[0]; + LC_normalize(dest); + return; + } + dest->digit_count = LC_unsigned_max(op1->digit_count, op2->digit_count); + dest->digits = ALLOC_DIGITS(dest->digit_count); + for (size_t i = 0; i < dest->digit_count; i += 1) { + uint64_t digit = 0; + if (i < op1->digit_count) { + digit |= op1_digits[i]; + } + if (i < op2->digit_count) { + digit |= op2_digits[i]; + } + dest->digits[i] = digit; + } + LC_normalize(dest); + } +} + +LC_FUNCTION void LC_Bigint_and(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->digit_count == 0 || op2->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + if (op1->is_negative || op2->is_negative) { + size_t big_bit_count = LC_size_max(LC_Bigint_bits_needed(op1), LC_Bigint_bits_needed(op2)); + + LC_BigInt twos_comp_op1 = {0}; + LC_to_twos_complement(&twos_comp_op1, op1, big_bit_count); + + LC_BigInt twos_comp_op2 = {0}; + LC_to_twos_complement(&twos_comp_op2, op2, big_bit_count); + + LC_BigInt twos_comp_dest = {0}; + LC_Bigint_and(&twos_comp_dest, &twos_comp_op1, &twos_comp_op2); + + LC_from_twos_complement(dest, &twos_comp_dest, big_bit_count, true); + } else { + dest->is_negative = false; + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + if (op1->digit_count == 1 && op2->digit_count == 1) { + dest->digit_count = 1; + dest->digit = op1_digits[0] & op2_digits[0]; + LC_normalize(dest); + return; + } + + dest->digit_count = LC_unsigned_max(op1->digit_count, op2->digit_count); + dest->digits = ALLOC_DIGITS(dest->digit_count); + + size_t i = 0; + for (; i < op1->digit_count && i < op2->digit_count; i += 1) { + dest->digits[i] = op1_digits[i] & op2_digits[i]; + } + for (; i < dest->digit_count; i += 1) { + dest->digits[i] = 0; + } + LC_normalize(dest); + } +} + +LC_FUNCTION void LC_Bigint_xor(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + if (op1->digit_count == 0) { + LC_Bigint_init_bigint(dest, op2); + return; + } + if (op2->digit_count == 0) { + LC_Bigint_init_bigint(dest, op1); + return; + } + if (op1->is_negative || op2->is_negative) { + size_t big_bit_count = LC_size_max(LC_Bigint_bits_needed(op1), LC_Bigint_bits_needed(op2)); + + LC_BigInt twos_comp_op1 = {0}; + LC_to_twos_complement(&twos_comp_op1, op1, big_bit_count); + + LC_BigInt twos_comp_op2 = {0}; + LC_to_twos_complement(&twos_comp_op2, op2, big_bit_count); + + LC_BigInt twos_comp_dest = {0}; + LC_Bigint_xor(&twos_comp_dest, &twos_comp_op1, &twos_comp_op2); + + LC_from_twos_complement(dest, &twos_comp_dest, big_bit_count, true); + } else { + dest->is_negative = false; + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + + LC_ASSERT(NULL, op1->digit_count > 0 && op2->digit_count > 0); + if (op1->digit_count == 1 && op2->digit_count == 1) { + dest->digit_count = 1; + dest->digit = op1_digits[0] ^ op2_digits[0]; + LC_normalize(dest); + return; + } + dest->digit_count = LC_unsigned_max(op1->digit_count, op2->digit_count); + dest->digits = ALLOC_DIGITS(dest->digit_count); + size_t i = 0; + for (; i < op1->digit_count && i < op2->digit_count; i += 1) { + dest->digits[i] = op1_digits[i] ^ op2_digits[i]; + } + for (; i < dest->digit_count; i += 1) { + if (i < op1->digit_count) { + dest->digits[i] = op1_digits[i]; + } else if (i < op2->digit_count) { + dest->digits[i] = op2_digits[i]; + } else { + LC_ASSERT(NULL, !"Unreachable"); + } + } + LC_normalize(dest); + } +} + +LC_FUNCTION void LC_Bigint_shl(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + LC_ASSERT(NULL, !op2->is_negative); + + if (op2->digit_count == 0) { + return; + } + if (op2->digit_count != 1) { + LC_ASSERT(NULL, !"Unsupported: shift left by amount greater than 64 bit integer"); + } + LC_Bigint_shl_int(dest, op1, LC_Bigint_as_unsigned(op2)); +} + +LC_FUNCTION void LC_Bigint_shl_int(LC_BigInt *dest, LC_BigInt *op1, uint64_t shift) { + if (shift == 0) { + LC_Bigint_init_bigint(dest, op1); + return; + } + + if (op1->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + + uint64_t *op1_digits = LC_Bigint_ptr(op1); + + if (op1->digit_count == 1 && shift < 64) { + dest->digit = op1_digits[0] << shift; + if (dest->digit > op1_digits[0]) { + dest->digit_count = 1; + dest->is_negative = op1->is_negative; + return; + } + } + + uint64_t digit_shift_count = shift / 64; + uint64_t leftover_shift_count = shift % 64; + + dest->digits = ALLOC_DIGITS(op1->digit_count + digit_shift_count + 1); + dest->digit_count = (unsigned)digit_shift_count; + uint64_t carry = 0; + for (size_t i = 0; i < op1->digit_count; i += 1) { + uint64_t digit = op1_digits[i]; + dest->digits[dest->digit_count] = carry | (digit << leftover_shift_count); + dest->digit_count++; + if (leftover_shift_count > 0) { + carry = digit >> (64 - leftover_shift_count); + } else { + carry = 0; + } + } + dest->digits[dest->digit_count] = carry; + dest->digit_count += 1; + dest->is_negative = op1->is_negative; + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_shl_trunc(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed) { + LC_BigInt unwrapped = {0}; + LC_Bigint_shl(&unwrapped, op1, op2); + LC_Bigint_truncate(dest, &unwrapped, bit_count, is_signed); +} + +LC_FUNCTION void LC_Bigint_shr(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2) { + LC_ASSERT(NULL, !op2->is_negative); + + if (op1->digit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + + if (op2->digit_count == 0) { + LC_Bigint_init_bigint(dest, op1); + return; + } + + if (op2->digit_count != 1) { + LC_ASSERT(NULL, !"Unsupported: shift right by amount greater than 64 bit integer"); + } + + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t shift_amt = LC_Bigint_as_unsigned(op2); + + if (op1->digit_count == 1) { + dest->digit = shift_amt < 64 ? op1_digits[0] >> shift_amt : 0; + dest->digit_count = 1; + dest->is_negative = op1->is_negative; + LC_normalize(dest); + return; + } + + uint64_t digit_shift_count = shift_amt / 64; + uint64_t leftover_shift_count = shift_amt % 64; + + if (digit_shift_count >= op1->digit_count) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + + dest->digit_count = (unsigned)(op1->digit_count - digit_shift_count); + uint64_t *digits; + if (dest->digit_count == 1) { + digits = &dest->digit; + } else { + digits = ALLOC_DIGITS(dest->digit_count); + dest->digits = digits; + } + + uint64_t carry = 0; + for (size_t op_digit_index = op1->digit_count - 1;;) { + uint64_t digit = op1_digits[op_digit_index]; + size_t dest_digit_index = op_digit_index - digit_shift_count; + digits[dest_digit_index] = carry | (digit >> leftover_shift_count); + carry = digit << (64 - leftover_shift_count); + + if (dest_digit_index == 0) break; + op_digit_index -= 1; + } + dest->is_negative = op1->is_negative; + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_not(LC_BigInt *dest, LC_BigInt *op, size_t bit_count, bool is_signed) { + if (bit_count == 0) { + LC_Bigint_init_unsigned(dest, 0); + return; + } + + if (is_signed) { + LC_BigInt twos_comp = {0}; + LC_to_twos_complement(&twos_comp, op, bit_count); + + LC_BigInt inverted = {0}; + LC_Bigint_not(&inverted, &twos_comp, bit_count, false); + + LC_from_twos_complement(dest, &inverted, bit_count, true); + return; + } + + LC_ASSERT(NULL, !op->is_negative); + + dest->is_negative = false; + uint64_t *op_digits = LC_Bigint_ptr(op); + if (bit_count <= 64) { + dest->digit_count = 1; + if (op->digit_count == 0) { + if (bit_count == 64) { + dest->digit = UINT64_MAX; + } else { + dest->digit = (1ULL << bit_count) - 1; + } + } else if (op->digit_count == 1) { + dest->digit = ~op_digits[0]; + if (bit_count != 64) { + uint64_t + mask = (1ULL << bit_count) - 1; + dest->digit &= mask; + } + } + LC_normalize(dest); + return; + } + dest->digit_count = (unsigned int)((bit_count + 63) / 64); + LC_ASSERT(NULL, dest->digit_count >= op->digit_count); + dest->digits = ALLOC_DIGITS(dest->digit_count); + size_t i = 0; + for (; i < op->digit_count; i += 1) { + dest->digits[i] = ~op_digits[i]; + } + for (; i < dest->digit_count; i += 1) { + dest->digits[i] = 0xffffffffffffffffULL; + } + size_t digit_index = dest->digit_count - 1; + size_t digit_bit_index = bit_count % 64; + if (digit_bit_index != 0) { + uint64_t + mask = (1ULL << digit_bit_index) - 1; + dest->digits[digit_index] &= mask; + } + LC_normalize(dest); +} + +LC_FUNCTION void LC_Bigint_truncate(LC_BigInt *dst, LC_BigInt *op, size_t bit_count, bool is_signed) { + LC_BigInt twos_comp; + LC_to_twos_complement(&twos_comp, op, bit_count); + LC_from_twos_complement(dst, &twos_comp, bit_count, is_signed); +} + +LC_FUNCTION LC_CmpRes LC_Bigint_cmp(LC_BigInt *op1, LC_BigInt *op2) { + if (op1->is_negative && !op2->is_negative) return LC_CmpRes_LT; + if (!op1->is_negative && op2->is_negative) return LC_CmpRes_GT; + if (op1->digit_count > op2->digit_count) return op1->is_negative ? LC_CmpRes_LT : LC_CmpRes_GT; + if (op2->digit_count > op1->digit_count) return op1->is_negative ? LC_CmpRes_GT : LC_CmpRes_LT; + if (op1->digit_count == 0) return LC_CmpRes_EQ; + + uint64_t *op1_digits = LC_Bigint_ptr(op1); + uint64_t *op2_digits = LC_Bigint_ptr(op2); + for (unsigned i = op1->digit_count - 1;; i--) { + uint64_t op1_digit = op1_digits[i]; + uint64_t op2_digit = op2_digits[i]; + + if (op1_digit > op2_digit) { + return op1->is_negative ? LC_CmpRes_LT : LC_CmpRes_GT; + } + if (op1_digit < op2_digit) { + return op1->is_negative ? LC_CmpRes_GT : LC_CmpRes_LT; + } + if (i == 0) { + return LC_CmpRes_EQ; + } + } +} + +LC_FUNCTION char *LC_Bigint_str(LC_BigInt *bigint, uint64_t base) { + LC_StringList out = {0}; + if (bigint->digit_count == 0) { + return "0"; + } + if (bigint->is_negative) { + LC_Addf(L->arena, &out, "-"); + } + if (bigint->digit_count == 1 && base == 10) { + LC_Addf(L->arena, &out, "%llu", (unsigned long long)bigint->digit); + } else { + size_t len = bigint->digit_count * 64; + char *start = (char *)malloc_arena(len); + char *buf = start; + + LC_BigInt digit_bi = {0}; + LC_BigInt a1 = {0}; + LC_BigInt a2 = {0}; + LC_BigInt base_bi = {0}; + LC_BigInt *a = &a1; + LC_BigInt *other_a = &a2; + + LC_Bigint_init_bigint(a, bigint); + LC_Bigint_init_unsigned(&base_bi, base); + + for (;;) { + LC_Bigint_rem(&digit_bi, a, &base_bi); + uint8_t digit = (uint8_t)LC_Bigint_as_unsigned(&digit_bi); + *(buf++) = LC_digit_to_char(digit, false); + LC_Bigint_div_trunc(other_a, a, &base_bi); + { + LC_BigInt *tmp = a; + a = other_a; + other_a = tmp; + } + if (LC_Bigint_cmp_zero(a) == LC_CmpRes_EQ) { + break; + } + } + + // reverse + + for (char *ptr = buf - 1; ptr >= start; ptr--) { + LC_Addf(L->arena, &out, "%c", *ptr); + } + } + LC_String s = LC_MergeString(L->arena, out); + return s.str; +} + +LC_FUNCTION int64_t LC_Bigint_as_signed(LC_BigInt *bigint) { + if (bigint->digit_count == 0) return 0; + if (bigint->digit_count != 1) { + LC_ASSERT(NULL, !"LC_BigInt larger than i64"); + } + + if (bigint->is_negative) { + // TODO this code path is untested + if (bigint->digit <= 9223372036854775808ULL) { + return (-((int64_t)(bigint->digit - 1))) - 1; + } + LC_ASSERT(NULL, !"LC_BigInt does not fit in i64"); + } + return (int64_t)bigint->digit; +} + +LC_FUNCTION LC_CmpRes LC_Bigint_cmp_zero(LC_BigInt *op) { + if (op->digit_count == 0) { + return LC_CmpRes_EQ; + } + return op->is_negative ? LC_CmpRes_LT : LC_CmpRes_GT; +} + +LC_FUNCTION double LC_Bigint_as_float(LC_BigInt *bigint) { + if (LC_Bigint_fits_in_bits(bigint, 64, bigint->is_negative)) { + return bigint->is_negative ? (double)LC_Bigint_as_signed(bigint) : (double)LC_Bigint_as_unsigned(bigint); + } + LC_BigInt div; + uint64_t mult = 0x100000000000ULL; + double mul = 1; + LC_Bigint_init_unsigned(&div, mult); + LC_BigInt current; + LC_Bigint_init_bigint(¤t, bigint); + double f = 0; + do { + LC_BigInt temp; + LC_Bigint_mod(&temp, ¤t, &div); + f += LC_Bigint_as_signed(&temp) * mul; + mul *= mult; + LC_Bigint_div_trunc(&temp, ¤t, &div); + current = temp; + } while (current.digit_count > 0); + return f; +} \ No newline at end of file diff --git a/src/compiler/common.c b/src/compiler/common.c new file mode 100644 index 0000000..7e60b66 --- /dev/null +++ b/src/compiler/common.c @@ -0,0 +1,198 @@ +#if __cplusplus + #define LC_Alignof(...) alignof(__VA_ARGS__) +#else + #define LC_Alignof(...) _Alignof(__VA_ARGS__) +#endif + +#define LC_WRAP_AROUND_POWER_OF_2(x, pow2) (((x) & ((pow2)-1llu))) + +#if defined(_MSC_VER) + #define LC_DebugBreak() (L->breakpoint_on_error && IsDebuggerPresent() && (__debugbreak(), 0)) +#else + #define LC_DebugBreak() (L->breakpoint_on_error && (__builtin_trap(), 0)) +#endif +#define LC_FatalError() (L->breakpoint_on_error ? LC_DebugBreak() : (LC_Exit(1), 0)) + +LC_FUNCTION void LC_IgnoreMessage(LC_Token *pos, char *str, int len) { +} + +LC_FUNCTION void LC_SendErrorMessage(LC_Token *pos, LC_String s8) { + if (L->on_message) { + L->on_message(pos, s8.str, (int)s8.len); + } else { + if (pos) { + LC_String line = LC_GetTokenLine(pos); + LC_String fmt = LC_Format(L->arena, "%s(%d,%d): error: %.*s\n%.*s", (char *)pos->lex->file, pos->line, pos->column, LC_Expand(s8), LC_Expand(line)); + LC_Print(fmt.str, fmt.len); + } else { + LC_Print(s8.str, s8.len); + } + } + LC_DebugBreak(); +} + +LC_FUNCTION void LC_SendErrorMessagef(LC_Lex *x, LC_Token *pos, const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + LC_SendErrorMessage(pos, s8); +} + +LC_FUNCTION void LC_HandleFatalError(void) { + if (L->on_fatal_error) { + L->on_fatal_error(); + return; + } + LC_FatalError(); +} + +LC_FUNCTION void LC_MapReserve(LC_Map *map, int size) { + LC_Map old_map = *map; + + LC_ASSERT(NULL, LC_IS_POW2(size)); + map->len = 0; + map->cap = size; + LC_ASSERT(NULL, map->arena); + + map->entries = LC_PushArray(map->arena, LC_MapEntry, map->cap); + + if (old_map.entries) { + for (int i = 0; i < old_map.cap; i += 1) { + LC_MapEntry *it = old_map.entries + i; + if (it->key) LC_InsertMapEntry(map, it->key, it->value); + } + } +} + +// FNV HASH (1a?) +LC_FUNCTION uint64_t LC_HashBytes(void *data, uint64_t size) { + uint8_t *data8 = (uint8_t *)data; + uint64_t hash = (uint64_t)14695981039346656037ULL; + for (uint64_t i = 0; i < size; i++) { + hash = hash ^ (uint64_t)(data8[i]); + hash = hash * (uint64_t)1099511628211ULL; + } + return hash; +} + +LC_FUNCTION uint64_t LC_HashMix(uint64_t x, uint64_t y) { + x ^= y; + x *= 0xff51afd7ed558ccd; + x ^= x >> 32; + return x; +} + +LC_FUNCTION int LC_NextPow2(int v) { + v--; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + v++; + return v; +} + +LC_FUNCTION LC_MapEntry *LC_GetMapEntryEx(LC_Map *map, uint64_t key) { + LC_ASSERT(NULL, key); + if (map->len * 2 >= map->cap) { + LC_MapReserve(map, map->cap * 2); + } + + uint64_t hash = LC_HashBytes(&key, sizeof(key)); + if (hash == 0) hash += 1; + uint64_t index = LC_WRAP_AROUND_POWER_OF_2(hash, map->cap); + uint64_t i = index; + for (;;) { + LC_MapEntry *it = map->entries + i; + if (it->key == key || it->key == 0) { + return it; + } + + i = LC_WRAP_AROUND_POWER_OF_2(i + 1, map->cap); + if (i == index) return NULL; + } + LC_ASSERT(NULL, !"invalid codepath"); +} + +LC_FUNCTION bool LC_InsertWithoutReplace(LC_Map *map, void *key, void *value) { + LC_MapEntry *entry = LC_GetMapEntryEx(map, (uint64_t)key); + if (entry->key != 0) return false; + + map->len += 1; + entry->key = (uint64_t)key; + entry->value = (uint64_t)value; + return true; +} + +LC_FUNCTION LC_MapEntry *LC_InsertMapEntry(LC_Map *map, uint64_t key, uint64_t value) { + LC_MapEntry *entry = LC_GetMapEntryEx(map, key); + if (entry->key == key) { + entry->value = value; + } + if (entry->key == 0) { + entry->key = key; + entry->value = value; + map->len += 1; + } + return entry; +} + +LC_FUNCTION LC_MapEntry *LC_GetMapEntry(LC_Map *map, uint64_t key) { + LC_MapEntry *entry = LC_GetMapEntryEx(map, key); + if (entry && entry->key == key) { + return entry; + } + return NULL; +} + +LC_FUNCTION void LC_MapInsert(LC_Map *map, LC_String keystr, void *value) { + uint64_t key = LC_HashBytes(keystr.str, keystr.len); + LC_InsertMapEntry(map, key, (uint64_t)value); +} + +LC_FUNCTION void *LC_MapGet(LC_Map *map, LC_String keystr) { + uint64_t key = LC_HashBytes(keystr.str, keystr.len); + LC_MapEntry *r = LC_GetMapEntry(map, key); + return r ? (void *)r->value : 0; +} + +LC_FUNCTION void LC_MapInsertU64(LC_Map *map, uint64_t key, void *value) { + LC_InsertMapEntry(map, key, (uint64_t)value); +} + +LC_FUNCTION void *LC_MapGetU64(LC_Map *map, uint64_t key) { + LC_MapEntry *r = LC_GetMapEntry(map, key); + return r ? (void *)r->value : 0; +} + +LC_FUNCTION void *LC_MapGetP(LC_Map *map, void *key) { + return LC_MapGetU64(map, (uint64_t)key); +} + +LC_FUNCTION void LC_MapInsertP(LC_Map *map, void *key, void *value) { + LC_InsertMapEntry(map, (uint64_t)key, (uint64_t)value); +} + +LC_FUNCTION void LC_MapClear(LC_Map *map) { + if (map->len != 0) LC_MemoryZero(map->entries, map->cap * sizeof(LC_MapEntry)); + map->len = 0; +} + +LC_FUNCTION size_t LC_GetAlignOffset(size_t size, size_t align) { + size_t mask = align - 1; + size_t val = size & mask; + if (val) { + val = align - val; + } + return val; +} + +LC_FUNCTION size_t LC_AlignUp(size_t size, size_t align) { + size_t result = size + LC_GetAlignOffset(size, align); + return result; +} + +LC_FUNCTION size_t LC_AlignDown(size_t size, size_t align) { + size += 1; // Make sure when align is 8 doesn't get rounded down to 0 + size_t result = size - (align - LC_GetAlignOffset(size, align)); + return result; +} diff --git a/src/compiler/extended_passes.c b/src/compiler/extended_passes.c new file mode 100644 index 0000000..7182a18 --- /dev/null +++ b/src/compiler/extended_passes.c @@ -0,0 +1,72 @@ +LC_FUNCTION void WalkAndCountDeclRefs(LC_ASTWalker *ctx, LC_AST *n) { + LC_Decl *decl = NULL; + if (n->kind == LC_ASTKind_ExprIdent || n->kind == LC_ASTKind_TypespecIdent) { + if (n->eident.resolved_decl) decl = n->eident.resolved_decl; + } + if (n->kind == LC_ASTKind_ExprField) { + if (n->efield.resolved_decl) decl = n->efield.resolved_decl; + } + if (decl) { + LC_Map *map_of_visits = (LC_Map *)ctx->user_data; + intptr_t visited = (intptr_t)LC_MapGetP(map_of_visits, decl); + LC_MapInsertP(map_of_visits, decl, (void *)(visited + 1)); + if (visited == 0 && decl->ast->kind != LC_ASTKind_Null) { + LC_WalkAST(ctx, decl->ast); + } + } +} + +LC_FUNCTION LC_Map LC_CountDeclRefs(LC_Arena *arena) { + LC_Map map = {arena}; + LC_MapReserve(&map, 512); + + LC_AST *package = LC_GetPackageByName(L->first_package); + LC_ASTWalker walker = LC_GetDefaultWalker(arena, WalkAndCountDeclRefs); + walker.user_data = (void *)↦ + walker.visit_notes = true; + LC_WalkAST(&walker, package); + + return map; +} + +LC_FUNCTION void LC_RemoveUnreferencedGlobalDecls(LC_Map *map_of_visits) { + for (LC_ASTRef *it = L->ordered_packages.first; it; it = it->next) { + for (LC_Decl *decl = it->ast->apackage.first_ordered; decl;) { + intptr_t ref_count = (intptr_t)LC_MapGetP(map_of_visits, decl); + + LC_Decl *remove = decl; + decl = decl->next; + if (ref_count == 0 && remove->foreign_name != LC_ILit("main")) { + LC_DLLRemove(it->ast->apackage.first_ordered, it->ast->apackage.last_ordered, remove); + } + } + } +} + +LC_FUNCTION void LC_ErrorOnUnreferencedLocals(LC_Map *map_of_visits) { + LC_Decl *first = (LC_Decl *)L->decl_arena->memory.data; + for (int i = 0; i < L->decl_count; i += 1) { + LC_Decl *decl = first + i; + if (decl->package == L->builtin_package) { + continue; + } + + intptr_t ref_count = (intptr_t)LC_MapGetP(map_of_visits, decl); + if (ref_count == 0) { + if (LC_IsStmt(decl->ast)) { + if (!LC_HasNote(decl->ast, L->iunused)) LC_ReportASTError(decl->ast, "unused local variable '%s'", decl->name); + } + } + } +} + +LC_FUNCTION void LC_FindUnusedLocalsAndRemoveUnusedGlobalDecls(void) { + if (L->errors) return; + LC_TempArena check = LC_BeginTemp(L->arena); + + LC_Map map = LC_CountDeclRefs(check.arena); + LC_ErrorOnUnreferencedLocals(&map); + LC_RemoveUnreferencedGlobalDecls(&map); + + LC_EndTemp(check); +} \ No newline at end of file diff --git a/src/compiler/genc.c b/src/compiler/genc.c new file mode 100644 index 0000000..7ff9ad4 --- /dev/null +++ b/src/compiler/genc.c @@ -0,0 +1,677 @@ +const bool LC_GenCInternalGenerateSizeofs = true; + +LC_FUNCTION void LC_GenCLineDirective(LC_AST *node) { + if (L->emit_line_directives) { + L->printer.last_line_num = node->pos->line; + LC_GenLinef("#line %d", L->printer.last_line_num); + LC_Intern file = node->pos->lex->file; + if (file != L->printer.last_filename) { + L->printer.last_filename = file; + LC_Genf(" \"%s\"", (char *)L->printer.last_filename); + } + } +} + +LC_FUNCTION void LC_GenLastCLineDirective(void) { + if (L->emit_line_directives) { + LC_Genf("#line %d", L->printer.last_line_num); + } +} + +LC_FUNCTION void LC_GenCLineDirectiveNum(int num) { + if (L->emit_line_directives) { + LC_Genf("#line %d", num); + } +} + +LC_FUNCTION char *LC_GenCTypeParen(char *str, char c) { + return c && c != '[' ? LC_Strf("(%s)", str) : str; +} + +LC_FUNCTION char *LC_GenCType(LC_Type *type, char *str) { + switch (type->kind) { + case LC_TypeKind_Pointer: { + return LC_GenCType(type->tptr.base, LC_GenCTypeParen(LC_Strf("*%s", str), *str)); + } break; + case LC_TypeKind_Array: { + if (type->tarray.size == 0) { + return LC_GenCType(type->tarray.base, LC_GenCTypeParen(LC_Strf("%s[]", str), *str)); + } else { + return LC_GenCType(type->tarray.base, LC_GenCTypeParen(LC_Strf("%s[%d]", str, type->tarray.size), *str)); + } + + } break; + case LC_TypeKind_Proc: { + LC_StringList out = {0}; + LC_Addf(L->arena, &out, "(*%s)", str); + LC_Addf(L->arena, &out, "("); + if (type->tagg.mems.count == 0) { + LC_Addf(L->arena, &out, "void"); + } else { + int i = 0; + for (LC_TypeMember *it = type->tproc.args.first; it; it = it->next) { + LC_Addf(L->arena, &out, "%s%s", i == 0 ? "" : ", ", LC_GenCType(it->type, "")); + i += 1; + } + } + if (type->tproc.vargs) { + LC_Addf(L->arena, &out, ", ..."); + } + LC_Addf(L->arena, &out, ")"); + char *front = LC_MergeString(L->arena, out).str; + char *result = LC_GenCType(type->tproc.ret, front); + return result; + } break; + default: return LC_Strf("%s%s%s", type->decl->foreign_name, str[0] ? " " : "", str); + } +} + +LC_FUNCTION LC_Intern LC_GetStringFromSingleArgNote(LC_AST *note) { + LC_ASSERT(note, note->kind == LC_ASTKind_Note); + LC_ASSERT(note, note->ecompo.first == note->ecompo.last); + LC_AST *arg = note->ecompo.first; + LC_ASSERT(note, arg->kind == LC_ASTKind_ExprCallItem); + LC_AST *str = arg->ecompo_item.expr; + LC_ASSERT(note, str->kind == LC_ASTKind_ExprString); + return str->eatom.name; +} + +LC_FUNCTION void LC_GenCCompound(LC_AST *n) { + LC_Type *type = n->type; + if (LC_IsAggType(type)) { + LC_ResolvedCompo *rd = n->ecompo.resolved_items; + LC_Genf("{"); + if (rd->first == NULL) LC_Genf("0"); + for (LC_ResolvedCompoItem *it = rd->first; it; it = it->next) { + LC_Genf(".%s = ", (char *)it->t->name); + LC_GenCExpr(it->expr); + if (it->next) LC_Genf(", "); + } + LC_Genf("}"); + } else if (LC_IsArray(type)) { + LC_ResolvedArrayCompo *rd = n->ecompo.resolved_array_items; + LC_Genf("{"); + for (LC_ResolvedCompoArrayItem *it = rd->first; it; it = it->next) { + LC_Genf("[%d] = ", it->index); + LC_GenCExpr(it->comp->ecompo_item.expr); + if (it->next) LC_Genf(", "); + } + LC_Genf("}"); + } else { + LC_ReportASTError(n, "internal compiler error: got unhandled case in %s", __FUNCTION__); + } +} + +LC_THREAD_LOCAL bool GC_SpecialCase_GlobalScopeStringDecl; + +LC_FUNCTION void LC_GenCString(char *s, LC_Type *type) { + if (type == L->tstring) { + if (!GC_SpecialCase_GlobalScopeStringDecl) LC_Genf("(LC_String)"); + LC_Genf("{ "); + } + LC_Genf("\""); + for (int i = 0; s[i]; i += 1) { + LC_String escape = LC_GetEscapeString(s[i]); + if (escape.len) { + LC_Genf("%.*s", LC_Expand(escape)); + } else { + LC_Genf("%c", s[i]); + } + } + LC_Genf("\""); + if (type == L->tstring) LC_Genf(", %d }", (int)LC_StrLen(s)); +} + +LC_FUNCTION char *LC_GenCVal(LC_TypeAndVal v, LC_Type *type) { + char *str = LC_GenLCTypeVal(v); + switch (type->kind) { + case LC_TypeKind_uchar: + case LC_TypeKind_ushort: + case LC_TypeKind_uint: str = LC_Strf("%su", str); break; + case LC_TypeKind_ulong: str = LC_Strf("%sul", str); break; + case LC_TypeKind_Pointer: + case LC_TypeKind_Proc: + case LC_TypeKind_ullong: str = LC_Strf("%sull", str); break; + case LC_TypeKind_long: str = LC_Strf("%sull", str); break; + case LC_TypeKind_llong: str = LC_Strf("%sull", str); break; + case LC_TypeKind_float: str = LC_Strf("%sf", str); break; + case LC_TypeKind_UntypedFloat: str = LC_Strf(" /*utfloat*/%s", str); break; + case LC_TypeKind_UntypedInt: str = LC_Strf(" /*utint*/%sull", str); break; + default: { + } + } + if (LC_IsUTInt(v.type) && !LC_IsUntyped(type) && type->size < 4) { + str = LC_Strf("(%s)%s", LC_GenCType(type, ""), str); + } + return str; +} + +LC_FUNCTION void LC_GenCExpr(LC_AST *n) { + LC_ASSERT(n, LC_IsExpr(n)); + intptr_t is_any = (intptr_t)LC_MapGetP(&L->implicit_any, n); + if (is_any) LC_Genf("(LC_Any){%d, (%s[]){", n->type->id, LC_GenCType(n->type, "")); + + if (n->const_val.type) { + bool contains_sizeof_like = LC_GenCInternalGenerateSizeofs ? LC_ContainsCBuiltin(n) : false; + if (!contains_sizeof_like) { + if (LC_IsUTStr(n->const_val.type)) { + LC_GenCString((char *)n->const_val.name, n->type); + } else { + char *val = LC_GenCVal(n->const_val, n->type); + LC_Genf("%s", val); + } + if (is_any) LC_Genf("}}"); + return; + } + } + + LC_Type *type = n->type; + switch (n->kind) { + case LC_ASTKind_ExprIdent: { + LC_Genf("%s", (char *)n->eident.resolved_decl->foreign_name); + } break; + + case LC_ASTKind_ExprCast: { + LC_Genf("("); + LC_Genf("(%s)", LC_GenCType(type, "")); + LC_Genf("("); + LC_GenCExpr(n->ecast.expr); + LC_Genf(")"); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprUnary: { + LC_Genf("%s(", LC_TokenKindToOperator(n->eunary.op)); + LC_GenCExpr(n->eunary.expr); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprAddPtr: { + LC_Genf("("); + LC_GenCExpr(n->ebinary.left); + LC_Genf("+"); + LC_GenCExpr(n->ebinary.right); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprBinary: { + LC_Genf("("); + LC_GenCExpr(n->ebinary.left); + LC_Genf("%s", LC_TokenKindToOperator(n->ebinary.op)); + LC_GenCExpr(n->ebinary.right); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprIndex: { + LC_Genf("("); + LC_GenCExpr(n->eindex.base); + LC_Genf("["); + LC_GenCExpr(n->eindex.index); + LC_Genf("]"); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprGetValueOfPointer: { + LC_Genf("(*("); + LC_GenCExpr(n->eunary.expr); + LC_Genf("))"); + } break; + + case LC_ASTKind_ExprGetPointerOfValue: { + LC_Genf("(&("); + LC_GenCExpr(n->eunary.expr); + LC_Genf("))"); + } break; + + case LC_ASTKind_ExprField: { + if (n->efield.parent_decl->kind != LC_DeclKind_Import) { + LC_Type *left_type = n->efield.left->type; + LC_GenCExpr(n->efield.left); + if (LC_IsPtr(left_type)) LC_Genf("->"); + else LC_Genf("."); + LC_Genf("%s", (char *)n->efield.right); + } else { + LC_Genf("%s", (char *)n->efield.resolved_decl->foreign_name); + } + } break; + + case LC_ASTKind_ExprCall: { + LC_ResolvedCompo *rd = n->ecompo.resolved_items; + LC_GenCExpr(n->ecompo.name); + LC_Genf("("); + for (LC_ResolvedCompoItem *it = rd->first; it; it = it->next) { + LC_GenCExpr(it->expr); + if (it->next) LC_Genf(", "); + } + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprCompound: { + LC_Genf("(%s)", LC_GenCType(type, "")); + LC_GenCCompound(n); + } break; + + case LC_ASTKind_ExprBuiltin: { + LC_ASSERT(n, n->ecompo.name->kind == LC_ASTKind_ExprIdent); + if (n->ecompo.name->eident.name == L->isizeof) { + LC_Genf("sizeof("); + LC_AST *expr = n->ecompo.first->ecompo_item.expr; + if (expr->kind == LC_ASTKind_ExprType) { + LC_Genf("%s", LC_GenCType(expr->type, "")); + } else { + LC_GenCExpr(expr); + } + LC_Genf(")"); + } else if (n->ecompo.name->eident.name == L->ialignof) { + LC_Genf("LC_Alignof("); + LC_AST *expr = n->ecompo.first->ecompo_item.expr; + if (expr->kind == LC_ASTKind_ExprType) { + LC_Genf("%s", LC_GenCType(expr->type, "")); + } else { + LC_GenCExpr(expr); + } + LC_Genf(")"); + } else if (n->ecompo.name->eident.name == L->ioffsetof) { + LC_AST *i1 = n->ecompo.first->ecompo_item.expr; + LC_AST *i2 = n->ecompo.first->next->ecompo_item.expr; + LC_Genf("offsetof(%s, %s)", LC_GenCType(i1->type, ""), (char *)i2->eident.name); + } else { + LC_ReportASTError(n, "internal compiler error: got unhandled case in %s / LC_ASTKind_ExprBuiltin", __FUNCTION__); + } + } break; + + default: LC_ReportASTError(n, "internal compiler error: got unhandled case in %s", __FUNCTION__); + } + + if (is_any) LC_Genf("}}"); +} + +const int GC_Stmt_OmitSemicolonAndNewLine = 1; + +LC_FUNCTION void LC_GenCNote(LC_AST *note) { + if (note->ecompo.name->eident.name == L->ic) { + LC_Genf("%s", (char *)LC_GetStringFromSingleArgNote(note)); + } +} + +LC_FUNCTION void LC_GenCVarExpr(LC_AST *n, bool is_declaration) { + if (LC_HasNote(n, L->inot_init)) return; + + LC_AST *e = n->dvar.expr; + if (n->kind == LC_ASTKind_StmtVar) e = n->svar.expr; + if (e) { + LC_Genf(" = "); + if (e->kind == LC_ASTKind_ExprNote) { + LC_GenCNote(e->enote.expr); + } else if (is_declaration && e->kind == LC_ASTKind_ExprCompound) { + LC_GenCCompound(e); + } else { + LC_GenCExpr(e); + } + } else { + LC_Genf(" = {0}"); + } +} + +LC_FUNCTION void LC_GenCDefers(LC_AST *block) { + LC_AST *first = block->sblock.first_defer; + if (first == NULL) return; + + int save = L->printer.last_line_num; + LC_GenLine(); + LC_GenLastCLineDirective(); + + LC_GenLinef("/*defer*/"); + for (LC_AST *it = first; it; it = it->sdefer.next) { + LC_GenCStmtBlock(it->sdefer.body); + } + + L->printer.last_line_num = save + 1; + LC_GenLine(); + LC_GenLastCLineDirective(); +} + +LC_FUNCTION void LC_GenCDefersLoopBreak(LC_AST *n) { + LC_ASSERT(n, n->kind == LC_ASTKind_StmtBreak || n->kind == LC_ASTKind_StmtContinue); + LC_AST *it = NULL; + for (int i = L->printer.out_block_stack.len - 1; i >= 0; i -= 1) { + it = L->printer.out_block_stack.data[i]; + LC_GenCDefers(it); + LC_ASSERT(it, it->sblock.kind != SBLK_Proc); + if (it->sblock.kind == SBLK_Loop) { + if (!n->sbreak.name) break; + if (n->sbreak.name && it->sblock.name == n->sbreak.name) break; + } + } + LC_ASSERT(it, it->sblock.kind == SBLK_Loop); +} + +LC_FUNCTION void LC_GenCDefersReturn(LC_AST *n) { + LC_ASSERT(n, n->kind == LC_ASTKind_StmtReturn); + LC_AST *it = NULL; + for (int i = L->printer.out_block_stack.len - 1; i >= 0; i -= 1) { + it = L->printer.out_block_stack.data[i]; + LC_GenCDefers(it); + if (it->sblock.kind == SBLK_Proc) { + break; + } + } + LC_ASSERT(it, it); + LC_ASSERT(it, it->sblock.kind == SBLK_Proc); +} + +LC_FUNCTION void LC_GenCStmt2(LC_AST *n, int flags) { + LC_ASSERT(n, LC_IsStmt(n)); + bool semicolon = !(flags & GC_Stmt_OmitSemicolonAndNewLine); + + if (semicolon) { + LC_GenLine(); + } + + switch (n->kind) { + case LC_ASTKind_StmtVar: { + LC_Type *type = n->type; + LC_Genf("%s", LC_GenCType(type, (char *)n->svar.name)); + LC_GenCVarExpr(n, true); + } break; + case LC_ASTKind_StmtExpr: LC_GenCExpr(n->sexpr.expr); break; + + case LC_ASTKind_StmtAssign: { + // Assigning to array doesn't work in C so we need to handle that + // specific compo case here. :CompoArray + if (LC_IsArray(n->type) && n->sassign.right->kind == LC_ASTKind_ExprCompound) { + LC_ASSERT(n, n->sassign.op == LC_TokenKind_Assign); + LC_AST *expr = n->sassign.right; + LC_Genf("memset("); + LC_GenCExpr(n->sassign.left); + LC_Genf(", 0, sizeof("); + LC_GenCExpr(n->sassign.left); + LC_Genf("));"); + + LC_ResolvedArrayCompo *rd = expr->ecompo.resolved_array_items; + for (LC_ResolvedCompoArrayItem *it = rd->first; it; it = it->next) { + LC_GenCExpr(n->sassign.left); + LC_Genf("[%d] = ", it->index); + LC_GenCExpr(it->comp->ecompo_item.expr); + LC_Genf(";"); + } + + } else { + LC_GenCExpr(n->sassign.left); + LC_Genf(" %s ", LC_TokenKindToOperator(n->sassign.op)); + LC_GenCExpr(n->sassign.right); + } + } break; + default: LC_ReportASTError(n, "internal compiler error: got unhandled case in %s", __FUNCTION__); + } + + if (semicolon) LC_Genf(";"); +} + +LC_FUNCTION void LC_GenCStmt(LC_AST *n) { + LC_ASSERT(n, LC_IsStmt(n)); + LC_GenCLineDirective(n); + switch (n->kind) { + case LC_ASTKind_StmtConst: + case LC_ASTKind_StmtDefer: break; + case LC_ASTKind_StmtNote: { + LC_GenLine(); + LC_GenCNote(n->snote.expr); + LC_Genf(";"); + } break; + + case LC_ASTKind_StmtReturn: { + LC_GenCDefersReturn(n); + LC_GenLinef("return"); + if (n->sreturn.expr) { + LC_Genf(" "); + LC_GenCExpr(n->sreturn.expr); + } + LC_Genf(";"); + } break; + + case LC_ASTKind_StmtContinue: + case LC_ASTKind_StmtBreak: { + const char *stmt = n->kind == LC_ASTKind_StmtBreak ? "break" : "continue"; + LC_GenCDefersLoopBreak(n); + if (n->sbreak.name) { + LC_GenLinef("goto %s_%s;", (char *)n->sbreak.name, stmt); + } else { + LC_GenLinef("%s;", stmt); + } + } break; + + case LC_ASTKind_StmtBlock: { + LC_GenLinef("/*block*/"); + LC_GenCStmtBlock(n); + } break; + + case LC_ASTKind_StmtSwitch: { + LC_GenLinef("switch("); + LC_GenCExpr(n->sswitch.expr); + LC_Genf(") {"); + + L->printer.indent += 1; + LC_ASTFor(it, n->sswitch.first) { + LC_GenCLineDirective(it); + if (it->kind == LC_ASTKind_StmtSwitchCase) { + LC_ASTFor(label_it, it->scase.first) { + LC_GenLinef("case "); + LC_GenCExpr(label_it); + LC_Genf(":"); + } + } + if (it->kind == LC_ASTKind_StmtSwitchDefault) { + LC_GenLinef("default:"); + } + LC_GenCStmtBlock(it->scase.body); + if (LC_HasNote(it, L->ifallthrough)) { + LC_Genf(" /*@fallthough*/"); + } else { + LC_Genf(" break;"); + } + } + L->printer.indent -= 1; + LC_GenLinef("}"); + } break; + + case LC_ASTKind_StmtFor: { + LC_GenLinef("for ("); + if (n->sfor.init) LC_GenCStmt2(n->sfor.init, GC_Stmt_OmitSemicolonAndNewLine); + LC_Genf(";"); + if (n->sfor.cond) { + LC_Genf(" "); + LC_GenCExpr(n->sfor.cond); + } + LC_Genf(";"); + if (n->sfor.inc) { + LC_Genf(" "); + LC_GenCStmt2(n->sfor.inc, GC_Stmt_OmitSemicolonAndNewLine); + } + LC_Genf(")"); + LC_GenCStmtBlock(n->sfor.body); + } break; + + case LC_ASTKind_StmtIf: { + LC_GenLinef("if "); + LC_GenCExprParen(n->sif.expr); + LC_GenCStmtBlock(n->sif.body); + LC_ASTFor(it, n->sif.first) { + LC_GenCLineDirective(it); + LC_GenLinef("else"); + if (it->kind == LC_ASTKind_StmtElseIf) { + LC_Genf(" if "); + LC_GenCExprParen(it->sif.expr); + } + LC_GenCStmtBlock(it->sif.body); + } + } break; + + default: LC_GenCStmt2(n, 0); + } +} + +LC_FUNCTION void LC_GenCExprParen(LC_AST *expr) { + bool paren = expr->kind != LC_ASTKind_ExprBinary; + if (paren) LC_Genf("("); + LC_GenCExpr(expr); + if (paren) LC_Genf(")"); +} + +LC_FUNCTION void LC_GenCStmtBlock(LC_AST *n) { + LC_PushAST(&L->printer.out_block_stack, n); + LC_ASSERT(n, n->kind == LC_ASTKind_StmtBlock); + LC_Genf(" {"); + L->printer.indent += 1; + LC_ASTFor(it, n->sblock.first) { + LC_GenCStmt(it); + } + LC_GenCDefers(n); + if (n->sblock.name) LC_GenLinef("%s_continue:;", (char *)n->sblock.name); + L->printer.indent -= 1; + LC_GenLinef("}"); + if (n->sblock.name) LC_GenLinef("%s_break:;", (char *)n->sblock.name); + LC_PopAST(&L->printer.out_block_stack); +} + +LC_FUNCTION void LC_GenCProcDecl(LC_Decl *decl) { + LC_StringList out = {0}; + LC_Type *type = decl->type; + LC_AST *n = decl->ast; + LC_AST *typespec = n->dproc.type; + + LC_Addf(L->arena, &out, "%s(", (char *)decl->foreign_name); + if (type->tagg.mems.count == 0) { + LC_Addf(L->arena, &out, "void"); + } else { + int i = 0; + LC_ASTFor(it, typespec->tproc.first) { + LC_Type *type = it->type; + LC_Addf(L->arena, &out, "%s%s", i == 0 ? "" : ", ", LC_GenCType(type, (char *)it->tproc_arg.name)); + i += 1; + } + } + if (type->tproc.vargs) { + LC_Addf(L->arena, &out, ", ..."); + } + LC_Addf(L->arena, &out, ")"); + char *front = LC_MergeString(L->arena, out).str; + char *result = LC_GenCType(type->tproc.ret, front); + + LC_GenLine(); + bool is_public = LC_HasNote(n, L->iapi) || decl->foreign_name == L->imain; + if (!is_public) LC_Genf("static "); + LC_Genf("%s", result); +} + +LC_FUNCTION void LC_GenCAggForwardDecl(LC_Decl *decl) { + LC_ASSERT(decl->ast, LC_IsAgg(decl->ast)); + char *agg = LC_GenLCAggName(decl->type); + LC_GenLinef("typedef %s %s %s;", agg, (char *)decl->foreign_name, (char *)decl->foreign_name); +} + +LC_FUNCTION void LC_GenCTypeDecl(LC_Decl *decl) { + LC_AST *n = decl->ast; + LC_ASSERT(n, decl->kind == LC_DeclKind_Type); + if (n->kind == LC_ASTKind_DeclTypedef) { + LC_Type *type = decl->typedef_renamed_type_decl ? decl->typedef_renamed_type_decl->type : decl->type; + LC_GenLinef("typedef %s;", LC_GenCType(type, (char *)decl->foreign_name)); + } else { + LC_Type *type = decl->type; + LC_Intern name = decl->foreign_name; + { + bool packed = LC_HasNote(n, L->ipacked) ? true : false; + if (packed) LC_GenLinef("#pragma pack(push, 1)"); + + LC_GenLinef("%s %s {", LC_GenLCAggName(type), name ? (char *)name : ""); + L->printer.indent += 1; + for (LC_TypeMember *it = type->tagg.mems.first; it; it = it->next) { + LC_GenLinef("%s;", LC_GenCType(it->type, (char *)it->name)); + } + L->printer.indent -= 1; + LC_GenLinef("};"); + if (packed) LC_GenLinef("#pragma pack(pop)"); + LC_GenLine(); + } + } +} + +LC_FUNCTION void LC_GenCVarFDecl(LC_Decl *decl) { + if (!LC_HasNote(decl->ast, L->iapi)) return; + LC_Type *type = decl->type; // make string arrays assignable + LC_GenLinef("extern "); + if (LC_HasNote(decl->ast, L->ithread_local)) LC_Genf("_Thread_local "); + LC_Genf("%s;", LC_GenCType(type, (char *)decl->foreign_name)); +} + +LC_FUNCTION void LC_GenCHeader(LC_AST *package) { + // C notes + LC_ASTFor(file, package->apackage.ffile) { + LC_ASTFor(it, file->afile.fdecl) { + if (it->kind != LC_ASTKind_DeclNote) continue; + + LC_AST *note = it->dnote.expr; + if (note->ecompo.name->eident.name == L->ic) { + LC_GenLinef("%s", (char *)LC_GetStringFromSingleArgNote(note)); + } + } + } + + // struct forward decls + LC_DeclFor(decl, package->apackage.first_ordered) { + if (decl->is_foreign) continue; + LC_AST *n = decl->ast; + if (decl->kind == LC_DeclKind_Type && LC_IsAgg(n)) LC_GenCAggForwardDecl(decl); + } + + // type decls + LC_GenLine(); + LC_DeclFor(decl, package->apackage.first_ordered) { + if (decl->is_foreign) continue; + LC_AST *n = decl->ast; + if (decl->kind == LC_DeclKind_Type) LC_GenCTypeDecl(decl); + } + + // proc and var forward decls + LC_DeclFor(decl, package->apackage.first_ordered) { + if (decl->is_foreign) continue; + LC_AST *n = decl->ast; + if (decl->kind == LC_DeclKind_Var) { + LC_GenCVarFDecl(decl); + } else if (decl->kind == LC_DeclKind_Proc) { + LC_GenCProcDecl(decl); + LC_Genf(";"); + } + } +} + +LC_FUNCTION void LC_GenCImpl(LC_AST *package) { + // implementation of vars + LC_DeclFor(decl, package->apackage.first_ordered) { + if (decl->kind == LC_DeclKind_Var && !decl->is_foreign) { + LC_AST *n = decl->ast; + LC_Type *type = decl->type; // make string arrays assignable + LC_GenLine(); + if (!LC_HasNote(n, L->iapi)) LC_Genf("static "); + if (LC_HasNote(n, L->ithread_local)) LC_Genf("_Thread_local "); + LC_Genf("%s", LC_GenCType(type, (char *)decl->foreign_name)); + + GC_SpecialCase_GlobalScopeStringDecl = true; + LC_GenCVarExpr(n, true); + GC_SpecialCase_GlobalScopeStringDecl = false; + LC_Genf(";"); + LC_GenLine(); + } + } + + // implementation of procs + LC_DeclFor(decl, package->apackage.first_ordered) { + LC_AST *n = decl->ast; + if (decl->kind == LC_DeclKind_Proc && n->dproc.body && !decl->is_foreign) { + LC_GenCLineDirective(n); + LC_GenCProcDecl(decl); + LC_GenCStmtBlock(n->dproc.body); + LC_GenLine(); + } + } +} diff --git a/src/compiler/init.c b/src/compiler/init.c new file mode 100644 index 0000000..7622dab --- /dev/null +++ b/src/compiler/init.c @@ -0,0 +1,259 @@ +LC_FUNCTION LC_Lang *LC_LangAlloc(void) { + LC_Arena *arena = LC_BootstrapArena(); + LC_Arena *lex_arena = LC_PushStruct(arena, LC_Arena); + LC_Arena *decl_arena = LC_PushStruct(arena, LC_Arena); + LC_Arena *ast_arena = LC_PushStruct(arena, LC_Arena); + LC_Arena *type_arena = LC_PushStruct(arena, LC_Arena); + LC_InitArena(lex_arena); + LC_InitArena(decl_arena); + LC_InitArena(ast_arena); + LC_InitArena(type_arena); + + LC_Lang *l = LC_PushStruct(arena, LC_Lang); + l->arena = arena; + l->lex_arena = lex_arena; + l->decl_arena = decl_arena; + l->ast_arena = ast_arena; + l->type_arena = type_arena; + + l->emit_line_directives = true; + l->breakpoint_on_error = true; + l->use_colored_terminal_output = true; + + return l; +} + +LC_FUNCTION void LC_LangEnd(LC_Lang *lang) { + LC_DeallocateArena(lang->lex_arena); + LC_DeallocateArena(lang->type_arena); + LC_DeallocateArena(lang->decl_arena); + LC_DeallocateArena(lang->ast_arena); + LC_DeallocateArena(lang->arena); + if (L == lang) L = NULL; +} + +LC_FUNCTION void LC_LangBegin(LC_Lang *l) { + L = l; + + // Init default target settings + { + if (L->os == LC_OS_Invalid) { + L->os = LC_OS_LINUX; +#if LC_OPERATING_SYSTEM_WINDOWS + L->os = LC_OS_WINDOWS; +#elif LC_OPERATING_SYSTEM_MAC + L->os = LC_OS_MAC; +#endif + } + if (L->arch == LC_ARCH_Invalid) { + L->arch = LC_ARCH_X64; + } + if (L->gen == LC_GEN_Invalid) { + L->gen = LC_GEN_C; + } + } + + // + // Init declared notes, interns and foreign names checker + // + { + L->declared_notes.arena = L->arena; + L->interns.arena = L->arena; + L->foreign_names.arena = L->arena; + L->implicit_any.arena = L->arena; + + LC_MapReserve(&L->declared_notes, 128); + LC_MapReserve(&L->interns, 4096); + LC_MapReserve(&L->foreign_names, 256); + LC_MapReserve(&L->implicit_any, 64); + +#define X(x) l->k##x = LC_InternStrLen(#x, sizeof(#x) - 1); + LC_LIST_KEYWORDS +#undef X + l->first_keyword = l->kfor; + l->last_keyword = l->kfalse; + +#define X(x, declare) l->i##x = LC_InternStrLen(#x, sizeof(#x) - 1); + LC_LIST_INTERNS +#undef X +#define X(x, declare) \ + if (declare) LC_DeclareNote(L->i##x); + LC_LIST_INTERNS +#undef X + } + + // Nulls + { + L->NullLEX.begin = "builtin declarations"; + L->NullLEX.file = LC_ILit("builtin declarations"); + L->BuiltinToken.lex = &L->NullLEX; + L->BuiltinToken.str = "builtin declarations"; + L->BuiltinToken.len = sizeof("builtin declarations") - 1; + L->NullAST.pos = &L->BuiltinToken; + } + + { + LC_AST *builtins = LC_CreateAST(0, LC_ASTKind_Package); + L->builtin_package = builtins; + builtins->apackage.name = LC_ILit("builtins"); + builtins->apackage.scope = LC_CreateScope(256); + LC_AddPackageToList(builtins); + } + + LC_InitDeclStack(&L->resolver.locals, 128); + L->resolver.duplicate_map.arena = L->arena; + LC_MapReserve(&L->resolver.duplicate_map, 32); + + L->resolver.stmt_block_stack.arena = L->arena; + L->printer.out_block_stack.arena = L->arena; + + LC_PUSH_PACKAGE(L->builtin_package); + + // + // Init default type sizes using current platform + // + // Here we use the sizes of our current platform but + // later on it gets swapped based on LC override global variables in + // InitTarget + // + { + l->type_map.arena = L->arena; + LC_MapReserve(&l->type_map, 256); + + typedef long long llong; + typedef unsigned long long ullong; + typedef unsigned long ulong; + typedef unsigned short ushort; + typedef unsigned char uchar; + typedef unsigned int uint; + + L->pointer_align = LC_Alignof(void *); + L->pointer_size = sizeof(void *); + + int i = 0; +#define X(TNAME, IS_UNSIGNED) \ + l->types[i].kind = LC_TypeKind_##TNAME; \ + l->types[i].size = sizeof(TNAME); \ + l->types[i].align = LC_Alignof(TNAME); \ + l->types[i].is_unsigned = IS_UNSIGNED; \ + l->t##TNAME = l->types + i++; + + LC_LIST_TYPES +#undef X + + // + // Overwrite types with target + // + if (L->arch == LC_ARCH_X64) { + LC_SetPointerSizeAndAlign(8, 8); + if (L->os == LC_OS_WINDOWS) { + L->tlong->size = 4; + L->tlong->align = 4; + L->tulong->size = 4; + L->tulong->align = 4; + } else { + L->tlong->size = 8; + L->tlong->align = 8; + L->tulong->size = 8; + L->tulong->align = 8; + } + } else if (L->arch == LC_ARCH_X86) { + LC_SetPointerSizeAndAlign(4, 4); + L->tlong->size = 4; + L->tlong->align = 4; + L->tulong->size = 4; + L->tulong->align = 4; + } + + l->types[i].kind = LC_TypeKind_void; + l->tvoid = l->types + i++; + + // Init decls for types + for (int i = 0; i < T_Count; i += 1) { + char *it = (char *)LC_TypeKindToString((LC_TypeKind)i) + 12; + LC_Intern intern = LC_ILit(it); + LC_Type *t = l->types + i; + t->id = ++l->typeids; + + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Type, intern, &L->NullAST); + decl->state = LC_DeclState_Resolved; + decl->type = t; + t->decl = decl; + LC_AddDeclToScope(L->builtin_package->apackage.scope, decl); + + if (t->kind == LC_TypeKind_uchar) decl->foreign_name = LC_ILit("unsigned char"); + if (t->kind == LC_TypeKind_ushort) decl->foreign_name = LC_ILit("unsigned short"); + if (t->kind == LC_TypeKind_uint) decl->foreign_name = LC_ILit("unsigned"); + if (t->kind == LC_TypeKind_ulong) decl->foreign_name = LC_ILit("unsigned long"); + if (t->kind == LC_TypeKind_llong) decl->foreign_name = LC_ILit("long long"); + if (t->kind == LC_TypeKind_ullong) decl->foreign_name = LC_ILit("unsigned long long"); + } + } + + l->tpvoid = LC_CreatePointerType(l->tvoid); + l->tpchar = LC_CreatePointerType(l->tchar); + + { + l->tuntypedint = LC_CreateUntypedInt(L->tint); + l->tuntypedbool = LC_CreateUntypedInt(L->tbool); + l->tuntypednil = LC_CreateUntypedInt(L->tullong); + + l->ttuntypedfloat.kind = LC_TypeKind_UntypedFloat; + l->ttuntypedfloat.id = ++L->typeids; + l->tuntypedfloat = &L->ttuntypedfloat; + l->tuntypedfloat->tutdefault = l->tdouble; + l->tuntypedfloat->decl = LC_CreateDecl(LC_DeclKind_Type, LC_ILit("UntypedFloat"), &L->NullAST); + + l->ttuntypedstring.kind = LC_TypeKind_UntypedString; + l->ttuntypedstring.id = ++L->typeids; + l->tuntypedstring = &L->ttuntypedstring; + l->tuntypedstring->tutdefault = l->tpchar; + l->tuntypedstring->decl = LC_CreateDecl(LC_DeclKind_Type, LC_ILit("UntypedString"), &L->NullAST); + } + + // Add builtin "String" type + { + L->ttstring.kind = LC_TypeKind_Incomplete; + L->ttstring.id = ++L->typeids; + L->tstring = &L->ttstring; + + LC_AST *ast = LC_ParseDeclf("String :: struct { str: *char; len: int; }"); + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Type, ast->dbase.name, ast); + decl->foreign_name = LC_ILit("LC_String"); + decl->state = LC_DeclState_Resolved; + decl->type = L->tstring; + L->tstring->decl = decl; + LC_AddDeclToScope(L->builtin_package->apackage.scope, decl); + LC_Operand result = LC_ResolveTypeAggregate(ast, decl->type); + LC_ASSERT(ast, !LC_IsError(result)); + } + + // Add builtin "Any" type + { + L->ttany.kind = LC_TypeKind_Incomplete; + L->ttany.id = ++L->typeids; + L->tany = &L->ttany; + + LC_AST *ast = LC_ParseDeclf("Any :: struct { type: int; data: *void; }"); + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Type, ast->dbase.name, ast); + decl->foreign_name = LC_ILit("LC_Any"); + decl->state = LC_DeclState_Resolved; + decl->type = L->tany; + L->tany->decl = decl; + LC_AddDeclToScope(L->builtin_package->apackage.scope, decl); + LC_Operand result = LC_ResolveTypeAggregate(ast, decl->type); + LC_ASSERT(ast, !LC_IsError(result)); + } + + LC_Decl *decl_nil = LC_AddConstIntDecl("nil", 0); + decl_nil->type = L->tuntypednil; + + for (int i = LC_ARCH_X64; i < LC_ARCH_Count; i += 1) LC_AddBuiltinConstInt((char *)LC_ARCHToString((LC_ARCH)i), i); + for (int i = LC_OS_WINDOWS; i < LC_OS_Count; i += 1) LC_AddBuiltinConstInt((char *)LC_OSToString((LC_OS)i), i); + for (int i = LC_GEN_C; i < LC_GEN_Count; i += 1) LC_AddBuiltinConstInt((char *)LC_GENToString((LC_GEN)i), i); + LC_AddBuiltinConstInt("LC_ARCH", L->arch); + LC_AddBuiltinConstInt("LC_GEN", L->gen); + LC_AddBuiltinConstInt("LC_OS", L->os); + + LC_POP_PACKAGE(); +} diff --git a/src/compiler/intern.c b/src/compiler/intern.c new file mode 100644 index 0000000..56aa465 --- /dev/null +++ b/src/compiler/intern.c @@ -0,0 +1,44 @@ +typedef struct { + int len; + char str[]; +} INTERN_Entry; + +LC_FUNCTION LC_Intern LC_InternStrLen(char *str, int len) { + LC_String key = LC_MakeString(str, len); + INTERN_Entry *entry = (INTERN_Entry *)LC_MapGet(&L->interns, key); + if (entry == NULL) { + LC_ASSERT(NULL, sizeof(INTERN_Entry) == sizeof(int)); + entry = (INTERN_Entry *)LC_PushSize(L->arena, sizeof(int) + sizeof(char) * (len + 1)); + entry->len = len; + LC_MemoryCopy(entry->str, str, len); + entry->str[len] = 0; + LC_MapInsert(&L->interns, key, entry); + } + + return (uintptr_t)entry->str; +} + +LC_FUNCTION LC_Intern LC_ILit(char *str) { + return LC_InternStrLen(str, (int)LC_StrLen(str)); +} + +LC_FUNCTION LC_Intern LC_GetUniqueIntern(const char *name_for_debug) { + LC_String name = LC_Format(L->arena, "U%u_%s", ++L->unique_counter, name_for_debug); + LC_Intern result = LC_InternStrLen(name.str, (int)name.len); + return result; +} + +LC_FUNCTION char *LC_GetUniqueName(const char *name_for_debug) { + LC_String name = LC_Format(L->arena, "U%u_%s", ++L->unique_counter, name_for_debug); + return name.str; +} + +LC_FUNCTION void LC_DeclareNote(LC_Intern intern) { + LC_MapInsertU64(&L->declared_notes, intern, (void *)intern); +} + +LC_FUNCTION bool LC_IsNoteDeclared(LC_Intern intern) { + void *p = LC_MapGetU64(&L->declared_notes, intern); + bool result = p != NULL; + return result; +} \ No newline at end of file diff --git a/src/compiler/lex.c b/src/compiler/lex.c new file mode 100644 index 0000000..337a65e --- /dev/null +++ b/src/compiler/lex.c @@ -0,0 +1,535 @@ +LC_FUNCTION void LC_LexingError(LC_Token *pos, const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + LC_SendErrorMessage(pos, s8); + L->errors += 1; + pos->kind = LC_TokenKind_Error; +} + +#define LC_IF(cond, ...) \ + do { \ + if (cond) { \ + LC_LexingError(t, __VA_ARGS__); \ + return; \ + } \ + } while (0) + +LC_FUNCTION bool LC_IsAssign(LC_TokenKind kind) { + bool result = kind >= LC_TokenKind_Assign && kind <= LC_TokenKind_RightShiftAssign; + return result; +} + +LC_FUNCTION bool LC_IsHexDigit(char c) { + bool result = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); + return result; +} + +LC_FUNCTION bool LC_IsBinDigit(char c) { + bool result = (c >= '0' && c <= '1'); + return result; +} + +LC_FUNCTION uint64_t LC_MapCharToNumber(char c) { + // clang-format off + switch (c) { + case '0': return 0; + case '1': return 1; + case '2': return 2; + case '3': return 3; + case '4': return 4; + case '5': return 5; + case '6': return 6; + case '7': return 7; + case '8': return 8; + case '9': return 9; + case 'a': case 'A': return 10; + case 'b': case 'B': return 11; + case 'c': case 'C': return 12; + case 'd': case 'D': return 13; + case 'e': case 'E': return 14; + case 'f': case 'F': return 15; + default: return 255; + } + // clang-format on +} + +LC_FUNCTION uint64_t LC_GetEscapeCode(char c) { + switch (c) { + case 'a': return '\a'; + case 'b': return '\b'; + case 'e': return 0x1B; + case 'f': return '\f'; + case 'n': return '\n'; + case 'r': return '\r'; + case 't': return '\t'; + case 'v': return '\v'; + case '\\': return '\\'; + case '\'': return '\''; + case '\"': return '\"'; + case '0': return '\0'; + default: return UINT64_MAX; + } +} + +LC_FUNCTION LC_String LC_GetEscapeString(char c) { + switch (c) { + case '\a': return LC_Lit("\\a"); + case '\b': return LC_Lit("\\b"); + case 0x1B: return LC_Lit("\\x1B"); + case '\f': return LC_Lit("\\f"); + case '\n': return LC_Lit("\\n"); + case '\r': return LC_Lit("\\r"); + case '\t': return LC_Lit("\\t"); + case '\v': return LC_Lit("\\v"); + case '\\': return LC_Lit("\\\\"); + case '\'': return LC_Lit("\\'"); + case '\"': return LC_Lit("\\\""); + case '\0': return LC_Lit("\\0"); + default: return LC_Lit(""); + } +} + +LC_FUNCTION void LC_LexAdvance(LC_Lex *x) { + if (x->at[0] == 0) { + return; + } else if (x->at[0] == '\n') { + x->line += 1; + x->column = 0; + } + x->column += 1; + x->at += 1; +} + +LC_FUNCTION void LC_EatWhitespace(LC_Lex *x) { + while (LC_IsWhitespace(x->at[0])) LC_LexAdvance(x); +} + +LC_FUNCTION void LC_EatIdent(LC_Lex *x) { + while (x->at[0] == '_' || LC_IsAlphanumeric(x->at[0])) LC_LexAdvance(x); +} + +LC_FUNCTION void LC_SetTokenLen(LC_Lex *x, LC_Token *t) { + t->len = (int)(x->at - t->str); + LC_ASSERT(NULL, t->len < 2000000000); +} + +LC_FUNCTION void LC_EatUntilIncluding(LC_Lex *x, char c) { + while (x->at[0] != 0 && x->at[0] != c) LC_LexAdvance(x); + LC_LexAdvance(x); +} + +// @todo: add temporary allocation + copy at end to perm +LC_FUNCTION LC_BigInt LC_LexBigInt(char *string, int len, uint64_t base) { + LC_ASSERT(NULL, base >= 2 && base <= 16); + LC_BigInt m = LC_Bigint_u64(1); + LC_BigInt base_mul = LC_Bigint_u64(base); + LC_BigInt result = LC_Bigint_u64(0); + + LC_BigInt tmp = {0}; + for (int i = len - 1; i >= 0; --i) { + uint64_t u = LC_MapCharToNumber(string[i]); + LC_ASSERT(NULL, u < base); + LC_BigInt val = LC_Bigint_u64(u); + LC_Bigint_mul(&tmp, &val, &m); + LC_BigInt new_val = tmp; + LC_Bigint_add(&tmp, &result, &new_val); + result = tmp; + LC_Bigint_mul(&tmp, &m, &base_mul); + m = tmp; + } + + return result; +} + +LC_FUNCTION void LC_LexNestedComments(LC_Lex *x, LC_Token *t) { + t->kind = LC_TokenKind_Comment; + LC_LexAdvance(x); + + if (x->at[0] == '*') { + LC_LexAdvance(x); + t->kind = LC_TokenKind_DocComment; + + if (x->at[0] == ' ' && x->at[1] == 'f' && x->at[2] == 'i' && x->at[3] == 'l' && x->at[4] == 'e') { + t->kind = LC_TokenKind_FileDocComment; + } + + if (x->at[0] == ' ' && x->at[1] == 'p' && x->at[2] == 'a' && x->at[3] == 'c' && x->at[4] == 'k' && x->at[5] == 'a' && x->at[6] == 'g' && x->at[7] == 'e') { + t->kind = LC_TokenKind_PackageDocComment; + } + } + + int counter = 0; + for (;;) { + if (x->at[0] == '*' && x->at[1] == '/') { + if (counter <= 0) break; + counter -= 1; + } else if (x->at[0] == '/' && x->at[1] == '*') { + counter += 1; + LC_LexAdvance(x); + } + LC_IF(x->at[0] == 0, "Unclosed block comment"); + LC_LexAdvance(x); + } + t->str += 2; + LC_SetTokenLen(x, t); + LC_LexAdvance(x); + LC_LexAdvance(x); +} + +LC_FUNCTION void LC_LexStringLiteral(LC_Lex *x, LC_Token *t, LC_TokenKind kind) { + t->kind = kind; + if (kind == LC_TokenKind_RawString) { + LC_EatUntilIncluding(x, '`'); + } else if (kind == LC_TokenKind_String) { + for (;;) { + LC_IF(x->at[0] == '\n', "got a new line while parsing a '\"' string literal"); + LC_IF(x->at[0] == 0, "reached end of file during string lexing"); + if (x->at[0] == '"') break; + if (x->at[0] == '\\' && x->at[1] == '"') LC_LexAdvance(x); + LC_LexAdvance(x); + } + LC_LexAdvance(x); + } else { + LC_IF(1, "internal compiler error: unhandled case in %s", __FUNCTION__); + } + + LC_SetTokenLen(x, t); + t->len -= 2; + t->str += 1; +} + +LC_FUNCTION void LC_LexUnicodeLiteral(LC_Lex *x, LC_Token *t) { + t->kind = LC_TokenKind_Unicode; + LC_UTF32Result decode = LC_ConvertUTF8ToUTF32(x->at, 4); + LC_IF(decode.error, "invalid utf8 sequence"); + + uint8_t c[8] = {0}; + for (int i = 0; i < decode.advance; i += 1) { + c[i] = x->at[0]; + LC_LexAdvance(x); + } + uint64_t result = *(uint64_t *)&c[0]; + + if (result == '\\') { + LC_ASSERT(NULL, decode.advance == 1); + result = LC_GetEscapeCode(x->at[0]); + LC_IF(result == UINT64_MAX, "invalid escape code"); + LC_LexAdvance(x); + } + LC_IF(x->at[0] != '\'', "unclosed unicode literal"); + + LC_Bigint_init_signed(&t->i, result); + LC_LexAdvance(x); + LC_SetTokenLen(x, t); + t->str += 1; + t->len -= 2; + + LC_IF(t->len == 0, "empty unicode literal"); +} + +LC_FUNCTION void LC_LexIntOrFloat(LC_Lex *x, LC_Token *t) { + t->kind = LC_TokenKind_Int; + for (;;) { + if (x->at[0] == '.') { + LC_IF(t->kind == LC_TokenKind_Float, "failed to parse a floating point number, invalid format, found multiple '.'"); + if (t->kind == LC_TokenKind_Int) t->kind = LC_TokenKind_Float; + } else if (!LC_IsDigit(x->at[0])) break; + LC_LexAdvance(x); + } + + LC_SetTokenLen(x, t); + if (t->kind == LC_TokenKind_Int) { + t->i = LC_LexBigInt(t->str, t->len, 10); + } else if (t->kind == LC_TokenKind_Float) { + t->f64 = LC_ParseFloat(t->str, t->len); + } else { + LC_IF(1, "internal compiler error: unhandled case in %s", __FUNCTION__); + } +} + +LC_FUNCTION void LC_LexCase2(LC_Lex *x, LC_Token *t, LC_TokenKind tk0, char c, LC_TokenKind tk1) { + t->kind = tk0; + if (x->at[0] == c) { + LC_LexAdvance(x); + t->kind = tk1; + } +} + +LC_FUNCTION void LC_LexCase3(LC_Lex *x, LC_Token *t, LC_TokenKind tk, char c0, LC_TokenKind tk0, char c1, LC_TokenKind tk1) { + t->kind = tk; + if (x->at[0] == c0) { + t->kind = tk0; + LC_LexAdvance(x); + } else if (x->at[0] == c1) { + t->kind = tk1; + LC_LexAdvance(x); + } +} + +LC_FUNCTION void LC_LexCase4(LC_Lex *x, LC_Token *t, LC_TokenKind tk, char c0, LC_TokenKind tk0, char c1, LC_TokenKind tk1, char c2, LC_TokenKind tk2) { + t->kind = tk; + if (x->at[0] == c0) { + t->kind = tk0; + LC_LexAdvance(x); + } else if (x->at[0] == c1) { + LC_LexAdvance(x); + LC_LexCase2(x, t, tk1, c2, tk2); + } +} + +LC_FUNCTION void LC_LexNext(LC_Lex *x, LC_Token *t) { + LC_EatWhitespace(x); + LC_MemoryZero(t, sizeof(LC_Token)); + t->str = x->at; + t->line = x->line + 1; + t->column = x->column; + t->lex = x; + char *c = x->at; + LC_LexAdvance(x); + + switch (c[0]) { + case 0: t->kind = LC_TokenKind_EOF; break; + case '(': t->kind = LC_TokenKind_OpenParen; break; + case ')': t->kind = LC_TokenKind_CloseParen; break; + case '{': t->kind = LC_TokenKind_OpenBrace; break; + case '}': t->kind = LC_TokenKind_CloseBrace; break; + case '[': t->kind = LC_TokenKind_OpenBracket; break; + case ']': t->kind = LC_TokenKind_CloseBracket; break; + case ',': t->kind = LC_TokenKind_Comma; break; + case ':': t->kind = LC_TokenKind_Colon; break; + case ';': t->kind = LC_TokenKind_Semicolon; break; + case '~': t->kind = LC_TokenKind_Neg; break; + case '#': t->kind = LC_TokenKind_Hash; break; + case '@': t->kind = LC_TokenKind_Note; break; + case '\'': LC_LexUnicodeLiteral(x, t); break; + case '"': LC_LexStringLiteral(x, t, LC_TokenKind_String); break; + case '`': LC_LexStringLiteral(x, t, LC_TokenKind_RawString); break; + case '=': LC_LexCase2(x, t, LC_TokenKind_Assign, '=', LC_TokenKind_Equals); break; + case '!': LC_LexCase2(x, t, LC_TokenKind_Not, '=', LC_TokenKind_NotEquals); break; + case '*': LC_LexCase2(x, t, LC_TokenKind_Mul, '=', LC_TokenKind_MulAssign); break; + case '%': LC_LexCase2(x, t, LC_TokenKind_Mod, '=', LC_TokenKind_ModAssign); break; + case '+': LC_LexCase2(x, t, LC_TokenKind_Add, '=', LC_TokenKind_AddAssign); break; + case '-': LC_LexCase2(x, t, LC_TokenKind_Sub, '=', LC_TokenKind_SubAssign); break; + case '^': LC_LexCase2(x, t, LC_TokenKind_BitXor, '=', LC_TokenKind_BitXorAssign); break; + case '&': LC_LexCase3(x, t, LC_TokenKind_BitAnd, '=', LC_TokenKind_BitAndAssign, '&', LC_TokenKind_And); break; + case '|': LC_LexCase3(x, t, LC_TokenKind_BitOr, '=', LC_TokenKind_BitOrAssign, '|', LC_TokenKind_Or); break; + case '>': LC_LexCase4(x, t, LC_TokenKind_GreaterThen, '=', LC_TokenKind_GreaterThenEq, '>', LC_TokenKind_RightShift, '=', LC_TokenKind_RightShiftAssign); break; + case '<': LC_LexCase4(x, t, LC_TokenKind_LesserThen, '=', LC_TokenKind_LesserThenEq, '<', LC_TokenKind_LeftShift, '=', LC_TokenKind_LeftShiftAssign); break; + case '.': { + t->kind = LC_TokenKind_Dot; + if (x->at[0] == '.' && x->at[1] == '.') { + t->kind = LC_TokenKind_ThreeDots; + LC_LexAdvance(x); + LC_LexAdvance(x); + } + } break; + + case '0': { + if (x->at[0] == 'x') { + t->kind = LC_TokenKind_Int; + LC_LexAdvance(x); + while (LC_IsHexDigit(x->at[0])) LC_LexAdvance(x); + LC_SetTokenLen(x, t); + LC_IF(t->len < 3, "invalid hex number"); + t->i = LC_LexBigInt(t->str + 2, t->len - 2, 16); + break; + } + if (x->at[0] == 'b') { + t->kind = LC_TokenKind_Int; + LC_LexAdvance(x); + while (LC_IsBinDigit(x->at[0])) LC_LexAdvance(x); + LC_SetTokenLen(x, t); + LC_IF(t->len < 3, "invalid binary number"); + t->i = LC_LexBigInt(t->str + 2, t->len - 2, 2); + break; + } + } // @fallthrough + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': { + LC_LexIntOrFloat(x, t); + } break; + + case 'A': + case 'a': + case 'B': + case 'b': + case 'C': + case 'c': + case 'D': + case 'd': + case 'E': + case 'e': + case 'F': + case 'f': + case 'G': + case 'g': + case 'H': + case 'h': + case 'I': + case 'i': + case 'J': + case 'j': + case 'K': + case 'k': + case 'L': + case 'l': + case 'M': + case 'm': + case 'N': + case 'n': + case 'O': + case 'o': + case 'P': + case 'p': + case 'Q': + case 'q': + case 'R': + case 'r': + case 'S': + case 's': + case 'T': + case 't': + case 'U': + case 'u': + case 'V': + case 'v': + case 'W': + case 'w': + case 'X': + case 'x': + case 'Y': + case 'y': + case 'Z': + case 'z': + case '_': { + t->kind = LC_TokenKind_Ident; + LC_EatIdent(x); + } break; + + case '/': { + t->kind = LC_TokenKind_Div; + if (x->at[0] == '=') { + t->kind = LC_TokenKind_DivAssign; + LC_LexAdvance(x); + } else if (x->at[0] == '/') { + t->kind = LC_TokenKind_Comment; + LC_LexAdvance(x); + while (x->at[0] != '\n' && x->at[0] != 0) LC_LexAdvance(x); + LC_SetTokenLen(x, t); + } else if (x->at[0] == '*') { + LC_LexNestedComments(x, t); + } + } break; + + default: LC_IF(1, "invalid character"); + } + if (t->len == 0 && t->kind != LC_TokenKind_String && t->kind != LC_TokenKind_RawString) LC_SetTokenLen(x, t); + if (t->kind == LC_TokenKind_Comment) LC_LexNext(x, t); +} + +LC_FUNCTION LC_Lex *LC_LexStream(char *file, char *str, int line) { + LC_Lex *x = LC_PushStruct(L->lex_arena, LC_Lex); + x->begin = str; + x->at = str; + x->file = LC_ILit(file); + x->line = line; + + for (;;) { + LC_Token *t = LC_PushStruct(L->lex_arena, LC_Token); + if (!x->tokens) x->tokens = t; + x->token_count += 1; + + LC_LexNext(x, t); + if (t->kind == LC_TokenKind_EOF) break; + } + + return x; +} + +LC_FUNCTION LC_String LC_GetTokenLine(LC_Token *token) { + LC_Lex *x = token->lex; + LC_String content = LC_MakeFromChar(x->begin); + LC_StringList lines = LC_Split(L->arena, content, LC_Lit("\n"), 0); + + LC_String l[3] = {LC_MakeEmptyString()}; + + int line = 1; + for (LC_StringNode *it = lines.first; it; it = it->next) { + LC_String sline = it->string; + if (token->line - 1 == line) { + l[0] = LC_Format(L->arena, "> %.*s\n", LC_Expand(sline)); + } + if (token->line + 1 == line) { + l[2] = LC_Format(L->arena, "> %.*s\n", LC_Expand(sline)); + break; + } + if (token->line == line) { + int begin = (int)(token->str - sline.str); + LC_String left = LC_GetPrefix(sline, begin); + LC_String past_left = LC_Skip(sline, begin); + LC_String mid = LC_GetPrefix(past_left, token->len); + LC_String right = LC_Skip(past_left, token->len); + + char *green = "\033[32m"; + char *reset = "\033[0m"; + if (!L->use_colored_terminal_output) { + green = ">>>>"; + reset = "<<<<"; + } + l[1] = LC_Format(L->arena, "> %.*s%s%.*s%s%.*s\n", LC_Expand(left), green, LC_Expand(mid), reset, LC_Expand(right)); + } + line += 1; + } + + LC_String result = LC_Format(L->arena, "%.*s%.*s%.*s", LC_Expand(l[0]), LC_Expand(l[1]), LC_Expand(l[2])); + return result; +} + +LC_FUNCTION void LC_InternTokens(LC_Lex *x) { + // @todo: add scratch, we can dump the LC_PushArray strings + for (int i = 0; i < x->token_count; i += 1) { + LC_Token *t = x->tokens + i; + if (t->kind == LC_TokenKind_String) { + int string_len = 0; + char *string = LC_PushArray(L->arena, char, t->len); + for (int i = 0; i < t->len; i += 1) { + char c0 = t->str[i]; + char c1 = t->str[i + 1]; + if (i + 1 >= t->len) c1 = 0; + + if (c0 == '\\') { + uint64_t code = LC_GetEscapeCode(c1); + if (code == UINT64_MAX) { + LC_LexingError(t, "invalid escape code in string '%c%c'", c0, c1); + break; + } + + c0 = (char)code; + i += 1; + } + + string[string_len++] = c0; + } + t->ident = LC_InternStrLen(string, string_len); + } + if (t->kind == LC_TokenKind_Note || t->kind == LC_TokenKind_Ident || t->kind == LC_TokenKind_RawString) { + t->ident = LC_InternStrLen(t->str, t->len); + } + if (t->kind == LC_TokenKind_Ident) { + bool is_keyword = t->ident >= L->first_keyword && t->ident <= L->last_keyword; + if (is_keyword) { + t->kind = LC_TokenKind_Keyword; + if (L->kaddptr == t->ident) t->kind = LC_TokenKind_AddPtr; + } + } + } +} + +#undef LC_IF diff --git a/src/compiler/lib_compiler.c b/src/compiler/lib_compiler.c new file mode 100644 index 0000000..8cfaf60 --- /dev/null +++ b/src/compiler/lib_compiler.c @@ -0,0 +1,95 @@ +#include "lib_compiler.h" + +#if __clang__ + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wswitch" + #pragma clang diagnostic ignored "-Wwritable-strings" +#endif + +#ifndef LC_ParseFloat // @override + #include + #define LC_ParseFloat(str, len) strtod(str, NULL) +#endif + +#ifndef LC_Print // @override + #include + #define LC_Print(str, len) printf("%.*s", (int)len, str) +#endif + +#ifndef LC_Exit // @override + #include + #define LC_Exit(x) exit(x) +#endif + +#ifndef LC_MemoryZero // @override + #include + #define LC_MemoryZero(p, size) memset(p, 0, size) +#endif + +#ifndef LC_MemoryCopy // @override + #include + #define LC_MemoryCopy(dst, src, size) memcpy(dst, src, size); +#endif + +#ifndef LC_vsnprintf // @override + #include + #define LC_vsnprintf vsnprintf +#endif + +#ifdef _WIN32 + #ifndef NOMINMAX + #define NOMINMAX + #endif + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include +#endif + +LC_THREAD_LOCAL LC_Lang *L; + +#include "unicode.c" +#include "string.c" +#include "to_string.c" +#include "common.c" +#include "intern.c" +#include "lex.c" +#include "bigint.c" +#include "value.c" +#include "ast.c" +#include "ast_walk.c" +#include "ast_copy.c" +#include "resolver.c" +#include "resolve.c" +#include "parse.c" +#include "printer.c" +#include "genc.c" +#include "extended_passes.c" +#include "packages.c" +#include "init.c" + +#if _WIN32 + #include "win32_filesystem.c" +#elif __linux__ || __APPLE__ || __unix__ + #include + #include + #include + #include + #include + #include + + #include "unix_filesystem.c" +#endif + +#ifndef LC_USE_CUSTOM_ARENA + #include "arena.c" + #if _WIN32 + #include "win32_arena.c" + #elif __linux__ || __APPLE__ || __unix__ + #include "unix_arena.c" + #endif +#endif + +#if __clang__ + #pragma clang diagnostic pop +#endif diff --git a/src/compiler/lib_compiler.h b/src/compiler/lib_compiler.h new file mode 100644 index 0000000..59d07f2 --- /dev/null +++ b/src/compiler/lib_compiler.h @@ -0,0 +1,1696 @@ +#ifndef LIB_COMPILER_HEADER +#define LIB_COMPILER_HEADER + +#define LIB_COMPILER_MAJOR 0 +#define LIB_COMPILER_MINOR 6 + +#include +#include +#include +#include + +#ifndef LC_THREAD_LOCAL // @override + #if defined(__cplusplus) && __cplusplus >= 201103L + #define LC_THREAD_LOCAL thread_local + #elif defined(__GNUC__) + #define LC_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define LC_THREAD_LOCAL __declspec(thread) + #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) + #define LC_THREAD_LOCAL _Thread_local + #elif defined(__TINYC__) + #define LC_THREAD_LOCAL _Thread_local + #else + #error Couldnt figure out thread local, needs to be provided manually + #endif +#endif + +#ifndef LC_FUNCTION // @override + #define LC_FUNCTION +#endif + +#ifndef LC_String // @override +typedef struct { + char *str; + int64_t len; +} LC_String; +#endif + +#ifndef LC_USE_CUSTOM_ARENA // @override +typedef struct LC_VMemory LC_VMemory; +typedef struct LC_TempArena LC_TempArena; +typedef struct LC_Arena LC_Arena; +typedef struct LC_SourceLoc LC_SourceLoc; + +struct LC_VMemory { + size_t commit; + size_t reserve; + uint8_t *data; +}; + +struct LC_Arena { + LC_VMemory memory; + int alignment; + size_t len; + size_t base_len; // When popping to 0 this is the minimum "len" value + // It's so that Bootstrapped arena won't delete itself when Reseting. +}; + +struct LC_TempArena { + LC_Arena *arena; + size_t pos; +}; +#endif + +typedef struct LC_MapEntry LC_MapEntry; +typedef struct LC_Map LC_Map; +typedef struct LC_AST LC_AST; +typedef struct LC_ASTPackage LC_ASTPackage; +typedef struct LC_ASTNoteList LC_ASTNoteList; +typedef struct LC_ExprCompo LC_ExprCompo; +typedef union LC_Val LC_Val; +typedef struct LC_ExprIdent LC_ExprIdent; +typedef struct LC_ExprUnary LC_ExprUnary; +typedef struct LC_ExprBinary LC_ExprBinary; +typedef struct LC_ExprField LC_ExprField; +typedef struct LC_ExprIndex LC_ExprIndex; +typedef struct LC_ExprCompoItem LC_ExprCompoItem; +typedef struct LC_ExprType LC_ExprType; +typedef struct LC_ExprCast LC_ExprCast; +typedef struct LC_ExprNote LC_ExprNote; +typedef struct LC_StmtBlock LC_StmtBlock; +typedef struct LC_StmtFor LC_StmtFor; +typedef struct LC_StmtDefer LC_StmtDefer; +typedef struct LC_StmtSwitch LC_StmtSwitch; +typedef struct LC_StmtCase LC_StmtCase; +typedef struct LC_StmtIf LC_StmtIf; +typedef struct LC_StmtBreak LC_StmtBreak; +typedef struct LC_StmtAssign LC_StmtAssign; +typedef struct LC_StmtExpr LC_StmtExpr; +typedef struct LC_StmtVar LC_StmtVar; +typedef struct LC_StmtConst LC_StmtConst; +typedef struct LC_StmtReturn LC_StmtReturn; +typedef struct LC_StmtNote LC_StmtNote; +typedef struct LC_TypespecArray LC_TypespecArray; +typedef struct LC_TypespecProc LC_TypespecProc; +typedef struct LC_TypespecAggMem LC_TypespecAggMem; +typedef struct LC_TypespecProcArg LC_TypespecProcArg; +typedef struct LC_DeclBase LC_DeclBase; +typedef struct LC_DeclProc LC_DeclProc; +typedef struct LC_DeclTypedef LC_DeclTypedef; +typedef struct LC_DeclAgg LC_DeclAgg; +typedef struct LC_DeclVar LC_DeclVar; +typedef struct LC_DeclConst LC_DeclConst; +typedef struct LC_DeclNote LC_DeclNote; +typedef union LC_ASTValue LC_ASTValue; +typedef struct LC_TypeAndVal LC_TypeAndVal; +typedef struct LC_TypeArray LC_TypeArray; +typedef struct LC_TypePtr LC_TypePtr; +typedef struct LC_TypeMemberList LC_TypeMemberList; +typedef struct LC_TypeProc LC_TypeProc; +typedef struct LC_TypeAgg LC_TypeAgg; +typedef union LC_TypeValue LC_TypeValue; +typedef struct LC_Type LC_Type; +typedef struct LC_TypeMember LC_TypeMember; +typedef struct LC_Decl LC_Decl; +typedef struct LC_DeclStack LC_DeclStack; +typedef struct LC_Map DeclScope; +typedef struct LC_ResolvedCompo LC_ResolvedCompo; +typedef struct LC_ResolvedCompoItem LC_ResolvedCompoItem; +typedef struct LC_ResolvedCompoArrayItem LC_ResolvedCompoArrayItem; +typedef struct LC_ResolvedArrayCompo LC_ResolvedArrayCompo; +typedef union LC_TokenVal LC_TokenVal; +typedef struct LC_Token LC_Token; +typedef struct LC_Lex LC_Lex; +typedef struct LC_Parser LC_Parser; +typedef struct LC_Resolver LC_Resolver; +typedef struct LC_Lang LC_Lang; +typedef struct LC_ASTRef LC_ASTRef; +typedef struct LC_ASTRefList LC_ASTRefList; +typedef struct LC_ASTFile LC_ASTFile; +typedef LC_Val Expr_Atom; +typedef LC_TypespecArray Typespec_Pointer; +typedef uintptr_t LC_Intern; +typedef struct LC_GlobImport LC_GlobImport; +typedef struct LC_UTF32Result LC_UTF32Result; +typedef struct LC_UTF8Result LC_UTF8Result; +typedef struct LC_UTF16Result LC_UTF16Result; + +typedef struct LC_StringNode LC_StringNode; +struct LC_StringNode { + LC_StringNode *next; + LC_String string; +}; + +typedef struct LC_StringList LC_StringList; +struct LC_StringList { + int64_t node_count; + int64_t char_count; + LC_StringNode *first; + LC_StringNode *last; +}; + +typedef struct LC_String16 { + wchar_t *str; + int64_t len; +} LC_String16; + +struct LC_MapEntry { + uint64_t key; + uint64_t value; +}; + +struct LC_Map { + LC_Arena *arena; + LC_MapEntry *entries; + int cap; + int len; +}; + +typedef struct LC_BigInt LC_BigInt; +struct LC_BigInt { + unsigned digit_count; + bool is_negative; + union { + uint64_t digit; + uint64_t *digits; + }; +}; + +typedef enum LC_ASTKind { + LC_ASTKind_Null, + LC_ASTKind_Error, + LC_ASTKind_Note, + LC_ASTKind_NoteList, + LC_ASTKind_File, + LC_ASTKind_Package, + LC_ASTKind_Ignore, + LC_ASTKind_TypespecProcArg, + LC_ASTKind_TypespecAggMem, + LC_ASTKind_ExprCallItem, + LC_ASTKind_ExprCompoundItem, + LC_ASTKind_ExprNote, // a: int = #`sizeof(int)`; + LC_ASTKind_StmtSwitchCase, + LC_ASTKind_StmtSwitchDefault, + LC_ASTKind_StmtElseIf, + LC_ASTKind_StmtElse, + LC_ASTKind_GlobImport, + LC_ASTKind_DeclNote, + LC_ASTKind_DeclProc, + LC_ASTKind_DeclStruct, + LC_ASTKind_DeclUnion, + LC_ASTKind_DeclVar, + LC_ASTKind_DeclConst, + LC_ASTKind_DeclTypedef, + LC_ASTKind_TypespecIdent, + LC_ASTKind_TypespecField, + LC_ASTKind_TypespecPointer, + LC_ASTKind_TypespecArray, + LC_ASTKind_TypespecProc, + LC_ASTKind_StmtBlock, + LC_ASTKind_StmtNote, + LC_ASTKind_StmtReturn, + LC_ASTKind_StmtBreak, + LC_ASTKind_StmtContinue, + LC_ASTKind_StmtDefer, + LC_ASTKind_StmtFor, + LC_ASTKind_StmtIf, + LC_ASTKind_StmtSwitch, + LC_ASTKind_StmtAssign, + LC_ASTKind_StmtExpr, + LC_ASTKind_StmtVar, + LC_ASTKind_StmtConst, + LC_ASTKind_ExprIdent, + LC_ASTKind_ExprString, + LC_ASTKind_ExprInt, + LC_ASTKind_ExprFloat, + LC_ASTKind_ExprBool, + LC_ASTKind_ExprType, + LC_ASTKind_ExprBinary, + LC_ASTKind_ExprUnary, + LC_ASTKind_ExprBuiltin, + LC_ASTKind_ExprCall, + LC_ASTKind_ExprCompound, + LC_ASTKind_ExprCast, + LC_ASTKind_ExprField, + LC_ASTKind_ExprIndex, + LC_ASTKind_ExprAddPtr, + LC_ASTKind_ExprGetValueOfPointer, + LC_ASTKind_ExprGetPointerOfValue, + LC_ASTKind_Count, + LC_ASTKind_FirstExpr = LC_ASTKind_ExprIdent, + LC_ASTKind_LastExpr = LC_ASTKind_ExprGetPointerOfValue, + LC_ASTKind_FirstStmt = LC_ASTKind_StmtBlock, + LC_ASTKind_LastStmt = LC_ASTKind_StmtConst, + LC_ASTKind_FirstTypespec = LC_ASTKind_TypespecIdent, + LC_ASTKind_LastTypespec = LC_ASTKind_TypespecProc, + LC_ASTKind_FirstDecl = LC_ASTKind_DeclProc, + LC_ASTKind_LastDecl = LC_ASTKind_DeclTypedef, +} LC_ASTKind; + +typedef enum LC_TypeKind { + LC_TypeKind_char, + LC_TypeKind_uchar, + LC_TypeKind_short, + LC_TypeKind_ushort, + LC_TypeKind_bool, + LC_TypeKind_int, + LC_TypeKind_uint, + LC_TypeKind_long, + LC_TypeKind_ulong, + LC_TypeKind_llong, + LC_TypeKind_ullong, + LC_TypeKind_float, + LC_TypeKind_double, + LC_TypeKind_void, + LC_TypeKind_Struct, + LC_TypeKind_Union, + LC_TypeKind_Pointer, + LC_TypeKind_Array, + LC_TypeKind_Proc, + LC_TypeKind_UntypedInt, + LC_TypeKind_UntypedFloat, + LC_TypeKind_UntypedString, + LC_TypeKind_Incomplete, + LC_TypeKind_Completing, + LC_TypeKind_Error, + T_TotalCount, + T_NumericCount = LC_TypeKind_void, + T_Count = LC_TypeKind_void + 1, +} LC_TypeKind; + +typedef enum LC_DeclState { + LC_DeclState_Unresolved, + LC_DeclState_Resolving, + LC_DeclState_Resolved, + LC_DeclState_ResolvedBody, // proc + LC_DeclState_Error, + LC_DeclState_Count, +} LC_DeclState; + +typedef enum LC_DeclKind { + LC_DeclKind_Error, + LC_DeclKind_Type, + LC_DeclKind_Const, + LC_DeclKind_Var, + LC_DeclKind_Proc, + LC_DeclKind_Import, + LC_DeclKind_Count, +} LC_DeclKind; + +typedef enum LC_TokenKind { + LC_TokenKind_EOF, + LC_TokenKind_Error, + LC_TokenKind_Comment, + LC_TokenKind_DocComment, + LC_TokenKind_FileDocComment, + LC_TokenKind_PackageDocComment, + LC_TokenKind_Note, + LC_TokenKind_Hash, + LC_TokenKind_Ident, + LC_TokenKind_Keyword, + LC_TokenKind_String, + LC_TokenKind_RawString, + LC_TokenKind_Int, + LC_TokenKind_Float, + LC_TokenKind_Unicode, + LC_TokenKind_OpenParen, + LC_TokenKind_CloseParen, + LC_TokenKind_OpenBrace, + LC_TokenKind_CloseBrace, + LC_TokenKind_OpenBracket, + LC_TokenKind_CloseBracket, + LC_TokenKind_Comma, + LC_TokenKind_Question, + LC_TokenKind_Semicolon, + LC_TokenKind_Dot, + LC_TokenKind_ThreeDots, + LC_TokenKind_Colon, + LC_TokenKind_Mul, + LC_TokenKind_Div, + LC_TokenKind_Mod, + LC_TokenKind_LeftShift, + LC_TokenKind_RightShift, + LC_TokenKind_Add, + LC_TokenKind_Sub, + LC_TokenKind_Equals, + LC_TokenKind_LesserThen, + LC_TokenKind_GreaterThen, + LC_TokenKind_LesserThenEq, + LC_TokenKind_GreaterThenEq, + LC_TokenKind_NotEquals, + LC_TokenKind_BitAnd, + LC_TokenKind_BitOr, + LC_TokenKind_BitXor, + LC_TokenKind_And, + LC_TokenKind_Or, + LC_TokenKind_AddPtr, + LC_TokenKind_Neg, + LC_TokenKind_Not, + LC_TokenKind_Assign, + LC_TokenKind_DivAssign, + LC_TokenKind_MulAssign, + LC_TokenKind_ModAssign, + LC_TokenKind_SubAssign, + LC_TokenKind_AddAssign, + LC_TokenKind_BitAndAssign, + LC_TokenKind_BitOrAssign, + LC_TokenKind_BitXorAssign, + LC_TokenKind_LeftShiftAssign, + LC_TokenKind_RightShiftAssign, + LC_TokenKind_Count, +} LC_TokenKind; + +struct LC_ASTFile { + LC_AST *package; + LC_Lex *x; + + LC_AST *fimport; + LC_AST *limport; + LC_AST *fdecl; + LC_AST *ldecl; + LC_AST *fdiscarded; + LC_AST *ldiscarded; // @build_if + + LC_Token *doc_comment; + + bool build_if; +}; + +struct LC_ASTPackage { + LC_Intern name; + LC_DeclState state; + LC_String path; + LC_StringList injected_filepaths; // to sidestep regular file finding, implement single file packages etc. + LC_AST *ffile; + LC_AST *lfile; + LC_AST *fdiscarded; + LC_AST *ldiscarded; // #build_if + + LC_Token *doc_comment; + + // These are resolved later: + // @todo: add foreign name? + LC_Decl *first_ordered; + LC_Decl *last_ordered; + DeclScope *scope; +}; + +struct LC_ASTNoteList { + LC_AST *first; + LC_AST *last; +}; + +struct LC_ResolvedCompo { + int count; + LC_ResolvedCompoItem *first; + LC_ResolvedCompoItem *last; +}; + +struct LC_ResolvedCompoItem { + LC_ResolvedCompoItem *next; + LC_AST *comp; // for proc this may be null because we might match default value + LC_AST *expr; // for proc this is very important, the result, ordered expression + LC_TypeMember *t; + bool varg; + bool defaultarg; +}; + +struct LC_ResolvedCompoArrayItem { + LC_ResolvedCompoArrayItem *next; + LC_AST *comp; + int index; +}; + +struct LC_ResolvedArrayCompo { + int count; + LC_ResolvedCompoArrayItem *first; + LC_ResolvedCompoArrayItem *last; +}; + +struct LC_ExprCompo { + LC_AST *name; // :name{thing} or name(thing) + LC_AST *first; // {LC_ExprCompoItem, LC_ExprCompoItem} + LC_AST *last; + int size; + union { + LC_ResolvedCompo *resolved_items; + LC_ResolvedArrayCompo *resolved_array_items; + }; +}; + +struct LC_ExprCompoItem { + LC_Intern name; + LC_AST *index; + LC_AST *expr; +}; + +// clang-format off +union LC_Val { LC_BigInt i; double d; LC_Intern name; }; +struct LC_ExprIdent { LC_Intern name; LC_Decl *resolved_decl; }; +struct LC_ExprUnary { LC_TokenKind op; LC_AST *expr; }; +struct LC_ExprBinary { LC_TokenKind op; LC_AST *left; LC_AST *right; }; +struct LC_ExprField { LC_AST *left; LC_Intern right; LC_Decl *resolved_decl; LC_Decl *parent_decl; }; +struct LC_ExprIndex { LC_AST *base; LC_AST *index; }; +struct LC_ExprType { LC_AST *type; }; +struct LC_ExprCast { LC_AST *type; LC_AST *expr; }; +struct LC_ExprNote { LC_AST *expr; }; // v := #c(``) + +typedef enum { SBLK_Norm, SBLK_Loop, SBLK_Proc, SBLK_Defer } LC_StmtBlockKind; +struct LC_StmtBlock { LC_AST *first; LC_AST *last; LC_AST *first_defer; LC_StmtBlockKind kind; LC_Intern name; }; +struct LC_StmtFor { LC_AST *init; LC_AST *cond; LC_AST *inc; LC_AST *body; }; +struct LC_StmtDefer { LC_AST *next; LC_AST *body; }; +struct LC_StmtSwitch { LC_AST *first; LC_AST *last; LC_AST *expr; int total_switch_case_count; }; +struct LC_StmtCase { LC_AST *first; LC_AST *last; LC_AST *body; }; +// 'else if' and 'else' is avaialable from 'first'. +// The else_if and else are also LC_StmtIf but +// have different kinds and don't use 'first', 'last' +struct LC_StmtIf { LC_AST *expr; LC_AST *body; LC_AST *first; LC_AST *last; }; +struct LC_StmtBreak { LC_Intern name; }; +struct LC_StmtAssign { LC_TokenKind op; LC_AST *left; LC_AST *right; }; +struct LC_StmtExpr { LC_AST *expr; }; +struct LC_StmtVar { LC_AST *expr; LC_AST *type; LC_Intern name; LC_Decl *resolved_decl; }; +struct LC_StmtConst { LC_AST *expr; LC_Intern name; }; +struct LC_StmtReturn { LC_AST *expr; }; +struct LC_StmtNote { LC_AST *expr; }; // #c(``) in block +struct LC_TypespecArray { LC_AST *base; LC_AST *index; }; +struct LC_TypespecProc { LC_AST *first; LC_AST *last; LC_AST *ret; bool vargs; bool vargs_any_promotion; }; +struct LC_TypespecAggMem { LC_Intern name; LC_AST *type; }; +struct LC_TypespecProcArg { LC_Intern name; LC_AST *type; LC_AST *expr; LC_Decl *resolved_decl; }; +struct LC_DeclBase { LC_Intern name; LC_Token *doc_comment; LC_Decl *resolved_decl; }; +struct LC_DeclProc { LC_DeclBase base; LC_AST *body; LC_AST *type; }; +struct LC_DeclTypedef { LC_DeclBase base; LC_AST *type; }; +struct LC_DeclAgg { LC_DeclBase base; LC_AST *first; LC_AST *last; }; +struct LC_DeclVar { LC_DeclBase base; LC_AST *expr; LC_AST *type; }; +struct LC_DeclConst { LC_DeclBase base; LC_AST *expr; }; +struct LC_DeclNote { LC_DeclBase base; LC_AST *expr; bool processed; }; // #c(``) in file note list +struct LC_GlobImport { LC_Intern name; LC_Intern path; bool resolved; LC_Decl *resolved_decl; }; + +struct LC_ASTRef { LC_ASTRef *next; LC_ASTRef *prev; LC_AST *ast; }; +struct LC_ASTRefList { LC_ASTRef *first; LC_ASTRef *last; }; +// clang-format on + +struct LC_TypeAndVal { + LC_Type *type; + union { + LC_Val v; + union { + LC_BigInt i; + double d; + LC_Intern name; + }; + }; +}; + +struct LC_AST { + LC_ASTKind kind; + uint32_t id; + LC_AST *next; + LC_AST *prev; + LC_AST *notes; + LC_Token *pos; + + LC_TypeAndVal const_val; + LC_Type *type; + union { + LC_ASTFile afile; + LC_ASTPackage apackage; + LC_ASTNoteList anote_list; + LC_ExprCompo anote; + LC_Val eatom; + LC_ExprIdent eident; + LC_ExprUnary eunary; + LC_ExprBinary ebinary; + LC_ExprField efield; + LC_ExprIndex eindex; + LC_ExprCompo ecompo; + LC_ExprCompoItem ecompo_item; + LC_ExprType etype; + LC_ExprCast ecast; + LC_ExprNote enote; + LC_StmtBlock sblock; + LC_StmtFor sfor; + LC_StmtDefer sdefer; + LC_StmtSwitch sswitch; + LC_StmtCase scase; + LC_StmtIf sif; + LC_StmtBreak sbreak; + LC_StmtBreak scontinue; + LC_StmtAssign sassign; + LC_StmtExpr sexpr; + LC_StmtVar svar; + LC_StmtConst sconst; + LC_StmtReturn sreturn; + LC_StmtNote snote; + LC_ExprIdent tident; + LC_TypespecArray tarray; + LC_TypespecArray tpointer; + LC_TypespecProc tproc; + LC_TypespecAggMem tagg_mem; + LC_TypespecProcArg tproc_arg; + LC_DeclBase dbase; + LC_DeclProc dproc; + LC_DeclTypedef dtypedef; + LC_DeclAgg dagg; + LC_DeclVar dvar; + LC_DeclConst dconst; + LC_DeclNote dnote; + LC_GlobImport gimport; + }; +}; + +struct LC_TypeArray { + LC_Type *base; + int size; +}; + +struct LC_TypePtr { + LC_Type *base; +}; + +struct LC_TypeMemberList { + LC_TypeMember *first; + LC_TypeMember *last; + int count; +}; + +struct LC_TypeProc { + LC_TypeMemberList args; + LC_Type *ret; + bool vargs; + bool vargs_any_promotion; +}; + +struct LC_TypeAgg { + LC_TypeMemberList mems; +}; + +struct LC_Type { + LC_TypeKind kind; + int size; + int align; + int is_unsigned; + int id; + int padding; + LC_Decl *decl; + union { + LC_TypeArray tarray; + LC_TypePtr tptr; + LC_TypeProc tproc; + LC_TypeAgg tagg; + LC_Type *tbase; + LC_Type *tutdefault; + }; +}; + +struct LC_TypeMember { + LC_TypeMember *next; + LC_TypeMember *prev; + LC_Intern name; + LC_Type *type; + LC_AST *default_value_expr; + LC_AST *ast; + int offset; +}; + +struct LC_Decl { + LC_DeclKind kind; + LC_DeclState state; + uint8_t is_foreign; + + LC_Decl *next; + LC_Decl *prev; + LC_Intern name; + LC_Intern foreign_name; + LC_AST *ast; + LC_AST *package; + + LC_TypeMember *type_member; + DeclScope *scope; + LC_Decl *typedef_renamed_type_decl; + union { + LC_TypeAndVal val; + struct { + LC_Type *type; + LC_Val v; + }; + }; +}; + +typedef struct { + LC_Arena *arena; + LC_AST **data; + int cap; + int len; +} LC_ASTArray; + +typedef struct LC_ASTWalker LC_ASTWalker; +typedef void LC_ASTWalkProc(LC_ASTWalker *, LC_AST *); +struct LC_ASTWalker { + LC_ASTArray stack; + + int inside_builtin; + int inside_discarded; + int inside_note; + + uint8_t visit_discarded; + uint8_t visit_notes; + uint8_t depth_first; + uint8_t dont_recurse; // breathfirst only + void *user_data; + LC_ASTWalkProc *proc; +}; + +struct LC_DeclStack { + LC_Decl **stack; + int len; + int cap; +}; + +union LC_TokenVal { + LC_BigInt i; + double f64; + LC_Intern ident; +}; + +struct LC_Token { + LC_TokenKind kind; + int line; + int column; + int len; + char *str; + LC_Lex *lex; + union { + LC_BigInt i; + double f64; + LC_Intern ident; + }; +}; + +struct LC_Lex { + char *at; + char *begin; + LC_Intern file; + int line; + int column; + LC_Token *tokens; + int token_count; + bool insert_semicolon; +}; + +struct LC_Parser { + LC_Token *at; + LC_Token *begin; + LC_Token *end; + LC_Lex *x; +}; + +struct LC_Resolver { + LC_Type *compo_context_type; + int compo_context_array_size; + LC_Type *expected_ret_type; + LC_AST *package; + DeclScope *active_scope; + LC_DeclStack locals; + LC_Map duplicate_map; // currently used for finding duplicates in compos + LC_ASTArray stmt_block_stack; +}; + +typedef struct LC_Printer LC_Printer; +struct LC_Printer { + LC_Arena *arena; + LC_StringList list; + int indent; + LC_Intern last_filename; + int last_line_num; + LC_ASTArray out_block_stack; +}; + +const int LC_OPF_Error = 1; +const int LC_OPF_UTConst = 2; +const int LC_OPF_LValue = 4; +const int LC_OPF_Const = 8; +const int LC_OPF_Returned = 16; + +// warning: I introduced a null compare using the values in the operand +// make sure to revisit that when modifying the struct +typedef struct { + int flags; + union { + LC_Decl *decl; + LC_TypeAndVal val; + struct { + LC_Type *type; + LC_Val v; + }; + }; +} LC_Operand; + +typedef enum { + LC_ARCH_Invalid, + LC_ARCH_X64, + LC_ARCH_X86, + LC_ARCH_Count, +} LC_ARCH; + +typedef enum { + LC_GEN_Invalid, + LC_GEN_C, + LC_GEN_Count, +} LC_GEN; + +typedef enum { + LC_OS_Invalid, + LC_OS_WINDOWS, + LC_OS_LINUX, + LC_OS_MAC, + LC_OS_Count, +} LC_OS; + +typedef struct { + LC_String path; + LC_String content; + int line; +} LoadedFile; + +typedef enum { + LC_OPResult_Error, + LC_OPResult_Ok, + LC_OPResult_Bool, +} LC_OPResult; + +typedef struct { + int left; + int right; +} LC_BindingPower; + +typedef enum { + LC_Binding_Prefix, + LC_Binding_Infix, + LC_Binding_Postfix, +} LC_Binding; + +typedef enum { + LC_CmpRes_LT, + LC_CmpRes_GT, + LC_CmpRes_EQ, +} LC_CmpRes; + +typedef struct LC_FileIter LC_FileIter; +struct LC_FileIter { + bool is_valid; + bool is_directory; + LC_String absolute_path; + LC_String relative_path; + LC_String filename; + + LC_String path; + LC_Arena *arena; + union { + struct LC_Win32_FileIter *w32; + void *dir; + }; +}; + +#define LC_LIST_KEYWORDS \ + X(for) \ + X(import) \ + X(if) \ + X(else) \ + X(return) \ + X(defer) \ + X(continue) \ + X(break) \ + X(default) \ + X(case) \ + X(typedef) \ + X(switch) \ + X(proc) \ + X(struct) \ + X(union) \ + X(addptr) \ + X(and) \ + X(or) \ + X(bit_and) \ + X(bit_or) \ + X(bit_xor) \ + X(not ) \ + X(true) \ + X(false) + +#define LC_LIST_INTERNS \ + X(foreign, true) \ + X(api, true) \ + X(weak, true) \ + X(c, true) \ + X(fallthrough, true) \ + X(packed, true) \ + X(not_init, true) \ + X(unused, true) \ + X(static_assert, true) \ + X(str, true) \ + X(thread_local, true) \ + X(dont_mangle, true) \ + X(build_if, true) \ + X(Any, false) \ + X(main, false) \ + X(debug_break, false) \ + X(sizeof, false) \ + X(alignof, false) \ + X(typeof, false) \ + X(lengthof, false) \ + X(offsetof, false) + +#define LC_LIST_TYPES \ + X(char, false) \ + X(uchar, true) \ + X(short, false) \ + X(ushort, true) \ + X(bool, false) \ + X(int, false) \ + X(uint, true) \ + X(long, false) \ + X(ulong, true) \ + X(llong, false) \ + X(ullong, true) \ + X(float, false) \ + X(double, false) + +struct LC_Lang { + LC_Arena *arena; + + LC_Arena *lex_arena; + + LC_Arena *ast_arena; + int ast_count; + + LC_Arena *decl_arena; + int decl_count; + + LC_Arena *type_arena; + int type_count; + + int errors; + + int typeids; + LC_Map type_map; + + LC_AST *builtin_package; + LC_Resolver resolver; + LC_Parser *parser; + + // Package registry + LC_AST *fpackage; + LC_AST *lpackage; + LC_Intern first_package; + LC_ASTRefList ordered_packages; + LC_StringList package_dirs; + + LC_Map interns; + LC_Map declared_notes; + LC_Map foreign_names; + LC_Map implicit_any; + unsigned unique_counter; + + LC_Intern first_keyword; + LC_Intern last_keyword; + +#define X(x) LC_Intern k##x; + LC_LIST_KEYWORDS +#undef X + +#define X(x, declare) LC_Intern i##x; + LC_LIST_INTERNS +#undef X + + LC_Type types[14]; // be careful when changing +#define X(TNAME, IS_UNSIGNED) LC_Type *t##TNAME; + LC_LIST_TYPES +#undef X + + // When adding new special pointer types make sure to + // also update LC_SetPointerSizeAndAlign so that it properly + // updates the types after LC_LangBegin + int pointer_size; + int pointer_align; + LC_Type *tvoid; + LC_Type *tpvoid; + LC_Type *tpchar; + + LC_Type ttstring; + LC_Type *tstring; + LC_Type *tuntypednil; + LC_Type *tuntypedbool; + LC_Type *tuntypedint; + LC_Type ttuntypedfloat; + LC_Type *tuntypedfloat; + LC_Type ttuntypedstring; + LC_Type *tuntypedstring; + LC_Type ttany; + LC_Type *tany; + + LC_Token NullToken; + LC_AST NullAST; + LC_Token BuiltinToken; + LC_Lex NullLEX; + + LC_Printer printer; + LC_Parser quick_parser; + + // @configurable + LC_ARCH arch; + LC_GEN gen; + LC_OS os; + + bool emit_line_directives; + bool breakpoint_on_error; + bool use_colored_terminal_output; + + bool (*on_decl_parsed)(bool discarded, LC_AST *n); // returning 'true' from here indicates that declaration should be discarded + void (*on_expr_parsed)(LC_AST *n); + void (*on_stmt_parsed)(LC_AST *n); + void (*on_typespec_parsed)(LC_AST *n); + void (*on_decl_type_resolved)(LC_Decl *decl); + void (*on_proc_body_resolved)(LC_Decl *decl); + void (*on_expr_resolved)(LC_AST *expr, LC_Operand *op); + void (*on_stmt_resolved)(LC_AST *n); + void (*before_call_args_resolved)(LC_AST *n, LC_Type *type); + void (*on_file_load)(LC_AST *package, LoadedFile *file); + void (*on_message)(LC_Token *pos, char *str, int len); // pos and x can be null + void (*on_fatal_error)(void); + void *user_data; +}; + +extern LC_THREAD_LOCAL LC_Lang *L; +extern LC_Operand LC_OPNull; + +// +// Main @api +// + +LC_FUNCTION LC_Lang *LC_LangAlloc(void); // This allocates memory for LC_Lang which can be used to register callbacks and set configurables +LC_FUNCTION void LC_LangBegin(LC_Lang *l); // Prepare for compilation: init types, init builtins, set architecture variables stuff like that +LC_FUNCTION void LC_LangEnd(LC_Lang *lang); // Deallocate language memory + +LC_FUNCTION void LC_RegisterPackageDir(char *dir); // Add a package search directory +LC_FUNCTION LC_ASTRefList LC_ResolvePackageByName(LC_Intern name); // Fully resolve a package and all it's dependences +LC_FUNCTION LC_String LC_GenerateUnityBuild(LC_ASTRefList packages); // Generate the C program and return as a string + +// Smaller passes for AST modification +LC_FUNCTION void LC_ParsePackagesUsingRegistry(LC_Intern name); // These 3 functions are equivalent to LC_ResolvePackageByName, +LC_FUNCTION void LC_OrderAndResolveTopLevelDecls(LC_Intern name); // you can use them to hook into the compilation process - you can modify the AST +LC_FUNCTION void LC_ResolveAllProcBodies(void); // before resolving or use resolved top declarations to generate some code. + // The Parse and Order functions can be called multiple times to accommodate this. + +// Extended pass / optimization +LC_FUNCTION void LC_FindUnusedLocalsAndRemoveUnusedGlobalDecls(void); // Extended pass that you can execute once you have resolved all packages + +// These three functions are used to implement LC_FindUnusedLocalsAndRemoveUnusedGlobalDecls +LC_FUNCTION LC_Map LC_CountDeclRefs(LC_Arena *arena); +LC_FUNCTION void LC_RemoveUnreferencedGlobalDecls(LC_Map *map_of_visits); +LC_FUNCTION void LC_ErrorOnUnreferencedLocals(LC_Map *map_of_visits); + +// Notes +LC_FUNCTION void LC_DeclareNote(LC_Intern intern); +LC_FUNCTION bool LC_IsNoteDeclared(LC_Intern intern); +LC_FUNCTION LC_AST *LC_HasNote(LC_AST *ast, LC_Intern i); + +// Quick parse functions +LC_FUNCTION LC_AST *LC_ParseStmtf(const char *str, ...); +LC_FUNCTION LC_AST *LC_ParseExprf(const char *str, ...); +LC_FUNCTION LC_AST *LC_ParseDeclf(const char *str, ...); + +// AST Walking and copy +LC_FUNCTION LC_AST *LC_CopyAST(LC_Arena *arena, LC_AST *n); // Deep copy the AST +LC_FUNCTION LC_ASTArray LC_FlattenAST(LC_Arena *arena, LC_AST *n); // This walks the passed down tree and generates a flat array of pointers, very nice to use for traversing AST +LC_FUNCTION void LC_WalkAST(LC_ASTWalker *ctx, LC_AST *n); +LC_FUNCTION LC_ASTWalker LC_GetDefaultWalker(LC_Arena *arena, LC_ASTWalkProc *proc); + +LC_FUNCTION void LC_ReserveAST(LC_ASTArray *arr, int size); +LC_FUNCTION void LC_PushAST(LC_ASTArray *arr, LC_AST *ast); +LC_FUNCTION void LC_PopAST(LC_ASTArray *arr); +LC_FUNCTION LC_AST *LC_GetLastAST(LC_ASTArray *arr); + +// Interning API +LC_FUNCTION LC_Intern LC_ILit(char *str); +LC_FUNCTION void LC_InternTokens(LC_Lex *x); + +LC_FUNCTION LC_Intern LC_InternStrLen(char *str, int len); +LC_FUNCTION LC_Intern LC_GetUniqueIntern(const char *name_for_debug); +LC_FUNCTION char *LC_GetUniqueName(const char *name_for_debug); + +// +// Package functions +// +LC_FUNCTION LC_Operand LC_ImportPackage(LC_AST *import, LC_AST *dst, LC_AST *src); +LC_FUNCTION LC_Intern LC_MakePackageNameFromPath(LC_String path); +LC_FUNCTION bool LC_PackageNameValid(LC_Intern name); +LC_FUNCTION bool LC_PackageNameDuplicate(LC_Intern name); +LC_FUNCTION void LC_AddPackageToList(LC_AST *n); +LC_FUNCTION LC_AST *LC_RegisterPackage(LC_String path); +LC_FUNCTION void LC_AddFileToPackage(LC_AST *pkg, LC_AST *f); +LC_FUNCTION LC_AST *LC_FindImportInRefList(LC_ASTRefList *arr, LC_Intern path); +LC_FUNCTION void LC_AddASTToRefList(LC_ASTRefList *refs, LC_AST *ast); +LC_FUNCTION LC_ASTRefList LC_GetPackageImports(LC_AST *package); +LC_FUNCTION LC_AST *LC_GetPackageByName(LC_Intern name); +LC_FUNCTION LC_StringList LC_ListFilesInPackage(LC_Arena *arena, LC_String path); +LC_FUNCTION LoadedFile LC_ReadFileHook(LC_AST *package, LC_String path); +LC_FUNCTION void LC_ParsePackage(LC_AST *n); +LC_FUNCTION void LC_AddOrderedPackageToRefList(LC_AST *n); +LC_FUNCTION LC_AST *LC_OrderPackagesAndBasicResolve(LC_AST *pos, LC_Intern name); +LC_FUNCTION void LC_AddSingleFilePackage(LC_Intern name, LC_String path); + +// +// Lexing functions +// +LC_FUNCTION LC_Lex *LC_LexStream(char *file, char *str, int line); +LC_FUNCTION LC_String LC_GetTokenLine(LC_Token *token); + +LC_FUNCTION void LC_LexingError(LC_Token *pos, const char *str, ...); +LC_FUNCTION bool LC_IsAssign(LC_TokenKind kind); +LC_FUNCTION bool LC_IsHexDigit(char c); +LC_FUNCTION bool LC_IsBinDigit(char c); +LC_FUNCTION uint64_t LC_MapCharToNumber(char c); +LC_FUNCTION uint64_t LC_GetEscapeCode(char c); +LC_FUNCTION LC_String LC_GetEscapeString(char c); +LC_FUNCTION void LC_LexAdvance(LC_Lex *x); +LC_FUNCTION void LC_EatWhitespace(LC_Lex *x); +LC_FUNCTION void LC_EatIdent(LC_Lex *x); +LC_FUNCTION void LC_SetTokenLen(LC_Lex *x, LC_Token *t); +LC_FUNCTION void LC_EatUntilIncluding(LC_Lex *x, char c); +LC_FUNCTION LC_BigInt LC_LexBigInt(char *string, int len, uint64_t base); +LC_FUNCTION void LC_LexNestedComments(LC_Lex *x, LC_Token *t); +LC_FUNCTION void LC_LexStringLiteral(LC_Lex *x, LC_Token *t, LC_TokenKind kind); +LC_FUNCTION void LC_LexUnicodeLiteral(LC_Lex *x, LC_Token *t); +LC_FUNCTION void LC_LexIntOrFloat(LC_Lex *x, LC_Token *t); +LC_FUNCTION void LC_LexCase2(LC_Lex *x, LC_Token *t, LC_TokenKind tk0, char c, LC_TokenKind tk1); +LC_FUNCTION void LC_LexCase3(LC_Lex *x, LC_Token *t, LC_TokenKind tk, char c0, LC_TokenKind tk0, char c1, LC_TokenKind tk1); +LC_FUNCTION void LC_LexCase4(LC_Lex *x, LC_Token *t, LC_TokenKind tk, char c0, LC_TokenKind tk0, char c1, LC_TokenKind tk1, char c2, LC_TokenKind tk2); +LC_FUNCTION void LC_LexNext(LC_Lex *x, LC_Token *t); + +// +// LC_Map API +// +LC_FUNCTION void LC_MapReserve(LC_Map *map, int size); +LC_FUNCTION int LC_NextPow2(int v); +LC_FUNCTION LC_MapEntry *LC_GetMapEntryEx(LC_Map *map, uint64_t key); +LC_FUNCTION bool LC_InsertWithoutReplace(LC_Map *map, void *key, void *value); +LC_FUNCTION LC_MapEntry *LC_InsertMapEntry(LC_Map *map, uint64_t key, uint64_t value); +LC_FUNCTION LC_MapEntry *LC_GetMapEntry(LC_Map *map, uint64_t key); +LC_FUNCTION void LC_MapInsert(LC_Map *map, LC_String keystr, void *value); +LC_FUNCTION void *LC_MapGet(LC_Map *map, LC_String keystr); +LC_FUNCTION void LC_MapInsertU64(LC_Map *map, uint64_t key, void *value); +LC_FUNCTION void *LC_MapGetU64(LC_Map *map, uint64_t key); +LC_FUNCTION void *LC_MapGetP(LC_Map *map, void *key); +LC_FUNCTION void LC_MapInsertP(LC_Map *map, void *key, void *value); +LC_FUNCTION void LC_MapClear(LC_Map *map); + +// +// LC_AST Creation +// +LC_FUNCTION LC_AST *LC_CreateAST(LC_Token *pos, LC_ASTKind kind); +LC_FUNCTION LC_AST *LC_CreateUnary(LC_Token *pos, LC_TokenKind op, LC_AST *expr); +LC_FUNCTION LC_AST *LC_CreateBinary(LC_Token *pos, LC_AST *left, LC_AST *right, LC_TokenKind op); +LC_FUNCTION LC_AST *LC_CreateIndex(LC_Token *pos, LC_AST *left, LC_AST *index); + +LC_FUNCTION bool LC_ContainsCallExpr(LC_AST *ast); +LC_FUNCTION void LC_SetASTPosOnAll(LC_AST *n, LC_Token *pos); +LC_FUNCTION bool LC_ContainsCBuiltin(LC_AST *n); + +// +// LC_Type functions +// +LC_FUNCTION void LC_SetPointerSizeAndAlign(int size, int align); +LC_FUNCTION LC_Type *LC_CreateType(LC_TypeKind kind); +LC_FUNCTION LC_Type *LC_CreateTypedef(LC_Decl *decl, LC_Type *base); +LC_FUNCTION LC_Type *LC_CreatePointerType(LC_Type *type); +LC_FUNCTION LC_Type *LC_CreateArrayType(LC_Type *type, int size); +LC_FUNCTION LC_Type *LC_CreateProcType(LC_TypeMemberList args, LC_Type *ret, bool has_vargs, bool has_vargs_any_promotion); +LC_FUNCTION LC_Type *LC_CreateIncompleteType(LC_Decl *decl); +LC_FUNCTION LC_Type *LC_CreateUntypedIntEx(LC_Type *base, LC_Decl *decl); +LC_FUNCTION LC_Type *LC_CreateUntypedInt(LC_Type *base); +LC_FUNCTION LC_TypeMember *LC_AddTypeToList(LC_TypeMemberList *list, LC_Intern name, LC_Type *type, LC_AST *ast); +LC_FUNCTION int LC_GetLevelsOfIndirection(LC_Type *type); +LC_FUNCTION bool LC_BigIntFits(LC_BigInt i, LC_Type *type); +LC_FUNCTION LC_Type *LC_StripPointer(LC_Type *type); + +// +// Parsing functions +// +LC_FUNCTION LC_AST *LC_ParseFile(LC_AST *package, char *filename, char *content, int line); +LC_FUNCTION LC_AST *LC_ParseTokens(LC_AST *package, LC_Lex *x); + +LC_FUNCTION LC_Parser LC_MakeParser(LC_Lex *x); +LC_FUNCTION LC_Parser *LC_MakeParserQuick(char *str); +LC_FUNCTION LC_Token *LC_Next(void); +LC_FUNCTION LC_Token *LC_Get(void); +LC_FUNCTION LC_Token *LC_GetI(int i); +LC_FUNCTION LC_Token *LC_Is(LC_TokenKind kind); +LC_FUNCTION LC_Token *LC_IsKeyword(LC_Intern intern); +LC_FUNCTION LC_Token *LC_Match(LC_TokenKind kind); +LC_FUNCTION LC_Token *LC_MatchKeyword(LC_Intern intern); +LC_FUNCTION LC_BindingPower LC_MakeBP(int left, int right); +LC_FUNCTION LC_BindingPower LC_GetBindingPower(LC_Binding binding, LC_TokenKind kind); +LC_FUNCTION LC_AST *LC_ParseExprEx(int min_bp); +LC_FUNCTION LC_AST *LC_ParseCompo(LC_Token *pos, LC_AST *left); +LC_FUNCTION LC_AST *LC_ParseExpr(void); +LC_FUNCTION LC_AST *LC_ParseProcType(LC_Token *pos); +LC_FUNCTION LC_AST *LC_ParseType(void); +LC_FUNCTION LC_AST *LC_ParseForStmt(LC_Token *pos); +LC_FUNCTION LC_AST *LC_ParseSwitchStmt(LC_Token *pos); +LC_FUNCTION LC_AST *LC_ParseStmt(bool check_semicolon); +LC_FUNCTION LC_AST *LC_ParseStmtBlock(int flags); +LC_FUNCTION LC_AST *LC_ParseProcDecl(LC_Token *name); +LC_FUNCTION LC_AST *LC_ParseStruct(LC_ASTKind kind, LC_Token *ident); +LC_FUNCTION LC_AST *LC_ParseTypedef(LC_Token *ident); +LC_FUNCTION LC_AST *LC_CreateNote(LC_Token *pos, LC_Intern ident); +LC_FUNCTION LC_AST *LC_ParseNote(void); +LC_FUNCTION LC_AST *LC_ParseNotes(void); +LC_FUNCTION bool LC_ResolveBuildIf(LC_AST *build_if); +LC_FUNCTION LC_AST *LC_ParseImport(void); +LC_FUNCTION LC_AST *LC_ParseDecl(LC_AST *file); +LC_FUNCTION bool LC_EatUntilNextValidDecl(void); +LC_FUNCTION bool LC_ParseHashBuildOn(LC_AST *n); +LC_FUNCTION LC_AST *LC_ParseFileEx(LC_AST *package); + +// +// Resolution functions +// +LC_FUNCTION void LC_AddDecl(LC_DeclStack *scope, LC_Decl *decl); +LC_FUNCTION void LC_InitDeclStack(LC_DeclStack *stack, int size); +LC_FUNCTION LC_DeclStack *LC_CreateDeclStack(int size); +LC_FUNCTION LC_Decl *LC_FindDeclOnStack(LC_DeclStack *scp, LC_Intern name); + +LC_FUNCTION DeclScope *LC_CreateScope(int size); +LC_FUNCTION LC_Decl *LC_CreateDecl(LC_DeclKind kind, LC_Intern name, LC_AST *n); +LC_FUNCTION LC_Operand LC_AddDeclToScope(DeclScope *scp, LC_Decl *decl); +LC_FUNCTION LC_Decl *LC_FindDeclInScope(DeclScope *scope, LC_Intern name); +LC_FUNCTION LC_Operand LC_ThereIsNoDecl(DeclScope *scp, LC_Decl *decl, bool check_locals); +LC_FUNCTION void LC_MarkDeclError(LC_Decl *decl); +LC_FUNCTION LC_Decl *LC_GetLocalOrGlobalDecl(LC_Intern name); +LC_FUNCTION LC_Operand LC_PutGlobalDecl(LC_Decl *decl); +LC_FUNCTION LC_Operand LC_CreateLocalDecl(LC_DeclKind kind, LC_Intern name, LC_AST *ast); +LC_FUNCTION LC_Decl *LC_AddConstIntDecl(char *key, int64_t value); +LC_FUNCTION LC_Decl *LC_GetBuiltin(LC_Intern name); +LC_FUNCTION void LC_AddBuiltinConstInt(char *key, int64_t value); + +LC_FUNCTION void LC_RegisterDeclsFromFile(LC_AST *file); +LC_FUNCTION void LC_ResolveDeclsFromFile(LC_AST *file); +LC_FUNCTION void LC_PackageDecls(LC_AST *package); +LC_FUNCTION void LC_ResolveProcBodies(LC_AST *package); +LC_FUNCTION void LC_ResolveIncompleteTypes(LC_AST *package); +LC_FUNCTION LC_Operand LC_ResolveNote(LC_AST *n, bool is_decl); +LC_FUNCTION LC_Operand LC_ResolveProcBody(LC_Decl *decl); +LC_FUNCTION LC_ResolvedCompoItem *LC_AddResolvedCallItem(LC_ResolvedCompo *list, LC_TypeMember *t, LC_AST *comp, LC_AST *expr); +LC_FUNCTION LC_Operand LC_ResolveCompoCall(LC_AST *n, LC_Type *type); +LC_FUNCTION LC_Operand LC_ResolveCompoAggregate(LC_AST *n, LC_Type *type); +LC_FUNCTION LC_ResolvedCompoArrayItem *LC_AddResolvedCompoArrayItem(LC_ResolvedArrayCompo *arr, int index, LC_AST *comp); +LC_FUNCTION LC_Operand LC_ResolveCompoArray(LC_AST *n, LC_Type *type); +LC_FUNCTION LC_Operand LC_ResolveTypeOrExpr(LC_AST *n); +LC_FUNCTION LC_Operand LC_ExpectBuiltinWithOneArg(LC_AST *n); +LC_FUNCTION LC_Operand LC_ResolveBuiltin(LC_AST *n); +LC_FUNCTION bool LC_TryTyping(LC_AST *n, LC_Operand op); +LC_FUNCTION bool LC_TryDefaultTyping(LC_AST *n, LC_Operand *o); +LC_FUNCTION LC_Operand LC_ResolveNameInScope(LC_AST *n, LC_Decl *parent_decl); +LC_FUNCTION LC_Operand LC_ResolveExpr(LC_AST *expr); +LC_FUNCTION LC_Operand LC_ResolveExprAndPushCompoContext(LC_AST *expr, LC_Type *type); +LC_FUNCTION LC_Operand LC_ResolveExprEx(LC_AST *n); +LC_FUNCTION LC_Operand LC_ResolveStmtBlock(LC_AST *n); +LC_FUNCTION LC_Operand LC_ResolveVarDecl(LC_Decl *decl); +LC_FUNCTION LC_Operand LC_MakeSureNoDeferBlock(LC_AST *n, char *str); +LC_FUNCTION LC_Operand LC_MakeSureInsideLoopBlock(LC_AST *n, char *str); +LC_FUNCTION LC_Operand LC_MatchLabeledBlock(LC_AST *n); +LC_FUNCTION LC_Operand LC_ResolveStmt(LC_AST *n); +LC_FUNCTION LC_Operand LC_ResolveConstDecl(LC_Decl *decl); +LC_FUNCTION LC_Operand LC_ResolveName(LC_AST *pos, LC_Intern intern); +LC_FUNCTION LC_Operand LC_ResolveConstInt(LC_AST *n, LC_Type *int_type, uint64_t *out_size); +LC_FUNCTION LC_Operand LC_ResolveType(LC_AST *n); +LC_FUNCTION LC_Operand LC_ResolveBinaryExpr(LC_AST *n, LC_Operand l, LC_Operand r); +LC_FUNCTION LC_Operand LC_ResolveTypeVargs(LC_AST *pos, LC_Operand v); +LC_FUNCTION LC_Operand LC_ResolveTypeCast(LC_AST *pos, LC_Operand t, LC_Operand v); +LC_FUNCTION LC_Operand LC_ResolveTypeVarDecl(LC_AST *pos, LC_Operand t, LC_Operand v); +LC_FUNCTION LC_Operand LC_ResolveTypeAggregate(LC_AST *pos, LC_Type *type); + +LC_FUNCTION LC_Operand LC_OPError(void); +LC_FUNCTION LC_Operand LC_OPConstType(LC_Type *type); +LC_FUNCTION LC_Operand LC_OPDecl(LC_Decl *decl); +LC_FUNCTION LC_Operand LC_OPType(LC_Type *type); +LC_FUNCTION LC_Operand LC_OPLValueAndType(LC_Type *type); +LC_FUNCTION LC_Operand LC_ConstCastFloat(LC_AST *pos, LC_Operand op); +LC_FUNCTION LC_Operand LC_ConstCastInt(LC_AST *pos, LC_Operand op); +LC_FUNCTION LC_Operand LC_OPInt(int64_t v); +LC_FUNCTION LC_Operand LC_OPIntT(LC_Type *type, int64_t v); +LC_FUNCTION LC_Operand LC_OPModDefaultUT(LC_Operand val); +LC_FUNCTION LC_Operand LC_OPModType(LC_Operand op, LC_Type *type); +LC_FUNCTION LC_Operand LC_OPModBool(LC_Operand op); +LC_FUNCTION LC_Operand LC_OPModBoolV(LC_Operand op, int v); +LC_FUNCTION LC_Operand LC_EvalBinary(LC_AST *pos, LC_Operand a, LC_TokenKind op, LC_Operand b); +LC_FUNCTION LC_Operand LC_EvalUnary(LC_AST *pos, LC_TokenKind op, LC_Operand a); +LC_FUNCTION LC_OPResult LC_IsBinaryExprValidForType(LC_TokenKind op, LC_Type *type); +LC_FUNCTION LC_OPResult LC_IsUnaryOpValidForType(LC_TokenKind op, LC_Type *type); +LC_FUNCTION LC_OPResult LC_IsAssignValidForType(LC_TokenKind op, LC_Type *type); + +// +// Error +// +LC_FUNCTION void LC_IgnoreMessage(LC_Token *pos, char *str, int len); +LC_FUNCTION void LC_SendErrorMessage(LC_Token *pos, LC_String s8); +LC_FUNCTION void LC_SendErrorMessagef(LC_Lex *x, LC_Token *pos, const char *str, ...); +LC_FUNCTION LC_AST *LC_ReportParseError(LC_Token *pos, const char *str, ...); +LC_FUNCTION LC_Operand LC_ReportASTError(LC_AST *n, const char *str, ...); +LC_FUNCTION LC_Operand LC_ReportASTErrorEx(LC_AST *n1, LC_AST *n2, const char *str, ...); +LC_FUNCTION void LC_HandleFatalError(void); + +#define LC_ASSERT(n, cond) \ + if (!(cond)) { \ + LC_ReportASTError(n, "internal compiler error: assert condition failed: %s, inside of %s", #cond, __FUNCTION__); \ + LC_HandleFatalError(); \ + } + +// +// Code generation and printing helpers +// +LC_FUNCTION LC_StringList *LC_BeginStringGen(LC_Arena *arena); +LC_FUNCTION LC_String LC_EndStringGen(LC_Arena *arena); + +// clang-format off +#define LC_Genf(...) LC_Addf(L->printer.arena, &L->printer.list, __VA_ARGS__) +#define LC_GenLinef(...) do { LC_Genf("\n"); LC_GenIndent(); LC_Genf(__VA_ARGS__); } while (0) +// clang-format on + +LC_FUNCTION void LC_GenIndent(void); +LC_FUNCTION void LC_GenLine(void); +LC_FUNCTION char *LC_Strf(const char *str, ...); +LC_FUNCTION char *LC_GenLCType(LC_Type *type); +LC_FUNCTION char *LC_GenLCTypeVal(LC_TypeAndVal v); +LC_FUNCTION char *LC_GenLCAggName(LC_Type *t); +LC_FUNCTION void LC_GenLCNode(LC_AST *n); + +// C code generation +LC_FUNCTION void LC_GenCHeader(LC_AST *package); +LC_FUNCTION void LC_GenCImpl(LC_AST *package); + +LC_FUNCTION void LC_GenCLineDirective(LC_AST *node); +LC_FUNCTION void LC_GenLastCLineDirective(void); +LC_FUNCTION void LC_GenCLineDirectiveNum(int num); + +LC_FUNCTION char *LC_GenCTypeParen(char *str, char c); +LC_FUNCTION char *LC_GenCType(LC_Type *type, char *str); +LC_FUNCTION LC_Intern LC_GetStringFromSingleArgNote(LC_AST *note); +LC_FUNCTION void LC_GenCCompound(LC_AST *n); +LC_FUNCTION void LC_GenCString(char *s, LC_Type *type); +LC_FUNCTION char *LC_GenCVal(LC_TypeAndVal v, LC_Type *type); +LC_FUNCTION void LC_GenCExpr(LC_AST *n); +LC_FUNCTION void LC_GenCNote(LC_AST *note); +LC_FUNCTION void LC_GenCVarExpr(LC_AST *n, bool is_declaration); +LC_FUNCTION void LC_GenCDefers(LC_AST *block); +LC_FUNCTION void LC_GenCDefersLoopBreak(LC_AST *n); +LC_FUNCTION void LC_GenCDefersReturn(LC_AST *n); +LC_FUNCTION void LC_GenCStmt2(LC_AST *n, int flags); +LC_FUNCTION void LC_GenCStmt(LC_AST *n); +LC_FUNCTION void LC_GenCExprParen(LC_AST *expr); +LC_FUNCTION void LC_GenCStmtBlock(LC_AST *n); +LC_FUNCTION void LC_GenCProcDecl(LC_Decl *decl); +LC_FUNCTION void LC_GenCAggForwardDecl(LC_Decl *decl); +LC_FUNCTION void LC_GenCTypeDecl(LC_Decl *decl); +LC_FUNCTION void LC_GenCVarFDecl(LC_Decl *decl); + +// +// Inline helpers +// +static inline bool LC_IsUTInt(LC_Type *x) { return x->kind == LC_TypeKind_UntypedInt; } +static inline bool LC_IsUTFloat(LC_Type *x) { return x->kind == LC_TypeKind_UntypedFloat; } +static inline bool LC_IsUTStr(LC_Type *x) { return x->kind == LC_TypeKind_UntypedString; } +static inline bool LC_IsUntyped(LC_Type *x) { return (x)->kind >= LC_TypeKind_UntypedInt && x->kind <= LC_TypeKind_UntypedString; } + +static inline bool LC_IsNum(LC_Type *x) { return x->kind >= LC_TypeKind_char && x->kind <= LC_TypeKind_double; } +static inline bool LC_IsInt(LC_Type *x) { return (x->kind >= LC_TypeKind_char && x->kind <= LC_TypeKind_ullong) || LC_IsUTInt(x); } +static inline bool LC_IsIntLike(LC_Type *x) { return LC_IsInt(x) || x->kind == LC_TypeKind_Pointer || x->kind == LC_TypeKind_Proc; } +static inline bool LC_IsFloat(LC_Type *x) { return ((x)->kind == LC_TypeKind_float || (x->kind == LC_TypeKind_double)) || LC_IsUTFloat(x); } +static inline bool LC_IsSmallerThenInt(LC_Type *x) { return x->kind < LC_TypeKind_int; } + +static inline bool LC_IsAggType(LC_Type *x) { return ((x)->kind == LC_TypeKind_Struct || (x)->kind == LC_TypeKind_Union); } +static inline bool LC_IsArray(LC_Type *x) { return (x)->kind == LC_TypeKind_Array; } +static inline bool LC_IsProc(LC_Type *x) { return (x)->kind == LC_TypeKind_Proc; } +static inline bool LC_IsVoidPtr(LC_Type *x) { return (x) == L->tpvoid; } +static inline bool LC_IsPtr(LC_Type *x) { return (x)->kind == LC_TypeKind_Pointer; } +static inline bool LC_IsPtrLike(LC_Type *x) { return (x)->kind == LC_TypeKind_Pointer || x->kind == LC_TypeKind_Proc; } +static inline bool LC_IsStr(LC_Type *x) { return x == L->tpchar || x == L->tstring; } + +static inline bool LC_IsDecl(LC_AST *x) { return (x->kind >= LC_ASTKind_FirstDecl && x->kind <= LC_ASTKind_LastDecl); } +static inline bool LC_IsStmt(LC_AST *x) { return (x->kind >= LC_ASTKind_FirstStmt && x->kind <= LC_ASTKind_LastStmt); } +static inline bool LC_IsExpr(LC_AST *x) { return (x->kind >= LC_ASTKind_FirstExpr && x->kind <= LC_ASTKind_LastExpr); } +static inline bool LC_IsType(LC_AST *x) { return (x->kind >= LC_ASTKind_FirstTypespec && x->kind <= LC_ASTKind_LastTypespec); } +static inline bool LC_IsAgg(LC_AST *x) { return (x->kind == LC_ASTKind_DeclStruct || x->kind == LC_ASTKind_DeclUnion); } + +// I tried removing this because I thought it's redundant +// but this reminded me that "Untyped bool" can appear from normal expressions: (a == b) +// This is required, maybe there is a way around it, not sure +static inline bool LC_IsUTConst(LC_Operand op) { return (op.flags & LC_OPF_UTConst) != 0; } +static inline bool LC_IsConst(LC_Operand op) { return (op.flags & LC_OPF_Const) != 0; } +static inline bool LC_IsLValue(LC_Operand op) { return (op.flags & LC_OPF_LValue) != 0; } +static inline bool LC_IsError(LC_Operand op) { return (op.flags & LC_OPF_Error) != 0; } + +static inline LC_Type *LC_GetBase(LC_Type *x) { return (x)->tbase; } + +// +// Stringifying functions +// +LC_FUNCTION const char *LC_OSToString(LC_OS os); +LC_FUNCTION const char *LC_GENToString(LC_GEN os); +LC_FUNCTION const char *LC_ARCHToString(LC_ARCH arch); +LC_FUNCTION const char *LC_ASTKindToString(LC_ASTKind kind); +LC_FUNCTION const char *LC_TypeKindToString(LC_TypeKind kind); +LC_FUNCTION const char *LC_DeclKindToString(LC_DeclKind decl_kind); +LC_FUNCTION const char *LC_TokenKindToString(LC_TokenKind token_kind); +LC_FUNCTION const char *LC_TokenKindToOperator(LC_TokenKind token_kind); + +// +// bigint functions +// +LC_FUNCTION LC_BigInt LC_Bigint_u64(uint64_t val); +LC_FUNCTION uint64_t *LC_Bigint_ptr(LC_BigInt *big_int); +LC_FUNCTION size_t LC_Bigint_bits_needed(LC_BigInt *big_int); +LC_FUNCTION void LC_Bigint_init_unsigned(LC_BigInt *big_int, uint64_t value); +LC_FUNCTION void LC_Bigint_init_signed(LC_BigInt *dest, int64_t value); +LC_FUNCTION void LC_Bigint_init_bigint(LC_BigInt *dest, LC_BigInt *src); +LC_FUNCTION void LC_Bigint_negate(LC_BigInt *dest, LC_BigInt *source); +LC_FUNCTION size_t LC_Bigint_clz(LC_BigInt *big_int, size_t bit_count); +LC_FUNCTION bool LC_Bigint_eql(LC_BigInt a, LC_BigInt b); +LC_FUNCTION bool LC_Bigint_fits_in_bits(LC_BigInt *big_int, size_t bit_count, bool is_signed); +LC_FUNCTION uint64_t LC_Bigint_as_unsigned(LC_BigInt *bigint); +LC_FUNCTION void LC_Bigint_add(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_add_wrap(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed); +LC_FUNCTION void LC_Bigint_sub(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_sub_wrap(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed); +LC_FUNCTION void LC_Bigint_mul(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_mul_wrap(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed); +LC_FUNCTION void LC_Bigint_unsigned_division(LC_BigInt *op1, LC_BigInt *op2, LC_BigInt *Quotient, LC_BigInt *Remainder); +LC_FUNCTION void LC_Bigint_div_trunc(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_div_floor(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_rem(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_mod(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_or(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_and(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_xor(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_shl(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_shl_int(LC_BigInt *dest, LC_BigInt *op1, uint64_t shift); +LC_FUNCTION void LC_Bigint_shl_trunc(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2, size_t bit_count, bool is_signed); +LC_FUNCTION void LC_Bigint_shr(LC_BigInt *dest, LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION void LC_Bigint_not(LC_BigInt *dest, LC_BigInt *op, size_t bit_count, bool is_signed); +LC_FUNCTION void LC_Bigint_truncate(LC_BigInt *dst, LC_BigInt *op, size_t bit_count, bool is_signed); +LC_FUNCTION LC_CmpRes LC_Bigint_cmp(LC_BigInt *op1, LC_BigInt *op2); +LC_FUNCTION char *LC_Bigint_str(LC_BigInt *bigint, uint64_t base); +LC_FUNCTION int64_t LC_Bigint_as_signed(LC_BigInt *bigint); +LC_FUNCTION LC_CmpRes LC_Bigint_cmp_zero(LC_BigInt *op); +LC_FUNCTION double LC_Bigint_as_float(LC_BigInt *bigint); + +// +// Unicode API +// +struct LC_UTF32Result { + uint32_t out_str; + int advance; + int error; +}; + +struct LC_UTF8Result { + uint8_t out_str[4]; + int len; + int error; +}; + +struct LC_UTF16Result { + uint16_t out_str[2]; + int len; + int error; +}; + +LC_FUNCTION LC_UTF32Result LC_ConvertUTF16ToUTF32(uint16_t *c, int max_advance); +LC_FUNCTION LC_UTF8Result LC_ConvertUTF32ToUTF8(uint32_t codepoint); +LC_FUNCTION LC_UTF32Result LC_ConvertUTF8ToUTF32(char *c, int max_advance); +LC_FUNCTION LC_UTF16Result LC_ConvertUTF32ToUTF16(uint32_t codepoint); +LC_FUNCTION int64_t LC_CreateCharFromWidechar(char *buffer, int64_t buffer_size, wchar_t *in, int64_t inlen); +LC_FUNCTION int64_t LC_CreateWidecharFromChar(wchar_t *buffer, int64_t buffer_size, char *in, int64_t inlen); + +// +// Filesystem API +// +LC_FUNCTION bool LC_IsDir(LC_Arena *temp, LC_String path); +LC_FUNCTION LC_String LC_GetAbsolutePath(LC_Arena *arena, LC_String relative); +LC_FUNCTION bool LC_EnableTerminalColors(void); +LC_FUNCTION LC_String LC_ReadFile(LC_Arena *arena, LC_String path); + +LC_FUNCTION bool LC_IsValid(LC_FileIter it); +LC_FUNCTION void LC_Advance(LC_FileIter *it); +LC_FUNCTION LC_FileIter LC_IterateFiles(LC_Arena *scratch_arena, LC_String path); + +// +// Arena API +// +#define LC_PushSize(a, size) LC__PushSize(a, size) +#define LC_PushSizeNonZeroed(a, size) LC__PushSizeNonZeroed(a, size) + +#define LC_PushArrayNonZeroed(a, T, c) (T *)LC__PushSizeNonZeroed(a, sizeof(T) * (c)) +#define LC_PushStructNonZeroed(a, T) (T *)LC__PushSizeNonZeroed(a, sizeof(T)) +#define LC_PushStruct(a, T) (T *)LC__PushSize(a, sizeof(T)) +#define LC_PushArray(a, T, c) (T *)LC__PushSize(a, sizeof(T) * (c)) + +#define LC_Assertf(cond, ...) LC_ASSERT(NULL, cond) + +#ifndef LC_USE_CUSTOM_ARENA +LC_FUNCTION void LC_InitArenaEx(LC_Arena *a, size_t reserve); +LC_FUNCTION void LC_InitArena(LC_Arena *a); +LC_FUNCTION void LC_InitArenaFromBuffer(LC_Arena *arena, void *buffer, size_t size); +LC_FUNCTION LC_Arena *LC_BootstrapArena(void); +LC_FUNCTION LC_Arena LC_PushArena(LC_Arena *arena, size_t size); +LC_FUNCTION LC_Arena *LC_PushArenaP(LC_Arena *arena, size_t size); + +LC_FUNCTION void *LC__PushSizeNonZeroed(LC_Arena *a, size_t size); +LC_FUNCTION void *LC__PushSize(LC_Arena *arena, size_t size); +LC_FUNCTION LC_TempArena LC_BeginTemp(LC_Arena *arena); +LC_FUNCTION void LC_EndTemp(LC_TempArena checkpoint); + +LC_FUNCTION void LC_PopToPos(LC_Arena *arena, size_t pos); +LC_FUNCTION void LC_PopSize(LC_Arena *arena, size_t size); +LC_FUNCTION void LC_DeallocateArena(LC_Arena *arena); +LC_FUNCTION void LC_ResetArena(LC_Arena *arena); + +LC_FUNCTION LC_VMemory LC_VReserve(size_t size); +LC_FUNCTION bool LC_VCommit(LC_VMemory *m, size_t commit); +LC_FUNCTION void LC_VDeallocate(LC_VMemory *m); +LC_FUNCTION bool LC_VDecommitPos(LC_VMemory *m, size_t pos); +#endif // LC_USE_CUSTOM_ARENA + +LC_FUNCTION size_t LC_GetAlignOffset(size_t size, size_t align); +LC_FUNCTION size_t LC_AlignUp(size_t size, size_t align); +LC_FUNCTION size_t LC_AlignDown(size_t size, size_t align); + +#define LC_IS_POW2(x) (((x) & ((x)-1)) == 0) +#define LC_MIN(x, y) ((x) <= (y) ? (x) : (y)) +#define LC_MAX(x, y) ((x) >= (y) ? (x) : (y)) +#define LC_StrLenof(x) ((int64_t)((sizeof(x) / sizeof((x)[0])))) + +#define LC_CLAMP_TOP(x, max) ((x) >= (max) ? (max) : (x)) +#define LC_CLAMP_BOT(x, min) ((x) <= (min) ? (min) : (x)) +#define LC_CLAMP(x, min, max) ((x) >= (max) ? (max) : (x) <= (min) ? (min) \ + : (x)) +#define LC_KIB(x) ((x##ull) * 1024ull) +#define LC_MIB(x) (LC_KIB(x) * 1024ull) +#define LC_GIB(x) (LC_MIB(x) * 1024ull) +#define LC_TIB(x) (LC_GIB(x) * 1024ull) + +// +// String API +// + +typedef int LC_FindFlag; +enum { + LC_FindFlag_None = 0, + LC_FindFlag_IgnoreCase = 1, + LC_FindFlag_MatchFindLast = 2, +}; + +typedef int LC_SplitFlag; +enum { + LC_SplitFlag_None = 0, + LC_SplitFlag_IgnoreCase = 1, + LC_SplitFlag_SplitInclusive = 2, +}; + +static const bool LC_IgnoreCase = true; + +#if defined(__has_attribute) + #if __has_attribute(format) + #define LC__PrintfFormat(fmt, va) __attribute__((format(printf, fmt, va))) + #endif +#endif + +#ifndef LC__PrintfFormat + #define LC__PrintfFormat(fmt, va) +#endif + +#define LC_Lit(string) LC_MakeString((char *)string, sizeof(string) - 1) +#define LC_Expand(string) (int)(string).len, (string).str + +#define LC_FORMAT(allocator, str, result) \ + va_list args1; \ + va_start(args1, str); \ + LC_String result = LC_FormatV(allocator, str, args1); \ + va_end(args1) + +#ifdef __cplusplus + #define LC_IF_CPP(x) x +#else + #define LC_IF_CPP(x) +#endif + +LC_FUNCTION char LC_ToLowerCase(char a); +LC_FUNCTION char LC_ToUpperCase(char a); +LC_FUNCTION bool LC_IsWhitespace(char w); +LC_FUNCTION bool LC_IsAlphabetic(char a); +LC_FUNCTION bool LC_IsIdent(char a); +LC_FUNCTION bool LC_IsDigit(char a); +LC_FUNCTION bool LC_IsAlphanumeric(char a); + +LC_FUNCTION int64_t LC_StrLen(char *string); +LC_FUNCTION bool LC_AreEqual(LC_String a, LC_String b, unsigned ignore_case LC_IF_CPP(= false)); +LC_FUNCTION bool LC_EndsWith(LC_String a, LC_String end, unsigned ignore_case LC_IF_CPP(= false)); +LC_FUNCTION bool LC_StartsWith(LC_String a, LC_String start, unsigned ignore_case LC_IF_CPP(= false)); +LC_FUNCTION LC_String LC_MakeString(char *str, int64_t len); +LC_FUNCTION LC_String LC_CopyString(LC_Arena *allocator, LC_String string); +LC_FUNCTION LC_String LC_CopyChar(LC_Arena *allocator, char *s); +LC_FUNCTION LC_String LC_NormalizePath(LC_Arena *allocator, LC_String s); +LC_FUNCTION void LC_NormalizePathUnsafe(LC_String s); // make sure there is no way string is const etc. +LC_FUNCTION LC_String LC_Chop(LC_String string, int64_t len); +LC_FUNCTION LC_String LC_Skip(LC_String string, int64_t len); +LC_FUNCTION LC_String LC_GetPostfix(LC_String string, int64_t len); +LC_FUNCTION LC_String LC_GetPrefix(LC_String string, int64_t len); +LC_FUNCTION bool LC_Seek(LC_String string, LC_String find, LC_FindFlag flags LC_IF_CPP(= LC_FindFlag_None), int64_t *index_out LC_IF_CPP(= 0)); +LC_FUNCTION int64_t LC_Find(LC_String string, LC_String find, LC_FindFlag flags LC_IF_CPP(= LC_FindFlag_None)); +LC_FUNCTION LC_String LC_ChopLastSlash(LC_String s); +LC_FUNCTION LC_String LC_ChopLastPeriod(LC_String s); +LC_FUNCTION LC_String LC_SkipToLastSlash(LC_String s); +LC_FUNCTION LC_String LC_SkipToLastPeriod(LC_String s); +LC_FUNCTION LC_String LC_GetNameNoExt(LC_String s); +LC_FUNCTION LC_String LC_MakeFromChar(char *string); +LC_FUNCTION LC_String LC_MakeEmptyString(void); +LC_FUNCTION LC_StringList LC_MakeEmptyList(void); +LC_FUNCTION LC_String LC_FormatV(LC_Arena *allocator, const char *str, va_list args1); +LC_FUNCTION LC_String LC_Format(LC_Arena *allocator, const char *str, ...) LC__PrintfFormat(2, 3); + +LC_FUNCTION LC_StringList LC_Split(LC_Arena *allocator, LC_String string, LC_String find, LC_SplitFlag flags LC_IF_CPP(= LC_SplitFlag_None)); +LC_FUNCTION LC_String LC_MergeWithSeparator(LC_Arena *allocator, LC_StringList list, LC_String separator LC_IF_CPP(= LC_Lit(" "))); +LC_FUNCTION LC_String LC_MergeString(LC_Arena *allocator, LC_StringList list); + +LC_FUNCTION LC_StringNode *LC_CreateNode(LC_Arena *allocator, LC_String string); +LC_FUNCTION void LC_ReplaceNodeString(LC_StringList *list, LC_StringNode *node, LC_String new_string); +LC_FUNCTION void LC_AddExistingNode(LC_StringList *list, LC_StringNode *node); +LC_FUNCTION void LC_AddArray(LC_Arena *allocator, LC_StringList *list, char **array, int count); +LC_FUNCTION void LC_AddArrayWithPrefix(LC_Arena *allocator, LC_StringList *list, char *prefix, char **array, int count); +LC_FUNCTION LC_StringList LC_MakeList(LC_Arena *allocator, LC_String a); +LC_FUNCTION LC_StringList LC_CopyList(LC_Arena *allocator, LC_StringList a); +LC_FUNCTION LC_StringList LC_ConcatLists(LC_Arena *allocator, LC_StringList a, LC_StringList b); +LC_FUNCTION LC_StringNode *LC_AddNode(LC_Arena *allocator, LC_StringList *list, LC_String string); +LC_FUNCTION LC_StringNode *LC_Add(LC_Arena *allocator, LC_StringList *list, LC_String string); +LC_FUNCTION LC_String LC_Addf(LC_Arena *allocator, LC_StringList *list, const char *str, ...) LC__PrintfFormat(3, 4); + +LC_FUNCTION wchar_t *LC_ToWidechar(LC_Arena *allocator, LC_String string); + +// +// Linked list API +// +#define LC_SLLAddMod(f, l, n, next) \ + do { \ + (n)->next = 0; \ + if ((f) == 0) { \ + (f) = (l) = (n); \ + } else { \ + (l) = (l)->next = (n); \ + } \ + } while (0) +#define LC_AddSLL(f, l, n) LC_SLLAddMod(f, l, n, next) + +#define LC_SLLPopFirstMod(f, l, next) \ + do { \ + if ((f) == (l)) { \ + (f) = (l) = 0; \ + } else { \ + (f) = (f)->next; \ + } \ + } while (0) +#define LC_SLLPopFirst(f, l) LC_SLLPopFirstMod(f, l, next) + +#define LC_SLLStackAddMod(stack_base, new_stack_base, next) \ + do { \ + (new_stack_base)->next = (stack_base); \ + (stack_base) = (new_stack_base); \ + } while (0) + +#define LC_DLLAddMod(f, l, node, next, prev) \ + do { \ + if ((f) == 0) { \ + (f) = (l) = (node); \ + (node)->prev = 0; \ + (node)->next = 0; \ + } else { \ + (l)->next = (node); \ + (node)->prev = (l); \ + (node)->next = 0; \ + (l) = (node); \ + } \ + } while (0) +#define LC_DLLAdd(f, l, node) LC_DLLAddMod(f, l, node, next, prev) +#define LC_DLLAddFront(f, l, node) LC_DLLAddMod(l, f, node, prev, next) +#define LC_DLLRemoveMod(first, last, node, next, prev) \ + do { \ + if ((first) == (last)) { \ + (first) = (last) = 0; \ + } else if ((last) == (node)) { \ + (last) = (last)->prev; \ + (last)->next = 0; \ + } else if ((first) == (node)) { \ + (first) = (first)->next; \ + (first)->prev = 0; \ + } else { \ + (node)->prev->next = (node)->next; \ + (node)->next->prev = (node)->prev; \ + } \ + if (node) { \ + (node)->prev = 0; \ + (node)->next = 0; \ + } \ + } while (0) +#define LC_DLLRemove(first, last, node) LC_DLLRemoveMod(first, last, node, next, prev) + +#define LC_ASTFor(it, x) for (LC_AST *it = x; it; it = it->next) +#define LC_DeclFor(it, x) for (LC_Decl *it = x; it; it = it->next) +#define LC_TypeFor(it, x) for (LC_TypeMember *it = x; it; it = it->next) + +#if defined(__APPLE__) && defined(__MACH__) + #define LC_OPERATING_SYSTEM_MAC 1 + #define LC_OPERATING_SYSTEM_UNIX 1 +#elif defined(_WIN32) + #define LC_OPERATING_SYSTEM_WINDOWS 1 +#elif defined(__linux__) + #define LC_OPERATING_SYSTEM_UNIX 1 + #define LC_OPERATING_SYSTEM_LINUX 1 +#endif + +#ifndef LC_OPERATING_SYSTEM_MAC + #define LC_OPERATING_SYSTEM_MAC 0 +#endif + +#ifndef LC_OPERATING_SYSTEM_UNIX + #define LC_OPERATING_SYSTEM_UNIX 0 +#endif + +#ifndef LC_OPERATING_SYSTEM_WINDOWS + #define LC_OPERATING_SYSTEM_WINDOWS 0 +#endif + +#ifndef LC_OPERATING_SYSTEM_LINUX + #define LC_OPERATING_SYSTEM_LINUX 0 +#endif + +#endif \ No newline at end of file diff --git a/src/compiler/packages.c b/src/compiler/packages.c new file mode 100644 index 0000000..3eab82a --- /dev/null +++ b/src/compiler/packages.c @@ -0,0 +1,363 @@ +LC_FUNCTION LC_Operand LC_ImportPackage(LC_AST *import, LC_AST *dst, LC_AST *src) { + DeclScope *dst_scope = dst->apackage.scope; + int scope_size = LC_NextPow2(src->apackage.scope->len * 2 + 1); + if (import && import->gimport.name) { + LC_PUSH_PACKAGE(dst); + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Import, import->gimport.name, import); + decl->scope = LC_CreateScope(scope_size); + LC_PutGlobalDecl(decl); + import->gimport.resolved_decl = decl; + LC_POP_PACKAGE(); + dst_scope = decl->scope; + } + + for (int i = 0; i < src->apackage.scope->cap; i += 1) { + LC_MapEntry entry = src->apackage.scope->entries[i]; + if (entry.key != 0) { + LC_Decl *decl = (LC_Decl *)entry.value; + if (decl->package != src) continue; + LC_Decl *existing = (LC_Decl *)LC_MapGetU64(dst_scope, decl->name); + if (existing && decl->package == L->builtin_package) { + continue; + } + if (existing) { + LC_MarkDeclError(existing); + LC_MarkDeclError(decl); + return LC_ReportASTErrorEx(decl->ast, existing->ast, "name colission while importing '%s' into '%s', there are 2 decls with the same name '%s'", src->apackage.name, dst->apackage.name, decl->name); + } + LC_MapInsertU64(dst_scope, decl->name, decl); + } + } + + if (import && import->gimport.name) { + LC_ASSERT(import, dst_scope->cap == scope_size); + } + + if (import) import->gimport.resolved = true; + return LC_OPNull; +} + +LC_FUNCTION LC_Intern LC_MakePackageNameFromPath(LC_String path) { + if (path.str[path.len - 1] == '/') path = LC_Chop(path, 1); + LC_String s8name = LC_SkipToLastSlash(path); + if (!LC_IsDir(L->arena, path) && LC_EndsWith(path, LC_Lit(".lc"), true)) { + s8name = LC_ChopLastPeriod(s8name); + } + if (s8name.len == 0) { + L->errors += 1; + LC_SendErrorMessagef(NULL, NULL, "failed to extract name from path %.*s", LC_Expand(path)); + return LC_GetUniqueIntern("invalid_package_name"); + } + LC_Intern result = LC_InternStrLen(s8name.str, (int)s8name.len); + return result; +} + +LC_FUNCTION bool LC_PackageNameValid(LC_Intern name) { + char *str = (char *)name; + if (LC_IsDigit(str[0])) return false; + for (int i = 0; str[i]; i += 1) { + bool is_valid = LC_IsIdent(str[i]) || LC_IsDigit(str[i]); + if (!is_valid) return false; + } + return true; +} + +LC_FUNCTION bool LC_PackageNameDuplicate(LC_Intern name) { + LC_ASTFor(it, L->fpackage) { + if (it->apackage.name == name) return true; + } + return false; +} + +LC_FUNCTION void LC_AddPackageToList(LC_AST *n) { + LC_Intern name = n->apackage.name; + if (LC_PackageNameDuplicate(name)) { + LC_SendErrorMessagef(NULL, NULL, "found 2 packages with the same name: '%s' / '%.*s'\n", name, LC_Expand(n->apackage.path)); + L->errors += 1; + return; + } + if (!LC_PackageNameValid(name)) { + LC_SendErrorMessagef(NULL, NULL, "invalid package name, please change the name of the package directory: '%s'\n", name); + L->errors += 1; + return; + } + LC_DLLAdd(L->fpackage, L->lpackage, n); +} + +LC_FUNCTION LC_AST *LC_RegisterPackage(LC_String path) { + LC_ASSERT(NULL, path.len != 0); + LC_AST *n = LC_CreateAST(NULL, LC_ASTKind_Package); + n->apackage.name = LC_MakePackageNameFromPath(path); + n->apackage.path = path; + LC_AddPackageToList(n); + return n; +} + +LC_FUNCTION LC_AST *LC_FindImportInRefList(LC_ASTRefList *arr, LC_Intern path) { + for (LC_ASTRef *it = arr->first; it; it = it->next) { + if (it->ast->gimport.path == path) return it->ast; + } + return NULL; +} + +LC_FUNCTION void LC_AddASTToRefList(LC_ASTRefList *refs, LC_AST *ast) { + LC_ASTRef *ref = LC_PushStruct(L->arena, LC_ASTRef); + ref->ast = ast; + LC_DLLAdd(refs->first, refs->last, ref); +} + +LC_FUNCTION LC_ASTRefList LC_GetPackageImports(LC_AST *package) { + LC_ASSERT(package, package->kind == LC_ASTKind_Package); + + LC_ASTRefList refs = {0}; + LC_ASTFor(file, package->apackage.ffile) { + LC_ASTFor(import, file->afile.fimport) { + LC_AST *found = LC_FindImportInRefList(&refs, import->gimport.path); + if (found) { + LC_ReportASTErrorEx(import, found, "duplicate import of: '%s', into package '%s'\n", import->gimport.path, package->apackage.name); + continue; + } + LC_AddASTToRefList(&refs, import); + } + } + + return refs; +} + +LC_FUNCTION void LC_RegisterPackageDir(char *dir) { + LC_String sdir = LC_MakeFromChar(dir); + if (!LC_IsDir(L->arena, sdir)) { + LC_SendErrorMessagef(NULL, NULL, "dir with name '%s', doesn't exist\n", dir); + return; + } + LC_AddNode(L->arena, &L->package_dirs, sdir); +} + +LC_FUNCTION LC_AST *LC_GetPackageByName(LC_Intern name) { + LC_ASTFor(it, L->fpackage) { + if (it->apackage.name == name) return it; + } + + LC_AST *result = NULL; + for (LC_StringNode *it = L->package_dirs.first; it; it = it->next) { + LC_String s = it->string; + LC_String path = LC_Format(L->arena, "%.*s/%s", LC_Expand(s), (char *)name); + if (LC_IsDir(L->arena, path)) { + if (result != NULL) { + LC_SendErrorMessagef(NULL, NULL, "found 2 directories with the same name: '%.*s', '%.*s'\n", LC_Expand(path), LC_Expand(result->apackage.path)); + L->errors += 1; + break; + } + result = LC_RegisterPackage(path); + } + } + + return result; +} + +LC_FUNCTION LC_StringList LC_ListFilesInPackage(LC_Arena *arena, LC_String path) { + LC_StringList result = LC_MakeEmptyList(); + for (LC_FileIter it = LC_IterateFiles(arena, path); LC_IsValid(it); LC_Advance(&it)) { + if (LC_EndsWith(it.absolute_path, LC_Lit(".lc"), LC_IgnoreCase)) { + LC_AddNode(arena, &result, it.absolute_path); + } + } + return result; +} + +LC_FUNCTION LoadedFile LC_ReadFileHook(LC_AST *package, LC_String path) { + LoadedFile result = {path}; + if (L->on_file_load) { + L->on_file_load(package, &result); + } else { + result.content = LC_ReadFile(L->arena, result.path); + } + + return result; +} + +LC_FUNCTION void LC_ParsePackage(LC_AST *n) { + LC_ASSERT(n, n->kind == LC_ASTKind_Package); + LC_ASSERT(n, n->apackage.scope == NULL); + n->apackage.scope = LC_CreateScope(256); + + LC_StringList files = n->apackage.injected_filepaths; + if (files.node_count == 0) { + files = LC_ListFilesInPackage(L->arena, n->apackage.path); + if (files.first == NULL) { + LC_SendErrorMessagef(NULL, NULL, "no valid .lc files in '%.*s'", LC_Expand(n->apackage.path)); + n->apackage.state = LC_DeclState_Error; + L->errors += 1; + return; + } + } + + for (LC_StringNode *it = files.first; it; it = it->next) { + LoadedFile file = LC_ReadFileHook(n, it->string); + if (file.content.str == NULL) file.content.str = ""; + + LC_AST *ast_file = LC_ParseFile(n, file.path.str, file.content.str, file.line); + if (!ast_file) { + n->apackage.state = LC_DeclState_Error; + return; + } + } +} + +LC_FUNCTION void LC_ParsePackagesUsingRegistry(LC_Intern name) { + LC_AST *n = LC_GetPackageByName(name); + if (!n) { + LC_SendErrorMessagef(NULL, NULL, "no package with name '%s'\n", name); + L->errors += 1; + return; + } + if (n->apackage.scope) { + return; + } + LC_ParsePackage(n); + LC_ASTRefList imports = LC_GetPackageImports(n); + for (LC_ASTRef *it = imports.first; it; it = it->next) { + LC_ParsePackagesUsingRegistry(it->ast->gimport.path); + } +} + +LC_FUNCTION void LC_AddOrderedPackageToRefList(LC_AST *n) { + LC_ASTRefList *ordered = &L->ordered_packages; + for (LC_ASTRef *it = ordered->first; it; it = it->next) { + if (it->ast->apackage.name == n->apackage.name) { + return; + } + } + LC_AddASTToRefList(ordered, n); +} + +// Here we use import statements to produce a list of ordered packages. +// While we are at it we also resolve most top level declarations. I say +// most because aggregations are handled a bit differently, their resolution +// is deffered. This is added because a pointer doesn't require full typeinfo of +// an aggregate. It's just a number. +LC_FUNCTION LC_AST *LC_OrderPackagesAndBasicResolve(LC_AST *pos, LC_Intern name) { + LC_AST *n = LC_GetPackageByName(name); + if (n->apackage.state == LC_DeclState_Error) { + return NULL; + } + if (n->apackage.state == LC_DeclState_Resolved) { + // This function can be called multiple times, I assume user might + // want to use type information to generate something. Pattern: + // typecheck -> generate -> typecheck is expected! + LC_PackageDecls(n); + return n; + } + if (n->apackage.state == LC_DeclState_Resolving) { + LC_ReportASTError(pos, "circular import '%s'", name); + n->apackage.state = LC_DeclState_Error; + return NULL; + } + LC_ASSERT(pos, n->apackage.state == LC_DeclState_Unresolved); + n->apackage.state = LC_DeclState_Resolving; + + LC_Operand op = LC_ImportPackage(NULL, n, L->builtin_package); + LC_ASSERT(pos, !LC_IsError(op)); + + // Resolve all imports regardless of errors. + // If current package has wrong import it means it's also + // wrong but it should still look into all imports + // despite this. + int wrong_import = 0; + LC_ASTRefList refs = LC_GetPackageImports(n); + for (LC_ASTRef *it = refs.first; it; it = it->next) { + LC_AST *import = LC_OrderPackagesAndBasicResolve(it->ast, it->ast->gimport.path); + if (!import) { + n->apackage.state = LC_DeclState_Error; + wrong_import += 1; + continue; + } + + LC_Operand op = LC_ImportPackage(it->ast, n, import); + if (LC_IsError(op)) { + n->apackage.state = LC_DeclState_Error; + wrong_import += 1; + continue; + } + } + + if (wrong_import) return NULL; + + LC_PackageDecls(n); + LC_AddOrderedPackageToRefList(n); + n->apackage.state = LC_DeclState_Resolved; + return n; +} + +LC_FUNCTION void LC_OrderAndResolveTopLevelDecls(LC_Intern name) { + L->first_package = name; + LC_OrderPackagesAndBasicResolve(NULL, name); + + // Resolve still incomplete aggregate types, this operates on all packages + // that didn't have errors so even if something broke in package ordering + // it should still be fine to go forward with this and also proc body analysis + for (LC_ASTRef *it = L->ordered_packages.first; it; it = it->next) { + LC_AST *package = it->ast; + LC_ASSERT(package, package->apackage.state == LC_DeclState_Resolved); + LC_ResolveIncompleteTypes(package); + } +} + +LC_FUNCTION void LC_ResolveAllProcBodies(void) { + // We don't need to check errors, only valid packages should have been put into + // the list. + for (LC_ASTRef *it = L->ordered_packages.first; it; it = it->next) { + LC_AST *package = it->ast; + LC_ASSERT(package, package->apackage.state == LC_DeclState_Resolved); + LC_ResolveProcBodies(package); + } +} + +LC_FUNCTION LC_ASTRefList LC_ResolvePackageByName(LC_Intern name) { + LC_ParsePackagesUsingRegistry(name); + LC_ASTRefList empty = {0}; + if (L->errors) return empty; + + LC_OrderAndResolveTopLevelDecls(name); + LC_ResolveAllProcBodies(); + return L->ordered_packages; +} + +LC_FUNCTION LC_String LC_GenerateUnityBuild(LC_ASTRefList packages) { + if (L->errors) return LC_MakeEmptyString(); + + LC_BeginStringGen(L->arena); + + LC_GenLinef("#include "); + LC_GenLinef("#include "); + LC_GenLinef("#ifndef LC_String_IMPL"); + LC_GenLinef("#define LC_String_IMPL"); + LC_GenLinef("typedef struct { char *str; long long len; } LC_String;"); + LC_GenLinef("#endif"); + LC_GenLinef("#ifndef LC_Any_IMPL"); + LC_GenLinef("#define LC_Any_IMPL"); + LC_GenLinef("typedef struct { int type; void *data; } LC_Any;"); + LC_GenLinef("#endif"); + + LC_GenLinef("#ifndef LC_Alignof"); + LC_GenLinef("#if defined(__TINYC__)"); + LC_GenLinef("#define LC_Alignof(...) __alignof__(__VA_ARGS__)"); + LC_GenLinef("#else"); + LC_GenLinef("#define LC_Alignof(...) _Alignof(__VA_ARGS__)"); + LC_GenLinef("#endif"); + LC_GenLinef("#endif"); + LC_GenLinef("void *memset(void *, int, size_t);"); + + for (LC_ASTRef *it = packages.first; it; it = it->next) LC_GenCHeader(it->ast); + for (LC_ASTRef *it = packages.first; it; it = it->next) LC_GenCImpl(it->ast); + LC_String s = LC_EndStringGen(L->arena); + return s; +} + +LC_FUNCTION void LC_AddSingleFilePackage(LC_Intern name, LC_String path) { + LC_AST *n = LC_CreateAST(0, LC_ASTKind_Package); + n->apackage.name = name; + n->apackage.path = path; + LC_AddNode(L->arena, &n->apackage.injected_filepaths, path); + LC_AddPackageToList(n); +} \ No newline at end of file diff --git a/src/compiler/parse.c b/src/compiler/parse.c new file mode 100644 index 0000000..af5ead9 --- /dev/null +++ b/src/compiler/parse.c @@ -0,0 +1,1079 @@ +const int ParseStmtBlock_AllowSingleStmt = 1; + +LC_FUNCTION LC_Parser LC_MakeParser(LC_Lex *x) { + LC_Parser p = {0}; + p.at = x->tokens; + p.begin = x->tokens; + p.end = x->tokens + x->token_count; + p.x = x; + return p; +} + +LC_FUNCTION LC_Parser *LC_MakeParserQuick(char *str) { + LC_Lex *x = LC_LexStream("quick_lex", str, 0); + LC_InternTokens(x); + + L->quick_parser = LC_MakeParser(x); + L->parser = &L->quick_parser; + return L->parser; +} + +LC_FUNCTION LC_AST *LC_ReportParseError(LC_Token *pos, const char *str, ...) { + LC_FORMAT(L->arena, str, n); + LC_SendErrorMessage(pos, n); + L->errors += 1; + LC_AST *r = LC_CreateAST(pos, LC_ASTKind_Error); + return r; +} + +LC_FUNCTION LC_Token *LC_Next(void) { + if (L->parser->at < L->parser->end) { + LC_Token *result = L->parser->at; + L->parser->at += 1; + return result; + } + return &L->NullToken; +} + +LC_FUNCTION LC_Token *LC_Get(void) { + if (L->parser->at < L->parser->end) { + return L->parser->at; + } + return &L->NullToken; +} + +LC_FUNCTION LC_Token *LC_GetI(int i) { + LC_Token *result = L->parser->at + i; + if (result >= L->parser->begin && result < L->parser->end) { + return result; + } + return &L->NullToken; +} + +LC_FUNCTION LC_Token *LC_Is(LC_TokenKind kind) { + LC_Token *t = LC_Get(); + if (t->kind == kind) { + return t; + } + return 0; +} + +LC_FUNCTION LC_Token *LC_IsKeyword(LC_Intern intern) { + LC_Token *t = LC_Get(); + if (t->kind == LC_TokenKind_Keyword && t->ident == intern) { + return t; + } + return 0; +} + +LC_FUNCTION LC_Token *LC_Match(LC_TokenKind kind) { + LC_Token *t = LC_Get(); + if (t->kind == kind) { + LC_Next(); + return t; + } + return 0; +} + +LC_FUNCTION LC_Token *LC_MatchKeyword(LC_Intern intern) { + LC_Token *t = LC_Get(); + if (t->kind == LC_TokenKind_Keyword && t->ident == intern) { + LC_Next(); + return t; + } + return 0; +} + +#define LC_EXPECT(token, KIND, context) \ + LC_Token *token = LC_Match(KIND); \ + if (!token) { \ + LC_Token *t = LC_Get(); \ + return LC_ReportParseError(t, "expected %s got instead %s, this happened while parsing: %s", LC_TokenKindToString(KIND), LC_TokenKindToString(t->kind), context); \ + } + +#define LC_PROP_ERROR(expr, ...) \ + expr = __VA_ARGS__; \ + do { \ + if (expr->kind == LC_ASTKind_Error) { \ + return expr; \ + } \ + } while (0) + +// Pratt expression parser +// Based on this really good article: https://matklad.github.io/2020/04/13/simple-but-powerful-pratt-parsing.html +// clang-format off +LC_FUNCTION LC_BindingPower LC_MakeBP(int left, int right) { + LC_BindingPower result = {left, right}; + return result; +} + +LC_FUNCTION LC_BindingPower LC_GetBindingPower(LC_Binding binding, LC_TokenKind kind) { + if (binding == LC_Binding_Prefix) goto Prefix; + if (binding == LC_Binding_Infix) goto Infix; + if (binding == LC_Binding_Postfix) goto Postfix; + LC_ASSERT(NULL, !"invalid codepath"); + +Prefix: + switch (kind) { + case LC_TokenKind_OpenBracket: return LC_MakeBP(-2, 22); + case LC_TokenKind_Mul: case LC_TokenKind_BitAnd: case LC_TokenKind_Keyword: case LC_TokenKind_OpenParen: + case LC_TokenKind_Sub: case LC_TokenKind_Add: case LC_TokenKind_Neg: case LC_TokenKind_Not: case LC_TokenKind_OpenBrace: return LC_MakeBP(-2, 20); + default: return LC_MakeBP(-1, -1); + } +Infix: + switch (kind) { + case LC_TokenKind_Or: return LC_MakeBP(9, 10); + case LC_TokenKind_And: return LC_MakeBP(11, 12); + case LC_TokenKind_Equals: case LC_TokenKind_NotEquals: case LC_TokenKind_GreaterThen: + case LC_TokenKind_GreaterThenEq: case LC_TokenKind_LesserThen: case LC_TokenKind_LesserThenEq: return LC_MakeBP(13, 14); + case LC_TokenKind_Sub: case LC_TokenKind_Add: case LC_TokenKind_BitOr: case LC_TokenKind_BitXor: return LC_MakeBP(15, 16); + case LC_TokenKind_RightShift: case LC_TokenKind_LeftShift: case LC_TokenKind_BitAnd: + case LC_TokenKind_Mul: case LC_TokenKind_Div: case LC_TokenKind_Mod: return LC_MakeBP(17, 18); + default: return LC_MakeBP(0, 0); + } +Postfix: + switch (kind) { + case LC_TokenKind_Dot: case LC_TokenKind_OpenBracket: case LC_TokenKind_OpenParen: return LC_MakeBP(21, -2); + default: return LC_MakeBP(-1, -1); + } +} + +LC_FUNCTION LC_AST *LC_ParseExprEx(int min_bp) { + LC_AST *left = NULL; + LC_Token *prev = LC_GetI(-1); + LC_Token *t = LC_Next(); + LC_BindingPower prefixbp = LC_GetBindingPower(LC_Binding_Prefix, t->kind); + + // parse prefix expression + switch (t->kind) { + case LC_TokenKind_RawString: + case LC_TokenKind_String: { left = LC_CreateAST(t, LC_ASTKind_ExprString); left->eatom.name = t->ident; } break; + case LC_TokenKind_Ident: { left = LC_CreateAST(t, LC_ASTKind_ExprIdent); left->eident.name = t->ident; } break; + case LC_TokenKind_Int: { left = LC_CreateAST(t, LC_ASTKind_ExprInt); left->eatom.i = t->i; } break; + case LC_TokenKind_Float: { left = LC_CreateAST(t, LC_ASTKind_ExprFloat); left->eatom.d = t->f64; } break; + case LC_TokenKind_Unicode: { left = LC_CreateAST(t, LC_ASTKind_ExprInt); left->eatom.i = t->i; } break; + + case LC_TokenKind_Keyword: { + if (t->ident == L->kfalse) { + left = LC_CreateAST(t, LC_ASTKind_ExprBool); + LC_Bigint_init_signed(&left->eatom.i, false); + } else if (t->ident == L->ktrue) { + left = LC_CreateAST(t, LC_ASTKind_ExprBool); + LC_Bigint_init_signed(&left->eatom.i, true); + } else { + return LC_ReportParseError(t, "got unexpected keyword '%s' while parsing expression", t->ident); + } + } break; + + case LC_TokenKind_AddPtr: { + LC_EXPECT(open_paren, LC_TokenKind_OpenParen, "addptr"); + LC_AST *LC_PROP_ERROR(ptr, LC_ParseExprEx(0)); + LC_EXPECT(comma, LC_TokenKind_Comma, "addptr"); + LC_AST *LC_PROP_ERROR(offset, LC_ParseExprEx(0)); + LC_EXPECT(close_paren, LC_TokenKind_CloseParen, "addptr"); + left = LC_CreateBinary(t, ptr, offset, LC_TokenKind_EOF); + left->kind = LC_ASTKind_ExprAddPtr; + } break; + + case LC_TokenKind_Colon: { + left = LC_CreateAST(t, LC_ASTKind_ExprType); + LC_PROP_ERROR(left->etype.type, LC_ParseType()); + + LC_Token *open = LC_Get(); + if (LC_Match(LC_TokenKind_OpenBrace)) { + left = LC_ParseCompo(open, left); + if (left->kind == LC_ASTKind_Error) { + L->parser->at = t; + return left; + } + } else if (LC_Match(LC_TokenKind_OpenParen)) { + LC_AST *type = left; + left = LC_CreateAST(open, LC_ASTKind_ExprCast); + left->ecast.type = type->etype.type; + type->kind = LC_ASTKind_Ignore; + + LC_PROP_ERROR(left->ecast.expr, LC_ParseExpr()); + LC_EXPECT(close_paren, LC_TokenKind_CloseParen, "cast expression"); + } + } break; + + case LC_TokenKind_OpenBrace: { + left = LC_ParseCompo(t, left); + if (left->kind == LC_ASTKind_Error) { + L->parser->at = prev; + return left; + } + } break; + + case LC_TokenKind_Not: case LC_TokenKind_Neg: case LC_TokenKind_Add: case LC_TokenKind_Sub: { + LC_AST *LC_PROP_ERROR(expr, LC_ParseExprEx(prefixbp.right)); + left = LC_CreateUnary(t, t->kind, expr); + } break; + + case LC_TokenKind_BitAnd: { + LC_AST *LC_PROP_ERROR(expr, LC_ParseExprEx(prefixbp.right)); + left = LC_CreateUnary(t, t->kind, expr); + left->kind = LC_ASTKind_ExprGetPointerOfValue; + } break; + + case LC_TokenKind_Mul: { + LC_AST *LC_PROP_ERROR(expr, LC_ParseExprEx(prefixbp.right)); + left = LC_CreateUnary(t, t->kind, expr); + left->kind = LC_ASTKind_ExprGetValueOfPointer; + } break; + + case LC_TokenKind_OpenParen: { + LC_AST *LC_PROP_ERROR(expr, LC_ParseExprEx(0)); + left = expr; + LC_EXPECT(_c, LC_TokenKind_CloseParen, "expression"); + } break; + + default: return LC_ReportParseError(prev, "got invalid token: %s, while parsing expression", LC_TokenKindToString(t->kind)); + } + + for (;;) { + t = LC_Get(); + + // lets say [+] is left:1, right:2 and we parse 2+3+4 + // We pass min_bp of 2 to the next recursion + // in recursion we check if left(1) > min_bp(2) + // it's not so we don't recurse - we break + // We do the for loop instead + + LC_BindingPower postfix_bp = LC_GetBindingPower(LC_Binding_Postfix, t->kind); + LC_BindingPower infix_bp = LC_GetBindingPower(LC_Binding_Infix, t->kind); + + // parse postfix expression + if (postfix_bp.left > min_bp) { + LC_Next(); + switch (t->kind) { + case LC_TokenKind_OpenBracket: { + LC_AST *LC_PROP_ERROR(index, LC_ParseExprEx(0)); + LC_EXPECT(close_bracket, LC_TokenKind_CloseBracket, "index expression"); + left = LC_CreateIndex(t, left, index); + } break; + case LC_TokenKind_OpenParen: { + LC_PROP_ERROR(left, LC_ParseCompo(t, left)); + } break; + case LC_TokenKind_Dot: { + LC_EXPECT(ident, LC_TokenKind_Ident, "field access expression"); + LC_AST *field = LC_CreateAST(t, LC_ASTKind_ExprField); + field->efield.left = left; + field->efield.right = ident->ident; + left = field; + } break; + default: {} + } + } + + // parse infix expression + else if (infix_bp.left > min_bp) { + t = LC_Next(); + LC_AST *LC_PROP_ERROR(right, LC_ParseExprEx(infix_bp.right)); + left = LC_CreateBinary(t, left, right, t->kind); + } + + else break; + } + + if (L->on_expr_parsed) L->on_expr_parsed(left); + return left; +} +// clang-format on + +LC_FUNCTION LC_AST *LC_ParseCompo(LC_Token *pos, LC_AST *left) { + if (pos->kind != LC_TokenKind_OpenBrace && pos->kind != LC_TokenKind_OpenParen) { + return LC_ReportParseError(pos, "internal compiler error: expected open brace or open paren in %s", __FUNCTION__); + } + + LC_ASTKind kind = pos->kind == LC_TokenKind_OpenBrace ? LC_ASTKind_ExprCompound : LC_ASTKind_ExprCall; + LC_TokenKind close_kind = pos->kind == LC_TokenKind_OpenBrace ? LC_TokenKind_CloseBrace : LC_TokenKind_CloseParen; + LC_ASTKind item_kind = pos->kind == LC_TokenKind_OpenBrace ? LC_ASTKind_ExprCompoundItem : LC_ASTKind_ExprCallItem; + + LC_AST *n = LC_CreateAST(pos, kind); + n->ecompo.name = left; + + while (!LC_Is(close_kind)) { + LC_Token *vpos = LC_Get(); + LC_AST *v = LC_CreateAST(vpos, item_kind); + + if (LC_Match(LC_TokenKind_OpenBracket)) { + if (kind == LC_ASTKind_ExprCall) return LC_ReportParseError(vpos, "procedure calls cant have indexed arguments"); + LC_PROP_ERROR(v->ecompo_item.index, LC_ParseExpr()); + LC_EXPECT(close_bracket, LC_TokenKind_CloseBracket, "compo expression"); + LC_EXPECT(assign, LC_TokenKind_Assign, "compo expression"); + LC_PROP_ERROR(v->ecompo_item.expr, LC_ParseExpr()); + } else { + LC_PROP_ERROR(v->ecompo_item.expr, LC_ParseExpr()); + if (LC_Match(LC_TokenKind_Assign)) { + LC_AST *e = v->ecompo_item.expr; + if (e->kind != LC_ASTKind_ExprIdent) return LC_ReportParseError(LC_GetI(-1), "named argument is required to be an identifier"); + LC_PROP_ERROR(v->ecompo_item.expr, LC_ParseExpr()); + v->ecompo_item.name = e->eident.name; + e->kind = LC_ASTKind_Ignore; // :FreeAST + } + } + + n->ecompo.size += 1; + LC_DLLAdd(n->ecompo.first, n->ecompo.last, v); + if (!LC_Match(LC_TokenKind_Comma)) break; + } + LC_EXPECT(close_token, close_kind, "compo expression"); + return n; +} + +LC_FUNCTION LC_AST *LC_ParseExpr(void) { + return LC_ParseExprEx(0); +} + +LC_FUNCTION LC_AST *LC_ParseProcType(LC_Token *pos) { + LC_AST *n = LC_CreateAST(pos, LC_ASTKind_TypespecProc); + LC_EXPECT(open_paren, LC_TokenKind_OpenParen, "procedure typespec"); + if (!LC_Match(LC_TokenKind_CloseParen)) { + for (;;) { + if (LC_Match(LC_TokenKind_ThreeDots)) { + n->tproc.vargs = true; + + LC_Token *any = LC_Get(); + if (any->kind == LC_TokenKind_Ident && any->ident == L->iAny) { + n->tproc.vargs_any_promotion = true; + LC_Next(); + } + break; + } + LC_EXPECT(ident, LC_TokenKind_Ident, "procedure typespec argument list"); + LC_AST *v = LC_CreateAST(ident, LC_ASTKind_TypespecProcArg); + v->tproc_arg.name = ident->ident; + + LC_EXPECT(colon, LC_TokenKind_Colon, "procedure typespec argument list"); + LC_PROP_ERROR(v->tproc_arg.type, LC_ParseType()); + + if (LC_Match(LC_TokenKind_Assign)) { + LC_PROP_ERROR(v->tproc_arg.expr, LC_ParseExpr()); + } + + v->notes = LC_ParseNotes(); + LC_DLLAdd(n->tproc.first, n->tproc.last, v); + + if (!LC_Match(LC_TokenKind_Comma)) break; + } + LC_EXPECT(close_paren, LC_TokenKind_CloseParen, "procedure typespec argument list"); + } + if (LC_Match(LC_TokenKind_Colon)) { + LC_PROP_ERROR(n->tproc.ret, LC_ParseType()); + } + return n; +} + +LC_FUNCTION LC_AST *LC_ParseType(void) { + LC_AST *n = NULL; + LC_Token *t = LC_Next(); + if (t->kind == LC_TokenKind_Ident) { + n = LC_CreateAST(t, LC_ASTKind_TypespecIdent); + n->eident.name = t->ident; + LC_Token *dot = LC_Match(LC_TokenKind_Dot); + if (dot) { + LC_AST *field = LC_CreateAST(t, LC_ASTKind_TypespecField); + field->efield.left = n; + LC_EXPECT(ident, LC_TokenKind_Ident, "field access typespec"); + field->efield.right = ident->ident; + return field; + } + } else if (t->kind == LC_TokenKind_Mul) { + n = LC_CreateAST(t, LC_ASTKind_TypespecPointer); + LC_PROP_ERROR(n->tpointer.base, LC_ParseType()); + } else if (t->kind == LC_TokenKind_OpenBracket) { + n = LC_CreateAST(t, LC_ASTKind_TypespecArray); + if (!LC_Match(LC_TokenKind_CloseBracket)) { + LC_PROP_ERROR(n->tarray.index, LC_ParseExpr()); + LC_EXPECT(close_bracket, LC_TokenKind_CloseBracket, "array typespec"); + } + LC_PROP_ERROR(n->tarray.base, LC_ParseType()); + } else if (t->kind == LC_TokenKind_Keyword && t->ident == L->kproc) { + LC_PROP_ERROR(n, LC_ParseProcType(t)); + } else { + return LC_ReportParseError(t, "failed to parse typespec, invalid token %s", LC_TokenKindToString(t->kind)); + } + + if (L->on_typespec_parsed) L->on_typespec_parsed(n); + return n; +} + +LC_FUNCTION LC_AST *LC_ParseForStmt(LC_Token *pos) { + LC_AST *n = LC_CreateAST(pos, LC_ASTKind_StmtFor); + + if (LC_Get()->kind != LC_TokenKind_OpenBrace) { + if (!LC_Is(LC_TokenKind_Semicolon)) { + LC_PROP_ERROR(n->sfor.init, LC_ParseStmt(false)); + if (n->sfor.init->kind == LC_ASTKind_StmtExpr) { + n->sfor.cond = n->sfor.init->sexpr.expr; + n->sfor.init->kind = LC_ASTKind_Ignore; // :FreeAST + n->sfor.init = NULL; + goto skip_to_last; + } else if (n->sfor.init->kind != LC_ASTKind_StmtVar && n->sfor.init->kind != LC_ASTKind_StmtAssign) { + return LC_ReportParseError(n->sfor.init->pos, "invalid for loop syntax, expected variable intializer or assignment"); + } + } + + if (LC_Match(LC_TokenKind_Semicolon) && !LC_Is(LC_TokenKind_Semicolon)) { + LC_PROP_ERROR(n->sfor.cond, LC_ParseExpr()); + } + + skip_to_last:; + if (LC_Match(LC_TokenKind_Semicolon)) { + LC_PROP_ERROR(n->sfor.inc, LC_ParseStmt(false)); + if (n->sfor.inc->kind != LC_ASTKind_StmtAssign && n->sfor.inc->kind != LC_ASTKind_StmtExpr) { + return LC_ReportParseError(n->sfor.inc->pos, "invalid for loop syntax, expected assignment or expression"); + } + } + } + + LC_PROP_ERROR(n->sfor.body, LC_ParseStmtBlock(ParseStmtBlock_AllowSingleStmt)); + n->sfor.body->sblock.kind = SBLK_Loop; + return n; +} + +LC_FUNCTION LC_AST *LC_ParseSwitchStmt(LC_Token *pos) { + LC_AST *n = LC_CreateAST(pos, LC_ASTKind_StmtSwitch); + LC_PROP_ERROR(n->sswitch.expr, LC_ParseExpr()); + LC_EXPECT(open_brace, LC_TokenKind_OpenBrace, "switch statement"); + for (;;) { + LC_Token *pos = LC_Get(); + if (LC_MatchKeyword(L->kcase)) { + LC_AST *v = LC_CreateAST(pos, LC_ASTKind_StmtSwitchCase); + do { + LC_AST *LC_PROP_ERROR(expr, LC_ParseExpr()); + LC_DLLAdd(v->scase.first, v->scase.last, expr); + n->sswitch.total_switch_case_count += 1; + } while (LC_Match(LC_TokenKind_Comma)); + LC_EXPECT(colon, LC_TokenKind_Colon, "switch statement case"); + LC_PROP_ERROR(v->scase.body, LC_ParseStmtBlock(ParseStmtBlock_AllowSingleStmt)); + v->notes = LC_ParseNotes(); + LC_DLLAdd(n->sswitch.first, n->sswitch.last, v); + } else if (LC_MatchKeyword(L->kdefault)) { + LC_EXPECT(colon, LC_TokenKind_Colon, "switch statement default case"); + LC_AST *v = LC_CreateAST(pos, LC_ASTKind_StmtSwitchDefault); + LC_PROP_ERROR(v->scase.body, LC_ParseStmtBlock(ParseStmtBlock_AllowSingleStmt)); + LC_EXPECT(close_brace, LC_TokenKind_CloseBrace, "switch statement default case"); + v->notes = LC_ParseNotes(); + LC_DLLAdd(n->sswitch.first, n->sswitch.last, v); + break; + } else { + return LC_ReportParseError(LC_Get(), "invalid token while parsing switch statement"); + } + + if (LC_Match(LC_TokenKind_EOF)) return LC_ReportParseError(pos, "Unclosed '}' switch stmt, reached end of file"); + if (LC_Match(LC_TokenKind_CloseBrace)) break; + } + return n; +} + +LC_FUNCTION LC_AST *LC_ParseStmt(bool check_semicolon) { + LC_AST *n = 0; + LC_Token *pos = LC_Get(); + LC_Token *pos1 = LC_GetI(1); + if (LC_MatchKeyword(L->kreturn)) { + n = LC_CreateAST(pos, LC_ASTKind_StmtReturn); + if (LC_Get()->kind != LC_TokenKind_Semicolon) { + LC_PROP_ERROR(n->sreturn.expr, LC_ParseExpr()); + } + } + + else if (LC_MatchKeyword(L->kbreak)) { + n = LC_CreateAST(pos, LC_ASTKind_StmtBreak); + LC_Token *ident = LC_Match(LC_TokenKind_Ident); + if (ident) n->sbreak.name = ident->ident; + } + + else if (LC_MatchKeyword(L->kcontinue)) { + n = LC_CreateAST(pos, LC_ASTKind_StmtContinue); + LC_Token *ident = LC_Match(LC_TokenKind_Ident); + if (ident) n->scontinue.name = ident->ident; + } + + else if (LC_MatchKeyword(L->kdefer)) { + check_semicolon = false; + n = LC_CreateAST(pos, LC_ASTKind_StmtDefer); + LC_PROP_ERROR(n->sdefer.body, LC_ParseStmtBlock(ParseStmtBlock_AllowSingleStmt)); + n->sdefer.body->sblock.kind = SBLK_Defer; + } + + else if (LC_MatchKeyword(L->kfor)) { + LC_PROP_ERROR(n, LC_ParseForStmt(pos)); + check_semicolon = false; + } + + else if (LC_MatchKeyword(L->kswitch)) { + LC_PROP_ERROR(n, LC_ParseSwitchStmt(pos)); + check_semicolon = false; + } + + else if (LC_MatchKeyword(L->kif)) { + n = LC_CreateAST(pos, LC_ASTKind_StmtIf); + LC_PROP_ERROR(n->sif.expr, LC_ParseExpr()); + LC_PROP_ERROR(n->sif.body, LC_ParseStmtBlock(ParseStmtBlock_AllowSingleStmt)); + for (;;) { + if (!LC_MatchKeyword(L->kelse)) break; + + LC_AST *v = LC_CreateAST(LC_GetI(-1), LC_ASTKind_StmtElse); + if (LC_MatchKeyword(L->kif)) { + v->kind = LC_ASTKind_StmtElseIf; + LC_PROP_ERROR(v->sif.expr, LC_ParseExpr()); + } + LC_PROP_ERROR(v->sif.body, LC_ParseStmtBlock(ParseStmtBlock_AllowSingleStmt)); + LC_DLLAdd(n->sif.first, n->sif.last, v); + } + check_semicolon = false; + } + + else if (LC_Match(LC_TokenKind_Hash)) { // #c(``); + n = LC_CreateAST(LC_Get(), LC_ASTKind_StmtNote); + LC_PROP_ERROR(n->snote.expr, LC_ParseNote()); + } else if (pos->kind == LC_TokenKind_OpenBrace) { // { block } + n = LC_ParseStmtBlock(0); + check_semicolon = false; + } + + else if (pos->kind == LC_TokenKind_Ident && pos1->kind == LC_TokenKind_Colon) { // Name: ... + LC_Next(); + LC_Next(); + + if (LC_MatchKeyword(L->kfor)) { + LC_PROP_ERROR(n, LC_ParseForStmt(LC_GetI(-1))); + n->sfor.body->sblock.name = pos->ident; + check_semicolon = false; + } else { + n = LC_CreateAST(pos, LC_ASTKind_StmtVar); + LC_Intern name = pos->ident; + if (LC_Match(LC_TokenKind_Assign)) { + LC_PROP_ERROR(n->svar.expr, LC_ParseExpr()); + n->svar.name = name; + } else if (LC_Match(LC_TokenKind_Colon)) { + n->kind = LC_ASTKind_StmtConst; + LC_PROP_ERROR(n->sconst.expr, LC_ParseExpr()); + n->sconst.name = name; + } else { + n->svar.name = name; + LC_PROP_ERROR(n->svar.type, LC_ParseType()); + if (LC_Match(LC_TokenKind_Assign)) { + if (LC_Match(LC_TokenKind_Hash)) { + LC_AST *note = LC_CreateAST(LC_Get(), LC_ASTKind_ExprNote); + LC_PROP_ERROR(note->enote.expr, LC_ParseNote()); + n->svar.expr = note; + } else { + LC_PROP_ERROR(n->svar.expr, LC_ParseExpr()); + } + } + } + } + } else { + n = LC_CreateAST(pos, LC_ASTKind_StmtExpr); + LC_PROP_ERROR(n->sexpr.expr, LC_ParseExpr()); + + LC_Token *t = LC_Get(); + if (LC_IsAssign(t->kind)) { + LC_Next(); + LC_AST *left = n->sexpr.expr; + + n->kind = LC_ASTKind_StmtAssign; + LC_PROP_ERROR(n->sassign.right, LC_ParseExpr()); + n->sassign.left = left; + n->sassign.op = t->kind; + } + } + + if (check_semicolon) { + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "statement lacks a semicolon at the end"); + } + + n->notes = LC_ParseNotes(); + return n; +} + +LC_FUNCTION LC_AST *LC_ParseStmtBlock(int flags) { + LC_AST *n = LC_CreateAST(LC_Get(), LC_ASTKind_StmtBlock); + + bool single_stmt = false; + if (flags & ParseStmtBlock_AllowSingleStmt) { + if (!LC_Is(LC_TokenKind_OpenBrace)) { + LC_AST *LC_PROP_ERROR(v, LC_ParseStmt(true)); + LC_DLLAdd(n->sblock.first, n->sblock.last, v); + single_stmt = true; + } + } + + if (!single_stmt) { + LC_EXPECT(open_brace, LC_TokenKind_OpenBrace, "statement block"); + if (!LC_Match(LC_TokenKind_CloseBrace)) { + for (;;) { + LC_AST *v = LC_ParseStmt(true); + + // Eat until next statement in case of error + if (v->kind == LC_ASTKind_Error) { + for (;;) { + if (LC_Is(LC_TokenKind_EOF) || LC_Is(LC_TokenKind_OpenBrace) || LC_Match(LC_TokenKind_CloseBrace)) return v; + if (LC_Match(LC_TokenKind_Semicolon)) break; + LC_Next(); + } + } + + if (L->on_stmt_parsed) L->on_stmt_parsed(v); + LC_DLLAdd(n->sblock.first, n->sblock.last, v); + if (LC_Match(LC_TokenKind_EOF)) return LC_ReportParseError(open_brace, "Unclosed '}' stmt list, reached end of file"); + if (LC_Match(LC_TokenKind_CloseBrace)) break; + } + } + } + + if (L->on_stmt_parsed) L->on_stmt_parsed(n); + return n; +} + +LC_FUNCTION LC_AST *LC_ParseProcDecl(LC_Token *name) { + LC_AST *n = LC_CreateAST(name, LC_ASTKind_DeclProc); + n->dbase.name = name->ident; + LC_PROP_ERROR(n->dproc.type, LC_ParseProcType(name)); + + LC_Token *ob = LC_Get(); + if (ob->kind == LC_TokenKind_OpenBrace) { + // Here I added additional error handling which slows down compilation a bit. + // We can for sure deduce where procs end and where they begin because of the syntaxes + // nature - so to avoid any error spills from one procedure to another and I + // seek for the last brace of procedure and set 'end' on parser to 1 after that token. + LC_Token *cb = ob; + LC_Token *last_open_brace = ob; + int pair_counter = 0; + + // Seek for the last '}' close brace of procedure + for (;;) { + LC_Token *d = LC_GetI(3); + if (LC_GetI(0)->kind == LC_TokenKind_Ident && LC_GetI(1)->kind == LC_TokenKind_Colon && LC_GetI(2)->kind == LC_TokenKind_Colon && d->kind == LC_TokenKind_Keyword) { + if (d->ident == L->kproc || d->ident == L->kstruct || d->ident == L->kunion || d->ident == L->ktypedef) { + break; + } + } + + LC_Token *token = LC_Next(); + if (token == &L->NullToken) break; + if (token->kind == LC_TokenKind_OpenBrace) pair_counter += 1; + if (token->kind == LC_TokenKind_OpenBrace) last_open_brace = token; + if (token->kind == LC_TokenKind_CloseBrace) pair_counter -= 1; + if (token->kind == LC_TokenKind_CloseBrace) cb = token; + } + if (pair_counter != 0) return LC_ReportParseError(last_open_brace, "unclosed open brace '{' inside this procedure"); + L->parser->at = ob; + + // Set the parsing boundary to one after the last close brace + LC_Token *save_end = L->parser->end; + L->parser->end = cb + 1; + n->dproc.body = LC_ParseStmtBlock(0); + L->parser->end = save_end; + if (n->dproc.body->kind == LC_ASTKind_Error) return n->dproc.body; + + n->dproc.body->sblock.kind = SBLK_Proc; + } else { + LC_EXPECT(semicolon, LC_TokenKind_Semicolon, "procedure declaration"); + } + + return n; +} + +LC_FUNCTION LC_AST *LC_ParseStruct(LC_ASTKind kind, LC_Token *ident) { + LC_AST *n = LC_CreateAST(ident, kind); + n->dbase.name = ident->ident; + LC_EXPECT(open_brace, LC_TokenKind_OpenBrace, "struct declaration"); + for (;;) { + LC_AST *v = LC_CreateAST(ident, LC_ASTKind_TypespecAggMem); + LC_EXPECT(ident, LC_TokenKind_Ident, "struct member"); + v->tagg_mem.name = ident->ident; + LC_EXPECT(colon, LC_TokenKind_Colon, "struct member"); + LC_PROP_ERROR(v->tagg_mem.type, LC_ParseType()); + LC_EXPECT(semicolon, LC_TokenKind_Semicolon, "struct member"); + + v->notes = LC_ParseNotes(); + LC_DLLAdd(n->dagg.first, n->dagg.last, v); + if (LC_Match(LC_TokenKind_EOF)) return LC_ReportParseError(ident, "Unclosed '}' struct, reached end of file"); + if (LC_Match(LC_TokenKind_CloseBrace)) break; + } + + return n; +} + +LC_FUNCTION LC_AST *LC_ParseTypedef(LC_Token *ident) { + LC_AST *n = LC_CreateAST(ident, LC_ASTKind_DeclTypedef); + n->dbase.name = ident->ident; + LC_PROP_ERROR(n->dtypedef.type, LC_ParseType()); + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "expected semicolon ';' after typedef declaration, got instead %s", LC_TokenKindToString(LC_GetI(-1)->kind)); + return n; +} + +LC_FUNCTION LC_AST *LC_CreateNote(LC_Token *pos, LC_Intern ident) { + LC_AST *n = LC_CreateAST(pos, LC_ASTKind_Note); + + LC_AST *astident = LC_CreateAST(pos, LC_ASTKind_ExprIdent); + astident->eident.name = ident; + n->ecompo.name = astident; + + return n; +} + +LC_FUNCTION LC_AST *LC_ParseNote(void) { + LC_AST *n = NULL; + + // syntactic sugar + // #`stuff` => #c(`stuff`) + LC_Token *str_token = LC_Match(LC_TokenKind_RawString); + if (str_token) { + n = LC_CreateNote(str_token, L->ic); + + // Add CallItem + { + LC_AST *astcallitem = LC_CreateAST(str_token, LC_ASTKind_ExprCallItem); + astcallitem->ecompo_item.expr = LC_CreateAST(str_token, LC_ASTKind_ExprString); + astcallitem->ecompo_item.expr->eatom.name = str_token->ident; + LC_DLLAdd(n->ecompo.first, n->ecompo.last, astcallitem); + } + } else { + + LC_EXPECT(ident, LC_TokenKind_Ident, "note"); + if (!LC_IsNoteDeclared(ident->ident)) { + LC_ReportParseError(ident, "unregistered note name: '%s'", ident->ident); + } + + LC_AST *astident = LC_CreateAST(ident, LC_ASTKind_ExprIdent); + astident->eident.name = ident->ident; + + LC_Token *open_paren = LC_Match(LC_TokenKind_OpenParen); + if (open_paren) { + n = LC_ParseCompo(open_paren, astident); + } else { + n = LC_CreateAST(ident, LC_ASTKind_Note); + } + n->ecompo.name = astident; + n->kind = LC_ASTKind_Note; + } + return n; +} + +LC_FUNCTION LC_AST *LC_ParseNotes(void) { + LC_Token *pos = LC_Get(); + LC_AST *first = 0; + LC_AST *last = 0; + for (;;) { + LC_Token *t = LC_Match(LC_TokenKind_Note); + if (!t) break; + LC_AST *n = LC_ParseNote(); + if (n->kind == LC_ASTKind_Error) continue; + LC_DLLAdd(first, last, n); + } + + if (first) { + LC_AST *n = LC_CreateAST(pos, LC_ASTKind_NoteList); + n->anote_list.first = first; + n->anote_list.last = last; + return n; + } + return 0; +} + +LC_FUNCTION bool LC_ResolveBuildIf(LC_AST *build_if) { + LC_ExprCompo *note = &build_if->anote; + if (note->size != 1) { + LC_ReportParseError(LC_GetI(-1), "invalid argument count for #build_if directive, expected 1, got %d", note->size); + return true; + } + + LC_ExprCompoItem *item = ¬e->first->ecompo_item; + if (item->index != NULL || item->name != 0) { + LC_ReportParseError(LC_GetI(-1), "invalid syntax, #build_if shouldn't have a named or indexed first argument"); + return true; + } + + LC_PUSH_PACKAGE(L->builtin_package); + LC_Operand op = LC_ResolveExpr(item->expr); + LC_POP_PACKAGE(); + if (!LC_IsUTConst(op)) { + LC_ReportParseError(LC_GetI(-1), "expected #build_if to have an untyped constant expcession"); + return true; + } + if (!LC_IsUTInt(op.type)) { + LC_ReportParseError(LC_GetI(-1), "expected #build_if to have expression of type untyped int"); + return true; + } + + int64_t result = LC_Bigint_as_signed(&op.v.i); + return (bool)result; +} + +LC_FUNCTION LC_AST *LC_ParseDecl(LC_AST *file) { + LC_AST *n = 0; + LC_Token *doc_comment = LC_Match(LC_TokenKind_DocComment); + LC_Token *ident = LC_Get(); + + if (LC_Match(LC_TokenKind_Ident)) { + if (LC_Match(LC_TokenKind_Colon)) { + if (LC_Match(LC_TokenKind_Colon)) { + if (LC_MatchKeyword(L->kproc)) { + LC_PROP_ERROR(n, LC_ParseProcDecl(ident)); + } else if (LC_MatchKeyword(L->kstruct)) { + LC_PROP_ERROR(n, LC_ParseStruct(LC_ASTKind_DeclStruct, ident)); + } else if (LC_MatchKeyword(L->kunion)) { + LC_PROP_ERROR(n, LC_ParseStruct(LC_ASTKind_DeclUnion, ident)); + } else if (LC_MatchKeyword(L->ktypedef)) { + LC_PROP_ERROR(n, LC_ParseTypedef(ident)); + } else { + n = LC_CreateAST(ident, LC_ASTKind_DeclConst); + n->dbase.name = ident->ident; + if (LC_Match(LC_TokenKind_BitXor)) { + LC_AST *last_decl = file->afile.ldecl; + if (!last_decl || last_decl->kind != LC_ASTKind_DeclConst) return LC_ReportParseError(LC_GetI(-1), "invalid usage, there is no constant declaration preceding '^', this operator implies - PREV_CONST + 1"); + LC_AST *left = LC_CreateAST(n->pos, LC_ASTKind_ExprIdent); + left->eident.name = last_decl->dbase.name; + LC_AST *right = LC_CreateAST(n->pos, LC_ASTKind_ExprInt); + right->eatom.i = LC_Bigint_u64(1); + + n->dconst.expr = LC_CreateBinary(n->pos, left, right, LC_TokenKind_Add); + } else if (LC_Match(LC_TokenKind_LeftShift)) { + LC_AST *last_decl = file->afile.ldecl; + if (!last_decl || last_decl->kind != LC_ASTKind_DeclConst) return LC_ReportParseError(LC_GetI(-1), "invalid usage, there is no constant declaration preceding '^', this operator implies - PREV_CONST << 1"); + LC_AST *left = LC_CreateAST(n->pos, LC_ASTKind_ExprIdent); + left->eident.name = last_decl->dbase.name; + LC_AST *right = LC_CreateAST(n->pos, LC_ASTKind_ExprInt); + right->eatom.i = LC_Bigint_u64(1); + + n->dconst.expr = LC_CreateBinary(n->pos, left, right, LC_TokenKind_LeftShift); + } else { + LC_PROP_ERROR(n->dconst.expr, LC_ParseExpr()); + } + + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "expected ';' semicolon"); + } + } else if (LC_Match(LC_TokenKind_Assign)) { + n = LC_CreateAST(ident, LC_ASTKind_DeclVar); + LC_PROP_ERROR(n->dvar.expr, LC_ParseExpr()); + n->dbase.name = ident->ident; + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "expected ';' semicolon"); + } else { + n = LC_CreateAST(ident, LC_ASTKind_DeclVar); + n->dbase.name = ident->ident; + + LC_PROP_ERROR(n->dvar.type, LC_ParseType()); + if (LC_Match(LC_TokenKind_Assign)) { + if (LC_Match(LC_TokenKind_Hash)) { + LC_AST *note = LC_CreateAST(LC_Get(), LC_ASTKind_ExprNote); + LC_PROP_ERROR(note->enote.expr, LC_ParseNote()); + n->dvar.expr = note; + } else { + LC_PROP_ERROR(n->dvar.expr, LC_ParseExpr()); + } + } + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "expected ';' semicolon"); + } + } else return LC_ReportParseError(ident, "got unexpected token: %s, while parsing declaration", LC_TokenKindToString(ident->kind)); + } else if (LC_Match(LC_TokenKind_Hash)) { + n = LC_CreateAST(ident, LC_ASTKind_DeclNote); + LC_PROP_ERROR(n->dnote.expr, LC_ParseNote()); + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "expected ';' semicolon"); + } else if (LC_MatchKeyword(L->kimport)) { + return LC_ReportParseError(LC_Get(), "imports can only appear at the top level"); + } else if (ident->kind == LC_TokenKind_EOF) return NULL; + else return LC_ReportParseError(ident, "got unexpected token: %s, while parsing declaration", LC_TokenKindToString(ident->kind)); + + LC_AST *notes = LC_ParseNotes(); + if (n) { + n->notes = notes; + n->dbase.doc_comment = doc_comment; + } + return n; +} + +LC_FUNCTION bool LC_EatUntilNextValidDecl(void) { + for (;;) { + LC_Token *a = LC_GetI(0); + if (a->kind == LC_TokenKind_Keyword && a->ident == L->kimport) { + return true; + } + + LC_Token *d = LC_GetI(3); + if (a->kind == LC_TokenKind_Ident && LC_GetI(1)->kind == LC_TokenKind_Colon && LC_GetI(2)->kind == LC_TokenKind_Colon && d->kind == LC_TokenKind_Keyword) { + if (d->ident == L->kproc || d->ident == L->kstruct || d->ident == L->kunion || d->ident == L->ktypedef) { + return false; + } + } + + LC_Token *token = LC_Next(); + if (token == &L->NullToken) { + return false; + } + } +} + +LC_FUNCTION bool LC_ParseHashBuildOn(LC_AST *n) { + LC_Token *t0 = LC_GetI(0); + LC_Token *t1 = LC_GetI(1); + if (t0->kind == LC_TokenKind_Hash && t1->kind == LC_TokenKind_Ident && t1->ident == L->ibuild_if) { + LC_Next(); + + LC_AST *build_if = LC_CreateAST(t1, LC_ASTKind_DeclNote); + build_if->dnote.expr = LC_ParseNote(); + if (build_if->dnote.expr->kind == LC_ASTKind_Error) { + LC_EatUntilNextValidDecl(); + return true; + } + + if (!LC_Match(LC_TokenKind_Semicolon)) { + LC_ReportParseError(LC_GetI(-1), "expected ';' semicolon"); + LC_EatUntilNextValidDecl(); + return true; + } + + LC_AST *note_list = LC_CreateAST(t0, LC_ASTKind_NoteList); + LC_DLLAdd(note_list->anote_list.first, note_list->anote_list.last, build_if); + n->notes = note_list; + + return LC_ResolveBuildIf(build_if->dnote.expr); + } + return true; +} + +LC_FUNCTION LC_AST *LC_ParseImport(void) { + LC_AST *n = NULL; + LC_Token *import = LC_MatchKeyword(L->kimport); + if (import) { + n = LC_CreateAST(import, LC_ASTKind_GlobImport); + + LC_Token *ident = LC_Match(LC_TokenKind_Ident); + if (ident) n->gimport.name = ident->ident; + + LC_Token *path = LC_Match(LC_TokenKind_String); + if (!path) return LC_ReportParseError(LC_GetI(-1), "expected string after an import, instead got %s", LC_TokenKindToString(LC_Get()->kind)); + + n->gimport.path = path->ident; + if (!LC_Match(LC_TokenKind_Semicolon)) return LC_ReportParseError(LC_GetI(-1), "expected ';' semicolon"); + } + return n; +} + +LC_FUNCTION void LC_AddFileToPackage(LC_AST *pkg, LC_AST *f) { + f->afile.package = pkg; + LC_DLLAdd(pkg->apackage.ffile, pkg->apackage.lfile, f); +} + +LC_FUNCTION LC_AST *LC_ParseFileEx(LC_AST *package) { + LC_Token *package_doc_comment = LC_Match(LC_TokenKind_PackageDocComment); + + LC_AST *n = LC_CreateAST(LC_Get(), LC_ASTKind_File); + n->afile.x = L->parser->x; + n->afile.doc_comment = LC_Match(LC_TokenKind_FileDocComment); + n->afile.build_if = LC_ParseHashBuildOn(n); + + // Parse imports + while (!LC_Is(LC_TokenKind_EOF)) { + LC_AST *import = LC_ParseImport(); + if (!import) break; + + if (import->kind == LC_ASTKind_Error) { + bool is_import = LC_EatUntilNextValidDecl(); + if (!is_import) break; + } else { + LC_DLLAdd(n->afile.fimport, n->afile.limport, import); + } + } + + // Parse top level decls + while (!LC_Is(LC_TokenKind_EOF)) { + LC_AST *decl = LC_ParseDecl(n); + if (!decl) continue; + + if (decl->kind == LC_ASTKind_Error) { + LC_EatUntilNextValidDecl(); + } else { + bool skip = false; + + LC_AST *build_if = LC_HasNote(decl, L->ibuild_if); + if (build_if) { + skip = !LC_ResolveBuildIf(build_if); + } + + if (L->on_decl_parsed) { + skip = L->on_decl_parsed(skip, decl); + } + + if (skip) { + LC_DLLAdd(n->afile.fdiscarded, n->afile.ldiscarded, decl); + } else { + LC_DLLAdd(n->afile.fdecl, n->afile.ldecl, decl); + } + } + } + + if (package) { + if (package->apackage.doc_comment) LC_ReportParseError(package_doc_comment, "there are more then 1 package doc comments in %s package", (char *)package->apackage.name); + package->apackage.doc_comment = package_doc_comment; + + if (n->afile.build_if) { + LC_AddFileToPackage(package, n); + } else { + LC_DLLAdd(package->apackage.fdiscarded, package->apackage.ldiscarded, n); + n->afile.package = package; + } + } + + return n; +} + +LC_FUNCTION LC_AST *LC_ParseTokens(LC_AST *package, LC_Lex *x) { + LC_Parser p = LC_MakeParser(x); + L->parser = &p; + LC_AST *file = LC_ParseFileEx(package); + return L->errors ? NULL : file; +} + +LC_FUNCTION LC_AST *LC_ParseFile(LC_AST *package, char *filename, char *content, int line) { + if (content == NULL) { + LC_SendErrorMessagef(NULL, NULL, "internal compiler error: file passed to %s is null", __FUNCTION__); + return NULL; + } + if (filename == NULL) { + LC_SendErrorMessagef(NULL, NULL, "internal compiler error: filename passed to %s is null", __FUNCTION__); + return NULL; + } + + LC_Lex *x = LC_LexStream(filename, content, line); + if (L->errors) return NULL; + LC_InternTokens(x); + + LC_AST *file = LC_ParseTokens(package, x); + if (!file) return NULL; + return file; +} + +LC_FUNCTION LC_AST *LC_ParseStmtf(const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + LC_Parser *old = L->parser; + LC_Parser *p = LC_MakeParserQuick(s8.str); + LC_AST *result = LC_ParseStmt(false); + L->parser = old; + return result; +} + +LC_FUNCTION LC_AST *LC_ParseExprf(const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + LC_Parser *old = L->parser; + LC_Parser *p = LC_MakeParserQuick(s8.str); + LC_AST *result = LC_ParseExpr(); + L->parser = old; + return result; +} + +LC_FUNCTION LC_AST *LC_ParseDeclf(const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + LC_Parser *old = L->parser; + LC_Parser *p = LC_MakeParserQuick(s8.str); + LC_AST *result = LC_ParseDecl(&L->NullAST); + L->parser = old; + return result; +} + +#undef LC_EXPECT +#undef LC_PROP_ERROR \ No newline at end of file diff --git a/src/compiler/printer.c b/src/compiler/printer.c new file mode 100644 index 0000000..457d23c --- /dev/null +++ b/src/compiler/printer.c @@ -0,0 +1,477 @@ +LC_FUNCTION LC_StringList *LC_BeginStringGen(LC_Arena *arena) { + L->printer.list = LC_MakeEmptyList(); + L->printer.arena = arena; + L->printer.last_filename = 0; + L->printer.last_line_num = 0; + L->printer.indent = 0; + return &L->printer.list; +} + +LC_FUNCTION LC_String LC_EndStringGen(LC_Arena *arena) { + LC_String result = LC_MergeString(arena, L->printer.list); + return result; +} + +LC_FUNCTION void LC_GenIndent(void) { + LC_String s = LC_Lit(" "); + for (int i = 0; i < L->printer.indent; i++) { + LC_AddNode(L->printer.arena, &L->printer.list, s); + } +} + +LC_FUNCTION char *LC_Strf(const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + return s8.str; +} + +LC_FUNCTION void LC_GenLine(void) { + LC_Genf("\n"); + LC_GenIndent(); +} + +LC_FUNCTION char *LC_GenLCType(LC_Type *type) { + LC_StringList out = {0}; + for (LC_Type *it = type; it;) { + if (it->kind == LC_TypeKind_Pointer) { + LC_Addf(L->arena, &out, "*"); + it = it->tptr.base; + } else if (it->kind == LC_TypeKind_Array) { + LC_Addf(L->arena, &out, "[%d]", it->tarray.size); + it = it->tarray.base; + } else if (it->kind == LC_TypeKind_Proc) { + LC_Addf(L->arena, &out, "proc("); + LC_TypeFor(mem, it->tproc.args.first) { + LC_Addf(L->arena, &out, "%s: %s", (char *)mem->name, LC_GenLCType(mem->type)); + if (mem->default_value_expr) LC_Addf(L->arena, &out, "/*has default value*/"); + if (mem->next) LC_Addf(L->arena, &out, ", "); + } + if (it->tproc.vargs) LC_Addf(L->arena, &out, ".."); + LC_Addf(L->arena, &out, ")"); + if (it->tproc.ret->kind != LC_TypeKind_void) LC_Addf(L->arena, &out, ": %s", LC_GenLCType(it->tproc.ret)); + break; + } else if (it->decl) { + LC_Decl *decl = it->decl; + LC_ASSERT(decl->ast, decl); + LC_Addf(L->arena, &out, "%s", (char *)decl->name); + break; + } else { + LC_SendErrorMessagef(NULL, NULL, "internal compiler error: unhandled type kind in %s", __FUNCTION__); + } + } + LC_String s = LC_MergeString(L->arena, out); + return s.str; +} + +LC_FUNCTION char *LC_GenLCTypeVal(LC_TypeAndVal v) { + if (LC_IsInt(v.type) || LC_IsPtr(v.type) || LC_IsProc(v.type)) { + return LC_Bigint_str(&v.i, 10); + } + if (LC_IsFloat(v.type)) { + LC_String s = LC_Format(L->arena, "%f", v.d); + return s.str; + } + LC_ASSERT(NULL, !"invalid codepath"); + return ""; +} + +LC_FUNCTION char *LC_GenLCAggName(LC_Type *t) { + if (t->kind == LC_TypeKind_Struct) return "struct"; + if (t->kind == LC_TypeKind_Union) return "union"; + return NULL; +} + +LC_FUNCTION void LC_GenLCNode(LC_AST *n) { + switch (n->kind) { + case LC_ASTKind_Package: { + LC_ASTFor(it, n->apackage.ffile) { + LC_GenLCNode(it); + } + } break; + + case LC_ASTKind_File: { + LC_ASTFor(it, n->afile.fimport) { + LC_GenLCNode(it); + } + + LC_ASTFor(it, n->afile.fdecl) { + LC_GenLCNode(it); + } + // @todo: we need to do something with notes so we can generate them in order! + + } break; + + case LC_ASTKind_GlobImport: { + LC_GenLinef("import %s \"%s\";", (char *)n->gimport.name, (char *)n->gimport.path); + } break; + + case LC_ASTKind_DeclProc: { + LC_GenLinef("%s :: ", (char *)n->dbase.name); + LC_GenLCNode(n->dproc.type); + if (n->dproc.body) { + LC_Genf(" "); + LC_GenLCNode(n->dproc.body); + } else { + LC_Genf(";"); + } + } break; + + case LC_ASTKind_DeclUnion: + case LC_ASTKind_DeclStruct: { + const char *agg = n->kind == LC_ASTKind_DeclUnion ? "union" : "struct"; + LC_GenLinef("%s :: %s {", (char *)n->dbase.name, agg); + L->printer.indent += 1; + LC_ASTFor(it, n->dagg.first) { + LC_GenLine(); + LC_GenLCNode(it); + LC_Genf(";"); + } + L->printer.indent -= 1; + LC_GenLinef("}"); + } break; + + case LC_ASTKind_TypespecAggMem: { + LC_Genf("%s: ", (char *)n->tagg_mem.name); + LC_GenLCNode(n->tagg_mem.type); + } break; + + case LC_ASTKind_DeclVar: { + LC_GenLinef("%s ", (char *)n->dbase.name); + if (n->dvar.type) { + LC_Genf(": "); + LC_GenLCNode(n->dvar.type); + if (n->dvar.expr) { + LC_Genf("= "); + LC_GenLCNode(n->dvar.expr); + } + } else { + LC_Genf(":= "); + LC_GenLCNode(n->dvar.expr); + } + LC_Genf(";"); + } break; + + case LC_ASTKind_DeclConst: { + LC_GenLinef("%s :: ", (char *)n->dbase.name); + LC_GenLCNode(n->dconst.expr); + LC_Genf(";"); + } break; + + case LC_ASTKind_DeclTypedef: { + LC_GenLinef("%s :: typedef ", (char *)n->dbase.name); + LC_GenLCNode(n->dtypedef.type); + LC_Genf(";"); + } break; + + case LC_ASTKind_ExprIdent: + case LC_ASTKind_TypespecIdent: { + LC_Genf("%s", (char *)n->eident.name); + } break; + + case LC_ASTKind_ExprField: + case LC_ASTKind_TypespecField: { + LC_GenLCNode(n->efield.left); + LC_Genf(".%s", (char *)n->efield.right); + } break; + + case LC_ASTKind_TypespecPointer: { + LC_Genf("*"); + LC_GenLCNode(n->tpointer.base); + } break; + + case LC_ASTKind_TypespecArray: { + LC_Genf("["); + if (n->tarray.index) LC_GenLCNode(n->tarray.index); + LC_Genf("]"); + LC_GenLCNode(n->tpointer.base); + } break; + + case LC_ASTKind_TypespecProc: { + LC_Genf("proc("); + LC_ASTFor(it, n->tproc.first) { + LC_GenLCNode(it); + if (it != n->tproc.last) LC_Genf(", "); + } + if (n->tproc.vargs) { + LC_Genf(", ..."); + if (n->tproc.vargs_any_promotion) LC_Genf("Any"); + } + LC_Genf(")"); + if (n->tproc.ret) { + LC_Genf(": "); + LC_GenLCNode(n->tproc.ret); + } + } break; + + case LC_ASTKind_TypespecProcArg: { + LC_Genf("%s: ", (char *)n->tproc_arg.name); + LC_GenLCNode(n->tproc_arg.type); + if (n->tproc_arg.expr) { + LC_Genf(" = "); + LC_GenLCNode(n->tproc_arg.expr); + } + } break; + + case LC_ASTKind_StmtBlock: { + if (n->sblock.name && n->sblock.kind != SBLK_Loop) LC_Genf("%s: ", (char *)n->sblock.name); + LC_Genf("{"); + L->printer.indent += 1; + LC_ASTFor(it, n->sblock.first) { + LC_GenLine(); + LC_GenLCNode(it); + if (it->kind != LC_ASTKind_StmtBlock && it->kind != LC_ASTKind_StmtDefer && it->kind != LC_ASTKind_StmtFor && it->kind != LC_ASTKind_StmtIf && it->kind != LC_ASTKind_StmtSwitch) LC_Genf(";"); + } + L->printer.indent -= 1; + LC_GenLinef("}"); + } break; + + case LC_ASTKind_StmtReturn: { + LC_Genf("return"); + if (n->sreturn.expr) { + LC_Genf(" "); + LC_GenLCNode(n->sreturn.expr); + } + } break; + + case LC_ASTKind_StmtBreak: { + LC_Genf("break"); + if (n->sbreak.name) LC_Genf(" %s", (char *)n->sbreak.name); + } break; + + case LC_ASTKind_StmtContinue: { + LC_Genf("continue"); + if (n->scontinue.name) LC_Genf(" %s", (char *)n->scontinue.name); + } break; + + case LC_ASTKind_StmtDefer: { + LC_Genf("defer "); + LC_GenLCNode(n->sdefer.body); + } break; + + case LC_ASTKind_StmtFor: { + LC_StmtBlock *sblock = &n->sfor.body->sblock; + if (sblock->name && sblock->kind == SBLK_Loop) { + LC_Genf("%s: ", (char *)sblock->name); + } + + LC_Genf("for "); + if (n->sfor.init) { + LC_GenLCNode(n->sfor.init); + if (n->sfor.cond) LC_Genf("; "); + } + + if (n->sfor.cond) { + LC_GenLCNode(n->sfor.cond); + if (n->sfor.inc) { + LC_Genf("; "); + LC_GenLCNode(n->sfor.inc); + } + } + + LC_Genf(" "); + LC_GenLCNode(n->sfor.body); + } break; + + case LC_ASTKind_StmtElseIf: + LC_Genf("else "); + case LC_ASTKind_StmtIf: { + LC_Genf("if "); + LC_GenLCNode(n->sif.expr); + LC_GenLCNode(n->sif.body); + LC_ASTFor(it, n->sif.first) { + LC_GenLCNode(it); + } + } break; + + case LC_ASTKind_StmtElse: { + LC_Genf("else "); + LC_GenLCNode(n->sif.body); + } break; + + case LC_ASTKind_StmtSwitch: { + LC_Genf("switch "); + LC_GenLCNode(n->sswitch.expr); + LC_Genf("{"); + L->printer.indent += 1; + LC_ASTFor(it, n->sswitch.first) { + LC_GenLine(); + LC_GenLCNode(it); + } + L->printer.indent -= 1; + LC_Genf("}"); + } break; + + case LC_ASTKind_StmtSwitchCase: { + LC_Genf("case "); + LC_ASTFor(it, n->scase.first) { + LC_GenLCNode(it); + if (it != n->scase.last) LC_Genf(", "); + } + LC_Genf(": "); + LC_GenLCNode(n->scase.body); + } break; + case LC_ASTKind_StmtSwitchDefault: { + LC_Genf("default: "); + LC_GenLCNode(n->scase.body); + } break; + + case LC_ASTKind_StmtAssign: { + LC_GenLCNode(n->sassign.left); + LC_Genf(" %s ", LC_TokenKindToOperator(n->sassign.op)); + LC_GenLCNode(n->sassign.right); + } break; + + case LC_ASTKind_StmtExpr: { + LC_GenLCNode(n->sexpr.expr); + } break; + + case LC_ASTKind_StmtVar: { + LC_Genf("%s", (char *)n->svar.name); + if (n->svar.type) { + LC_Genf(": "); + LC_GenLCNode(n->svar.type); + if (n->svar.expr) { + LC_Genf(" = "); + LC_GenLCNode(n->svar.expr); + } + } else { + LC_Genf(" := "); + LC_GenLCNode(n->svar.expr); + } + } break; + + case LC_ASTKind_StmtConst: { + LC_GenLinef("%s :: ", (char *)n->sconst.name); + LC_GenLCNode(n->sconst.expr); + } break; + + case LC_ASTKind_ExprString: { + LC_Genf("`%s`", (char *)n->eatom.name); + } break; + + case LC_ASTKind_ExprInt: { + LC_Genf("%s", LC_Bigint_str(&n->eatom.i, 10)); + } break; + + case LC_ASTKind_ExprFloat: { + LC_Genf("%f", n->eatom.d); + } break; + + case LC_ASTKind_ExprBool: { + int64_t value = LC_Bigint_as_unsigned(&n->eatom.i); + if (value) { + LC_Genf("true"); + } else { + LC_Genf("false"); + } + } break; + + case LC_ASTKind_ExprType: { + LC_Genf(":"); + LC_GenLCNode(n->etype.type); + } break; + + case LC_ASTKind_ExprBinary: { + LC_Genf("("); + LC_GenLCNode(n->ebinary.left); + LC_Genf("%s", LC_TokenKindToOperator(n->ebinary.op)); + LC_GenLCNode(n->ebinary.right); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprUnary: { + LC_Genf("%s(", LC_TokenKindToOperator(n->eunary.op)); + LC_GenLCNode(n->eunary.expr); + LC_Genf(")"); + } break; + + case LC_ASTKind_StmtNote: { + LC_Genf("#"); + LC_GenLCNode(n->snote.expr); + } break; + + case LC_ASTKind_ExprNote: { + LC_Genf("#"); + LC_GenLCNode(n->enote.expr); + } break; + + case LC_ASTKind_DeclNote: { + LC_GenLinef("#"); + LC_GenLCNode(n->dnote.expr); + LC_Genf(";"); + } break; + + case LC_ASTKind_Note: + case LC_ASTKind_ExprBuiltin: + case LC_ASTKind_ExprCall: { + LC_GenLCNode(n->ecompo.name); + LC_Genf("("); + LC_ASTFor(it, n->ecompo.first) { + LC_GenLCNode(it); + if (it != n->ecompo.last) LC_Genf(", "); + } + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprCompoundItem: + case LC_ASTKind_ExprCallItem: { + if (n->ecompo_item.name) { + LC_Genf("%s = ", (char *)n->ecompo_item.name); + } + if (n->ecompo_item.index) { + LC_Genf("["); + LC_GenLCNode(n->ecompo_item.index); + LC_Genf("] = "); + } + LC_GenLCNode(n->ecompo_item.expr); + } break; + + case LC_ASTKind_ExprCompound: { + if (n->ecompo.name) LC_GenLCNode(n->ecompo.name); + LC_Genf("{"); + LC_ASTFor(it, n->ecompo.first) { + LC_GenLCNode(it); + if (it != n->ecompo.last) LC_Genf(", "); + } + LC_Genf("}"); + } break; + + case LC_ASTKind_ExprCast: { + LC_Genf(":"); + LC_GenLCNode(n->ecast.type); + LC_Genf("("); + LC_GenLCNode(n->ecast.expr); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprIndex: { + LC_Genf("("); + LC_GenLCNode(n->eindex.base); + LC_Genf("["); + LC_GenLCNode(n->eindex.index); + LC_Genf("]"); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprAddPtr: { + LC_Genf("addptr("); + LC_GenLCNode(n->ebinary.left); + LC_Genf(", "); + LC_GenLCNode(n->ebinary.right); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprGetValueOfPointer: { + LC_Genf("*("); + LC_GenLCNode(n->eunary.expr); + LC_Genf(")"); + } break; + + case LC_ASTKind_ExprGetPointerOfValue: { + LC_Genf("&("); + LC_GenLCNode(n->eunary.expr); + LC_Genf(")"); + } break; + + default: LC_ReportASTError(n, "internal compiler error: unhandled ast kind in %s", __FUNCTION__); + } +} diff --git a/src/compiler/resolve.c b/src/compiler/resolve.c new file mode 100644 index 0000000..bfe1572 --- /dev/null +++ b/src/compiler/resolve.c @@ -0,0 +1,1496 @@ +LC_FUNCTION void LC_RegisterDeclsFromFile(LC_AST *file) { + LC_ASTFor(n, file->afile.fdecl) { + if (n->dbase.resolved_decl) continue; + if (n->kind == LC_ASTKind_DeclNote) continue; + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Type, n->dbase.name, n); + switch (n->kind) { + case LC_ASTKind_DeclStruct: + case LC_ASTKind_DeclUnion: + decl->type = LC_CreateIncompleteType(decl); + decl->state = LC_DeclState_Resolved; + decl->kind = LC_DeclKind_Type; + break; + case LC_ASTKind_DeclTypedef: decl->kind = LC_DeclKind_Type; break; + case LC_ASTKind_DeclProc: decl->kind = LC_DeclKind_Proc; break; + case LC_ASTKind_DeclConst: decl->kind = LC_DeclKind_Const; break; + case LC_ASTKind_DeclVar: decl->kind = LC_DeclKind_Var; break; + default: LC_ReportASTError(n, "internal compiler error: got unhandled ast declaration kind in %s", __FUNCTION__); + } + LC_PutGlobalDecl(decl); + n->dbase.resolved_decl = decl; + } +} + +LC_FUNCTION void LC_ResolveDeclsFromFile(LC_AST *file) { + LC_ASTFor(n, file->afile.fdecl) { + if (n->kind == LC_ASTKind_DeclNote) { + LC_ResolveNote(n, false); + } else { + LC_ResolveName(n, n->dbase.name); + } + } +} + +LC_FUNCTION void LC_PackageDecls(LC_AST *package) { + LC_PUSH_PACKAGE(package); + + // Register top level declarations + LC_ASTFor(file, package->apackage.ffile) { + LC_ASTFor(import, file->afile.fimport) { + if (import->gimport.resolved == false) LC_ReportASTError(import, "internal compiler error: unresolved import got into typechecking stage"); + } + LC_RegisterDeclsFromFile(file); + } + + // Resolve declarations by name + LC_ASTFor(file, package->apackage.ffile) { + LC_ResolveDeclsFromFile(file); + } + + LC_POP_PACKAGE(); +} + +LC_FUNCTION void LC_ResolveProcBodies(LC_AST *package) { + LC_PUSH_PACKAGE(package); + + LC_ASTFor(file, package->apackage.ffile) { + LC_ASTFor(n, file->afile.fdecl) { + if (n->kind == LC_ASTKind_DeclNote) continue; + + LC_Decl *decl = n->dbase.resolved_decl; + if (decl->kind == LC_DeclKind_Proc) { + LC_Operand op = LC_ResolveProcBody(decl); + if (LC_IsError(op)) LC_MarkDeclError(decl); + } + } + } + + LC_POP_PACKAGE(); +} + +LC_FUNCTION void LC_ResolveIncompleteTypes(LC_AST *package) { + LC_PUSH_PACKAGE(package); + + LC_ASTFor(file, package->apackage.ffile) { + LC_ASTFor(n, file->afile.fdecl) { + if (n->kind == LC_ASTKind_DeclNote) continue; + + LC_Decl *decl = n->dbase.resolved_decl; + if (decl->kind == LC_DeclKind_Type) { + LC_ResolveTypeAggregate(decl->ast, decl->type); + } + } + } + + LC_POP_PACKAGE(); +} + +LC_FUNCTION LC_Operand LC_ResolveNote(LC_AST *n, bool is_decl) { + LC_AST *note = n->dnote.expr; + if (n->kind == LC_ASTKind_ExprNote) note = n->enote.expr; + else if (n->kind == LC_ASTKind_StmtNote) note = n->snote.expr; + else { + LC_ASSERT(n, n->kind == LC_ASTKind_DeclNote); + if (n->dnote.processed) return LC_OPNull; + } + + if (note->ecompo.name->eident.name == L->istatic_assert) { + LC_IF(is_decl, note, "#static_assert cant be used as variable initializer"); + LC_Operand LC_PROP_ERROR(op, n, LC_ExpectBuiltinWithOneArg(note)); + LC_IF(!LC_IsUTConst(op) || !LC_IsUTInt(op.type), n, "static assert requires constant untyped integer value"); + int val = (int)LC_Bigint_as_signed(&op.val.i); + LC_IF(!val, note, "#static_assert failed !"); + n->dnote.processed = true; + } + + return LC_OPNull; +} + +void SetConstVal(LC_AST *n, LC_TypeAndVal val) { + LC_ASSERT(n, LC_IsUntyped(val.type)); + n->const_val = val; +} + +LC_FUNCTION LC_Operand LC_ResolveProcBody(LC_Decl *decl) { + if (decl->state == LC_DeclState_Error) return LC_OPError(); + if (decl->state == LC_DeclState_ResolvedBody) return LC_OPNull; + LC_ASSERT(decl->ast, decl->state == LC_DeclState_Resolved); + + LC_AST *n = decl->ast; + if (n->dproc.body == NULL) return LC_OPNull; + L->resolver.locals.len = 0; + LC_ASTFor(it, n->dproc.type->tproc.first) { + if (it->kind == LC_ASTKind_Error) { + LC_MarkDeclError(decl); + return LC_OPError(); + } + LC_ASSERT(it, it->type); + LC_Operand LC_DECL_PROP_ERROR(op, LC_CreateLocalDecl(LC_DeclKind_Var, it->tproc_arg.name, it)); + op.decl->type = it->type; + op.decl->state = LC_DeclState_Resolved; + it->tproc_arg.resolved_decl = op.decl; + } + + int errors_before = L->errors; + LC_ASSERT(n, decl->type->tproc.ret); + L->resolver.expected_ret_type = decl->type->tproc.ret; + LC_Operand LC_DECL_PROP_ERROR(op, LC_ResolveStmtBlock(n->dproc.body)); + L->resolver.locals.len = 0; + + if (errors_before == L->errors && decl->type->tproc.ret != L->tvoid && !(op.flags & LC_OPF_Returned)) { + LC_ReportASTError(n, "you can get through this procedure without hitting a return stmt, add a return to cover all control paths"); + } + decl->state = LC_DeclState_ResolvedBody; + if (L->on_proc_body_resolved) L->on_proc_body_resolved(decl); + return LC_OPNull; +} + +LC_FUNCTION LC_ResolvedCompoItem *LC_AddResolvedCallItem(LC_ResolvedCompo *list, LC_TypeMember *t, LC_AST *comp, LC_AST *expr) { + LC_AST *duplicate1 = (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, list); + if (t && !duplicate1) { + for (LC_ResolvedCompoItem *it = list->first; it; it = it->next) { + if (t == it->t) { + LC_MapInsertP(&L->resolver.duplicate_map, list, comp); + LC_MapInsertP(&L->resolver.duplicate_map, comp, it->comp); // duplicate2 + break; + } + } + } + LC_ResolvedCompoItem *match = LC_PushStruct(L->arena, LC_ResolvedCompoItem); + list->count += 1; + match->t = t; + match->expr = expr; + match->comp = comp; + LC_AddSLL(list->first, list->last, match); + return match; +} + +LC_FUNCTION LC_Operand LC_ResolveCompoCall(LC_AST *n, LC_Type *type) { + LC_ASSERT(n, type->kind == LC_TypeKind_Proc); + LC_IF(type->tproc.vargs && type->tagg.mems.count > n->ecompo.size, n, "calling procedure with invalid argument count, expected at least %d args, got %d, the procedure type is: %s", type->tagg.mems.count, n->ecompo.size, LC_GenLCType(type)); + + bool named_field_appeared = false; + LC_ASTFor(it, n->ecompo.first) { + LC_IF(type->tproc.vargs && it->ecompo_item.name, it, "variadic procedures cannot have named arguments"); + LC_IF(it->ecompo_item.index, it, "index inside a call is not allowed"); + LC_IF(named_field_appeared && it->ecompo_item.name == 0, it, "mixing named and positional arguments is illegal"); + if (it->ecompo_item.name) named_field_appeared = true; + } + + LC_ResolvedCompo *matches = LC_PushStruct(L->arena, LC_ResolvedCompo); + LC_TypeMember *type_it = type->tproc.args.first; + LC_AST *npos_it = n->ecompo.first; + + // greedy match unnamed arguments + for (; type_it; type_it = type_it->next, npos_it = npos_it->next) { + if (npos_it == NULL || npos_it->ecompo_item.name) break; + LC_AddResolvedCallItem(matches, type_it, npos_it, npos_it->ecompo_item.expr); + } + + // greedy match variadic arguments + if (type->tproc.vargs) { + for (; npos_it; npos_it = npos_it->next) { + LC_ResolvedCompoItem *m = LC_AddResolvedCallItem(matches, NULL, npos_it, npos_it->ecompo_item.expr); + m->varg = true; + } + } + + // for every required proc type argument we seek a named argument + // in either default proc values or passed in call arguments + for (; type_it; type_it = type_it->next) { + LC_ASTFor(n_it, npos_it) { + if (type_it->name == n_it->ecompo_item.name) { + LC_AddResolvedCallItem(matches, type_it, n_it, n_it->ecompo_item.expr); + goto end_of_outer_loop; + } + } + + if (type_it->default_value_expr) { + LC_ResolvedCompoItem *m = LC_AddResolvedCallItem(matches, type_it, NULL, type_it->default_value_expr); + m->defaultarg = true; + } + end_of_outer_loop:; + } + + // make sure we matched every item in call + LC_ASTFor(n_it, n->ecompo.first) { + LC_AST *expr = n_it->ecompo_item.expr; + bool included = false; + for (LC_ResolvedCompoItem *it = matches->first; it; it = it->next) { + if (it->expr == expr) { + included = true; + break; + } + } + + LC_IF(!included, expr, "unknown argument to a procedure call, couldn't match it with any of the declared arguments, the procedure type is: %s", LC_GenLCType(type)); + } + + LC_IF(!type->tproc.vargs && matches->count != type->tproc.args.count, n, "invalid argument count passed in to procedure call, expected: %d, matched: %d, the procedure type is: %s", type->tproc.args.count, matches->count, LC_GenLCType(type)); + + // error on duplicates + LC_AST *duplicate1 = (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, matches); + LC_AST *duplicate2 = duplicate1 ? (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, duplicate1) : NULL; + LC_MapClear(&L->resolver.duplicate_map); + if (duplicate1) { + LC_Operand err = LC_ReportASTErrorEx(duplicate1, duplicate2, "two call items match the same procedure argument"); + n->kind = LC_ASTKind_Error; + return err; + } + + // resolve + for (LC_ResolvedCompoItem *it = matches->first; it; it = it->next) { + if (it->varg) { + if (type->tproc.vargs_any_promotion) { + LC_Operand LC_PROP_ERROR(opexpr, it->expr, LC_ResolveExprAndPushCompoContext(it->expr, L->tany)); + LC_TryTyping(it->expr, LC_OPType(L->tany)); + } else { + LC_Operand LC_PROP_ERROR(opexpr, it->expr, LC_ResolveExpr(it->expr)); + LC_Operand LC_PROP_ERROR(op, it->expr, LC_ResolveTypeVargs(it->expr, opexpr)); + LC_TryTyping(it->expr, op); + } + continue; + } + if (it->defaultarg) { + continue; + } + LC_Operand LC_PROP_ERROR(opexpr, it->expr, LC_ResolveExprAndPushCompoContext(it->expr, it->t->type)); + LC_Operand LC_PROP_ERROR(op, it->expr, LC_ResolveTypeVarDecl(it->expr, LC_OPType(it->t->type), opexpr)); + LC_TryTyping(it->expr, op); + } + + n->ecompo.resolved_items = matches; + LC_Operand result = LC_OPLValueAndType(type->tproc.ret); + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveCompoAggregate(LC_AST *n, LC_Type *type) { + LC_ASSERT(n, type->kind == LC_TypeKind_Union || type->kind == LC_TypeKind_Struct); + LC_IF(n->ecompo.size > 1 && type->kind == LC_TypeKind_Union, n, "too many union initializers, expected 1 or 0 got %d", n->ecompo.size); + LC_IF(n->ecompo.size > type->tagg.mems.count, n, "too many struct initializers, expected less then %d got instead %d", type->tagg.mems.count, n->ecompo.size); + + bool named_field_appeared = false; + LC_ASTFor(it, n->ecompo.first) { + LC_IF(type->kind == LC_TypeKind_Union && it->ecompo_item.name == 0, it, "unions can only be initialized using named arguments"); + LC_IF(named_field_appeared && it->ecompo_item.name == 0, it, "mixing named and positional arguments is illegal"); + LC_IF(it->ecompo_item.index, it, "index specifier in non array compound is illegal"); + if (it->ecompo_item.name) named_field_appeared = true; + } + + LC_ResolvedCompo *matches = LC_PushStruct(L->arena, LC_ResolvedCompo); + LC_TypeMember *type_it = type->tagg.mems.first; + LC_AST *npos_it = n->ecompo.first; + + // greedy match unnamed arguments + for (; type_it; type_it = type_it->next, npos_it = npos_it->next) { + if (npos_it == NULL || npos_it->ecompo_item.name) break; + LC_AddResolvedCallItem(matches, type_it, npos_it, npos_it->ecompo_item.expr); + } + + // match named arguments + for (; npos_it; npos_it = npos_it->next) { + bool found = false; + LC_TypeFor(type_it, type->tagg.mems.first) { + if (type_it->name == npos_it->ecompo_item.name) { + LC_AddResolvedCallItem(matches, type_it, npos_it, npos_it->ecompo_item.expr); + found = true; + break; + } + } + + LC_IF(!found, npos_it, "no matching declaration with name '%s' in type '%s'", npos_it->ecompo_item.name, LC_GenLCType(type)); + } + + // error on duplicates + LC_AST *duplicate1 = (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, matches); + LC_AST *duplicate2 = duplicate1 ? (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, duplicate1) : NULL; + if (duplicate1) { + LC_Operand err = LC_ReportASTErrorEx(duplicate1, duplicate2, "two compound items match the same struct variable"); + n->kind = LC_ASTKind_Error; + return err; + } + + // resolve + LC_Operand result = LC_OPLValueAndType(type); + result.flags |= LC_OPF_Const; + for (LC_ResolvedCompoItem *it = matches->first; it; it = it->next) { + LC_Operand LC_PROP_ERROR(opexpr, it->expr, LC_ResolveExprAndPushCompoContext(it->expr, it->t->type)); + LC_Operand LC_PROP_ERROR(op, it->expr, LC_ResolveTypeVarDecl(it->expr, LC_OPType(it->t->type), opexpr)); + LC_TryTyping(it->expr, op); + + if (!(opexpr.flags & LC_OPF_Const)) result.flags &= ~LC_OPF_Const; + } + + n->ecompo.resolved_items = matches; + return result; +} + +LC_FUNCTION LC_ResolvedCompoArrayItem *LC_AddResolvedCompoArrayItem(LC_ResolvedArrayCompo *arr, int index, LC_AST *comp) { + LC_AST *duplicate1 = (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, arr); + if (!duplicate1) { + for (LC_ResolvedCompoArrayItem *it = arr->first; it; it = it->next) { + if (index == it->index) { + LC_MapInsertP(&L->resolver.duplicate_map, arr, comp); + LC_MapInsertP(&L->resolver.duplicate_map, comp, it->comp); + break; + } + } + } + LC_ResolvedCompoArrayItem *result = LC_PushStruct(L->arena, LC_ResolvedCompoArrayItem); + result->index = index; + result->comp = comp; + arr->count += 1; + LC_AddSLL(arr->first, arr->last, result); + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveCompoArray(LC_AST *n, LC_Type *type) { + LC_ASSERT(n, type->kind == LC_TypeKind_Array); + LC_IF(n->ecompo.size > type->tarray.size, n, "too many array intializers, array is of size '%d', got '%d'", type->tarray.size, n->ecompo.size); + + bool index_appeared = false; + LC_ASTFor(it, n->ecompo.first) { + LC_IF(index_appeared && it->ecompo_item.index == NULL, it, "mixing indexed and positional arguments is illegal"); + LC_IF(it->ecompo_item.name, it, "named arguments are invalid in array compound literal"); + if (it->ecompo_item.index) index_appeared = true; + } + + LC_ResolvedArrayCompo *matches = LC_PushStruct(L->arena, LC_ResolvedArrayCompo); + LC_AST *npos_it = n->ecompo.first; + int index = 0; + + // greedy match unnamed arguments + for (; npos_it; npos_it = npos_it->next) { + if (npos_it->ecompo_item.index) break; + LC_ASSERT(n, index < type->tarray.size); + LC_AddResolvedCompoArrayItem(matches, index++, npos_it); + } + + // match indexed arguments + for (; npos_it; npos_it = npos_it->next) { + uint64_t val = 0; + LC_Operand LC_PROP_ERROR(op, npos_it, LC_ResolveConstInt(npos_it->ecompo_item.index, L->tint, &val)); + LC_IF(val > type->tarray.size, npos_it, "array index out of bounds, array is of size %d", type->tarray.size); + LC_AddResolvedCompoArrayItem(matches, (int)val, npos_it); + } + + // error on duplicates + LC_AST *duplicate1 = (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, matches); + LC_AST *duplicate2 = duplicate1 ? (LC_AST *)LC_MapGetP(&L->resolver.duplicate_map, duplicate1) : NULL; + if (duplicate1) { + LC_Operand err = LC_ReportASTErrorEx(duplicate1, duplicate2, "two items in compound array literal match the same index"); + n->kind = LC_ASTKind_Error; + return err; + } + + // resolve + LC_Operand result = LC_OPLValueAndType(type); + result.flags |= LC_OPF_Const; + for (LC_ResolvedCompoArrayItem *it = matches->first; it; it = it->next) { + LC_AST *expr = it->comp->ecompo_item.expr; + LC_Operand LC_PROP_ERROR(opexpr, expr, LC_ResolveExprAndPushCompoContext(expr, type->tbase)); + LC_Operand LC_PROP_ERROR(op, expr, LC_ResolveTypeVarDecl(expr, LC_OPType(type->tbase), opexpr)); + LC_TryTyping(expr, op); + + if (!(opexpr.flags & LC_OPF_Const)) result.flags &= ~LC_OPF_Const; + } + + n->ecompo.resolved_array_items = matches; + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveTypeOrExpr(LC_AST *n) { + if (n->kind == LC_ASTKind_ExprType) { + LC_Operand LC_PROP_ERROR(result, n, LC_ResolveType(n->etype.type)); + n->type = result.type; + return result; + } else { + LC_Operand LC_PROP_ERROR(result, n, LC_ResolveExpr(n)); + return result; + } +} + +LC_FUNCTION LC_Operand LC_ExpectBuiltinWithOneArg(LC_AST *n) { + LC_IF(n->ecompo.size != 1, n, "expected 1 argument to builtin procedure, got: %d", n->ecompo.size); + LC_IF(n->ecompo.first->ecompo_item.name, n, "named arguments in this builtin procedure are illegal"); + LC_AST *expr = n->ecompo.first->ecompo_item.expr; + LC_Operand LC_PROP_ERROR(op, expr, LC_ResolveTypeOrExpr(expr)); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, op.type)); + expr->type = op.type; + return op; +} + +LC_FUNCTION LC_Operand LC_ResolveBuiltin(LC_AST *n) { + LC_Operand result = {0}; + if (n->ecompo.name == 0 || n->ecompo.name->kind != LC_ASTKind_ExprIdent) return result; + LC_Intern ident = n->ecompo.name->eident.name; + + if (ident == L->ilengthof) { + LC_Operand LC_PROP_ERROR(op, n, LC_ExpectBuiltinWithOneArg(n)); + if (LC_IsArray(op.type)) { + result = LC_OPInt(op.type->tarray.size); + } else if (LC_IsUTStr(op.type)) { + int64_t length = LC_StrLen((char *)op.v.name); + result = LC_OPInt(length); + } else LC_IF(1, n, "expected array or constant string type, got instead '%s'", LC_GenLCType(op.type)); + n->kind = LC_ASTKind_ExprBuiltin; + } else if (ident == L->isizeof) { + LC_Operand LC_PROP_ERROR(op, n, LC_ExpectBuiltinWithOneArg(n)); + LC_IF(LC_IsUntyped(op.type), n, "cannot get sizeof a value that is untyped: '%s'", LC_GenLCType(op.type)); + result = LC_OPInt(op.type->size); + n->kind = LC_ASTKind_ExprBuiltin; + } else if (ident == L->ialignof) { + LC_Operand LC_PROP_ERROR(op, n, LC_ExpectBuiltinWithOneArg(n)); + LC_IF(LC_IsUntyped(op.type), n, "cannot get alignof a value that is untyped: '%s'", LC_GenLCType(op.type)); + + LC_AST *expr = n->ecompo.first->ecompo_item.expr; + LC_IF(expr->kind != LC_ASTKind_ExprType, expr, "argument should be a type, instead it's '%s'", LC_ASTKindToString(expr->kind)); + + result = LC_OPInt(op.type->align); + n->kind = LC_ASTKind_ExprBuiltin; + } else if (ident == L->itypeof) { + LC_Operand LC_PROP_ERROR(op, n, LC_ExpectBuiltinWithOneArg(n)); + LC_IF(LC_IsUntyped(op.type), n, "cannot get typeof a value that is untyped: '%s'", LC_GenLCType(op.type)); + result = LC_OPInt(op.type->id); + n->kind = LC_ASTKind_ExprBuiltin; + } else if (ident == L->ioffsetof) { + LC_IF(n->ecompo.size != 2, n, "expected 2 arguments to builtin procedure 'offsetof', got: %d", n->ecompo.size); + LC_AST *a1 = n->ecompo.first; + LC_AST *a2 = a1->next; + LC_IF(a1->ecompo_item.name, a1, "named arguments in this builtin procedure are illegal"); + LC_IF(a2->ecompo_item.name, a2, "named arguments in this builtin procedure are illegal"); + LC_AST *a1e = a1->ecompo_item.expr; + LC_AST *a2e = a2->ecompo_item.expr; + LC_IF(a1e->kind != LC_ASTKind_ExprType, a1e, "first argument should be a type, instead it's '%s'", LC_ASTKindToString(a1e->kind)); + LC_Operand LC_PROP_ERROR(optype, a1e, LC_ResolveType(a1e->etype.type)); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(a1e, optype.type)); + LC_IF(!LC_IsAggType(optype.type), a1e, "expected aggregate type in first parameter of 'offsetof', instead got '%s'", LC_GenLCType(optype.type)); + LC_IF(a2e->kind != LC_ASTKind_ExprIdent, a2e, "expected identifier as second parameter to 'offsetof', instead got '%s'", LC_ASTKindToString(a2e->kind)); + a1e->type = optype.type; + + LC_Type *type = optype.type; + LC_TypeMember *found_type = NULL; + LC_TypeFor(it, type->tagg.mems.first) { + if (it->name == a2e->eident.name) { + found_type = it; + break; + } + } + + LC_ASSERT(n, type->decl); + LC_IF(!found_type, n, "field '%s' not found in '%s'", a2e->eident.name, type->decl->name); + result = LC_OPInt(found_type->offset); + n->kind = LC_ASTKind_ExprBuiltin; + } + + if (LC_IsUTConst(result)) { + n->const_val = result.val; + } + + return result; +} + +LC_FUNCTION bool LC_TryTyping(LC_AST *n, LC_Operand op) { + LC_ASSERT(n, n->type); + + if (LC_IsUntyped(n->type)) { + if (LC_IsUTInt(n->type) && LC_IsFloat(op.type)) { + LC_Operand in = {LC_OPF_UTConst | LC_OPF_Const}; + in.val = n->const_val; + LC_Operand op = LC_ConstCastFloat(NULL, in); + SetConstVal(n, op.val); + } + if (L->tany == op.type) op = LC_OPModDefaultUT(LC_OPType(n->type)); + n->type = op.type; + + // Bounds check + if (n->const_val.type && LC_IsUTInt(n->const_val.type)) { + if (LC_IsInt(n->type) && !LC_BigIntFits(n->const_val.i, n->type)) { + const char *val = LC_Bigint_str(&n->const_val.i, 10); + LC_ReportASTError(n, "value '%s', doesn't fit into type '%s'", val, LC_GenLCType(n->type)); + } + } + } + + // I think it returns true to do this: (a, b) + return true; +} + +LC_FUNCTION bool LC_TryDefaultTyping(LC_AST *n, LC_Operand *o) { + LC_ASSERT(n, n->type); + if (LC_IsUntyped(n->type)) { + n->type = n->type->tbase; + if (o) o->type = n->type; + } + return true; +} + +LC_FUNCTION LC_Operand LC_ResolveNameInScope(LC_AST *n, LC_Decl *parent_decl) { + LC_ASSERT(n, n->kind == LC_ASTKind_ExprField || n->kind == LC_ASTKind_TypespecField); + LC_PUSH_SCOPE(parent_decl->scope); + LC_Operand op = LC_ResolveName(n, n->efield.right); + LC_POP_SCOPE(); + if (LC_IsError(op)) { + n->kind = LC_ASTKind_Error; + return op; + } + + LC_ASSERT(n, op.decl); + n->efield.resolved_decl = op.decl; + n->efield.parent_decl = parent_decl; + + LC_ASSERT(n, op.decl->kind != LC_DeclKind_Import); + return op; +} + +LC_FUNCTION LC_Operand LC_ResolveExpr(LC_AST *expr) { + return LC_ResolveExprAndPushCompoContext(expr, NULL); +} + +LC_FUNCTION LC_Operand LC_ResolveExprAndPushCompoContext(LC_AST *expr, LC_Type *type) { + LC_Type *save = L->resolver.compo_context_type; + L->resolver.compo_context_type = type; + LC_Operand LC_PROP_ERROR(result, expr, LC_ResolveExprEx(expr)); + L->resolver.compo_context_type = save; + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveExprEx(LC_AST *n) { + LC_Operand result = {0}; + LC_ASSERT(n, LC_IsExpr(n)); + + switch (n->kind) { + case LC_ASTKind_ExprFloat: { + result.flags = LC_OPF_UTConst | LC_OPF_Const; + result.val.d = n->eatom.d; + result.val.type = L->tuntypedfloat; + SetConstVal(n, result.val); + } break; + case LC_ASTKind_ExprInt: { + result.flags = LC_OPF_UTConst | LC_OPF_Const; + result.val.i = n->eatom.i; + result.val.type = L->tuntypedint; + SetConstVal(n, result.val); + } break; + case LC_ASTKind_ExprBool: { + result.flags = LC_OPF_UTConst | LC_OPF_Const; + result.val.i = n->eatom.i; + result.val.type = L->tuntypedbool; + SetConstVal(n, result.val); + } break; + case LC_ASTKind_ExprString: { + result.flags = LC_OPF_LValue | LC_OPF_UTConst | LC_OPF_Const; + result.val.name = n->eatom.name; + result.val.type = L->tuntypedstring; + SetConstVal(n, result.val); + } break; + case LC_ASTKind_ExprType: { + return LC_ReportASTError(n, "cannot use type as value"); + } break; + + case LC_ASTKind_ExprIdent: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveName(n, n->eident.name)); + LC_IF(op.decl->kind == LC_DeclKind_Type, n, "declaration is type, unexpected inside expression"); + LC_IF(op.decl->kind == LC_DeclKind_Import, n, "declaration is import, unexpected usage"); + + n->eident.resolved_decl = op.decl; + result.val = op.decl->val; + if (op.decl->kind == LC_DeclKind_Const) { + result.flags |= LC_OPF_UTConst | LC_OPF_Const; + SetConstVal(n, result.val); + } else { + result.flags |= LC_OPF_LValue | LC_OPF_Const; + } + } break; + + case LC_ASTKind_ExprCast: { + LC_Operand LC_PROP_ERROR(optype, n, LC_ResolveType(n->ecast.type)); + LC_Operand LC_PROP_ERROR(opexpr, n, LC_ResolveExpr(n->ecast.expr)); + // :ConstantFold + // the idea is that this will convert the literal into corresponding + // type. In c :uint(32) will become 32u. This way we can avoid doing + // typed arithmetic and let the backend handle it. + if (LC_IsUTConst(opexpr) && (LC_IsNum(optype.type) || LC_IsStr(optype.type))) { + if (LC_IsFloat(optype.type)) { + LC_PROP_ERROR(opexpr, n, LC_ConstCastFloat(n, opexpr)); + SetConstVal(n, opexpr.val); + } else if (LC_IsInt(optype.type)) { + LC_PROP_ERROR(opexpr, n, LC_ConstCastInt(n, opexpr)); + SetConstVal(n, opexpr.val); + } else if (LC_IsStr(optype.type)) { + LC_IF(!LC_IsUTStr(opexpr.type), n, "cannot cast constant expression of type '%s' to '%s'", LC_GenLCType(opexpr.type), LC_GenLCType(optype.type)); + SetConstVal(n, opexpr.val); + } else LC_IF(1, n, "cannot cast constant expression of type '%s' to '%s'", LC_GenLCType(opexpr.type), LC_GenLCType(optype.type)); + result.type = optype.type; + } else { + LC_PROP_ERROR(result, n, LC_ResolveTypeCast(n, optype, opexpr)); + LC_TryTyping(n->ecast.expr, result); + } + result.flags |= (opexpr.flags & LC_OPF_Const); + } break; + + case LC_ASTKind_ExprUnary: { + LC_PROP_ERROR(result, n, LC_ResolveExpr(n->eunary.expr)); + + if (LC_IsUTConst(result)) { + LC_PROP_ERROR(result, n, LC_EvalUnary(n, n->eunary.op, result)); + SetConstVal(n, result.val); + } else { + LC_OPResult r = LC_IsUnaryOpValidForType(n->eunary.op, result.type); + LC_IF(r == LC_OPResult_Error, n, "invalid unary operation for type '%s'", LC_GenLCType(result.type)); + if (r == LC_OPResult_Bool) result = LC_OPModBool(result); + } + } break; + + case LC_ASTKind_ExprBinary: { + LC_Operand LC_PROP_ERROR(left, n, LC_ResolveExpr(n->ebinary.left)); + LC_Operand LC_PROP_ERROR(right, n, LC_ResolveExpr(n->ebinary.right)); + LC_PROP_ERROR(result, n, LC_ResolveBinaryExpr(n, left, right)); + } break; + + case LC_ASTKind_ExprAddPtr: { + LC_Operand LC_PROP_ERROR(left, n, LC_ResolveExpr(n->ebinary.left)); + LC_Operand LC_PROP_ERROR(right, n, LC_ResolveExpr(n->ebinary.right)); + LC_IF(!LC_IsInt(right.type), n, "trying to addptr non integer value of type '%s'", LC_GenLCType(left.type)); + if (LC_IsUTStr(left.type)) LC_TryDefaultTyping(n->ebinary.left, &left); + LC_IF(!LC_IsPtr(left.type) && !LC_IsArray(left.type), n, "left type is required to be a pointer or array, instead got '%s'", LC_GenLCType(left.type)); + result = left; + if (!LC_IsUTConst(right)) result.flags &= ~LC_OPF_Const; + if (LC_IsArray(result.type)) result.type = LC_CreatePointerType(result.type->tbase); + LC_TryTyping(n->ebinary.right, result); + } break; + + case LC_ASTKind_ExprIndex: { + LC_Operand LC_PROP_ERROR(opindex, n, LC_ResolveExpr(n->eindex.index)); + LC_Operand LC_PROP_ERROR(opexpr, n, LC_ResolveExpr(n->eindex.base)); + LC_IF(!LC_IsInt(opindex.type), n, "indexing with non integer value of type '%s'", LC_GenLCType(opindex.type)); + if (LC_IsUTStr(opexpr.type)) LC_TryDefaultTyping(n->eindex.base, &opexpr); + LC_IF(!LC_IsPtr(opexpr.type) && !LC_IsArray(opexpr.type), n, "trying to index non indexable type '%s'", LC_GenLCType(opexpr.type)); + LC_IF(LC_IsVoidPtr(opexpr.type), n, "void is non indexable"); + LC_TryDefaultTyping(n->eindex.index, &opindex); + result.type = LC_GetBase(opexpr.type); + result.flags |= LC_OPF_LValue; + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, result.type)); + } break; + + case LC_ASTKind_ExprGetPointerOfValue: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveExpr(n->eunary.expr)); + LC_IF(!LC_IsLValue(op), n, "trying to access address of a temporal object"); + result.type = LC_CreatePointerType(op.type); + result.flags |= (op.flags & LC_OPF_Const); + } break; + + case LC_ASTKind_ExprGetValueOfPointer: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveExpr(n->eunary.expr)); + LC_IF(!LC_IsPtr(op.type), n, "trying to get value of non pointer type: '%s'", LC_GenLCType(op.type)); + result.type = LC_GetBase(op.type); + result.flags |= LC_OPF_LValue; + result.flags &= ~LC_OPF_Const; + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, result.type)); + } break; + + case LC_ASTKind_ExprField: { + bool first_part_executed = false; + + LC_Operand op = {0}; + if (n->efield.left->kind == LC_ASTKind_ExprIdent) { + LC_AST *nf = n->efield.left; + LC_Operand LC_PROP_ERROR(op_name, nf, LC_ResolveName(nf, nf->eident.name)); + + // LC_Match (Package.) and fold (Package.Other) into just (Other) + if (op_name.decl->kind == LC_DeclKind_Import) { + first_part_executed = true; + nf->eident.resolved_decl = op_name.decl; + nf->type = L->tvoid; + + LC_PROP_ERROR(op, n, LC_ResolveNameInScope(n, op_name.decl)); + } + } + + if (!first_part_executed) { + LC_ASTKind left_kind = n->efield.left->kind; + LC_PROP_ERROR(op, n, LC_ResolveExpr(n->efield.left)); + + LC_Type *type = LC_StripPointer(op.type); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, type)); + LC_IF(!LC_IsAggType(type), n->efield.left, "invalid operation, expected aggregate type, '%s' is not an aggregate", LC_GenLCType(type)); + LC_PROP_ERROR(op, n, LC_ResolveNameInScope(n, type->decl)); + LC_ASSERT(n, op.decl->kind == LC_DeclKind_Var); + result.flags |= LC_OPF_LValue | LC_OPF_Const; + } + result.val = op.decl->val; + } break; + + case LC_ASTKind_ExprCall: { + LC_ASSERT(n, n->ecompo.name); + LC_PROP_ERROR(result, n, LC_ResolveBuiltin(n)); + if (!result.type) { + LC_Operand LC_PROP_ERROR(left, n, LC_ResolveExpr(n->ecompo.name)); + LC_IF(!LC_IsProc(left.type), n, "trying to call value of invalid type '%s', not a procedure", LC_GenLCType(left.type)); + if (L->before_call_args_resolved) L->before_call_args_resolved(n, left.type); + LC_PROP_ERROR(result, n, LC_ResolveCompoCall(n, left.type)); + } + } break; + + case LC_ASTKind_ExprCompound: { + LC_Type *type = NULL; + if (n->ecompo.name) { + LC_PUSH_COMP_ARRAY_SIZE(n->ecompo.size); + LC_Operand LC_PROP_ERROR(left, n, LC_ResolveTypeOrExpr(n->ecompo.name)); + type = left.type; + LC_POP_COMP_ARRAY_SIZE(); + } + if (!n->ecompo.name) type = L->resolver.compo_context_type; + LC_IF(!type, n, "failed to deduce type of compound expression"); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, type)); + + if (LC_IsAggType(type)) { + LC_PROP_ERROR(result, n, LC_ResolveCompoAggregate(n, type)); + } else if (LC_IsArray(type)) { + LC_PROP_ERROR(result, n, LC_ResolveCompoArray(n, type)); + } else { + LC_IF(1, n, "compound of type '%s' is illegal, expected array, struct or union type", LC_GenLCType(type)); + } + } break; + + default: LC_IF(1, n, "internal compiler error: unhandled expression kind '%s'", LC_ASTKindToString(n->kind)); + } + + n->type = result.type; + if (n->type != L->tany && L->resolver.compo_context_type == L->tany) { + LC_MapInsertP(&L->implicit_any, n, (void *)(intptr_t)1); + result.flags &= ~LC_OPF_Const; + } + + if (L->on_expr_resolved) L->on_expr_resolved(n, &result); + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveStmtBlock(LC_AST *n) { + LC_ASSERT(n, n->kind == LC_ASTKind_StmtBlock); + + LC_PUSH_LOCAL_SCOPE(); + LC_PushAST(&L->resolver.stmt_block_stack, n); + + LC_Operand result = {0}; + for (LC_AST *it = n->sblock.first; it; it = it->next) { + LC_Operand op = LC_ResolveStmt(it); + + // We don't want to whine about non returned procedures if we spotted any errors + // inside of it. + if (LC_IsError(op) || (op.flags & LC_OPF_Returned)) result.flags |= LC_OPF_Returned; + } + + LC_PopAST(&L->resolver.stmt_block_stack); + LC_POP_LOCAL_SCOPE(); + + if (L->on_stmt_resolved) L->on_stmt_resolved(n); + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveVarDecl(LC_Decl *decl) { + LC_ASSERT(decl->ast, decl->kind == LC_DeclKind_Var); + LC_Operand result = {0}; + result.flags |= LC_OPF_Const; + + LC_AST *n = decl->ast; + LC_Operand optype = {0}; + LC_Operand opexpr = {0}; + + LC_AST *expr = n->dvar.expr; + LC_AST *type = n->dvar.type; + if (n->kind == LC_ASTKind_StmtVar) { + expr = n->svar.expr; + type = n->svar.type; + } else { + LC_ASSERT(n, n->kind == LC_ASTKind_DeclVar); + } + + // special case := #c(``) + if (expr && expr->kind == LC_ASTKind_ExprNote) { + LC_Operand LC_PROP_ERROR(opnote, expr, LC_ResolveNote(expr, true)); + LC_IF(type == NULL, n, "invalid usage of unknown type, need to add type annotation"); + LC_DECL_PROP_ERROR(optype, LC_ResolveType(type)); + decl->type = optype.type; + } else { + if (type) { + if (expr && expr->kind == LC_ASTKind_ExprCompound) { + LC_PUSH_COMP_ARRAY_SIZE(expr->ecompo.size); + LC_DECL_PROP_ERROR(optype, LC_ResolveType(type)); + LC_POP_COMP_ARRAY_SIZE(); + } else { + LC_DECL_PROP_ERROR(optype, LC_ResolveType(type)); + } + } + if (expr) { + LC_DECL_PROP_ERROR(opexpr, LC_ResolveExprAndPushCompoContext(expr, optype.type)); + if (!(opexpr.flags & LC_OPF_Const)) result.flags &= ~LC_OPF_Const; + } + + LC_Operand LC_DECL_PROP_ERROR(opcast, LC_ResolveTypeVarDecl(n, optype, opexpr)); + if (expr) LC_TryTyping(expr, opcast); + decl->val = opcast.val; + } + + LC_ASSERT(n, decl->type); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, decl->type)); + result.type = decl->type; + return result; +} + +LC_FUNCTION LC_Operand LC_MakeSureNoDeferBlock(LC_AST *n, char *str) { + for (int i = L->resolver.stmt_block_stack.len - 1; i >= 0; i -= 1) { + LC_AST *it = L->resolver.stmt_block_stack.data[i]; + if (it->kind == LC_ASTKind_Error) return LC_OPError(); + LC_ASSERT(it, it->kind == LC_ASTKind_StmtBlock); + LC_IF(it->sblock.kind == SBLK_Defer, n, str); + } + return LC_OPNull; +} + +LC_FUNCTION LC_Operand LC_MakeSureInsideLoopBlock(LC_AST *n, char *str) { + bool loop_found = false; + for (int i = L->resolver.stmt_block_stack.len - 1; i >= 0; i -= 1) { + LC_AST *it = L->resolver.stmt_block_stack.data[i]; + if (it->kind == LC_ASTKind_Error) return LC_OPError(); + LC_ASSERT(it, it->kind == LC_ASTKind_StmtBlock); + if (it->sblock.kind == SBLK_Loop) { + loop_found = true; + break; + } + } + LC_IF(!loop_found, n, str); + return LC_OPNull; +} + +LC_FUNCTION LC_Operand LC_MatchLabeledBlock(LC_AST *n) { + if (n->sbreak.name) { + bool found = false; + for (int i = L->resolver.stmt_block_stack.len - 1; i >= 0; i -= 1) { + LC_AST *it = L->resolver.stmt_block_stack.data[i]; + if (it->kind == LC_ASTKind_Error) return LC_OPError(); + if (it->sblock.name == n->sbreak.name) { + found = true; + break; + } + } + LC_IF(!found, n, "no label with name '%s'", n->sbreak.name); + } + return LC_OPNull; +} + +LC_FUNCTION void WalkToFindCall(LC_ASTWalker *w, LC_AST *n) { + if (n->kind == LC_ASTKind_ExprCall || n->kind == LC_ASTKind_ExprBuiltin) ((bool *)w->user_data)[0] = true; +} + +LC_FUNCTION bool LC_ContainsCallExpr(LC_AST *ast) { + LC_TempArena checkpoint = LC_BeginTemp(L->arena); + bool found_call = false; + { + LC_ASTWalker walker = LC_GetDefaultWalker(L->arena, WalkToFindCall); + walker.depth_first = false; + walker.user_data = (void *)&found_call; + LC_WalkAST(&walker, ast); + } + LC_EndTemp(checkpoint); + return found_call; +} + +LC_FUNCTION LC_Operand LC_ResolveStmt(LC_AST *n) { + LC_ASSERT(n, LC_IsStmt(n)); + + LC_Operand result = {0}; + switch (n->kind) { + case LC_ASTKind_StmtVar: { + LC_Operand LC_PROP_ERROR(opdecl, n, LC_CreateLocalDecl(LC_DeclKind_Var, n->svar.name, n)); + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveVarDecl(opdecl.decl)); + opdecl.decl->state = LC_DeclState_Resolved; + n->svar.resolved_decl = opdecl.decl; + n->type = op.type; + } break; + + case LC_ASTKind_StmtConst: { + LC_Operand LC_PROP_ERROR(opdecl, n, LC_CreateLocalDecl(LC_DeclKind_Const, n->sconst.name, n)); + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveConstDecl(opdecl.decl)); + opdecl.decl->state = LC_DeclState_Resolved; + n->type = op.type; + } break; + + case LC_ASTKind_StmtAssign: { + LC_Operand LC_PROP_ERROR(left, n, LC_ResolveExpr(n->sassign.left)); + LC_IF(!LC_IsLValue(left), n, "assigning value to a temporal object (lvalue)"); + LC_Type *type = left.type; + + LC_OPResult valid = LC_IsAssignValidForType(n->sassign.op, type); + LC_IF(valid == LC_OPResult_Error, n, "invalid assignment operation '%s' for type '%s'", LC_TokenKindToString(n->sassign.op), LC_GenLCType(type)); + + LC_Operand LC_PROP_ERROR(right, n, LC_ResolveExprAndPushCompoContext(n->sassign.right, type)); + LC_PROP_ERROR(result, n, LC_ResolveTypeVarDecl(n, left, right)); + LC_TryTyping(n->sassign.left, result); + LC_TryTyping(n->sassign.right, result); + n->type = result.type; + } break; + + case LC_ASTKind_StmtExpr: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveExpr(n->sexpr.expr)); + LC_TryDefaultTyping(n->sexpr.expr, &op); + n->type = op.type; + bool contains_call = LC_ContainsCallExpr(n->sexpr.expr); + LC_AST *note = LC_HasNote(n, L->iunused); + LC_IF(!note && !contains_call, n, "very likely a bug, expression statement doesn't contain any calls so it doesn't do anything"); + } break; + + case LC_ASTKind_StmtReturn: { + LC_PROP_ERROR(result, n, LC_MakeSureNoDeferBlock(n, "returning from defer block is illegal")); + LC_Operand op = LC_OPType(L->tvoid); + if (n->sreturn.expr) { + LC_PROP_ERROR(op, n, LC_ResolveExprAndPushCompoContext(n->sreturn.expr, L->resolver.expected_ret_type)); + } + + if (!(op.type == L->resolver.expected_ret_type && op.type == L->tvoid)) { + LC_PROP_ERROR(op, n, LC_ResolveTypeVarDecl(n, LC_OPType(L->resolver.expected_ret_type), op)); + if (n->sreturn.expr) LC_TryTyping(n->sreturn.expr, op); + } + result.flags |= LC_OPF_Returned; + } break; + + case LC_ASTKind_StmtNote: LC_PROP_ERROR(result, n, LC_ResolveNote(n, false)); break; + case LC_ASTKind_StmtContinue: + LC_PROP_ERROR(result, n, LC_MakeSureNoDeferBlock(n, "continue inside of defer is illegal")); + LC_PROP_ERROR(result, n, LC_MakeSureInsideLoopBlock(n, "continue outside of a for loop is illegal")); + case LC_ASTKind_StmtBreak: { + LC_PROP_ERROR(result, n, LC_MakeSureNoDeferBlock(n, "break inside of defer is illegal")); + LC_PROP_ERROR(result, n, LC_MakeSureInsideLoopBlock(n, "break outside of a for loop is illegal")); + LC_PROP_ERROR(result, n, LC_MatchLabeledBlock(n)); + } break; + + case LC_ASTKind_StmtDefer: { + LC_PROP_ERROR(result, n, LC_MakeSureNoDeferBlock(n, "defer inside of defer is illegal")); + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveStmtBlock(n->sdefer.body)); + LC_AST *parent_block = LC_GetLastAST(&L->resolver.stmt_block_stack); + LC_ASSERT(n, parent_block->kind == LC_ASTKind_StmtBlock); + LC_SLLStackAddMod(parent_block->sblock.first_defer, n, sdefer.next); + } break; + + case LC_ASTKind_StmtSwitch: { + LC_Operand LC_PROP_ERROR(opfirst, n, LC_ResolveExpr(n->sswitch.expr)); + LC_IF(!LC_IsInt(opfirst.type), n, "invalid type in switch condition '%s', it should be an integer", LC_GenLCType(opfirst.type)); + LC_TryDefaultTyping(n->sswitch.expr, &opfirst); + + bool all_returned = true; + bool has_default = n->sswitch.last && n->sswitch.last->kind == LC_ASTKind_StmtSwitchDefault; + + LC_Operand *ops = LC_PushArray(L->arena, LC_Operand, n->sswitch.total_switch_case_count); + int opi = 0; + LC_ASTFor(case_it, n->sswitch.first) { + if (case_it->kind == LC_ASTKind_StmtSwitchCase) { + LC_ASTFor(case_expr_it, case_it->scase.first) { + LC_Operand LC_PROP_ERROR(opcase, n, LC_ResolveExpr(case_expr_it)); + LC_IF(!LC_IsUTConst(opcase), case_expr_it, "expected an untyped constant"); + ops[opi++] = opcase; + + LC_Operand LC_PROP_ERROR(o, n, LC_ResolveTypeVarDecl(case_expr_it, opfirst, opcase)); + LC_TryTyping(case_expr_it, o); + } + } + LC_Operand LC_PROP_ERROR(opbody, case_it, LC_ResolveStmtBlock(case_it->scase.body)); + if (!(opbody.flags & LC_OPF_Returned)) all_returned = false; + } + LC_ASSERT(n, opi == n->sswitch.total_switch_case_count); + + for (int i = 0; i < opi; i += 1) { + LC_Operand a = ops[i]; + for (int j = 0; j < opi; j += 1) { + if (i == j) continue; + LC_Operand b = ops[j]; + + // bounds check error is thrown in LC_ResolveTypeVarDecl + if (LC_BigIntFits(a.v.i, opfirst.type) && LC_BigIntFits(b.v.i, opfirst.type)) { + uint64_t au = LC_Bigint_as_unsigned(&a.v.i); + uint64_t bu = LC_Bigint_as_unsigned(&b.v.i); + LC_IF(au == bu, n, "duplicate fields, with value: %llu, in a switch statement", au); + } + } + } + + if (all_returned && has_default) result.flags |= LC_OPF_Returned; + } break; + + case LC_ASTKind_StmtFor: { + LC_StmtFor *sfor = &n->sfor; + LC_PUSH_LOCAL_SCOPE(); + + if (sfor->init) { + LC_Operand opinit = LC_ResolveStmt(sfor->init); + if (LC_IsError(opinit)) { + n->kind = LC_ASTKind_Error; + LC_POP_LOCAL_SCOPE(); + return opinit; + } + + LC_TryDefaultTyping(sfor->init, &opinit); + } + if (sfor->cond) { + LC_Operand opcond = LC_ResolveExpr(sfor->cond); + if (LC_IsError(opcond)) { + n->kind = LC_ASTKind_Error; + LC_POP_LOCAL_SCOPE(); + return opcond; + } + + LC_TryDefaultTyping(sfor->cond, &opcond); + if (!LC_IsIntLike(opcond.type)) { + n->kind = LC_ASTKind_Error; + LC_POP_LOCAL_SCOPE(); + return LC_ReportASTError(n, "invalid type in for condition '%s', it should be an integer or pointer", LC_GenLCType(opcond.type)); + } + } + if (sfor->inc) { + LC_Operand opinc = LC_ResolveStmt(sfor->inc); + if (LC_IsError(opinc)) { + n->kind = LC_ASTKind_Error; + LC_POP_LOCAL_SCOPE(); + return opinc; + } + } + result = LC_ResolveStmtBlock(sfor->body); + if (LC_IsError(result)) { + n->kind = LC_ASTKind_Error; + LC_POP_LOCAL_SCOPE(); + return result; + } + + LC_POP_LOCAL_SCOPE(); + } break; + + case LC_ASTKind_StmtBlock: { + // we don't handle errors here explicitly + LC_Operand op = LC_ResolveStmtBlock(n); + if (op.flags & LC_OPF_Returned) result.flags |= LC_OPF_Returned; + } break; + + case LC_ASTKind_StmtIf: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveExpr(n->sif.expr)); + LC_TryDefaultTyping(n->sif.expr, &op); + LC_IF(!LC_IsIntLike(op.type), n, "invalid type in if clause expression %s it should be an integer or pointer", LC_GenLCType(op.type)); + + bool all_returned = true; + bool has_else = n->sif.last && n->sif.last->kind == LC_ASTKind_StmtElse; + + LC_Operand LC_PROP_ERROR(opbody, n, LC_ResolveStmtBlock(n->sif.body)); + if (!(opbody.flags & LC_OPF_Returned)) all_returned = false; + + LC_ASTFor(it, n->sif.first) { + if (it->kind == LC_ASTKind_StmtElseIf) { + LC_Operand LC_PROP_ERROR(op, it, LC_ResolveExpr(it->sif.expr)); + LC_TryDefaultTyping(it->sif.expr, &op); + LC_IF(!LC_IsIntLike(op.type), n, "invalid type in if clause expression %s it should be an integer or pointer", LC_GenLCType(op.type)); + } + LC_Operand LC_PROP_ERROR(opbody, it, LC_ResolveStmtBlock(it->sif.body)); + if (!(opbody.flags & LC_OPF_Returned)) all_returned = false; + } + + if (all_returned && has_else) result.flags |= LC_OPF_Returned; + } break; + default: LC_IF(1, n, "internal compiler error: unhandled statement kind '%s'", LC_ASTKindToString(n->kind)); + } + + if (L->on_stmt_resolved) L->on_stmt_resolved(n); + return result; +} + +LC_FUNCTION LC_Operand LC_ResolveConstDecl(LC_Decl *decl) { + LC_ASSERT(decl->ast, decl->kind == LC_DeclKind_Const); + LC_AST *n = decl->ast; + LC_AST *expr = n->dconst.expr; + if (n->kind == LC_ASTKind_StmtConst) { + expr = n->sconst.expr; + } else { + LC_ASSERT(n, n->kind == LC_ASTKind_DeclConst); + } + + LC_Operand LC_DECL_PROP_ERROR(opexpr, LC_ResolveExpr(expr)); + LC_DECL_IF(!LC_IsUTConst(opexpr), n, "expected an untyped constant"); + LC_DECL_IF(!LC_IsUntyped(opexpr.type), n, "type of constant expression is not a simple type"); + decl->val = opexpr.val; + return opexpr; +} + +LC_FUNCTION LC_Operand LC_ResolveName(LC_AST *pos, LC_Intern intern) { + LC_Decl *decl = LC_GetLocalOrGlobalDecl(intern); + LC_DECL_IF(!decl, pos, "undeclared identifier '%s'", intern); + LC_DECL_IF(decl->state == LC_DeclState_Resolving, pos, "cyclic dependency %s", intern); + if (decl->state == LC_DeclState_Error) return LC_OPError(); + if (decl->state == LC_DeclState_Resolved || decl->state == LC_DeclState_ResolvedBody) return LC_OPDecl(decl); + LC_ASSERT(pos, decl->state == LC_DeclState_Unresolved); + decl->state = LC_DeclState_Resolving; + + LC_AST *n = decl->ast; + switch (decl->kind) { + case LC_DeclKind_Const: { + LC_Operand LC_DECL_PROP_ERROR(op, LC_ResolveConstDecl(decl)); + } break; + case LC_DeclKind_Var: { + LC_Operand LC_DECL_PROP_ERROR(op, LC_ResolveVarDecl(decl)); + LC_DECL_IF(!(op.flags & LC_OPF_Const), n, "non constant global declarations are illegal"); + } break; + case LC_DeclKind_Proc: { + LC_Operand LC_DECL_PROP_ERROR(optype, LC_ResolveType(n->dproc.type)); + decl->type = optype.type; + decl->type->decl = decl; + } break; + case LC_DeclKind_Import: { + LC_ASSERT(n, decl->scope); + } break; + case LC_DeclKind_Type: { + LC_ASSERT(n, n->kind == LC_ASTKind_DeclTypedef); + LC_Operand LC_DECL_PROP_ERROR(op, LC_ResolveType(n->dtypedef.type)); + decl->val = op.val; + + // I have decided that aggregates cannot be hard typedefed. + // It brings issues to LC_ResolveTypeAggregate and is not needed, what's needed + // is typedef on numbers and pointers that create distinct new + // types. I have never had a use for typedefing a struct to make + // it more typesafe etc. + LC_AST *is_weak = LC_HasNote(n, L->iweak); + bool is_agg = op.type->decl && LC_IsAgg(op.type->decl->ast); + if (!is_weak && !is_agg) decl->type = LC_CreateTypedef(decl, decl->type); + LC_DECL_IF(is_weak && is_agg, n, "@weak doesn't work on aggregate types"); + } break; + default: LC_DECL_IF(1, n, "internal compiler error: unhandled LC_DeclKind: '%s'", LC_DeclKindToString(decl->kind)) + } + decl->state = LC_DeclState_Resolved; + + if (L->on_decl_type_resolved) L->on_decl_type_resolved(decl); + LC_AST *pkg = decl->package; + LC_DLLAdd(pkg->apackage.first_ordered, pkg->apackage.last_ordered, decl); + return LC_OPDecl(decl); +} + +LC_FUNCTION LC_Operand LC_ResolveConstInt(LC_AST *n, LC_Type *int_type, uint64_t *out_size) { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveExpr(n)); + LC_IF(!LC_IsUTConst(op), n, "expected a constant untyped int"); + LC_IF(!LC_IsUTInt(op.type), n, "expected untyped int constant instead: '%s'", LC_GenLCType(op.type)); + LC_IF(!LC_BigIntFits(op.val.i, int_type), n, "constant value: '%s', doesn't fit in type '%s'", LC_GenLCTypeVal(op.val), LC_GenLCType(int_type)); + if (out_size) *out_size = LC_Bigint_as_unsigned(&op.val.i); + LC_TryTyping(n, LC_OPType(int_type)); + return op; +} + +LC_FUNCTION LC_Operand LC_ResolveType(LC_AST *n) { + LC_ASSERT(n, LC_IsType(n)); + LC_Operand result = {0}; + + switch (n->kind) { + case LC_ASTKind_TypespecField: { + LC_ASSERT(n, n->efield.left->kind == LC_ASTKind_TypespecIdent); + LC_Operand LC_PROP_ERROR(l, n, LC_ResolveName(n, n->efield.left->eident.name)); + LC_IF(l.decl->kind != LC_DeclKind_Import, n, "only accessing '.' imports in type definitions is valid, you are trying to access: '%s'", LC_DeclKindToString(l.decl->kind)); + n->efield.left->eident.resolved_decl = l.decl; + n->efield.left->type = L->tvoid; + + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveNameInScope(n, l.decl)); + LC_IF(op.decl->kind != LC_DeclKind_Type, n, "expected reference to type, instead it's: '%s'", LC_DeclKindToString(op.decl->kind)); + result.type = op.decl->type; + } break; + + case LC_ASTKind_TypespecIdent: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveName(n, n->eident.name)); + LC_IF(op.decl->kind != LC_DeclKind_Type, n, "identifier is not a type"); + result.type = op.decl->type; + n->eident.resolved_decl = op.decl; + } break; + + case LC_ASTKind_TypespecPointer: { + LC_Operand LC_PROP_ERROR(op, n, LC_ResolveType(n->tpointer.base)); + result.type = LC_CreatePointerType(op.type); + } break; + + case LC_ASTKind_TypespecArray: { + LC_Operand LC_PROP_ERROR(opbase, n, LC_ResolveType(n->tarray.base)); + uint64_t size = L->resolver.compo_context_array_size; + if (n->tarray.index) { + LC_Operand LC_PROP_ERROR(opindex, n, LC_ResolveConstInt(n->tarray.index, L->tint, &size)); + } + LC_IF(size == 0, n, "failed to deduce array size"); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, opbase.type)); + + result.type = LC_CreateArrayType(opbase.type, (int)size); + } break; + + case LC_ASTKind_TypespecProc: { + LC_Type *ret = L->tvoid; + if (n->tproc.ret) { + LC_Operand LC_PROP_ERROR(op, n->tproc.ret, LC_ResolveType(n->tproc.ret)); + ret = op.type; + } + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(n, ret)); + LC_TypeMemberList typelist = {0}; + LC_ASTFor(it, n->tproc.first) { + LC_Operand LC_PROP_ERROR(op, it, LC_ResolveType(it->tproc_arg.type)); + LC_Operand LC_PROP_ERROR(maybe_err, n, LC_ResolveTypeAggregate(it, op.type)); + + LC_AST *expr = it->tproc_arg.expr; + if (expr) { + LC_Operand LC_PROP_ERROR(opexpr, expr, LC_ResolveExprAndPushCompoContext(expr, op.type)); + LC_Operand LC_PROP_ERROR(opfin, expr, LC_ResolveTypeVarDecl(expr, op, opexpr)); + LC_TryTyping(expr, opfin); + } + + LC_TypeMember *mem = LC_AddTypeToList(&typelist, it->tproc_arg.name, op.type, it); + LC_IF(!mem, it, "duplicate proc argument '%s'", it->tproc_arg.name); + mem->default_value_expr = expr; + it->type = op.type; + } + + LC_TypeFor(i, typelist.first) { + LC_TypeFor(j, typelist.first) { + LC_IF(i != j && i->name == j->name, i->ast, "procedure has 2 arguments with the same name"); + } + } + result.type = LC_CreateProcType(typelist, ret, n->tproc.vargs, n->tproc.vargs_any_promotion); + } break; + + default: LC_IF(1, n, "internal compiler error: unhandled kind in LC_ResolveType '%s'", LC_ASTKindToString(n->kind)); + } + + n->type = result.type; + LC_ASSERT(n, result.type); + return result; +} + +// clang-format off +// NA - Not applicable +// LC_RPS - OK if right side int of pointer size +// LC_LPS +// LC_TEQ - OK if types equal +// LC_RO0 - OK if right value is int equal nil +// LT - Left untyped to typed +// RT +// LF - Left to float +// RF +// LC_SR - String +enum { LC_INT, LC_FLOAT, LC_UT_INT, LC_UT_FLOAT, LC_UT_STR, LC_PTR, LC_VOID_PTR, LC_PROC, LC_AGG, LC_ARRAY, LC_ANY, LC_VOID, LC_TYPE_COUNT }; +typedef enum { LC_NO, LC_OK, LC_LPS, LC_RPS, LC_TEQ, LC_NA, LC_RO0, LC_LT, LC_RT, LC_LF, LC_RF, LC_SR } LC_TypeRule; + +LC_TypeRule CastingRules[LC_TYPE_COUNT][LC_TYPE_COUNT] = { +//\/:tgt( src)> LC_INT , LC_FLOAT , LC_UT_INT , LC_UT_FLOAT , LC_UT_STR , LC_PTR , LC_VOID_PTR , LC_PROC , LC_AGG , LC_ARRAY +/*[LC_INT] = */{LC_OK , LC_OK , LC_OK , LC_OK , LC_NO , LC_LPS , LC_LPS , LC_NO , LC_NO , LC_NO} , +/*[LC_FLOAT] = */{LC_OK , LC_OK , LC_OK , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO} , +/*[LC_UT_INT] = */{LC_NA , LC_NA , LC_NA , LC_NA , LC_NO , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA} , +/*[LC_UT_FLOAT] = */{LC_NA , LC_NA , LC_NA , LC_NA , LC_NO , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA} , +/*[LC_UT_STR] = */{LC_NA , LC_NA , LC_NA , LC_NA , LC_NO , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA} , +/*[LC_PTR] = */{LC_RPS , LC_NO , LC_OK , LC_NO , LC_SR , LC_OK , LC_OK , LC_OK , LC_NO , LC_NO} , +/*[LC_VOID_PTR] = */{LC_RPS , LC_NO , LC_OK , LC_NO , LC_OK , LC_OK , LC_OK , LC_OK , LC_NO , LC_NO} , +/*[LC_PROC] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_OK , LC_OK , LC_OK , LC_NO , LC_NO} , +/*[LC_AGG] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_SR , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO} , +/*[LC_ARRAY] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO} , +}; + +LC_TypeRule AssignRules[LC_TYPE_COUNT][LC_TYPE_COUNT] = { +//\/l r> LC_INT , LC_FLOAT , LC_UT_INT , LC_UT_FLOAT , LC_UT_STR , LC_PTR , LC_VOID_PTR , LC_PROC , LC_AGG , LC_ARRAY , LC_ANY +/*[LC_INT] = */{LC_TEQ , LC_NO , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO} , +/*[LC_FLOAT] = */{LC_NO , LC_TEQ , LC_OK , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO} , +/*[LC_UT_INT] = */{LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NO} , +/*[LC_UT_FLOAT] = */{LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NO} , +/*[LC_UT_STR] = */{LC_NA , LC_NA , LC_NA , LC_NA , LC_NA , LC_NO , LC_NA , LC_NA , LC_NA , LC_NA , LC_NO} , +/*[LC_PTR] = */{LC_NO , LC_NO , LC_RO0 , LC_NO , LC_SR , LC_TEQ , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO} , +/*[LC_VOID_PTR] = */{LC_NO , LC_NO , LC_RO0 , LC_NO , LC_OK , LC_OK , LC_OK , LC_OK , LC_NO , LC_NO , LC_NO} , +/*[LC_PROC] = */{LC_NO , LC_NO , LC_RO0 , LC_NO , LC_NO , LC_NO , LC_OK , LC_TEQ , LC_NO , LC_NO , LC_NO} , +/*[LC_AGG] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_SR , LC_NO , LC_NO , LC_NO , LC_TEQ , LC_NO , LC_TEQ} , +/*[LC_ARRAY] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_TEQ , LC_NO} , +/*[LC_ANY] = */{LC_OK , LC_OK , LC_OK , LC_OK , LC_OK , LC_OK , LC_NO , LC_OK , LC_OK , LC_OK , LC_OK} , +}; + +LC_TypeRule BinaryRules[LC_TYPE_COUNT][LC_TYPE_COUNT] = { +//\/l r> LC_INT , LC_FLOAT , LC_UT_INT , LC_UT_FLOAT , LC_UT_STR , LC_PTR , LC_VOID_PTR , LC_PROC , LC_AGG , LC_ARRAY +/*[LC_INT] = */{LC_TEQ , LC_NO , LC_RT , LC_NO , LC_NO , LC_NO , LC_OK , LC_OK , LC_NO , LC_NO , } , +/*[LC_FLOAT] = */{LC_NO , LC_TEQ , LC_RT , LC_RT , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , } , +/*[LC_UT_INT] = */{LC_LT , LC_LT , LC_OK , LC_LF , LC_NO , LC_OK , LC_OK , LC_OK , LC_NO , LC_NO , } , +/*[LC_UT_FLOAT]= */{LC_NO , LC_LT , LC_RF , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , } , +/*[LC_UT_STR] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , } , +/*[LC_PTR] = */{LC_OK , LC_NO , LC_OK , LC_NO , LC_NO , LC_OK , LC_OK , LC_NO , LC_NO , LC_NO , } , +/*[LC_VOID_PTR]= */{LC_OK , LC_NO , LC_OK , LC_NO , LC_NO , LC_OK , LC_OK , LC_NO , LC_NO , LC_NO , } , +/*[LC_PROC] = */{LC_OK , LC_NO , LC_OK , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , } , +/*[LC_AGG] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , } , +/*[LC_ARRAY] = */{LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , LC_NO , } , +}; +// clang-format on + +int GetTypeCategory(LC_Type *x) { + if (x->kind >= LC_TypeKind_char && x->kind <= LC_TypeKind_ullong) return LC_INT; + if ((x->kind == LC_TypeKind_float) || (x->kind == LC_TypeKind_double)) return LC_FLOAT; + if (x->kind == LC_TypeKind_UntypedInt) return LC_UT_INT; + if (x->kind == LC_TypeKind_UntypedFloat) return LC_UT_FLOAT; + if (x->kind == LC_TypeKind_UntypedString) return LC_UT_STR; + if (x == L->tpvoid) return LC_VOID_PTR; + if (x == L->tany) return LC_ANY; + if (x->kind == LC_TypeKind_Pointer) return LC_PTR; + if (x->kind == LC_TypeKind_Proc) return LC_PROC; + if (LC_IsAggType(x)) return LC_AGG; + if (LC_IsArray(x)) return LC_ARRAY; + return LC_VOID; +} + +LC_FUNCTION LC_Operand LC_ResolveBinaryExpr(LC_AST *n, LC_Operand l, LC_Operand r) { + bool isconst = LC_IsConst(l) && LC_IsConst(r); + + LC_TypeRule rule = BinaryRules[GetTypeCategory(l.type)][GetTypeCategory(r.type)]; + LC_IF(rule == LC_NO, n, "cannot perform binary operation, types don't qualify for it, left: '%s' right: '%s'", LC_GenLCType(l.type), LC_GenLCType(r.type)); + LC_IF(rule == LC_TEQ && l.type != r.type, n, "cannot perform binary operation, types are incompatible, left: '%s' right: '%s'", LC_GenLCType(l.type), LC_GenLCType(r.type)); + if (rule == LC_LT) l = LC_OPModType(l, r.type); + if (rule == LC_RT) r = LC_OPModType(r, l.type); + if (rule == LC_LF) l = LC_ConstCastFloat(n, l); + if (rule == LC_RF) r = LC_ConstCastFloat(n, r); + LC_ASSERT(n, rule == LC_LT || rule == LC_RT || rule == LC_LF || rule == LC_RF || rule == LC_OK || rule == LC_TEQ); + + // WARNING: if we allow for more then boolean operations on pointers then + // we need to fix the propagated type here, we are counting on it getting + // modified to bool. + LC_Operand op = LC_OPType(l.type); + if (isconst) op.flags |= LC_OPF_Const; + if (LC_IsUTConst(l) && LC_IsUTConst(r)) { + LC_PROP_ERROR(op, n, LC_EvalBinary(n, l, n->ebinary.op, r)); + SetConstVal(n, op.val); + } else { + LC_OPResult r = LC_IsBinaryExprValidForType(n->ebinary.op, op.type); + LC_IF(r == LC_OPResult_Error, n, "invalid binary operation for type '%s'", LC_GenLCType(op.type)); + (LC_TryTyping(n->ebinary.left, op), LC_TryTyping(n->ebinary.right, op)); + if (r == LC_OPResult_Bool) op = LC_OPModBool(op); + } + + return op; +} + +LC_FUNCTION LC_Operand LC_ResolveTypeVargs(LC_AST *pos, LC_Operand v) { + if (LC_IsUntyped(v.type)) v = LC_OPModDefaultUT(v); // untyped => typed + if (LC_IsSmallerThenInt(v.type)) v = LC_OPModType(v, L->tint); // c int promotion + if (v.type == L->tfloat) v = LC_OPModType(v, L->tdouble); // c int promotion + return v; +} + +LC_FUNCTION LC_Operand LC_ResolveTypeCast(LC_AST *pos, LC_Operand t, LC_Operand v) { + LC_TypeRule rule = CastingRules[GetTypeCategory(t.type)][GetTypeCategory(v.type)]; + LC_IF(rule == LC_NO, pos, "cannot cast, types are incompatible, left: '%s' right: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_RPS && v.type->size != L->tpvoid->size, pos, "cannot cast, integer type on right is not big enough to hold a pointer, left: '%s' right: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_LPS && t.type->size != L->tpvoid->size, pos, "cannot cast, integer type on left is not big enough to hold a pointer, left: '%s' right: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_SR && !LC_IsStr(t.type), pos, "cannot cast untyped string to non string type: '%s'", LC_GenLCType(t.type)); + LC_ASSERT(pos, rule == LC_LPS || rule == LC_RPS || rule == LC_OK); + + LC_Operand op = LC_OPType(t.type); + op.flags = (v.flags & LC_OPF_LValue) | (v.flags & LC_OPF_Const); + return op; +} + +LC_FUNCTION LC_Operand LC_ResolveTypeVarDecl(LC_AST *pos, LC_Operand t, LC_Operand v) { + t.v = v.v; + LC_IF(t.type && t.type->kind == LC_TypeKind_void, pos, "cannot create a variable of type void"); + LC_IF(v.type && v.type->kind == LC_TypeKind_void, pos, "cannot assign void expression to a variable"); + if (v.type && t.type) { + LC_TypeRule rule = AssignRules[GetTypeCategory(t.type)][GetTypeCategory(v.type)]; + LC_IF(rule == LC_NO, pos, "cannot assign, types are incompatible, variable type: '%s' expression type: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_RPS && v.type->size != L->tpvoid->size, pos, "cannot assign, integer type of expression is not big enough to hold a pointer, left: '%s' right: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_LPS && t.type->size != L->tpvoid->size, pos, "cannot assign, integer type of variable is not big enough to hold a pointer, left: '%s' right: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_TEQ && t.type != v.type, pos, "cannot assign, types require explicit cast, variable type: '%s' expression type: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_RO0 && v.type != L->tuntypednil, pos, "cannot assign, can assign only const integer equal to 0, variable type: '%s' expression type: '%s'", LC_GenLCType(t.type), LC_GenLCType(v.type)); + LC_IF(rule == LC_SR && !LC_IsStr(t.type), pos, "cannot assign untyped string to non string type: '%s'", LC_GenLCType(t.type)); + LC_ASSERT(pos, rule == LC_LPS || rule == LC_RPS || rule == LC_OK || rule == LC_TEQ || rule == LC_RO0 || rule == LC_SR); + return t; + } + + if (v.type) return LC_OPModDefaultUT(v); // NULL := untyped => default + if (t.type) return t; // T := NULL => T + return LC_ReportASTError(pos, "internal compiler error: failed to resolve type of variable, both type and expression are null"); +} + +LC_FUNCTION LC_Operand LC_ResolveTypeAggregate(LC_AST *pos, LC_Type *type) { + LC_Decl *decl = type->decl; + if (type->kind == LC_TypeKind_Error) return LC_OPError(); + LC_TYPE_IF(type->kind == LC_TypeKind_Completing, pos, "cyclic dependency in type '%s'", type->decl->name); + if (type->kind != LC_TypeKind_Incomplete) return LC_OPNull; + LC_PUSH_SCOPE(L->resolver.package->apackage.scope); + + LC_AST *n = decl->ast; + LC_ASSERT(n, decl); + LC_ASSERT(n, n->kind == LC_ASTKind_DeclStruct || n->kind == LC_ASTKind_DeclUnion); + int decl_stack_size = 0; + + type->kind = LC_TypeKind_Completing; + LC_ASTFor(it, n->dagg.first) { + LC_Intern name = it->tagg_mem.name; + + LC_Operand op = LC_ResolveType(it->tagg_mem.type); + if (LC_IsError(op)) { + LC_MarkDeclError(decl); + type->kind = LC_TypeKind_Error; + continue; // handle error after we go through all fields + } + + LC_Operand opc = LC_ResolveTypeAggregate(it, op.type); + if (LC_IsError(opc)) { + LC_MarkDeclError(decl); + type->kind = LC_TypeKind_Error; + continue; // handle error after we go through all fields + } + + LC_TypeMember *mem = LC_AddTypeToList(&type->tagg.mems, name, op.type, it); + LC_TYPE_IF(mem == NULL, it, "duplicate field '%s' in aggregate type '%s'", name, decl->name); + } + if (type->kind == LC_TypeKind_Error) { + return LC_OPError(); + } + LC_TYPE_IF(type->tagg.mems.count == 0, n, "aggregate type '%s' has no fields", decl->name); + decl_stack_size += type->tagg.mems.count; + + LC_AST *packed = LC_HasNote(n, L->ipacked); + if (n->kind == LC_ASTKind_DeclStruct) { + type->kind = LC_TypeKind_Struct; + int field_sizes = 0; + LC_TypeFor(it, type->tagg.mems.first) { + int mem_align = packed ? 1 : it->type->align; + LC_ASSERT(n, LC_IS_POW2(mem_align)); + type->size = (int)LC_AlignUp(type->size, mem_align); + it->offset = type->size; + field_sizes += it->type->size; + type->align = LC_MAX(type->align, mem_align); + type->size = it->type->size + (int)LC_AlignUp(type->size, mem_align); + } + type->size = (int)LC_AlignUp(type->size, type->align); + type->padding = type->size - field_sizes; + } + + if (n->kind == LC_ASTKind_DeclUnion) { + type->kind = LC_TypeKind_Union; + if (packed) LC_ReportASTError(packed, "@packed on union is invalid"); + LC_TypeFor(it, type->tagg.mems.first) { + LC_ASSERT(n, LC_IS_POW2(it->type->align)); + type->size = LC_MAX(type->size, it->type->size); + type->align = LC_MAX(type->align, it->type->align); + } + type->size = (int)LC_AlignUp(type->size, type->align); + } + + int map_size = LC_NextPow2(decl_stack_size * 2 + 1); + decl->scope = LC_CreateScope(map_size); + + LC_TypeFor(it, type->tagg.mems.first) { + LC_Decl *d = LC_CreateDecl(LC_DeclKind_Var, it->name, it->ast); + d->state = LC_DeclState_Resolved; + d->type = it->type; + d->type_member = it; + LC_AddDeclToScope(decl->scope, d); + } + + LC_ASSERT(n, decl->scope->cap == map_size); + + if (L->on_decl_type_resolved) L->on_decl_type_resolved(decl); + LC_AST *pkg = decl->package; + LC_DLLAdd(pkg->apackage.first_ordered, pkg->apackage.last_ordered, decl); + LC_POP_SCOPE(); + return LC_OPNull; +} + +#undef LC_IF +#undef LC_DECL_IF +#undef LC_PROP_ERROR +#undef LC_DECL_PROP_ERROR \ No newline at end of file diff --git a/src/compiler/resolver.c b/src/compiler/resolver.c new file mode 100644 index 0000000..5cd402d --- /dev/null +++ b/src/compiler/resolver.c @@ -0,0 +1,192 @@ +// clang-format off +#define LC_PUSH_COMP_ARRAY_SIZE(SIZE) int PREV_SIZE = L->resolver.compo_context_array_size; L->resolver.compo_context_array_size = SIZE; +#define LC_POP_COMP_ARRAY_SIZE() L->resolver.compo_context_array_size = PREV_SIZE +#define LC_PUSH_SCOPE(SCOPE) DeclScope *PREV_SCOPE = L->resolver.active_scope; L->resolver.active_scope = SCOPE +#define LC_POP_SCOPE() L->resolver.active_scope = PREV_SCOPE +#define LC_PUSH_LOCAL_SCOPE() int LOCAL_LEN = L->resolver.locals.len +#define LC_POP_LOCAL_SCOPE() L->resolver.locals.len = LOCAL_LEN +#define LC_PUSH_PACKAGE(PKG) LC_AST *PREV_PKG = L->resolver.package; L->resolver.package = PKG; LC_PUSH_SCOPE(PKG->apackage.scope) +#define LC_POP_PACKAGE() L->resolver.package = PREV_PKG; LC_POP_SCOPE() +#define LC_PROP_ERROR(OP, n, ...) OP = __VA_ARGS__; if (LC_IsError(OP)) { n->kind = LC_ASTKind_Error; return OP; } +#define LC_DECL_PROP_ERROR(OP, ...) OP = __VA_ARGS__; if (LC_IsError(OP)) { LC_MarkDeclError(decl); return OP; } + +#define LC_IF(COND, N, ...) if (COND) { LC_Operand R_ = LC_ReportASTError(N, __VA_ARGS__); N->kind = LC_ASTKind_Error; return R_; } +#define LC_DECL_IF(COND, ...) if (COND) { LC_MarkDeclError(decl); return LC_ReportASTError(__VA_ARGS__); } +#define LC_TYPE_IF(COND, ...) if (COND) { LC_MarkDeclError(decl); type->kind = LC_TypeKind_Error; return LC_ReportASTError(__VA_ARGS__); } +// clang-format on + +LC_FUNCTION void LC_AddDecl(LC_DeclStack *scope, LC_Decl *decl) { + if (scope->len + 1 > scope->cap) { + LC_ASSERT(NULL, scope->cap); + int new_cap = scope->cap * 2; + LC_Decl **new_stack = LC_PushArray(L->arena, LC_Decl *, new_cap); + LC_MemoryCopy(new_stack, scope->stack, scope->len * sizeof(LC_Decl *)); + scope->stack = new_stack; + scope->cap = new_cap; + } + scope->stack[scope->len++] = decl; +} + +LC_FUNCTION void LC_InitDeclStack(LC_DeclStack *stack, int size) { + stack->stack = LC_PushArray(L->arena, LC_Decl *, size); + stack->cap = size; +} + +LC_FUNCTION LC_DeclStack *LC_CreateDeclStack(int size) { + LC_DeclStack *stack = LC_PushStruct(L->arena, LC_DeclStack); + LC_InitDeclStack(stack, size); + return stack; +} + +LC_FUNCTION LC_Decl *LC_FindDeclOnStack(LC_DeclStack *scp, LC_Intern name) { + for (int i = 0; i < scp->len; i += 1) { + LC_Decl *it = scp->stack[i]; + if (it->name == name) { + return it; + } + } + return NULL; +} + +LC_FUNCTION void LC_MarkDeclError(LC_Decl *decl) { + if (decl) { + decl->kind = LC_DeclKind_Error; + decl->state = LC_DeclState_Error; + if (decl->ast) decl->ast->kind = LC_ASTKind_Error; + } +} + +LC_FUNCTION LC_Decl *LC_CreateDecl(LC_DeclKind kind, LC_Intern name, LC_AST *n) { + LC_Decl *decl = LC_PushStruct(L->decl_arena, LC_Decl); + L->decl_count += 1; + + decl->name = name; + decl->kind = kind; + decl->ast = n; + decl->package = L->resolver.package; + LC_ASSERT(n, decl->package); + + LC_AST *note = LC_HasNote(n, L->iforeign); + if (note) { + decl->is_foreign = true; + if (note->anote.first) { + if (note->anote.size != 1) LC_ReportASTError(note, "invalid format of @foreign(...), more then 1 argument"); + LC_AST *expr = note->anote.first->ecompo_item.expr; + if (expr->kind == LC_ASTKind_ExprIdent) decl->foreign_name = expr->eident.name; + if (expr->kind != LC_ASTKind_ExprIdent) LC_ReportASTError(note, "invalid format of @foreign(...), expected identifier"); + } + } + if (!decl->foreign_name) decl->foreign_name = decl->name; + return decl; +} + +LC_FUNCTION LC_Operand LC_ThereIsNoDecl(DeclScope *scp, LC_Decl *decl, bool check_locals) { + LC_Decl *r = (LC_Decl *)LC_MapGetU64(scp, decl->name); + if (check_locals && !r) { + r = LC_FindDeclOnStack(&L->resolver.locals, decl->name); + } + if (r) { + LC_MarkDeclError(r); + LC_MarkDeclError(decl); + return LC_ReportASTErrorEx(decl->ast, r->ast, "there are 2 decls with the same name '%s'", decl->name); + } + return LC_OPNull; +} + +LC_FUNCTION LC_Operand LC_AddDeclToScope(DeclScope *scp, LC_Decl *decl) { + LC_Operand LC_DECL_PROP_ERROR(op, LC_ThereIsNoDecl(scp, decl, false)); + LC_MapInsertU64(scp, decl->name, decl); + return LC_OPDecl(decl); +} + +LC_FUNCTION DeclScope *LC_CreateScope(int size) { + DeclScope *scope = LC_PushStruct(L->arena, DeclScope); + scope->arena = L->arena; + LC_MapReserve(scope, size); + return scope; +} + +LC_FUNCTION LC_Decl *LC_FindDeclInScope(DeclScope *scope, LC_Intern name) { + LC_Decl *decl = (LC_Decl *)LC_MapGetU64(scope, name); + return decl; +} + +LC_FUNCTION LC_Decl *LC_GetLocalOrGlobalDecl(LC_Intern name) { + LC_Decl *decl = LC_FindDeclInScope(L->resolver.active_scope, name); + if (!decl && L->resolver.package->apackage.scope == L->resolver.active_scope) { + decl = LC_FindDeclOnStack(&L->resolver.locals, name); + } + return decl; +} + +LC_FUNCTION LC_Operand LC_PutGlobalDecl(LC_Decl *decl) { + LC_Operand LC_DECL_PROP_ERROR(op, LC_AddDeclToScope(L->resolver.package->apackage.scope, decl)); + + // :Mangle global scope name + if (!decl->is_foreign && decl->package != L->builtin_package) { + bool mangle = true; + if (LC_HasNote(decl->ast, L->idont_mangle)) mangle = false; + if (LC_HasNote(decl->ast, L->iapi)) mangle = false; + if (decl->name == L->imain) { + if (L->first_package) { + if (L->first_package == decl->package->apackage.name) { + mangle = false; + } + } else mangle = false; + } + if (mangle) { + LC_String name = LC_Format(L->arena, "lc_%s_%s", (char *)decl->package->apackage.name, (char *)decl->name); + decl->foreign_name = LC_InternStrLen(name.str, (int)name.len); + } + } + + LC_Decl *conflict = (LC_Decl *)LC_MapGetU64(&L->foreign_names, decl->foreign_name); + if (conflict && !decl->is_foreign) { + LC_ReportASTErrorEx(decl->ast, conflict->ast, "found two global declarations with the same foreign name: %s", decl->foreign_name); + } else { + LC_MapInsertU64(&L->foreign_names, decl->foreign_name, decl); + } + + return op; +} + +LC_FUNCTION LC_Operand LC_CreateLocalDecl(LC_DeclKind kind, LC_Intern name, LC_AST *ast) { + LC_Decl *decl = LC_CreateDecl(kind, name, ast); + decl->state = LC_DeclState_Resolving; + LC_Operand LC_DECL_PROP_ERROR(operr0, LC_ThereIsNoDecl(L->resolver.package->apackage.scope, decl, true)); + LC_AddDecl(&L->resolver.locals, decl); + return LC_OPDecl(decl); +} + +LC_FUNCTION LC_Decl *LC_AddConstIntDecl(char *key, int64_t value) { + LC_Intern intern = LC_ILit(key); + LC_Decl *decl = LC_CreateDecl(LC_DeclKind_Const, intern, &L->NullAST); + decl->state = LC_DeclState_Resolved; + decl->type = L->tuntypedint; + LC_Bigint_init_signed(&decl->v.i, value); + LC_AddDeclToScope(L->resolver.package->apackage.scope, decl); + return decl; +} + +LC_FUNCTION LC_Decl *LC_GetBuiltin(LC_Intern name) { + LC_Decl *decl = (LC_Decl *)LC_MapGetU64(L->builtin_package->apackage.scope, name); + return decl; +} + +LC_FUNCTION void LC_AddBuiltinConstInt(char *key, int64_t value) { + LC_PUSH_PACKAGE(L->builtin_package); + LC_AddConstIntDecl(key, value); + LC_POP_PACKAGE(); +} + +LC_FUNCTION LC_AST *LC_HasNote(LC_AST *ast, LC_Intern i) { + if (ast && ast->notes) { + LC_ASTFor(it, ast->notes->anote_list.first) { + LC_ASSERT(it, "internal compiler error: note is not an identifier"); + if (it->anote.name->eident.name == i) { + return it; + } + } + } + return NULL; +} diff --git a/src/compiler/string.c b/src/compiler/string.c new file mode 100644 index 0000000..0c37730 --- /dev/null +++ b/src/compiler/string.c @@ -0,0 +1,422 @@ +LC_FUNCTION int64_t LC__ClampTop(int64_t val, int64_t max) { + if (val > max) val = max; + return val; +} + +LC_FUNCTION char LC_ToLowerCase(char a) { + if (a >= 'A' && a <= 'Z') a += 32; + return a; +} + +LC_FUNCTION char LC_ToUpperCase(char a) { + if (a >= 'a' && a <= 'z') a -= 32; + return a; +} + +LC_FUNCTION bool LC_IsWhitespace(char w) { + bool result = w == '\n' || w == ' ' || w == '\t' || w == '\v' || w == '\r'; + return result; +} + +LC_FUNCTION bool LC_IsAlphabetic(char a) { + bool result = (a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z'); + return result; +} + +LC_FUNCTION bool LC_IsIdent(char a) { + bool result = (a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z') || a == '_'; + return result; +} + +LC_FUNCTION bool LC_IsDigit(char a) { + bool result = a >= '0' && a <= '9'; + return result; +} + +LC_FUNCTION bool LC_IsAlphanumeric(char a) { + bool result = LC_IsDigit(a) || LC_IsAlphabetic(a); + return result; +} + +LC_FUNCTION bool LC_AreEqual(LC_String a, LC_String b, unsigned ignore_case) { + if (a.len != b.len) return false; + for (int64_t i = 0; i < a.len; i++) { + char A = a.str[i]; + char B = b.str[i]; + if (ignore_case) { + A = LC_ToLowerCase(A); + B = LC_ToLowerCase(B); + } + if (A != B) + return false; + } + return true; +} + +LC_FUNCTION bool LC_EndsWith(LC_String a, LC_String end, unsigned ignore_case) { + LC_String a_end = LC_GetPostfix(a, end.len); + bool result = LC_AreEqual(end, a_end, ignore_case); + return result; +} + +LC_FUNCTION bool LC_StartsWith(LC_String a, LC_String start, unsigned ignore_case) { + LC_String a_start = LC_GetPrefix(a, start.len); + bool result = LC_AreEqual(start, a_start, ignore_case); + return result; +} + +LC_FUNCTION LC_String LC_MakeString(char *str, int64_t len) { + LC_String result; + result.str = (char *)str; + result.len = len; + return result; +} + +LC_FUNCTION LC_String LC_CopyString(LC_Arena *allocator, LC_String string) { + char *copy = (char *)LC_PushSize(allocator, sizeof(char) * (string.len + 1)); + LC_MemoryCopy(copy, string.str, string.len); + copy[string.len] = 0; + LC_String result = LC_MakeString(copy, string.len); + return result; +} + +LC_FUNCTION LC_String LC_CopyChar(LC_Arena *allocator, char *s) { + int64_t len = LC_StrLen(s); + char *copy = (char *)LC_PushSize(allocator, sizeof(char) * (len + 1)); + LC_MemoryCopy(copy, s, len); + copy[len] = 0; + LC_String result = LC_MakeString(copy, len); + return result; +} + +LC_FUNCTION LC_String LC_NormalizePath(LC_Arena *allocator, LC_String s) { + LC_String copy = LC_CopyString(allocator, s); + for (int64_t i = 0; i < copy.len; i++) { + if (copy.str[i] == '\\') + copy.str[i] = '/'; + } + return copy; +} + +LC_FUNCTION void LC_NormalizePathUnsafe(LC_String s) { + for (int64_t i = 0; i < s.len; i++) { + if (s.str[i] == '\\') + s.str[i] = '/'; + } +} + +LC_FUNCTION LC_String LC_Chop(LC_String string, int64_t len) { + len = LC__ClampTop(len, string.len); + LC_String result = LC_MakeString(string.str, string.len - len); + return result; +} + +LC_FUNCTION LC_String LC_Skip(LC_String string, int64_t len) { + len = LC__ClampTop(len, string.len); + int64_t remain = string.len - len; + LC_String result = LC_MakeString(string.str + len, remain); + return result; +} + +LC_FUNCTION LC_String LC_GetPostfix(LC_String string, int64_t len) { + len = LC__ClampTop(len, string.len); + int64_t remain_len = string.len - len; + LC_String result = LC_MakeString(string.str + remain_len, len); + return result; +} + +LC_FUNCTION LC_String LC_GetPrefix(LC_String string, int64_t len) { + len = LC__ClampTop(len, string.len); + LC_String result = LC_MakeString(string.str, len); + return result; +} + +LC_FUNCTION LC_String LC_GetNameNoExt(LC_String s) { + return LC_SkipToLastSlash(LC_ChopLastPeriod(s)); +} + +LC_FUNCTION LC_String LC_Slice(LC_String string, int64_t first_index, int64_t one_past_last_index) { + if (one_past_last_index < 0) one_past_last_index = string.len + one_past_last_index + 1; + if (first_index < 0) first_index = string.len + first_index; + LC_ASSERT(NULL, first_index < one_past_last_index && "LC_Slice, first_index is bigger then one_past_last_index"); + LC_ASSERT(NULL, string.len > 0 && "Slicing string of length 0! Might be an error!"); + LC_String result = string; + if (string.len > 0) { + if (one_past_last_index > first_index) { + first_index = LC__ClampTop(first_index, string.len - 1); + one_past_last_index = LC__ClampTop(one_past_last_index, string.len); + result.str += first_index; + result.len = one_past_last_index - first_index; + } else { + result.len = 0; + } + } + return result; +} + +LC_FUNCTION bool LC_Seek(LC_String string, LC_String find, LC_FindFlag flags, int64_t *index_out) { + bool ignore_case = flags & LC_FindFlag_IgnoreCase ? true : false; + bool result = false; + if (flags & LC_FindFlag_MatchFindLast) { + for (int64_t i = string.len; i != 0; i--) { + int64_t index = i - 1; + LC_String substring = LC_Slice(string, index, index + find.len); + if (LC_AreEqual(substring, find, ignore_case)) { + if (index_out) + *index_out = index; + result = true; + break; + } + } + } else { + for (int64_t i = 0; i < string.len; i++) { + LC_String substring = LC_Slice(string, i, i + find.len); + if (LC_AreEqual(substring, find, ignore_case)) { + if (index_out) + *index_out = i; + result = true; + break; + } + } + } + + return result; +} + +LC_FUNCTION int64_t LC_Find(LC_String string, LC_String find, LC_FindFlag flag) { + int64_t result = -1; + LC_Seek(string, find, flag, &result); + return result; +} + +LC_FUNCTION LC_StringList LC_Split(LC_Arena *allocator, LC_String string, LC_String find, LC_SplitFlag flags) { + LC_StringList result = LC_MakeEmptyList(); + int64_t index = 0; + + LC_FindFlag find_flag = flags & LC_SplitFlag_IgnoreCase ? LC_FindFlag_IgnoreCase : LC_FindFlag_None; + while (LC_Seek(string, find, find_flag, &index)) { + LC_String before_match = LC_MakeString(string.str, index); + LC_AddNode(allocator, &result, before_match); + if (flags & LC_SplitFlag_SplitInclusive) { + LC_String match = LC_MakeString(string.str + index, find.len); + LC_AddNode(allocator, &result, match); + } + string = LC_Skip(string, index + find.len); + } + if (string.len) LC_AddNode(allocator, &result, string); + return result; +} + +LC_FUNCTION LC_String LC_MergeWithSeparator(LC_Arena *allocator, LC_StringList list, LC_String separator) { + if (list.node_count == 0) return LC_MakeEmptyString(); + if (list.char_count == 0) return LC_MakeEmptyString(); + + int64_t base_size = (list.char_count + 1); + int64_t sep_size = (list.node_count - 1) * separator.len; + int64_t size = base_size + sep_size; + char *buff = (char *)LC_PushSize(allocator, sizeof(char) * (size + 1)); + LC_String string = LC_MakeString(buff, 0); + for (LC_StringNode *it = list.first; it; it = it->next) { + LC_ASSERT(NULL, string.len + it->string.len <= size); + LC_MemoryCopy(string.str + string.len, it->string.str, it->string.len); + string.len += it->string.len; + if (it != list.last) { + LC_MemoryCopy(string.str + string.len, separator.str, separator.len); + string.len += separator.len; + } + } + LC_ASSERT(NULL, string.len == size - 1); + string.str[size] = 0; + return string; +} + +LC_FUNCTION LC_String LC_MergeString(LC_Arena *allocator, LC_StringList list) { + return LC_MergeWithSeparator(allocator, list, LC_Lit("")); +} + +LC_FUNCTION LC_String LC_ChopLastSlash(LC_String s) { + LC_String result = s; + LC_Seek(s, LC_Lit("/"), LC_FindFlag_MatchFindLast, &result.len); + return result; +} + +LC_FUNCTION LC_String LC_ChopLastPeriod(LC_String s) { + LC_String result = s; + LC_Seek(s, LC_Lit("."), LC_FindFlag_MatchFindLast, &result.len); + return result; +} + +LC_FUNCTION LC_String LC_SkipToLastSlash(LC_String s) { + int64_t pos; + LC_String result = s; + if (LC_Seek(s, LC_Lit("/"), LC_FindFlag_MatchFindLast, &pos)) { + result = LC_Skip(result, pos + 1); + } + return result; +} + +LC_FUNCTION LC_String LC_SkipToLastPeriod(LC_String s) { + int64_t pos; + LC_String result = s; + if (LC_Seek(s, LC_Lit("."), LC_FindFlag_MatchFindLast, &pos)) { + result = LC_Skip(result, pos + 1); + } + return result; +} + +LC_FUNCTION int64_t LC_StrLen(char *string) { + int64_t len = 0; + while (*string++ != 0) + len++; + return len; +} + +LC_FUNCTION LC_String LC_MakeFromChar(char *string) { + LC_String result; + result.str = (char *)string; + result.len = LC_StrLen(string); + return result; +} + +LC_FUNCTION LC_String LC_MakeEmptyString(void) { + return LC_MakeString(0, 0); +} + +LC_FUNCTION LC_StringList LC_MakeEmptyList(void) { + LC_StringList result; + result.first = 0; + result.last = 0; + result.char_count = 0; + result.node_count = 0; + return result; +} + +LC_FUNCTION LC_String LC_FormatV(LC_Arena *allocator, const char *str, va_list args1) { + va_list args2; + va_copy(args2, args1); + int64_t len = LC_vsnprintf(0, 0, str, args2); + va_end(args2); + + char *result = (char *)LC_PushSize(allocator, sizeof(char) * (len + 1)); + LC_vsnprintf(result, (int)(len + 1), str, args1); + LC_String res = LC_MakeString(result, len); + return res; +} + +LC_FUNCTION LC_String LC_Format(LC_Arena *allocator, const char *str, ...) { + LC_FORMAT(allocator, str, result); + return result; +} + +LC_FUNCTION LC_StringNode *LC_CreateNode(LC_Arena *allocator, LC_String string) { + LC_StringNode *result = (LC_StringNode *)LC_PushSize(allocator, sizeof(LC_StringNode)); + result->string = string; + result->next = 0; + return result; +} + +LC_FUNCTION void LC_ReplaceNodeString(LC_StringList *list, LC_StringNode *node, LC_String new_string) { + list->char_count -= node->string.len; + list->char_count += new_string.len; + node->string = new_string; +} + +LC_FUNCTION void LC_AddExistingNode(LC_StringList *list, LC_StringNode *node) { + if (list->first) { + list->last->next = node; + list->last = list->last->next; + } else { + list->first = list->last = node; + } + list->node_count += 1; + list->char_count += node->string.len; +} + +LC_FUNCTION void LC_AddArray(LC_Arena *allocator, LC_StringList *list, char **array, int count) { + for (int i = 0; i < count; i += 1) { + LC_String s = LC_MakeFromChar(array[i]); + LC_AddNode(allocator, list, s); + } +} + +LC_FUNCTION void LC_AddArrayWithPrefix(LC_Arena *allocator, LC_StringList *list, char *prefix, char **array, int count) { + for (int i = 0; i < count; i += 1) { + LC_Addf(allocator, list, "%s%s", prefix, array[i]); + } +} + +LC_FUNCTION LC_StringList LC_MakeList(LC_Arena *allocator, LC_String a) { + LC_StringList result = LC_MakeEmptyList(); + LC_AddNode(allocator, &result, a); + return result; +} + +LC_FUNCTION LC_StringList LC_CopyList(LC_Arena *allocator, LC_StringList a) { + LC_StringList result = LC_MakeEmptyList(); + for (LC_StringNode *it = a.first; it; it = it->next) LC_AddNode(allocator, &result, it->string); + return result; +} + +LC_FUNCTION LC_StringList LC_ConcatLists(LC_Arena *allocator, LC_StringList a, LC_StringList b) { + LC_StringList result = LC_MakeEmptyList(); + for (LC_StringNode *it = a.first; it; it = it->next) LC_AddNode(allocator, &result, it->string); + for (LC_StringNode *it = b.first; it; it = it->next) LC_AddNode(allocator, &result, it->string); + return result; +} + +LC_FUNCTION LC_StringNode *LC_AddNode(LC_Arena *allocator, LC_StringList *list, LC_String string) { + LC_StringNode *node = LC_CreateNode(allocator, string); + LC_AddExistingNode(list, node); + return node; +} + +LC_FUNCTION LC_StringNode *LC_Add(LC_Arena *allocator, LC_StringList *list, LC_String string) { + LC_String copy = LC_CopyString(allocator, string); + LC_StringNode *node = LC_CreateNode(allocator, copy); + LC_AddExistingNode(list, node); + return node; +} + +LC_FUNCTION LC_String LC_Addf(LC_Arena *allocator, LC_StringList *list, const char *str, ...) { + LC_FORMAT(allocator, str, result); + LC_AddNode(allocator, list, result); + return result; +} + +LC_FUNCTION LC_String16 LC_ToWidecharEx(LC_Arena *allocator, LC_String string) { + LC_ASSERT(NULL, sizeof(wchar_t) == 2); + wchar_t *buffer = (wchar_t *)LC_PushSize(allocator, sizeof(wchar_t) * (string.len + 1)); + int64_t size = LC_CreateWidecharFromChar(buffer, string.len + 1, string.str, string.len); + LC_String16 result = {buffer, size}; + return result; +} + +LC_FUNCTION wchar_t *LC_ToWidechar(LC_Arena *allocator, LC_String string) { + LC_String16 result = LC_ToWidecharEx(allocator, string); + return result.str; +} + +LC_FUNCTION LC_String LC_FromWidecharEx(LC_Arena *allocator, wchar_t *wstring, int64_t wsize) { + LC_ASSERT(NULL, sizeof(wchar_t) == 2); + + int64_t buffer_size = (wsize + 1) * 2; + char *buffer = (char *)LC_PushSize(allocator, buffer_size); + int64_t size = LC_CreateCharFromWidechar(buffer, buffer_size, wstring, wsize); + LC_String result = LC_MakeString(buffer, size); + + LC_ASSERT(NULL, size < buffer_size); + return result; +} + +LC_FUNCTION int64_t LC_WideLength(wchar_t *string) { + int64_t len = 0; + while (*string++ != 0) + len++; + return len; +} + +LC_FUNCTION LC_String LC_FromWidechar(LC_Arena *allocator, wchar_t *wstring) { + int64_t size = LC_WideLength(wstring); + LC_String result = LC_FromWidecharEx(allocator, wstring, size); + return result; +} diff --git a/src/compiler/to_string.c b/src/compiler/to_string.c new file mode 100644 index 0000000..6c328a8 --- /dev/null +++ b/src/compiler/to_string.c @@ -0,0 +1,277 @@ +LC_FUNCTION const char *LC_OSToString(LC_OS os) { + switch (os) { + case LC_OS_WINDOWS: return "OS_WINDOWS"; + case LC_OS_LINUX: return "OS_LINUX"; + case LC_OS_MAC: return "OS_MAC"; + default: return "UNKNOWN_OPERATING_SYSTEM"; + } +} + +LC_FUNCTION const char *LC_GENToString(LC_GEN os) { + switch (os) { + case LC_GEN_C: return "GEN_C"; + default: return "UNKNOWN_GENERATOR"; + } +} + +LC_FUNCTION const char *LC_ARCHToString(LC_ARCH arch) { + switch (arch) { + case LC_ARCH_X86: return "ARCH_X86"; + case LC_ARCH_X64: return "ARCH_X64"; + default: return "UNKNOWN_ARCHITECTURE"; + } +} + +LC_FUNCTION const char *LC_ASTKindToString(LC_ASTKind kind) { + static const char *strs[] = { + "ast null", + "ast error", + "ast note", + "ast note list", + "ast file", + "ast package", + "ast ignore", + "typespec procdure argument", + "typespec aggregate member", + "expr call item", + "expr compound item", + "expr note", + "stmt switch case", + "stmt switch default", + "stmt else if", + "stmt else", + "import", + "global note", + "decl proc", + "decl struct", + "decl union", + "decl var", + "decl const", + "decl typedef", + "typespec ident", + "typespec field", + "typespec pointer", + "typespec array", + "typespec proc", + "stmt block", + "stmt note", + "stmt return", + "stmt break", + "stmt continue", + "stmt defer", + "stmt for", + "stmt if", + "stmt switch", + "stmt assign", + "stmt expr", + "stmt var", + "stmt const", + "expr ident", + "expr string", + "expr int", + "expr float", + "expr bool", + "expr type", + "expr binary", + "expr unary", + "expr builtin", + "expr call", + "expr compound", + "expr cast", + "expr field", + "expr index", + "expr pointerindex", + "expr getvalueofpointer", + "expr getpointerofvalue", + }; + if (kind < 0 || kind >= LC_ASTKind_Count) { + return ""; + } + return strs[kind]; +} + +LC_FUNCTION const char *LC_TypeKindToString(LC_TypeKind kind) { + static const char *strs[] = { + "LC_TypeKind_char", + "LC_TypeKind_uchar", + "LC_TypeKind_short", + "LC_TypeKind_ushort", + "LC_TypeKind_bool", + "LC_TypeKind_int", + "LC_TypeKind_uint", + "LC_TypeKind_long", + "LC_TypeKind_ulong", + "LC_TypeKind_llong", + "LC_TypeKind_ullong", + "LC_TypeKind_float", + "LC_TypeKind_double", + "LC_TypeKind_void", + "LC_TypeKind_Struct", + "LC_TypeKind_Union", + "LC_TypeKind_Pointer", + "LC_TypeKind_Array", + "LC_TypeKind_Proc", + "LC_TypeKind_UntypedInt", + "LC_TypeKind_UntypedFloat", + "LC_TypeKind_UntypedString", + "LC_TypeKind_Incomplete", + "LC_TypeKind_Completing", + "LC_TypeKind_Error", + }; + if (kind < 0 || kind >= T_TotalCount) { + return ""; + } + return strs[kind]; +} + +LC_FUNCTION const char *LC_DeclKindToString(LC_DeclKind decl_kind) { + static const char *strs[] = { + "declaration of error kind", + "type declaration", + "const declaration", + "variable declaration", + "procedure declaration", + "import declaration", + }; + if (decl_kind < 0 || decl_kind >= LC_DeclKind_Count) { + return ""; + } + return strs[decl_kind]; +} + +LC_FUNCTION const char *LC_TokenKindToString(LC_TokenKind token_kind) { + static const char *strs[] = { + "end of file", + "token error", + "comment", + "doc comment", + "file doc comment", + "package doc comment", + "note '@'", + "hash '#'", + "identifier", + "keyword", + "string literal", + "raw string literal", + "integer literal", + "float literal", + "unicode literal", + "open paren '('", + "close paren ')'", + "open brace '{'", + "close brace '}'", + "open bracket '['", + "close bracket ']'", + "comma ','", + "question mark '?'", + "semicolon ';'", + "period '.'", + "three dots '...'", + "colon ':'", + "multiply '*'", + "divide '/'", + "modulo '%'", + "left shift '<<'", + "right shift '>>'", + "add '+'", + "subtract '-'", + "equals '=='", + "lesser then '<'", + "greater then '>'", + "lesser then or equal '<='", + "greater then or equal '>='", + "not equal '!='", + "bit and '&'", + "bit or '|'", + "bit xor '^'", + "and '&&'", + "or '||'", + "addptr keyword", + "negation '~'", + "exclamation '!'", + "assignment '='", + "assignment '/='", + "assignment '*='", + "assignment '%='", + "assignment '-='", + "assignment '+='", + "assignment '&='", + "assignment '|='", + "assignment '^='", + "assignment '<<='", + "assignment '>>='", + }; + + if (token_kind < 0 || token_kind >= LC_TokenKind_Count) { + return ""; + } + return strs[token_kind]; +} + +LC_FUNCTION const char *LC_TokenKindToOperator(LC_TokenKind token_kind) { + static const char *strs[] = { + "end of file", + "token error", + "comment", + "doc comment", + "file doc comment", + "package doc comment", + "@", + "#", + "identifier", + "keyword", + "string literal", + "raw string literal", + "integer literal", + "float literal", + "unicode literal", + "(", + ")", + "{", + "}", + "[", + "]", + ",", + "?", + ";", + ".", + "...", + ":", + "*", + "/", + "%", + "<<", + ">>", + "+", + "-", + "==", + "<", + ">", + "<=", + ">=", + "!=", + "&", + "|", + "^", + "&&", + "||", + "+", + "~", + "!", + "=", + "/=", + "*=", + "%=", + "-=", + "+=", + "&=", + "|=", + "^=", + "<<=", + ">>=", + }; + if (token_kind < 0 || token_kind >= LC_TokenKind_Count) { + return ""; + } + return strs[token_kind]; +} diff --git a/src/compiler/unicode.c b/src/compiler/unicode.c new file mode 100644 index 0000000..e1442c5 --- /dev/null +++ b/src/compiler/unicode.c @@ -0,0 +1,158 @@ +LC_FUNCTION LC_UTF32Result LC_ConvertUTF16ToUTF32(uint16_t *c, int max_advance) { + LC_UTF32Result result; + LC_MemoryZero(&result, sizeof(result)); + if (max_advance >= 1) { + result.advance = 1; + result.out_str = c[0]; + if (c[0] >= 0xD800 && c[0] <= 0xDBFF && c[1] >= 0xDC00 && c[1] <= 0xDFFF) { + if (max_advance >= 2) { + result.out_str = 0x10000; + result.out_str += (uint32_t)(c[0] & 0x03FF) << 10u | (c[1] & 0x03FF); + result.advance = 2; + } else + result.error = 2; + } + } else { + result.error = 1; + } + return result; +} + +LC_FUNCTION LC_UTF8Result LC_ConvertUTF32ToUTF8(uint32_t codepoint) { + LC_UTF8Result result; + LC_MemoryZero(&result, sizeof(result)); + + if (codepoint <= 0x7F) { + result.len = 1; + result.out_str[0] = (char)codepoint; + } else if (codepoint <= 0x7FF) { + result.len = 2; + result.out_str[0] = 0xc0 | (0x1f & (codepoint >> 6)); + result.out_str[1] = 0x80 | (0x3f & codepoint); + } else if (codepoint <= 0xFFFF) { // 16 bit word + result.len = 3; + result.out_str[0] = 0xe0 | (0xf & (codepoint >> 12)); // 4 bits + result.out_str[1] = 0x80 | (0x3f & (codepoint >> 6)); // 6 bits + result.out_str[2] = 0x80 | (0x3f & codepoint); // 6 bits + } else if (codepoint <= 0x10FFFF) { // 21 bit word + result.len = 4; + result.out_str[0] = 0xf0 | (0x7 & (codepoint >> 18)); // 3 bits + result.out_str[1] = 0x80 | (0x3f & (codepoint >> 12)); // 6 bits + result.out_str[2] = 0x80 | (0x3f & (codepoint >> 6)); // 6 bits + result.out_str[3] = 0x80 | (0x3f & codepoint); // 6 bits + } else { + result.error = 1; + } + + return result; +} + +LC_FUNCTION LC_UTF32Result LC_ConvertUTF8ToUTF32(char *c, int max_advance) { + LC_UTF32Result result; + LC_MemoryZero(&result, sizeof(result)); + + if ((c[0] & 0x80) == 0) { // Check if leftmost zero of first byte is unset + if (max_advance >= 1) { + result.out_str = c[0]; + result.advance = 1; + } else result.error = 1; + } + + else if ((c[0] & 0xe0) == 0xc0) { + if ((c[1] & 0xc0) == 0x80) { // Continuation byte required + if (max_advance >= 2) { + result.out_str = (uint32_t)(c[0] & 0x1f) << 6u | (c[1] & 0x3f); + result.advance = 2; + } else result.error = 2; + } else result.error = 2; + } + + else if ((c[0] & 0xf0) == 0xe0) { + if ((c[1] & 0xc0) == 0x80 && (c[2] & 0xc0) == 0x80) { // Two continuation bytes required + if (max_advance >= 3) { + result.out_str = (uint32_t)(c[0] & 0xf) << 12u | (uint32_t)(c[1] & 0x3f) << 6u | (c[2] & 0x3f); + result.advance = 3; + } else result.error = 3; + } else result.error = 3; + } + + else if ((c[0] & 0xf8) == 0xf0) { + if ((c[1] & 0xc0) == 0x80 && (c[2] & 0xc0) == 0x80 && (c[3] & 0xc0) == 0x80) { // Three continuation bytes required + if (max_advance >= 4) { + result.out_str = (uint32_t)(c[0] & 0xf) << 18u | (uint32_t)(c[1] & 0x3f) << 12u | (uint32_t)(c[2] & 0x3f) << 6u | (uint32_t)(c[3] & 0x3f); + result.advance = 4; + } else result.error = 4; + } else result.error = 4; + } else result.error = 4; + + return result; +} + +LC_FUNCTION LC_UTF16Result LC_ConvertUTF32ToUTF16(uint32_t codepoint) { + LC_UTF16Result result; + LC_MemoryZero(&result, sizeof(result)); + if (codepoint < 0x10000) { + result.out_str[0] = (uint16_t)codepoint; + result.out_str[1] = 0; + result.len = 1; + } else if (codepoint <= 0x10FFFF) { + uint32_t code = (codepoint - 0x10000); + result.out_str[0] = (uint16_t)(0xD800 | (code >> 10)); + result.out_str[1] = (uint16_t)(0xDC00 | (code & 0x3FF)); + result.len = 2; + } else { + result.error = 1; + } + + return result; +} + +#define LC__HANDLE_DECODE_ERROR(question_mark) \ + { \ + if (outlen < buffer_size - 1) buffer[outlen++] = (question_mark); \ + break; \ + } + +LC_FUNCTION int64_t LC_CreateCharFromWidechar(char *buffer, int64_t buffer_size, wchar_t *in, int64_t inlen) { + int64_t outlen = 0; + for (int64_t i = 0; i < inlen && in[i];) { + LC_UTF32Result decode = LC_ConvertUTF16ToUTF32((uint16_t *)(in + i), (int)(inlen - i)); + if (!decode.error) { + i += decode.advance; + LC_UTF8Result encode = LC_ConvertUTF32ToUTF8(decode.out_str); + if (!encode.error) { + for (int64_t j = 0; j < encode.len; j++) { + if (outlen < buffer_size - 1) { + buffer[outlen++] = encode.out_str[j]; + } + } + } else LC__HANDLE_DECODE_ERROR('?'); + } else LC__HANDLE_DECODE_ERROR('?'); + } + + buffer[outlen] = 0; + return outlen; +} + +LC_FUNCTION int64_t LC_CreateWidecharFromChar(wchar_t *buffer, int64_t buffer_size, char *in, int64_t inlen) { + int64_t outlen = 0; + for (int64_t i = 0; i < inlen;) { + LC_UTF32Result decode = LC_ConvertUTF8ToUTF32(in + i, (int)(inlen - i)); + if (!decode.error) { + i += decode.advance; + LC_UTF16Result encode = LC_ConvertUTF32ToUTF16(decode.out_str); + if (!encode.error) { + for (int64_t j = 0; j < encode.len; j++) { + if (outlen < buffer_size - 1) { + buffer[outlen++] = encode.out_str[j]; + } + } + } else LC__HANDLE_DECODE_ERROR(0x003f); + } else LC__HANDLE_DECODE_ERROR(0x003f); + } + + buffer[outlen] = 0; + return outlen; +} + +#undef LC__HANDLE_DECODE_ERROR \ No newline at end of file diff --git a/src/compiler/unix_arena.c b/src/compiler/unix_arena.c new file mode 100644 index 0000000..ec6ee0a --- /dev/null +++ b/src/compiler/unix_arena.c @@ -0,0 +1,30 @@ +#define LC_V_UNIX_PAGE_SIZE 4096 + +LC_FUNCTION LC_VMemory LC_VReserve(size_t size) { + LC_VMemory result = {}; + size_t size_aligned = LC_AlignUp(size, LC_V_UNIX_PAGE_SIZE); + result.data = (uint8_t *)mmap(0, size_aligned, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + LC_Assertf(result.data, "Failed to reserve memory using mmap!!"); + if (result.data) { + result.reserve = size_aligned; + } + return result; +} + +LC_FUNCTION bool LC_VCommit(LC_VMemory *m, size_t commit) { + uint8_t *pointer = LC_V_AdvanceCommit(m, &commit, LC_V_UNIX_PAGE_SIZE); + if (pointer) { + int mprotect_result = mprotect(pointer, commit, PROT_READ | PROT_WRITE); + LC_Assertf(mprotect_result == 0, "Failed to commit more memory using mmap"); + if (mprotect_result == 0) { + m->commit += commit; + return true; + } + } + return false; +} + +LC_FUNCTION void LC_VDeallocate(LC_VMemory *m) { + int result = munmap(m->data, m->reserve); + LC_Assertf(result == 0, "Failed to release virtual memory using munmap"); +} \ No newline at end of file diff --git a/src/compiler/unix_filesystem.c b/src/compiler/unix_filesystem.c new file mode 100644 index 0000000..945df19 --- /dev/null +++ b/src/compiler/unix_filesystem.c @@ -0,0 +1,89 @@ +LC_FUNCTION bool LC_EnableTerminalColors(void) { + return true; +} + +LC_FUNCTION bool LC_IsDir(LC_Arena *arena, LC_String path) { + bool result = false; + LC_TempArena ch = LC_BeginTemp(arena); + LC_String copy = LC_CopyString(arena, path); + + struct stat s; + if (stat(copy.str, &s) != 0) { + result = false; + } else { + result = S_ISDIR(s.st_mode); + } + + LC_EndTemp(ch); + return result; +} + +LC_FUNCTION LC_String LC_GetAbsolutePath(LC_Arena *arena, LC_String relative) { + LC_String copy = LC_CopyString(arena, relative); + char *buffer = (char *)LC_PushSizeNonZeroed(arena, PATH_MAX); + realpath((char *)copy.str, buffer); + LC_String result = LC_MakeFromChar(buffer); + return result; +} + +LC_FUNCTION bool LC_IsValid(LC_FileIter it) { + return it.is_valid; +} + +LC_FUNCTION void LC_Advance(LC_FileIter *it) { + struct dirent *file = 0; + while ((file = readdir((DIR *)it->dir)) != NULL) { + if (file->d_name[0] == '.' && file->d_name[1] == '.' && file->d_name[2] == 0) continue; + if (file->d_name[0] == '.' && file->d_name[1] == 0) continue; + + it->is_directory = file->d_type == DT_DIR; + it->filename = LC_CopyChar(it->arena, file->d_name); + + const char *dir_char_ending = it->is_directory ? "/" : ""; + const char *separator = it->path.str[it->path.len - 1] == '/' ? "" : "/"; + it->relative_path = LC_Format(it->arena, "%.*s%s%s%s", LC_Expand(it->path), separator, file->d_name, dir_char_ending); + it->absolute_path = LC_GetAbsolutePath(it->arena, it->relative_path); + if (it->is_directory) it->absolute_path = LC_Format(it->arena, "%.*s/", LC_Expand(it->absolute_path)); + it->is_valid = true; + return; + } + it->is_valid = false; + closedir((DIR *)it->dir); +} + +LC_FUNCTION LC_FileIter LC_IterateFiles(LC_Arena *arena, LC_String path) { + LC_FileIter it = {0}; + it.arena = arena; + it.path = path = LC_CopyString(arena, path); + it.dir = (void *)opendir((char *)path.str); + if (!it.dir) return it; + + LC_Advance(&it); + return it; +} + +LC_FUNCTION LC_String LC_ReadFile(LC_Arena *arena, LC_String path) { + LC_String result = LC_MakeEmptyString(); + + // ftell returns insane size if file is + // a directory **on some machines** KEKW + if (LC_IsDir(arena, path)) { + return result; + } + + path = LC_CopyString(arena, path); + FILE *f = fopen(path.str, "rb"); + if (f) { + fseek(f, 0, SEEK_END); + result.len = ftell(f); + fseek(f, 0, SEEK_SET); + + result.str = (char *)LC_PushSizeNonZeroed(arena, result.len + 1); + fread(result.str, result.len, 1, f); + result.str[result.len] = 0; + + fclose(f); + } + + return result; +} diff --git a/src/compiler/value.c b/src/compiler/value.c new file mode 100644 index 0000000..4067595 --- /dev/null +++ b/src/compiler/value.c @@ -0,0 +1,328 @@ +LC_Operand LC_OPNull; + +LC_FUNCTION LC_Operand LC_OPError(void) { + LC_Operand result = {LC_OPF_Error}; + return result; +} + +LC_FUNCTION LC_Operand LC_OPConstType(LC_Type *type) { + LC_Operand result = {LC_OPF_UTConst | LC_OPF_Const}; + result.type = type; + return result; +} + +LC_FUNCTION LC_Operand LC_OPDecl(LC_Decl *decl) { + LC_Operand result = {0}; + result.decl = decl; + return result; +} + +LC_FUNCTION LC_Operand LC_OPType(LC_Type *type) { + LC_Operand result = {0}; + result.type = type; + return result; +} + +LC_FUNCTION LC_Operand LC_OPLValueAndType(LC_Type *type) { + LC_Operand result = LC_OPType(type); + result.flags = LC_OPF_LValue; + return result; +} + +LC_FUNCTION LC_Operand LC_ReportASTError(LC_AST *n, const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + LC_SendErrorMessage(n ? n->pos : NULL, s8); + L->errors += 1; + return LC_OPError(); +} + +LC_FUNCTION LC_Operand LC_ReportASTErrorEx(LC_AST *n1, LC_AST *n2, const char *str, ...) { + LC_FORMAT(L->arena, str, s8); + LC_SendErrorMessage(n1->pos, s8); + LC_SendErrorMessage(n2->pos, s8); + L->errors += 1; + return LC_OPError(); +} + +LC_FUNCTION LC_Operand LC_ConstCastFloat(LC_AST *pos, LC_Operand op) { + LC_ASSERT(pos, LC_IsUTConst(op)); + LC_ASSERT(pos, LC_IsUntyped(op.type)); + if (LC_IsUTInt(op.type)) op.val.d = LC_Bigint_as_float(&op.val.i); + if (LC_IsUTStr(op.type)) return LC_ReportASTError(pos, "Trying to convert '%s' to float", LC_GenLCType(op.type)); + op.type = L->tuntypedfloat; + return op; +} + +LC_FUNCTION LC_Operand LC_ConstCastInt(LC_AST *pos, LC_Operand op) { + LC_ASSERT(pos, LC_IsUTConst(op)); + LC_ASSERT(pos, LC_IsUntyped(op.type)); + if (LC_IsUTFloat(op.type)) { + double v = op.val.d; // add rounding? + LC_Bigint_init_signed(&op.val.i, (int64_t)v); + } + if (LC_IsUTStr(op.type)) return LC_ReportASTError(pos, "Trying to convert %s to int", LC_GenLCType(op.type)); + op.type = L->tuntypedint; + return op; +} + +LC_FUNCTION LC_Operand LC_OPInt(int64_t v) { + LC_Operand op = {0}; + op.type = L->tuntypedint; + op.flags |= LC_OPF_UTConst | LC_OPF_Const; + LC_Bigint_init_signed(&op.v.i, v); + return op; +} + +LC_FUNCTION LC_Operand LC_OPIntT(LC_Type *type, int64_t v) { + LC_ASSERT(NULL, LC_IsInt(type)); + LC_Operand op = LC_OPInt(v); + op.type = type; + return op; +} + +LC_FUNCTION LC_Operand LC_OPModDefaultUT(LC_Operand val) { + if (LC_IsUntyped(val.type)) { + val.type = val.type->tbase; + } + return val; +} + +LC_FUNCTION LC_Operand LC_OPModType(LC_Operand op, LC_Type *type) { + if (LC_IsUTConst(op)) { + if (LC_IsUTInt(op.type) && LC_IsFloat(type)) { + op = LC_ConstCastFloat(NULL, op); + } + } + op.type = type; + return op; +} + +LC_FUNCTION LC_Operand LC_OPModBool(LC_Operand op) { + op.type = L->tuntypedbool; + return op; +} + +LC_FUNCTION LC_Operand LC_OPModBoolV(LC_Operand op, int v) { + op.type = L->tuntypedbool; + LC_Bigint_init_signed(&op.v.i, v); + return op; +} + +LC_FUNCTION LC_Operand LC_EvalBinary(LC_AST *pos, LC_Operand a, LC_TokenKind op, LC_Operand b) { + LC_ASSERT(pos, LC_IsUTConst(a)); + LC_ASSERT(pos, LC_IsUTConst(b)); + LC_ASSERT(pos, LC_IsUntyped(a.type)); + LC_ASSERT(pos, LC_IsUntyped(b.type)); + LC_ASSERT(pos, a.type->kind == b.type->kind); + + LC_Operand c = LC_OPConstType(a.type); + if (LC_IsUTStr(a.type)) { + return LC_ReportASTError(pos, "invalid operand %s for binary expr of type untyped string", LC_TokenKindToString(op)); + } + if (LC_IsUTFloat(a.type)) { + switch (op) { + case LC_TokenKind_Add: c.v.d = a.v.d + b.v.d; break; + case LC_TokenKind_Sub: c.v.d = a.v.d - b.v.d; break; + case LC_TokenKind_Mul: c.v.d = a.v.d * b.v.d; break; + case LC_TokenKind_Div: { + if (b.v.d == 0.0) return LC_ReportASTError(pos, "division by 0"); + c.v.d = a.v.d / b.v.d; + } break; + case LC_TokenKind_LesserThenEq: c = LC_OPModBoolV(c, a.v.d <= b.v.d); break; + case LC_TokenKind_GreaterThenEq: c = LC_OPModBoolV(c, a.v.d >= b.v.d); break; + case LC_TokenKind_GreaterThen: c = LC_OPModBoolV(c, a.v.d > b.v.d); break; + case LC_TokenKind_LesserThen: c = LC_OPModBoolV(c, a.v.d < b.v.d); break; + case LC_TokenKind_Equals: c = LC_OPModBoolV(c, a.v.d == b.v.d); break; + case LC_TokenKind_NotEquals: c = LC_OPModBoolV(c, a.v.d != b.v.d); break; + default: return LC_ReportASTError(pos, "invalid operand %s for binary expr of type untyped float", LC_TokenKindToString(op)); + } + } + if (LC_IsUTInt(a.type)) { + switch (op) { + case LC_TokenKind_BitXor: LC_Bigint_xor(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_BitAnd: LC_Bigint_and(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_BitOr: LC_Bigint_or(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_Add: LC_Bigint_add(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_Sub: LC_Bigint_sub(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_Mul: LC_Bigint_mul(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_Div: { + if (b.v.i.digit_count == 0) return LC_ReportASTError(pos, "division by zero in constant expression"); + LC_Bigint_div_floor(&c.v.i, &a.v.i, &b.v.i); + } break; + case LC_TokenKind_Mod: { + if (b.v.i.digit_count == 0) return LC_ReportASTError(pos, "modulo by zero in constant expression"); + LC_Bigint_mod(&c.v.i, &a.v.i, &b.v.i); + } break; + case LC_TokenKind_LeftShift: LC_Bigint_shl(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_RightShift: LC_Bigint_shr(&c.v.i, &a.v.i, &b.v.i); break; + case LC_TokenKind_And: { + int left = LC_Bigint_cmp_zero(&a.v.i) != LC_CmpRes_EQ; + int right = LC_Bigint_cmp_zero(&b.v.i) != LC_CmpRes_EQ; + c = LC_OPModBoolV(c, left && right); + } break; + case LC_TokenKind_Or: { + int left = LC_Bigint_cmp_zero(&a.v.i) != LC_CmpRes_EQ; + int right = LC_Bigint_cmp_zero(&b.v.i) != LC_CmpRes_EQ; + c = LC_OPModBoolV(c, left || right); + } break; + default: { + LC_CmpRes cmp = LC_Bigint_cmp(&a.v.i, &b.v.i); + switch (op) { + case LC_TokenKind_LesserThenEq: c = LC_OPModBoolV(c, (cmp == LC_CmpRes_LT) || (cmp == LC_CmpRes_EQ)); break; + case LC_TokenKind_GreaterThenEq: c = LC_OPModBoolV(c, (cmp == LC_CmpRes_GT) || (cmp == LC_CmpRes_EQ)); break; + case LC_TokenKind_GreaterThen: c = LC_OPModBoolV(c, cmp == LC_CmpRes_GT); break; + case LC_TokenKind_LesserThen: c = LC_OPModBoolV(c, cmp == LC_CmpRes_LT); break; + case LC_TokenKind_Equals: c = LC_OPModBoolV(c, cmp == LC_CmpRes_EQ); break; + case LC_TokenKind_NotEquals: c = LC_OPModBoolV(c, cmp != LC_CmpRes_EQ); break; + default: return LC_ReportASTError(pos, "invalid operand %s for binary expr of type untyped int", LC_TokenKindToString(op)); + } + } + } + } + + return c; +} + +LC_FUNCTION LC_Operand LC_EvalUnary(LC_AST *pos, LC_TokenKind op, LC_Operand a) { + LC_ASSERT(pos, LC_IsUTConst(a)); + LC_ASSERT(pos, LC_IsUntyped(a.type)); + LC_Operand c = a; + + if (LC_IsUTStr(a.type)) { + return LC_ReportASTError(pos, "invalid operand %s for unary expr of type untyped string", LC_TokenKindToString(op)); + } + if (LC_IsUTFloat(a.type)) { + switch (op) { + case LC_TokenKind_Sub: c.v.d = -a.v.d; break; + case LC_TokenKind_Add: c.v.d = +a.v.d; break; + default: return LC_ReportASTError(pos, "invalid operand %s for unary expr of type untyped float", LC_TokenKindToString(op)); + } + } + if (LC_IsUTInt(a.type)) { + switch (op) { + case LC_TokenKind_Not: c = LC_OPModBoolV(c, LC_Bigint_cmp_zero(&a.v.i) == LC_CmpRes_EQ); break; + case LC_TokenKind_Sub: LC_Bigint_negate(&c.v.i, &a.v.i); break; + case LC_TokenKind_Add: c = a; break; + case LC_TokenKind_Neg: LC_Bigint_not(&c.v.i, &a.v.i, a.type->tbase->size * 8, !a.type->tbase->is_unsigned); break; + default: return LC_ReportASTError(pos, "invalid operand %s for unary expr of type untyped int", LC_TokenKindToString(op)); + } + } + + return c; +} + +LC_FUNCTION bool LC_BigIntFits(LC_BigInt i, LC_Type *type) { + LC_ASSERT(NULL, LC_IsInt(type)); + if (!LC_Bigint_fits_in_bits(&i, type->size * 8, !type->is_unsigned)) { + return false; + } + return true; +} + +LC_FUNCTION LC_OPResult LC_IsBinaryExprValidForType(LC_TokenKind op, LC_Type *type) { + if (LC_IsFloat(type)) { + switch (op) { + case LC_TokenKind_Add: return LC_OPResult_Ok; break; + case LC_TokenKind_Sub: return LC_OPResult_Ok; break; + case LC_TokenKind_Mul: return LC_OPResult_Ok; break; + case LC_TokenKind_Div: return LC_OPResult_Ok; break; + case LC_TokenKind_LesserThenEq: return LC_OPResult_Bool; break; + case LC_TokenKind_GreaterThenEq: return LC_OPResult_Bool; break; + case LC_TokenKind_GreaterThen: return LC_OPResult_Bool; break; + case LC_TokenKind_LesserThen: return LC_OPResult_Bool; break; + case LC_TokenKind_Equals: return LC_OPResult_Bool; break; + case LC_TokenKind_NotEquals: return LC_OPResult_Bool; break; + default: return LC_OPResult_Error; + } + } + if (LC_IsInt(type)) { + switch (op) { + case LC_TokenKind_BitXor: return LC_OPResult_Ok; break; + case LC_TokenKind_BitAnd: return LC_OPResult_Ok; break; + case LC_TokenKind_BitOr: return LC_OPResult_Ok; break; + case LC_TokenKind_Add: return LC_OPResult_Ok; break; + case LC_TokenKind_Sub: return LC_OPResult_Ok; break; + case LC_TokenKind_Mul: return LC_OPResult_Ok; break; + case LC_TokenKind_Div: return LC_OPResult_Ok; break; + case LC_TokenKind_Mod: return LC_OPResult_Ok; break; + case LC_TokenKind_LeftShift: return LC_OPResult_Ok; break; + case LC_TokenKind_RightShift: return LC_OPResult_Ok; break; + case LC_TokenKind_And: return LC_OPResult_Bool; break; + case LC_TokenKind_Or: return LC_OPResult_Bool; break; + case LC_TokenKind_LesserThenEq: return LC_OPResult_Bool; break; + case LC_TokenKind_GreaterThenEq: return LC_OPResult_Bool; break; + case LC_TokenKind_GreaterThen: return LC_OPResult_Bool; break; + case LC_TokenKind_LesserThen: return LC_OPResult_Bool; break; + case LC_TokenKind_Equals: return LC_OPResult_Bool; break; + case LC_TokenKind_NotEquals: return LC_OPResult_Bool; break; + default: return LC_OPResult_Error; + } + } + if (LC_IsPtrLike(type)) { + switch (op) { + case LC_TokenKind_And: return LC_OPResult_Bool; break; + case LC_TokenKind_Or: return LC_OPResult_Bool; break; + case LC_TokenKind_LesserThenEq: return LC_OPResult_Bool; break; + case LC_TokenKind_GreaterThenEq: return LC_OPResult_Bool; break; + case LC_TokenKind_GreaterThen: return LC_OPResult_Bool; break; + case LC_TokenKind_LesserThen: return LC_OPResult_Bool; break; + case LC_TokenKind_Equals: return LC_OPResult_Bool; break; + case LC_TokenKind_NotEquals: return LC_OPResult_Bool; break; + default: return LC_OPResult_Error; + } + } + + return LC_OPResult_Error; +} + +LC_FUNCTION LC_OPResult LC_IsUnaryOpValidForType(LC_TokenKind op, LC_Type *type) { + if (LC_IsFloat(type)) { + if (op == LC_TokenKind_Sub) return LC_OPResult_Ok; + if (op == LC_TokenKind_Add) return LC_OPResult_Ok; + } + if (LC_IsInt(type)) { + if (op == LC_TokenKind_Not) return LC_OPResult_Bool; + if (op == LC_TokenKind_Sub) return LC_OPResult_Ok; + if (op == LC_TokenKind_Add) return LC_OPResult_Ok; + if (op == LC_TokenKind_Neg) return LC_OPResult_Ok; + } + if (LC_IsPtrLike(type)) { + if (op == LC_TokenKind_Not) return LC_OPResult_Bool; + } + return LC_OPResult_Error; +} + +LC_FUNCTION LC_OPResult LC_IsAssignValidForType(LC_TokenKind op, LC_Type *type) { + if (op == LC_TokenKind_Assign) return LC_OPResult_Ok; + if (LC_IsInt(type)) { + switch (op) { + case LC_TokenKind_DivAssign: return LC_OPResult_Ok; + case LC_TokenKind_MulAssign: return LC_OPResult_Ok; + case LC_TokenKind_ModAssign: return LC_OPResult_Ok; + case LC_TokenKind_SubAssign: return LC_OPResult_Ok; + case LC_TokenKind_AddAssign: return LC_OPResult_Ok; + case LC_TokenKind_BitAndAssign: return LC_OPResult_Ok; + case LC_TokenKind_BitOrAssign: return LC_OPResult_Ok; + case LC_TokenKind_BitXorAssign: return LC_OPResult_Ok; + case LC_TokenKind_LeftShiftAssign: return LC_OPResult_Ok; + case LC_TokenKind_RightShiftAssign: return LC_OPResult_Ok; + default: return LC_OPResult_Error; + } + } + if (LC_IsFloat(type)) { + switch (op) { + case LC_TokenKind_DivAssign: return LC_OPResult_Ok; + case LC_TokenKind_MulAssign: return LC_OPResult_Ok; + case LC_TokenKind_SubAssign: return LC_OPResult_Ok; + case LC_TokenKind_AddAssign: return LC_OPResult_Ok; + default: return LC_OPResult_Error; + } + } + return LC_OPResult_Error; +} + +LC_FUNCTION int LC_GetLevelsOfIndirection(LC_Type *type) { + if (type->kind == LC_TypeKind_Pointer) return LC_GetLevelsOfIndirection(type->tbase) + 1; + if (type->kind == LC_TypeKind_Array) return LC_GetLevelsOfIndirection(type->tbase) + 1; + return 0; +} diff --git a/src/compiler/win32_arena.c b/src/compiler/win32_arena.c new file mode 100644 index 0000000..cdc4beb --- /dev/null +++ b/src/compiler/win32_arena.c @@ -0,0 +1,44 @@ +const size_t LC_V_WIN32_PAGE_SIZE = 4096; + +LC_FUNCTION LC_VMemory LC_VReserve(size_t size) { + LC_VMemory result; + LC_MemoryZero(&result, sizeof(result)); + size_t adjusted_size = LC_AlignUp(size, LC_V_WIN32_PAGE_SIZE); + result.data = (uint8_t *)VirtualAlloc(0, adjusted_size, MEM_RESERVE, PAGE_READWRITE); + LC_Assertf(result.data, "Failed to reserve virtual memory"); + result.reserve = adjusted_size; + return result; +} + +LC_FUNCTION bool LC_VCommit(LC_VMemory *m, size_t commit) { + uint8_t *pointer = LC_V_AdvanceCommit(m, &commit, LC_V_WIN32_PAGE_SIZE); + if (pointer) { + void *result = VirtualAlloc(pointer, commit, MEM_COMMIT, PAGE_READWRITE); + LC_Assertf(result, "Failed to commit more memory"); + if (result) { + m->commit += commit; + return true; + } + } + return false; +} + +LC_FUNCTION void LC_VDeallocate(LC_VMemory *m) { + BOOL result = VirtualFree(m->data, 0, MEM_RELEASE); + LC_Assertf(result != 0, "Failed to release LC_VMemory"); +} + +LC_FUNCTION bool LC_VDecommitPos(LC_VMemory *m, size_t pos) { + size_t aligned = LC_AlignDown(pos, LC_V_WIN32_PAGE_SIZE); + size_t adjusted_pos = LC_CLAMP_TOP(aligned, m->commit); + size_t size_to_decommit = m->commit - adjusted_pos; + if (size_to_decommit) { + uint8_t *base_address = m->data + adjusted_pos; + BOOL result = VirtualFree(base_address, size_to_decommit, MEM_DECOMMIT); + if (result) { + m->commit -= size_to_decommit; + return true; + } + } + return false; +} \ No newline at end of file diff --git a/src/compiler/win32_filesystem.c b/src/compiler/win32_filesystem.c new file mode 100644 index 0000000..f0eaa28 --- /dev/null +++ b/src/compiler/win32_filesystem.c @@ -0,0 +1,118 @@ +typedef struct LC_Win32_FileIter { + HANDLE handle; + WIN32_FIND_DATAW data; +} LC_Win32_FileIter; + +LC_FUNCTION bool LC_IsDir(LC_Arena *arena, LC_String path) { + wchar_t wbuff[1024]; + LC_CreateWidecharFromChar(wbuff, LC_StrLenof(wbuff), path.str, path.len); + DWORD dwAttrib = GetFileAttributesW(wbuff); + return dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY); +} + +LC_FUNCTION LC_String LC_GetAbsolutePath(LC_Arena *arena, LC_String relative) { + wchar_t wpath[1024]; + LC_CreateWidecharFromChar(wpath, LC_StrLenof(wpath), relative.str, relative.len); + wchar_t wpath_abs[1024]; + DWORD written = GetFullPathNameW((wchar_t *)wpath, LC_StrLenof(wpath_abs), wpath_abs, 0); + if (written == 0) + return LC_MakeEmptyString(); + LC_String path = LC_FromWidecharEx(arena, wpath_abs, written); + LC_NormalizePathUnsafe(path); + return path; +} + +LC_FUNCTION bool LC_IsValid(LC_FileIter it) { + return it.is_valid; +} + +LC_FUNCTION void LC_Advance(LC_FileIter *it) { + while (FindNextFileW(it->w32->handle, &it->w32->data) != 0) { + WIN32_FIND_DATAW *data = &it->w32->data; + + // Skip '.' and '..' + if (data->cFileName[0] == '.' && data->cFileName[1] == '.' && data->cFileName[2] == 0) continue; + if (data->cFileName[0] == '.' && data->cFileName[1] == 0) continue; + + it->is_directory = data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; + it->filename = LC_FromWidecharEx(it->arena, data->cFileName, LC_WideLength(data->cFileName)); + const char *is_dir = it->is_directory ? "/" : ""; + const char *separator = it->path.str[it->path.len - 1] == '/' ? "" : "/"; + it->relative_path = LC_Format(it->arena, "%.*s%s%.*s%s", LC_Expand(it->path), separator, LC_Expand(it->filename), is_dir); + it->absolute_path = LC_GetAbsolutePath(it->arena, it->relative_path); + it->is_valid = true; + + if (it->is_directory) { + LC_ASSERT(NULL, it->relative_path.str[it->relative_path.len - 1] == '/'); + LC_ASSERT(NULL, it->absolute_path.str[it->absolute_path.len - 1] == '/'); + } + return; + } + + it->is_valid = false; + DWORD error = GetLastError(); + LC_ASSERT(NULL, error == ERROR_NO_MORE_FILES); + FindClose(it->w32->handle); +} + +LC_FUNCTION LC_FileIter LC_IterateFiles(LC_Arena *scratch_arena, LC_String path) { + LC_FileIter it = {0}; + it.arena = scratch_arena; + it.path = path; + + LC_String modified_path = LC_Format(it.arena, "%.*s\\*", LC_Expand(path)); + wchar_t *wbuff = LC_PushArray(it.arena, wchar_t, modified_path.len + 1); + int64_t wsize = LC_CreateWidecharFromChar(wbuff, modified_path.len + 1, modified_path.str, modified_path.len); + LC_ASSERT(NULL, wsize); + + it.w32 = LC_PushStruct(it.arena, LC_Win32_FileIter); + it.w32->handle = FindFirstFileW(wbuff, &it.w32->data); + if (it.w32->handle == INVALID_HANDLE_VALUE) { + it.is_valid = false; + return it; + } + + LC_ASSERT(NULL, it.w32->data.cFileName[0] == '.' && it.w32->data.cFileName[1] == 0); + LC_Advance(&it); + return it; +} + +LC_FUNCTION LC_String LC_ReadFile(LC_Arena *arena, LC_String path) { + LC_String result = LC_MakeEmptyString(); + + wchar_t wpath[1024]; + LC_CreateWidecharFromChar(wpath, LC_StrLenof(wpath), path.str, path.len); + HANDLE handle = CreateFileW(wpath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (handle != INVALID_HANDLE_VALUE) { + LARGE_INTEGER file_size; + if (GetFileSizeEx(handle, &file_size)) { + if (file_size.QuadPart != 0) { + result.len = (int64_t)file_size.QuadPart; + result.str = (char *)LC_PushSizeNonZeroed(arena, result.len + 1); + DWORD read; + if (ReadFile(handle, result.str, (DWORD)result.len, &read, NULL)) { // @todo: can only read 32 byte size files? + if (read == result.len) { + result.str[result.len] = 0; + } + } + } + } + CloseHandle(handle); + } + + return result; +} + +LC_FUNCTION bool LC_EnableTerminalColors(void) { + HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); + if (hOut != INVALID_HANDLE_VALUE) { + DWORD dwMode = 0; + if (GetConsoleMode(hOut, &dwMode)) { + dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; + if (SetConsoleMode(hOut, dwMode)) { + return true; + } + } + } + return false; +} diff --git a/src/core/allocator.c b/src/core/allocator.c new file mode 100644 index 0000000..6b9cd65 --- /dev/null +++ b/src/core/allocator.c @@ -0,0 +1,115 @@ +#ifndef MA_CMalloc + #include + #define MA_CMalloc(x) malloc(x) + #define MA_CFree(x) free(x) + #define MA_CRealloc(p, size) realloc(p, size) +#endif + +MA_API M_Allocator MA_BootstrapExclusive(void) { + MA_Arena bootstrap_arena = {0}; + MA_Arena *arena = MA_PushStruct(&bootstrap_arena, MA_Arena); + *arena = bootstrap_arena; + arena->base_len = arena->len; + return MA_GetExclusiveAllocator(arena); +} + +MA_API void *M__AllocNonZeroed(M_Allocator allocator, size_t size) { + void *p = allocator.p(allocator.obj, M_AllocatorOp_Allocate, NULL, size, 0); + return p; +} + +MA_API void *M__Alloc(M_Allocator allocator, size_t size) { + void *p = allocator.p(allocator.obj, M_AllocatorOp_Allocate, NULL, size, 0); + MA_MemoryZero(p, size); + return p; +} + +MA_API void *M__AllocCopy(M_Allocator allocator, void *p, size_t size) { + void *copy_buffer = M__AllocNonZeroed(allocator, size); + MA_MemoryCopy(copy_buffer, p, size); + return copy_buffer; +} + +MA_API void M__Dealloc(M_Allocator allocator, void *p) { + allocator.p(allocator.obj, M_AllocatorOp_Deallocate, p, 0, 0); +} + +MA_API void *M__Realloc(M_Allocator allocator, void *p, size_t size, size_t old_size) { + void *result = allocator.p(allocator.obj, M_AllocatorOp_Reallocate, p, size, old_size); + // @todo: add old_size? because we can't zero + return result; +} + +MA_StaticFunc void *M_ClibAllocatorProc(void *allocator, M_AllocatorOp kind, void *p, size_t size, size_t old_size) { + if (kind == M_AllocatorOp_Allocate) { + return MA_CMalloc(size); + } + + if (kind == M_AllocatorOp_Deallocate) { + MA_CFree(p); + return NULL; + } + + if (kind == M_AllocatorOp_Reallocate) { + return MA_CRealloc(p, size); + } + + MA_Assertf(0, "MA_Arena invalid codepath"); + return NULL; +} + +MA_API void *MA_AllocatorProc(void *allocator, M_AllocatorOp kind, void *p, size_t size, size_t old_size) { + if (kind == M_AllocatorOp_Allocate) { + return MA__PushSizeNonZeroed((MA_Arena *)allocator, size); + } + + else if (kind == M_AllocatorOp_Reallocate) { + void *new_p = MA__PushSizeNonZeroed((MA_Arena *)allocator, size); + MA_MemoryCopy(new_p, p, old_size); + return new_p; + } + + else if (kind == M_AllocatorOp_Deallocate) { + return NULL; + } + + MA_Assertf(0, "MA_Arena invalid codepath"); + return NULL; +} + +MA_API void *MA_ExclusiveAllocatorProc(void *allocator, M_AllocatorOp kind, void *p, size_t size, size_t old_size) { + MA_Arena *arena = (MA_Arena *)allocator; + if (kind == M_AllocatorOp_Reallocate) { + if (size > old_size) { + size_t size_to_push = size - old_size; + void *result = MA__PushSizeNonZeroed(arena, size_to_push); + if (!p) p = result; + return p; + } + } + + if (kind == M_AllocatorOp_Deallocate) { + MA_DeallocateArena(arena); + return NULL; + } + + MA_Assertf(0, "MA_Arena invalid codepath"); + return NULL; +} + +MA_API M_Allocator MA_GetExclusiveAllocator(MA_Arena *arena) { + M_Allocator allocator = {(int *)arena, MA_ExclusiveAllocatorProc}; + return allocator; +} + +MA_API M_Allocator MA_GetAllocator(MA_Arena *arena) { + M_Allocator allocator = {(int *)arena, MA_AllocatorProc}; + return allocator; +} + +MA_API M_Allocator M_GetSystemAllocator(void) { + M_Allocator allocator; + allocator.obj = 0; + allocator.p = M_ClibAllocatorProc; + return allocator; +} diff --git a/src/core/allocator.h b/src/core/allocator.h new file mode 100644 index 0000000..a525b74 --- /dev/null +++ b/src/core/allocator.h @@ -0,0 +1,44 @@ +typedef struct M_Allocator M_Allocator; + +typedef enum M_AllocatorOp { + M_AllocatorOp_Invalid, + M_AllocatorOp_Allocate, + M_AllocatorOp_Deallocate, + M_AllocatorOp_Reallocate, +} M_AllocatorOp; + +typedef void *M_AllocatorProc(void *allocator, M_AllocatorOp kind, void *p, size_t size, size_t old_size); +MA_API void *MA_AllocatorProc(void *allocator, M_AllocatorOp kind, void *p, size_t size, size_t old_size); +MA_API void *MA_ExclusiveAllocatorProc(void *allocator, M_AllocatorOp kind, void *p, size_t size, size_t old_size); + +struct M_Allocator { + // it's int for type safety because C++ somehow allows this: + // struct Array { M_Allocator allocator; } + // Array = {arena}; WTF???!??!? + // without actually passing M_Allocator but just a pointer + int *obj; + M_AllocatorProc *p; +}; + +#define M_AllocStruct(a, T) (T *)M_Alloc((a), sizeof(T)) +#define M_AllocArray(a, T, c) (T *)M_Alloc((a), sizeof(T) * (c)) +#define M_AllocStructNonZeroed(a, T) (T *)M_AllocNonZeroed((a), sizeof(T)) +#define M_AllocArrayNonZeroed(a, T, c) (T *)M_AllocNonZeroed((a), sizeof(T) * (c)) +#define M_AllocStructCopy(a, T, p) (T *)M_PushCopy(a, (p), sizeof(T)) + +#define M_Alloc(a, size) M__Alloc(a, size) +#define M_AllocNonZeroed(a, size) M__AllocNonZeroed(a, size) +#define M_AllocCopy(a, p, size) M__AllocCopy(a, p, size) +#define M_Realloc(a, p, size, old_size) M__Realloc(a, p, size, old_size) +#define M_Dealloc(a, p) M__Dealloc(a, p) + +MA_API void *M__AllocNonZeroed(M_Allocator allocator, size_t size); +MA_API void *M__Alloc(M_Allocator allocator, size_t size); +MA_API void *M__AllocCopy(M_Allocator allocator, void *p, size_t size); +MA_API void *M__Realloc(M_Allocator allocator, void *p, size_t size, size_t old_size); +MA_API void M__Dealloc(M_Allocator allocator, void *p); + +MA_API M_Allocator M_GetSystemAllocator(void); +MA_API M_Allocator MA_GetExclusiveAllocator(MA_Arena *arena); +MA_API M_Allocator MA_GetAllocator(MA_Arena *arena); +MA_API M_Allocator MA_BootstrapExclusive(void); diff --git a/src/core/array.hpp b/src/core/array.hpp new file mode 100644 index 0000000..612bcf1 --- /dev/null +++ b/src/core/array.hpp @@ -0,0 +1,270 @@ +// Iterating and removing elements +// +// ForArrayRemovable(array) { +// ForArrayRemovablePrepare(array); +// if (it == 4) ForArrayRemovableDeclare(); +// } +// +#define ForArrayRemovable(a) for (int __i = 0; __i < (a).len; __i += 1) +#define ForArrayRemovablePrepare(a) \ + auto &it = (a)[__i]; \ + bool remove_it = false; \ + defer { \ + if (remove_it) { \ + (a).ordered_remove(it); \ + __i -= 1; \ + } \ + } +#define ForArrayRemovableDeclare() (remove_it = true) +#define For2(it, array) for (auto &it : (array)) +#define For(array) For2(it, array) + +template +struct Array { + M_Allocator allocator; + T *data; + int cap, len; + + T &operator[](int index) { + IO_Assert(index >= 0 && index < len); + return data[index]; + } + + bool is_first(T &item) { return &item == first(); } + bool is_last(T &item) { return &item == last(); } + + bool contains(T &item) { + bool result = &item >= data && &item < data + len; + return result; + } + + int get_index(T &item) { + IO_Assert((data <= &item) && ((data + len) > &item)); + size_t offset = &item - data; + return (int)offset; + } + + void add(const T &item) { + try_growing(); + data[len++] = item; + } + + // Struct needs to have 'value_to_sort_by' field + void sorted_insert_decreasing(T item) { + int insert_index = -1; + For(*this) { + if (it.value_to_sort_by <= item.value_to_sort_by) { + insert_index = get_index(it); + insert(item, insert_index); + break; + } + } + + if (insert_index == -1) { + add(item); + } + } + + void bounded_add(T item) { + IO_Assert(len + 1 <= cap); + try_growing(); // in case of error + data[len++] = item; + } + + T *alloc(const T &item) { + try_growing(); + T *ref = data + len++; + *ref = item; + return ref; + } + + T *alloc() { + try_growing(); + T *ref = data + len++; + *ref = {}; + return ref; + } + + T *alloc_multiple(int size) { + try_growing_to_fit_item_count(size); + T *result = data + len; + len += size; + return result; + } + + void add_array(T *items, int item_count) { + for (int i = 0; i < item_count; i += 1) { + add(items[i]); + } + } + + void add_array(Array items) { + add_array(items.data, items.len); + } + + void reserve(int size) { + if (size > cap) { + if (!allocator.p) allocator = M_GetSystemAllocator(); + + void *p = M_Realloc(allocator, data, size * sizeof(T), cap * sizeof(T)); + IO_Assert(p); + + data = (T *)p; + cap = size; + } + } + + void init(M_Allocator allocator, int size) { + len = 0; + cap = 0; + data = 0; + this->allocator = allocator; + reserve(size); + } + + void reset() { + len = 0; + } + + T pop() { + IO_Assert(len > 0); + return data[--len]; + } + + void unordered_remove(T &item) { // DONT USE IN LOOPS !!!! + IO_Assert(len > 0); + IO_Assert(&item >= begin() && &item < end()); + item = data[--len]; + } + + void unordered_remove_index(int index) { + IO_Assert(index >= 0 && index < len); + data[index] = data[--len]; + } + + int get_index(const T &item) { + ptrdiff_t index = (ptrdiff_t)(&item - data); + IO_Assert(index >= 0 && index < len); + // IO_Assert(index > INT_MIN && index < INT_MAX); + return (int)index; + } + + void ordered_remove(T &item) { // DONT USE IN LOOPS !!! + IO_Assert(len > 0); + IO_Assert(&item >= begin() && &item < end()); + int index = get_index(item); + ordered_remove_index(index); + } + + void ordered_remove_index(int index) { + IO_Assert(index >= 0 && index < len); + int right_len = len - index - 1; + memmove(data + index, data + index + 1, right_len * sizeof(T)); + len -= 1; + } + + void insert(T item, int index) { + if (index == len) { + add(item); + return; + } + + IO_Assert(index < len); + IO_Assert(index >= 0); + + try_growing(); + int right_len = len - index; + memmove(data + index + 1, data + index, sizeof(T) * right_len); + data[index] = item; + len += 1; + } + + void dealloc() { + if (data) M_Dealloc(allocator, data); + data = 0; + len = cap = 0; + } + + Array copy(M_Allocator allocator) { + Array result = {}; + result.allocator = allocator; + result.reserve(cap); + + memmove(result.data, data, sizeof(T) * len); + result.len = len; + return result; + } + + Array tight_copy(M_Allocator allocator) { + Array result = {}; + result.allocator = allocator; + result.reserve(len); + + memmove(result.data, data, sizeof(T) * len); + result.len = len; + return result; + } + + T *first() { + IO_Assert(len > 0); + return data; + } + T *last() { + IO_Assert(len > 0); + return data + len - 1; + } + T *front() { + IO_Assert(len > 0); + return data; + } + T *back() { + IO_Assert(len > 0); + return data + len - 1; + } + T *begin() { return data; } + T *end() { return data + len; } + + // for (auto it = integers.begin(), end = integers.end(); it != end; ++it) + struct Reverse_Iter { + T *data; + Array *arr; + + Reverse_Iter operator++(int) { + Reverse_Iter ret = *this; + data -= 1; + return ret; + } + Reverse_Iter &operator++() { + data -= 1; + return *this; + } + + T &operator*() { return data[0]; } + T *operator->() { return data; } + + friend bool operator==(const Reverse_Iter &a, const Reverse_Iter &b) { return a.data == b.data; }; + friend bool operator!=(const Reverse_Iter &a, const Reverse_Iter &b) { return a.data != b.data; }; + + Reverse_Iter begin() { return Reverse_Iter{arr->end() - 1, arr}; } + Reverse_Iter end() { return Reverse_Iter{arr->begin() - 1, arr}; } + }; + + Reverse_Iter reverse() { return {end() - 1, this}; } + + void try_growing() { + if (len + 1 > cap) { + int new_size = cap * 2; + if (new_size < 16) new_size = 16; + + reserve(new_size); + } + } + + void try_growing_to_fit_item_count(int item_count) { + if (len + item_count > cap) { + int new_size = (cap + item_count) * 2; + if (new_size < 16) new_size = 16; + reserve(new_size); + } + } +}; diff --git a/src/core/cmd.c b/src/core/cmd.c new file mode 100644 index 0000000..68cc10a --- /dev/null +++ b/src/core/cmd.c @@ -0,0 +1,186 @@ + +CmdParser MakeCmdParser(MA_Arena *arena, int argc, char **argv, const char *custom_help) { + CmdParser result = {argc, argv, arena, custom_help}; + return result; +} + +void AddBool(CmdParser *p, bool *result, const char *name, const char *help) { + CmdDecl *decl = MA_PushStruct(p->arena, CmdDecl); + decl->kind = CmdDeclKind_Bool; + decl->name = S8_MakeFromChar((char *)name); + decl->help = S8_MakeFromChar((char *)help); + decl->bool_result = result; + SLL_QUEUE_ADD(p->fdecl, p->ldecl, decl); +} + +void AddInt(CmdParser *p, int *result, const char *name, const char *help) { + CmdDecl *decl = MA_PushStruct(p->arena, CmdDecl); + decl->kind = CmdDeclKind_Int; + decl->name = S8_MakeFromChar((char *)name); + decl->help = S8_MakeFromChar((char *)help); + decl->int_result = result; + SLL_QUEUE_ADD(p->fdecl, p->ldecl, decl); +} + +void AddList(CmdParser *p, S8_List *result, const char *name, const char *help) { + CmdDecl *decl = MA_PushStruct(p->arena, CmdDecl); + decl->kind = CmdDeclKind_List; + decl->name = S8_MakeFromChar((char *)name); + decl->help = S8_MakeFromChar((char *)help); + decl->list_result = result; + SLL_QUEUE_ADD(p->fdecl, p->ldecl, decl); +} + +void AddEnum(CmdParser *p, int *result, const char *name, const char *help, const char **enum_options, int enum_option_count) { + CmdDecl *decl = MA_PushStruct(p->arena, CmdDecl); + decl->kind = CmdDeclKind_Enum; + decl->name = S8_MakeFromChar((char *)name); + decl->help = S8_MakeFromChar((char *)help); + decl->enum_result = result; + decl->enum_options = enum_options; + decl->enum_option_count = enum_option_count; + SLL_QUEUE_ADD(p->fdecl, p->ldecl, decl); +} + +CmdDecl *FindDecl(CmdParser *p, S8_String name) { + for (CmdDecl *it = p->fdecl; it; it = it->next) { + if (S8_AreEqual(it->name, name, true)) { + return it; + } + } + return NULL; +} + +S8_String StrEnumValues(MA_Arena *arena, CmdDecl *decl) { + S8_List list = {0}; + S8_AddF(arena, &list, "["); + for (int i = 0; i < decl->enum_option_count; i += 1) { + S8_AddF(arena, &list, "%s", decl->enum_options[i]); + if (i != decl->enum_option_count - 1) S8_AddF(arena, &list, "|"); + } + S8_AddF(arena, &list, "]"); + return S8_Merge(arena, list); +} + +void PrintCmdUsage(CmdParser *p) { + IO_Printf("%s\nCommands:\n", p->custom_help); + for (CmdDecl *it = p->fdecl; it; it = it->next) { + IO_Printf(" "); + if (it->kind == CmdDeclKind_List) { + S8_String example = S8_Format(p->arena, "-%.*s a b c", S8_Expand(it->name)); + IO_Printf("%-30.*s %.*s\n", S8_Expand(example), S8_Expand(it->help)); + } else if (it->kind == CmdDeclKind_Bool) { + S8_String example = S8_Format(p->arena, "-%.*s", S8_Expand(it->name)); + IO_Printf("%-30.*s %.*s\n", S8_Expand(example), S8_Expand(it->help)); + } else if (it->kind == CmdDeclKind_Enum) { + S8_String enum_vals = StrEnumValues(p->arena, it); + S8_String example = S8_Format(p->arena, "-%.*s %.*s", S8_Expand(it->name), S8_Expand(enum_vals)); + IO_Printf("%-30.*s %.*s\n", S8_Expand(example), S8_Expand(it->help)); + } else if (it->kind == CmdDeclKind_Int) { + S8_String example = S8_Format(p->arena, "-%.*s 8", S8_Expand(it->name)); + IO_Printf("%-30.*s %.*s\n", S8_Expand(example), S8_Expand(it->help)); + } else IO_Todo(); + } +} + +bool InvalidCmdArg(CmdParser *p, S8_String arg) { + IO_Printf("invalid command line argument: %.*s\n", S8_Expand(arg)); + return false; +} + +bool ParseCmd(MA_Arena *arg_arena, CmdParser *p) { + for (int i = 1; i < p->argc; i += 1) { + S8_String arg = S8_MakeFromChar(p->argv[i]); + + if (S8_AreEqual(arg, S8_Lit("--help"), true) || S8_AreEqual(arg, S8_Lit("-h"), true) || S8_AreEqual(arg, S8_Lit("-help"), true)) { + PrintCmdUsage(p); + return false; + } + + if (arg.str[0] == '-') { + arg = S8_Skip(arg, 1); + if (arg.str[0] == '-') { + arg = S8_Skip(arg, 1); + } + + CmdDecl *decl = FindDecl(p, arg); + if (!decl) return InvalidCmdArg(p, arg); + + if (decl->kind == CmdDeclKind_Bool) { + *decl->bool_result = !*decl->bool_result; + } else if (decl->kind == CmdDeclKind_Int) { + if (i + 1 >= p->argc) { + IO_Printf("expected at least 1 argument after %.*s\n", S8_Expand(arg)); + return false; + } + S8_String num = S8_MakeFromChar(p->argv[++i]); + for (int i = 0; i < num.len; i += 1) { + if (!CHAR_IsDigit(num.str[i])) { + IO_Printf("expected argument to be a number, got instead: %.*s", S8_Expand(num)); + return false; + } + } + int count = atoi(num.str); + decl->int_result[0] = count; + + } else if (decl->kind == CmdDeclKind_Enum) { + if (i + 1 >= p->argc) { + IO_Printf("expected at least 1 argument after %.*s\n", S8_Expand(arg)); + return false; + } + S8_String option_from_cmd = S8_MakeFromChar(p->argv[++i]); + + bool found_option = false; + for (int i = 0; i < decl->enum_option_count; i += 1) { + S8_String option = S8_MakeFromChar((char *)decl->enum_options[i]); + if (S8_AreEqual(option, option_from_cmd, true)) { + *decl->enum_result = i; + found_option = true; + break; + } + } + + if (!found_option) { + IO_Printf("expected one of the enum values: %.*s", S8_Expand(StrEnumValues(p->arena, decl))); + IO_Printf(" got instead: %.*s\n", S8_Expand(option_from_cmd)); + return false; + } + + } else if (decl->kind == CmdDeclKind_List) { + if (i + 1 >= p->argc) { + IO_Printf("expected at least 1 argument after %.*s\n", S8_Expand(arg)); + return false; + } + + i += 1; + for (int counter = 0; i < p->argc; i += 1, counter += 1) { + S8_String arg = S8_MakeFromChar(p->argv[i]); + if (arg.str[0] == '-') { + if (counter == 0) { + IO_Printf("expected at least 1 argument after %.*s\n", S8_Expand(arg)); + return false; + } + i -= 1; + break; + } + + S8_AddNode(arg_arena, decl->list_result, arg); + } + } else IO_Todo(); + + } else { + if (p->require_one_standalone_arg && p->args.node_count == 0) { + S8_AddNode(arg_arena, &p->args, arg); + } else { + return InvalidCmdArg(p, arg); + } + } + } + + if (p->require_one_standalone_arg && p->args.node_count == 0) { + PrintCmdUsage(p); + return false; + } + + return true; +} diff --git a/src/core/cmd.h b/src/core/cmd.h new file mode 100644 index 0000000..e45c5de --- /dev/null +++ b/src/core/cmd.h @@ -0,0 +1,37 @@ + +typedef enum { + CmdDeclKind_Bool, + CmdDeclKind_Int, + CmdDeclKind_List, + CmdDeclKind_Enum, +} CmdDeclKind; + +typedef struct CmdDecl CmdDecl; +struct CmdDecl { + CmdDecl *next; + CmdDeclKind kind; + S8_String name; + S8_String help; + + bool *bool_result; + S8_List *list_result; + int *int_result; + + int *enum_result; + const char **enum_options; + int enum_option_count; +}; + +typedef struct CmdParser CmdParser; +struct CmdParser { + int argc; + char **argv; + MA_Arena *arena; + const char *custom_help; + + CmdDecl *fdecl; + CmdDecl *ldecl; + + bool require_one_standalone_arg; + S8_List args; +}; diff --git a/src/core/core.c b/src/core/core.c new file mode 100644 index 0000000..237749d --- /dev/null +++ b/src/core/core.c @@ -0,0 +1,23 @@ +#include "core.h" +#include "../standalone_libraries/stb_sprintf.c" +#define IO_VSNPRINTF stbsp_vsnprintf +#define IO_SNPRINTF stbsp_snprintf +#include "../standalone_libraries/io.c" +#define MA_Assertf(x, ...) IO_Assertf(x, __VA_ARGS__) +#include "../standalone_libraries/arena.c" +#define RE_ASSERT(x) IO_Assert(x) +#include "../standalone_libraries/regex.c" +#include "../standalone_libraries/unicode.c" +#define S8_VSNPRINTF stbsp_vsnprintf +#define S8_ALLOCATE(allocator, size) MA_PushSize(allocator, size) +#define S8_ASSERT(x) IO_Assert(x) +#define S8_MemoryCopy MA_MemoryCopy +#include "../standalone_libraries/string.c" +#define MU_ASSERT IO_Assert +#include "../standalone_libraries/multimedia.h" +#include "../standalone_libraries/hash.c" +#include "../standalone_libraries/load_library.c" +#include "filesystem.c" + +#include "cmd.c" +#include "allocator.c" \ No newline at end of file diff --git a/src/core/core.cpp b/src/core/core.cpp new file mode 100644 index 0000000..962f92f --- /dev/null +++ b/src/core/core.cpp @@ -0,0 +1 @@ +#include "core.c" \ No newline at end of file diff --git a/src/core/core.h b/src/core/core.h new file mode 100644 index 0000000..b60d7f9 --- /dev/null +++ b/src/core/core.h @@ -0,0 +1,25 @@ +#ifndef FIRST_CORE_HEADER +#define FIRST_CORE_HEADER + +#include "../standalone_libraries/preproc_env.h" +#include "../standalone_libraries/stb_sprintf.h" +#include "../standalone_libraries/io.h" +#include "../standalone_libraries/arena.h" +#include "../standalone_libraries/unicode.h" +#include "../standalone_libraries/string.h" +#include "../standalone_libraries/hash.h" +#include "../standalone_libraries/linked_list.h" +#include "../standalone_libraries/regex.h" +#include "../standalone_libraries/multimedia.h" +#include "../standalone_libraries/load_library.h" +#include "filesystem.h" +#include "cmd.h" +#include "allocator.h" + +#if LANG_CPP + #include "../standalone_libraries/defer.hpp" + #include "table.hpp" + #include "array.hpp" +#endif + +#endif \ No newline at end of file diff --git a/src/core/filesystem.c b/src/core/filesystem.c new file mode 100644 index 0000000..ce933f9 --- /dev/null +++ b/src/core/filesystem.c @@ -0,0 +1,720 @@ +#ifdef _WIN32 + #ifndef NOMINMAX + #define NOMINMAX + #endif + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #include + #include + +OS_API bool OS_EnableTerminalColors(void) { + // Enable color terminal output + { + // Set output mode to handle virtual terminal sequences + HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); + if (hOut != INVALID_HANDLE_VALUE) { + DWORD dwMode = 0; + if (GetConsoleMode(hOut, &dwMode)) { + dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; + if (SetConsoleMode(hOut, dwMode)) { + return true; + } else { + IO_Printf("Failed to enable colored terminal output C\n"); + } + } else { + IO_Printf("Failed to enable colored terminal output B\n"); + } + } else { + IO_Printf("Failed to enable colored terminal output A\n"); + } + } + return false; +} + +OS_API bool OS_IsAbsolute(S8_String path) { + bool result = path.len > 3 && CHAR_IsAlphabetic(path.str[0]) && path.str[1] == ':' && path.str[2] == '/'; + return result; +} + +OS_API S8_String OS_GetExePath(MA_Arena *arena) { + wchar_t wbuffer[1024]; + DWORD wsize = GetModuleFileNameW(0, wbuffer, MA_Lengthof(wbuffer)); + IO_Assert(wsize != 0); + + S8_String path = S8_FromWidecharEx(arena, wbuffer, wsize); + S8_NormalizePathUnsafe(path); + return path; +} + +OS_API S8_String OS_GetExeDir(MA_Arena *arena) { + MA_Temp scratch = MA_GetScratch(); + S8_String path = OS_GetExePath(scratch.arena); + path = S8_ChopLastSlash(path); + path = S8_Copy(arena, path); + MA_ReleaseScratch(scratch); + return path; +} + +OS_API S8_String OS_GetWorkingDir(MA_Arena *arena) { + wchar_t wbuffer[1024]; + DWORD wsize = GetCurrentDirectoryW(MA_Lengthof(wbuffer), wbuffer); + IO_Assert(wsize != 0); + IO_Assert(wsize < 1022); + wbuffer[wsize++] = '/'; + wbuffer[wsize] = 0; + + S8_String path = S8_FromWidecharEx(arena, wbuffer, wsize); + S8_NormalizePathUnsafe(path); + return path; +} + +OS_API void OS_SetWorkingDir(S8_String path) { + wchar_t wpath[1024]; + UTF_CreateWidecharFromChar(wpath, MA_Lengthof(wpath), path.str, path.len); + SetCurrentDirectoryW(wpath); +} + +OS_API S8_String OS_GetAbsolutePath(MA_Arena *arena, S8_String relative) { + wchar_t wpath[1024]; + UTF_CreateWidecharFromChar(wpath, MA_Lengthof(wpath), relative.str, relative.len); + wchar_t wpath_abs[1024]; + DWORD written = GetFullPathNameW((wchar_t *)wpath, MA_Lengthof(wpath_abs), wpath_abs, 0); + if (written == 0) + return S8_MakeEmpty(); + S8_String path = S8_FromWidecharEx(arena, wpath_abs, written); + S8_NormalizePathUnsafe(path); + return path; +} + +OS_API bool OS_FileExists(S8_String path) { + wchar_t wbuff[1024]; + UTF_CreateWidecharFromChar(wbuff, MA_Lengthof(wbuff), path.str, path.len); + DWORD attribs = GetFileAttributesW(wbuff); + bool result = attribs == INVALID_FILE_ATTRIBUTES ? false : true; + return result; +} + +OS_API bool OS_IsDir(S8_String path) { + wchar_t wbuff[1024]; + UTF_CreateWidecharFromChar(wbuff, MA_Lengthof(wbuff), path.str, path.len); + DWORD dwAttrib = GetFileAttributesW(wbuff); + return dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY); +} + +OS_API bool OS_IsFile(S8_String path) { + wchar_t wbuff[1024]; + UTF_CreateWidecharFromChar(wbuff, MA_Lengthof(wbuff), path.str, path.len); + DWORD dwAttrib = GetFileAttributesW(wbuff); + bool is_file = (dwAttrib & FILE_ATTRIBUTE_DIRECTORY) == 0; + return dwAttrib != INVALID_FILE_ATTRIBUTES && is_file; +} + +OS_API double OS_GetTime(void) { + static int64_t counts_per_second; + if (counts_per_second == 0) { + LARGE_INTEGER freq; + QueryPerformanceFrequency(&freq); + counts_per_second = freq.QuadPart; + } + + LARGE_INTEGER time; + QueryPerformanceCounter(&time); + double result = (double)time.QuadPart / (double)counts_per_second; + return result; +} + +/* +User needs to copy particular filename to keep it. + +for (OS_FileIter it = OS_IterateFiles(it); OS_IsValid(iter); OS_Advance(it)) { +} + +*/ + +typedef struct OS_Win32_FileIter { + HANDLE handle; + WIN32_FIND_DATAW data; +} OS_Win32_FileIter; + +OS_API bool OS_IsValid(OS_FileIter it) { + return it.is_valid; +} + +OS_API void OS_Advance(OS_FileIter *it) { + while (FindNextFileW(it->w32->handle, &it->w32->data) != 0) { + WIN32_FIND_DATAW *data = &it->w32->data; + + // Skip '.' and '..' + if (data->cFileName[0] == '.' && data->cFileName[1] == '.' && data->cFileName[2] == 0) continue; + if (data->cFileName[0] == '.' && data->cFileName[1] == 0) continue; + + it->is_directory = data->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; + it->filename = S8_FromWidecharEx(it->arena, data->cFileName, S8_WideLength(data->cFileName)); + const char *is_dir = it->is_directory ? "/" : ""; + const char *separator = it->path.str[it->path.len - 1] == '/' ? "" : "/"; + it->relative_path = S8_Format(it->arena, "%.*s%s%.*s%s", S8_Expand(it->path), separator, S8_Expand(it->filename), is_dir); + it->absolute_path = OS_GetAbsolutePath(it->arena, it->relative_path); + it->is_valid = true; + + if (it->is_directory) { + IO_Assert(it->relative_path.str[it->relative_path.len - 1] == '/'); + IO_Assert(it->absolute_path.str[it->absolute_path.len - 1] == '/'); + } + return; + } + + it->is_valid = false; + DWORD error = GetLastError(); + IO_Assert(error == ERROR_NO_MORE_FILES); + FindClose(it->w32->handle); +} + +OS_API OS_FileIter OS_IterateFiles(MA_Arena *scratch_arena, S8_String path) { + OS_FileIter it = {0}; + it.arena = scratch_arena; + it.path = path; + + S8_String modified_path = S8_Format(it.arena, "%.*s\\*", S8_Expand(path)); + wchar_t *wbuff = MA_PushArray(it.arena, wchar_t, modified_path.len + 1); + int64_t wsize = UTF_CreateWidecharFromChar(wbuff, modified_path.len + 1, modified_path.str, modified_path.len); + IO_Assert(wsize); + + it.w32 = MA_PushStruct(it.arena, OS_Win32_FileIter); + it.w32->handle = FindFirstFileW(wbuff, &it.w32->data); + if (it.w32->handle == INVALID_HANDLE_VALUE) { + it.is_valid = false; + return it; + } + + IO_Assert(it.w32->data.cFileName[0] == '.' && it.w32->data.cFileName[1] == 0); + OS_Advance(&it); + return it; +} + +OS_API OS_Result OS_MakeDir(S8_String path) { + wchar_t wpath[1024]; + UTF_CreateWidecharFromChar(wpath, MA_Lengthof(wpath), path.str, path.len); + BOOL success = CreateDirectoryW(wpath, NULL); + OS_Result result = OS_SUCCESS; + if (success == 0) { + DWORD error = GetLastError(); + if (error == ERROR_ALREADY_EXISTS) { + result = OS_ALREADY_EXISTS; + } else if (error == ERROR_PATH_NOT_FOUND) { + result = OS_PATH_NOT_FOUND; + } else { + IO_Assert(0); + } + } + return result; +} + +OS_API OS_Result OS_CopyFile(S8_String from, S8_String to, bool overwrite) { + wchar_t wfrom[1024]; + UTF_CreateWidecharFromChar(wfrom, MA_Lengthof(wfrom), from.str, from.len); + + wchar_t wto[1024]; + UTF_CreateWidecharFromChar(wto, MA_Lengthof(wto), to.str, to.len); + + BOOL fail_if_exists = !overwrite; + BOOL success = CopyFileW(wfrom, wto, fail_if_exists); + + OS_Result result = OS_SUCCESS; + if (success == FALSE) + result = OS_FAILURE; + return result; +} + +OS_API OS_Result OS_DeleteFile(S8_String path) { + wchar_t wpath[1024]; + UTF_CreateWidecharFromChar(wpath, MA_Lengthof(wpath), path.str, path.len); + BOOL success = DeleteFileW(wpath); + OS_Result result = OS_SUCCESS; + if (success == 0) + result = OS_PATH_NOT_FOUND; + return result; +} + +OS_API OS_Result OS_DeleteDir(S8_String path, unsigned flags) { + IO_Todo(); + return OS_FAILURE; + #if 0 + if (flags & OS_RECURSIVE) { + MA_Temp scratch = MA_GetScratch(); + S8_List list = OS_ListDir(scratch.arena, path, OS_RECURSIVE); + S8_Node *dirs_to_remove = 0; + for (S8_Node *it = list.first; it; it = it->next) { + if (!S8_EndsWith(it->string, S8_Lit("/"), S8_IgnoreCase)) { + OS_DeleteFile(it->string); + } + else { + S8_Node *node = S8_CreateNode(scratch.arena, it->string); + SLL_STACK_ADD(dirs_to_remove, node); + } + } + for (S8_Node *it = dirs_to_remove; it; it = it->next) { + OS_DeleteDir(it->string, OS_NO_FLAGS); + } + OS_Result result = OS_DeleteDir(path, OS_NO_FLAGS); + MA_ReleaseScratch(scratch); + return result; + } + else { + wchar_t wpath[1024]; + UTF_CreateWidecharFromChar(wpath, MA_Lengthof(wpath), path.str, path.len); + BOOL success = RemoveDirectoryW(wpath); + OS_Result result = OS_SUCCESS; + if (success == 0) + result = OS_PATH_NOT_FOUND; + return result; + } + #endif +} + +static OS_Result OS__WriteFile(S8_String path, S8_String data, bool append) { + wchar_t wpath[1024]; + UTF_CreateWidecharFromChar(wpath, MA_Lengthof(wpath), path.str, path.len); + OS_Result result = OS_FAILURE; + + DWORD access = GENERIC_WRITE; + DWORD creation_disposition = CREATE_ALWAYS; + if (append) { + access = FILE_APPEND_DATA; + creation_disposition = OPEN_ALWAYS; + } + + HANDLE handle = CreateFileW(wpath, access, 0, NULL, creation_disposition, FILE_ATTRIBUTE_NORMAL, NULL); + if (handle != INVALID_HANDLE_VALUE) { + DWORD bytes_written = 0; + IO_Assert(data.len == (DWORD)data.len); // @Todo: can only read 32 byte size files? + BOOL error = WriteFile(handle, data.str, (DWORD)data.len, &bytes_written, NULL); + if (error == TRUE) { + if (bytes_written == data.len) { + result = OS_SUCCESS; + } + } + CloseHandle(handle); + } else result = OS_PATH_NOT_FOUND; + + return result; +} + +OS_API OS_Result OS_AppendFile(S8_String path, S8_String string) { + return OS__WriteFile(path, string, true); +} + +OS_API OS_Result OS_WriteFile(S8_String path, S8_String string) { + return OS__WriteFile(path, string, false); +} + +OS_API S8_String OS_ReadFile(MA_Arena *arena, S8_String path) { + bool success = false; + S8_String result = S8_MakeEmpty(); + MA_Temp checkpoint = MA_BeginTemp(arena); + + wchar_t wpath[1024]; + UTF_CreateWidecharFromChar(wpath, MA_Lengthof(wpath), path.str, path.len); + HANDLE handle = CreateFileW(wpath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (handle != INVALID_HANDLE_VALUE) { + LARGE_INTEGER file_size; + if (GetFileSizeEx(handle, &file_size)) { + if (file_size.QuadPart != 0) { + result.len = (int64_t)file_size.QuadPart; + result.str = (char *)MA_PushSizeNonZeroed(arena, result.len + 1); + DWORD read; + if (ReadFile(handle, result.str, (DWORD)result.len, &read, NULL)) { // @todo: can only read 32 byte size files? + if (read == result.len) { + success = true; + result.str[result.len] = 0; + } + } + } + } + CloseHandle(handle); + } + + if (!success) { + result = S8_MakeEmpty(); + MA_EndTemp(checkpoint); + } + + return result; +} + +OS_API int64_t OS_GetFileModTime(S8_String file) { + FILETIME time = {0}; + WIN32_FIND_DATAW data; + + wchar_t wpath[1024]; + UTF_CreateWidecharFromChar(wpath, 1024, file.str, file.len); + HANDLE handle = FindFirstFileW(wpath, &data); + if (handle != INVALID_HANDLE_VALUE) { + FindClose(handle); + time = data.ftLastWriteTime; + } else { + return -1; + } + int64_t result = (int64_t)time.dwHighDateTime << 32 | time.dwLowDateTime; + return result; +} + +OS_API OS_Date OS_GetDate(void) { + SYSTEMTIME local; + GetLocalTime(&local); + + OS_Date result = {0}; + result.year = local.wYear; + result.month = local.wMonth; + result.day = local.wDay; + result.hour = local.wHour; + result.second = local.wSecond; + // result.milliseconds = local.wMilliseconds; + return result; +} + +#elif __linux__ || __APPLE__ || __unix__ + #include + #include + #include + #include + #include + + #if OS_MAC + #include + +OS_API S8_String OS_GetExePath(MA_Arena *arena) { + char buf[PATH_MAX]; + uint32_t bufsize = PATH_MAX; + if (_NSGetExecutablePath(buf, &bufsize)) { + return S8_MakeEmpty(); + } + + S8_String result = S8_Copy(arena, S8_MakeFromChar(buf)); + return result; +} + + #else + +OS_API S8_String OS_GetExePath(MA_Arena *arena) { + char buffer[PATH_MAX] = {}; + if (readlink("/proc/self/exe", buffer, PATH_MAX) == -1) { + return S8_MakeEmpty(); + } + S8_String result = S8_Copy(arena, S8_MakeFromChar(buffer)); + return result; +} + + #endif + +OS_API bool OS_EnableTerminalColors(void) { return true; } + +OS_API bool OS_IsAbsolute(S8_String path) { + bool result = path.len >= 1 && path.str[0] == '/'; + return result; +} + +OS_API S8_String OS_GetExeDir(MA_Arena *arena) { + MA_Temp scratch = MA_GetScratch(); + S8_String path = OS_GetExePath(scratch.arena); + S8_String dir = S8_ChopLastSlash(path); + S8_String copy = S8_Copy(arena, dir); + MA_ReleaseScratch(scratch); + return copy; +} + +OS_API S8_String OS_GetWorkingDir(MA_Arena *arena) { + char *buffer = (char *)MA_PushSizeNonZeroed(arena, PATH_MAX); + char *cwd = getcwd(buffer, PATH_MAX); + S8_String result = S8_MakeFromChar(cwd); + return result; +} + +OS_API void OS_SetWorkingDir(S8_String path) { + MA_Temp scratch = MA_GetScratch(); + S8_String copy = S8_Copy(scratch.arena, path); + chdir(copy.str); + MA_ReleaseScratch(scratch); +} + +OS_API S8_String OS_GetAbsolutePath(MA_Arena *arena, S8_String relative) { + MA_Temp scratch = MA_GetScratch1(arena); + S8_String copy = S8_Copy(scratch.arena, relative); + + char *buffer = (char *)MA_PushSizeNonZeroed(arena, PATH_MAX); + realpath((char *)copy.str, buffer); + S8_String result = S8_MakeFromChar(buffer); + + MA_ReleaseScratch(scratch); + return result; +} + +OS_API bool OS_FileExists(S8_String path) { + MA_Temp scratch = MA_GetScratch(); + S8_String copy = S8_Copy(scratch.arena, path); + + bool result = false; + if (access((char *)copy.str, F_OK) == 0) { + result = true; + } + + MA_ReleaseScratch(scratch); + return result; +} + +OS_API bool OS_IsDir(S8_String path) { + MA_Temp scratch = MA_GetScratch(); + S8_String copy = S8_Copy(scratch.arena, path); + + struct stat s; + if (stat(copy.str, &s) != 0) + return false; + + bool result = S_ISDIR(s.st_mode); + MA_ReleaseScratch(scratch); + return result; +} + +OS_API bool OS_IsFile(S8_String path) { + MA_Temp scratch = MA_GetScratch(); + S8_String copy = S8_Copy(scratch.arena, path); + + struct stat s; + if (stat(copy.str, &s) != 0) + return false; + bool result = S_ISREG(s.st_mode); + MA_ReleaseScratch(scratch); + return result; +} + +OS_API double OS_GetTime(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + uint64_t timeu64 = (((uint64_t)ts.tv_sec) * 1000000ull) + ((uint64_t)ts.tv_nsec) / 1000ull; + double timef = (double)timeu64; + double result = timef / 1000000.0; // Microseconds to seconds + return result; +} + +OS_API bool OS_IsValid(OS_FileIter it) { + return it.is_valid; +} + +OS_API void OS_Advance(OS_FileIter *it) { + struct dirent *file = 0; + while ((file = readdir((DIR *)it->dir)) != NULL) { + if (file->d_name[0] == '.' && file->d_name[1] == '.' && file->d_name[2] == 0) continue; + if (file->d_name[0] == '.' && file->d_name[1] == 0) continue; + + it->is_directory = file->d_type == DT_DIR; + it->filename = S8_CopyChar(it->arena, file->d_name); + + const char *dir_char_ending = it->is_directory ? "/" : ""; + const char *separator = it->path.str[it->path.len - 1] == '/' ? "" : "/"; + it->relative_path = S8_Format(it->arena, "%.*s%s%s%s", S8_Expand(it->path), separator, file->d_name, dir_char_ending); + it->absolute_path = OS_GetAbsolutePath(it->arena, it->relative_path); + if (it->is_directory) it->absolute_path = S8_Format(it->arena, "%.*s/", S8_Expand(it->absolute_path)); + it->is_valid = true; + return; + } + it->is_valid = false; + closedir((DIR *)it->dir); +} + +OS_API OS_FileIter OS_IterateFiles(MA_Arena *arena, S8_String path) { + OS_FileIter it = {0}; + it.arena = arena; + it.path = path = S8_Copy(arena, path); + it.dir = (void *)opendir((char *)path.str); + if (!it.dir) return it; + + OS_Advance(&it); + return it; +} + +OS_API OS_Result OS_MakeDir(S8_String path) { + MA_Temp scratch = MA_GetScratch(); + path = S8_Copy(scratch.arena, path); + int error = mkdir(path.str, 0755); + MA_ReleaseScratch(scratch); + return error == 0 ? OS_SUCCESS : OS_FAILURE; +} + +OS_API OS_Result OS_CopyFile(S8_String from, S8_String to, bool overwrite) { + const char *ow = overwrite ? "-n" : ""; + int result = OS_SystemF("cp %s %.*s %.*s", ow, S8_Expand(from), S8_Expand(to)); + return result == 0 ? OS_SUCCESS : OS_FAILURE; +} + +OS_API OS_Result OS_DeleteFile(S8_String path) { + int result = OS_SystemF("rm %.*s", S8_Expand(path)); + return result == 0 ? OS_SUCCESS : OS_FAILURE; +} + +OS_API OS_Result OS_DeleteDir(S8_String path, unsigned flags) { + IO_Assert(flags & OS_RECURSIVE); + int result = OS_SystemF("rm -r %.*s", S8_Expand(path)); + return result == 0 ? OS_SUCCESS : OS_FAILURE; +} + +OS_API int64_t OS_GetFileModTime(S8_String file) { + MA_Temp scratch = MA_GetScratch(); + file = S8_Copy(scratch.arena, file); + + struct stat attrib = {}; + stat(file.str, &attrib); + struct timespec ts = attrib.IF_LINUX_ELSE(st_mtim, st_mtimespec); + int64_t result = (((int64_t)ts.tv_sec) * 1000000ll) + ((int64_t)ts.tv_nsec) / 1000ll; + + MA_ReleaseScratch(scratch); + return result; +} + +OS_API OS_Date OS_GetDate(void) { + time_t t = time(NULL); + struct tm date = *localtime(&t); + + OS_Date s = {0}; + s.second = date.tm_sec; + s.year = date.tm_year; + s.month = date.tm_mon; + s.day = date.tm_mday; + s.hour = date.tm_hour; + s.minute = date.tm_min; + + return s; +} + +OS_API OS_Result OS_AppendFile(S8_String path, S8_String string) { + MA_Temp scratch = MA_GetScratch(); + path = S8_Copy(scratch.arena, path); + + OS_Result result = OS_FAILURE; + FILE *f = fopen((const char *)path.str, "a"); + if (f) { + result = OS_SUCCESS; + + size_t written = fwrite(string.str, 1, string.len, f); + if (written < string.len) { + result = OS_FAILURE; + } + + int error = fclose(f); + if (error != 0) { + result = OS_FAILURE; + } + } + + MA_ReleaseScratch(scratch); + return result; +} + +OS_API S8_String OS_ReadFile(MA_Arena *arena, S8_String path) { + S8_String result = {}; + + // ftell returns insane size if file is + // a directory **on some machines** KEKW + if (OS_IsDir(path)) { + return result; + } + + MA_Temp scratch = MA_GetScratch1(arena); + path = S8_Copy(scratch.arena, path); + + FILE *f = fopen(path.str, "rb"); + if (f) { + fseek(f, 0, SEEK_END); + result.len = ftell(f); + fseek(f, 0, SEEK_SET); + + result.str = (char *)MA_PushSizeNonZeroed(arena, result.len + 1); + fread(result.str, result.len, 1, f); + result.str[result.len] = 0; + + fclose(f); + } + + MA_ReleaseScratch(scratch); + return result; +} + +OS_API OS_Result OS_WriteFile(S8_String path, S8_String string) { + MA_Temp scratch = MA_GetScratch(); + path = S8_Copy(scratch.arena, path); + + OS_Result result = OS_FAILURE; + FILE *f = fopen((const char *)path.str, "w"); + if (f) { + result = OS_SUCCESS; + + size_t written = fwrite(string.str, 1, string.len, f); + if (written < string.len) { + result = OS_FAILURE; + } + + int error = fclose(f); + if (error != 0) { + result = OS_FAILURE; + } + } + + MA_ReleaseScratch(scratch); + return result; +} +#endif + +#if _WIN32 || __linux__ || __APPLE__ || __unix__ +OS_API int OS_SystemF(const char *string, ...) { + MA_Temp scratch = MA_GetScratch(); + S8_FORMAT(scratch.arena, string, result); + IO_Printf("Executing: %.*s\n", S8_Expand(result)); + fflush(stdout); + int error_code = system(result.str); + MA_ReleaseScratch(scratch); + return error_code; +} + +OS_API bool OS_ExpandIncludesList(MA_Arena *arena, S8_List *out, S8_String filepath) { + S8_String c = OS_ReadFile(arena, filepath); + if (c.str == 0) return false; + S8_String path = S8_ChopLastSlash(filepath); + S8_String include = S8_Lit("#include \""); + for (;;) { + int64_t idx = -1; + if (S8_Seek(c, include, 0, &idx)) { + S8_String str_to_add = S8_GetPrefix(c, idx); + S8_AddNode(arena, out, str_to_add); + S8_String save = c; + c = S8_Skip(c, idx + include.len); + + S8_String filename = c; + filename.len = 0; + while (filename.str[filename.len] != '"' && filename.len < c.len) { + filename.len += 1; + } + + c = S8_Skip(c, filename.len + 1); + S8_String inc_path = S8_Format(arena, "%.*s/%.*s", S8_Expand(path), S8_Expand(filename)); + if (!OS_ExpandIncludesList(arena, out, inc_path)) { + S8_String s = S8_GetPrefix(save, save.len - c.len); + S8_AddNode(arena, out, s); + } + } else { + S8_AddNode(arena, out, c); + break; + } + } + return true; +} + +OS_API S8_String OS_ExpandIncludes(MA_Arena *arena, S8_String filepath) { + S8_List out = S8_MakeEmptyList(); + S8_String result = S8_MakeEmpty(); + MA_ScratchScope(s) { + OS_ExpandIncludesList(s.arena, &out, filepath); + result = S8_Merge(arena, out); + } + return result; +} +#endif \ No newline at end of file diff --git a/src/core/filesystem.h b/src/core/filesystem.h new file mode 100644 index 0000000..b1c158a --- /dev/null +++ b/src/core/filesystem.h @@ -0,0 +1,73 @@ +// Quick and dirty filesystem operations + +#ifndef OS_API + #define OS_API +#endif + +typedef enum OS_Result { + OS_SUCCESS, + OS_ALREADY_EXISTS, + OS_PATH_NOT_FOUND, + OS_FAILURE, +} OS_Result; + +enum { + OS_NO_FLAGS = 0, + OS_RECURSIVE = 1, + OS_RELATIVE_PATHS = 2, +}; + +typedef struct OS_Date OS_Date; +struct OS_Date { + uint32_t year; + uint32_t month; + uint32_t day; + uint32_t hour; + uint32_t minute; + uint32_t second; +}; + +typedef struct OS_FileIter OS_FileIter; +struct OS_FileIter { + bool is_valid; + bool is_directory; + S8_String absolute_path; + S8_String relative_path; + S8_String filename; + + S8_String path; + MA_Arena *arena; + union { + struct OS_Win32_FileIter *w32; + void *dir; + }; +}; + +OS_API bool OS_IsAbsolute(S8_String path); +OS_API S8_String OS_GetExePath(MA_Arena *arena); +OS_API S8_String OS_GetExeDir(MA_Arena *arena); +OS_API S8_String OS_GetWorkingDir(MA_Arena *arena); +OS_API void OS_SetWorkingDir(S8_String path); +OS_API S8_String OS_GetAbsolutePath(MA_Arena *arena, S8_String relative); +OS_API bool OS_FileExists(S8_String path); +OS_API bool OS_IsDir(S8_String path); +OS_API bool OS_IsFile(S8_String path); +OS_API double OS_GetTime(void); +OS_API OS_Result OS_MakeDir(S8_String path); +OS_API OS_Result OS_CopyFile(S8_String from, S8_String to, bool overwrite); +OS_API OS_Result OS_DeleteFile(S8_String path); +OS_API OS_Result OS_DeleteDir(S8_String path, unsigned flags); +OS_API OS_Result OS_AppendFile(S8_String path, S8_String string); +OS_API OS_Result OS_WriteFile(S8_String path, S8_String string); +OS_API S8_String OS_ReadFile(MA_Arena *arena, S8_String path); +OS_API int OS_SystemF(const char *string, ...); +OS_API int64_t OS_GetFileModTime(S8_String file); +OS_API OS_Date OS_GetDate(void); +OS_API S8_String UTF_CreateStringFromWidechar(MA_Arena *arena, wchar_t *wstr, int64_t wsize); +OS_API bool OS_ExpandIncludesList(MA_Arena *arena, S8_List *out, S8_String filepath); +OS_API S8_String OS_ExpandIncludes(MA_Arena *arena, S8_String filepath); +OS_API bool OS_EnableTerminalColors(void); + +OS_API bool OS_IsValid(OS_FileIter it); +OS_API void OS_Advance(OS_FileIter *it); +OS_API OS_FileIter OS_IterateFiles(MA_Arena *scratch_arena, S8_String path); \ No newline at end of file diff --git a/src/core/table.hpp b/src/core/table.hpp new file mode 100644 index 0000000..374a803 --- /dev/null +++ b/src/core/table.hpp @@ -0,0 +1,204 @@ +/* + Hash table implementation: + Pointers to values + Open adressing + Linear Probing + Power of 2 + Robin Hood hashing + Resizes on high probe count (min max load factor) + + Hash 0 is reserved for empty hash table entry +*/ + +template +struct Table { + struct Entry { + uint64_t hash; + uint64_t key; + size_t distance; + Value value; + }; + + M_Allocator allocator; + size_t len, cap; + Entry *values; + + static const size_t max_load_factor = 80; + static const size_t min_load_factor = 50; + static const size_t significant_distance = 8; + + // load factor calculation was rearranged + // to get rid of division: + //> 100 * len / cap = load_factor + //> len * 100 = load_factor * cap + inline bool reached_load_factor(size_t lfactor) { + return (len + 1) * 100 >= lfactor * cap; + } + + inline bool is_empty(Entry *entry) { return entry->hash == 0; } + inline bool is_occupied(Entry *entry) { return entry->hash != 0; } + + void reserve(size_t size) { + IO_Assert(size > cap && "New size is smaller then original size"); + IO_Assert(MA_IS_POW2(size)); + if (!allocator.p) allocator = M_GetSystemAllocator(); + + Entry *old_values = values; + size_t old_cap = cap; + + values = (Entry *)M_Alloc(allocator, sizeof(Entry) * size); + for (int i = 0; i < size; i += 1) values[i] = {}; + cap = size; + + IO_Assert(!(old_values == 0 && len != 0)); + if (len == 0) { + if (old_values) M_Dealloc(allocator, old_values); + return; + } + + len = 0; + for (size_t i = 0; i < old_cap; i += 1) { + Entry *it = old_values + i; + if (is_occupied(it)) { + insert(it->key, it->value); + } + } + M_Dealloc(allocator, old_values); + } + + Entry *get_table_entry(uint64_t key) { + if (len == 0) return 0; + uint64_t hash = HashBytes(&key, sizeof(key)); + if (hash == 0) hash += 1; + uint64_t index = WRAP_AROUND_POWER_OF_2(hash, cap); + uint64_t i = index; + uint64_t distance = 0; + for (;;) { + Entry *it = values + i; + if (distance > it->distance) { + return 0; + } + + if (it->hash == hash && it->key == key) { + return it; + } + + distance += 1; + i = WRAP_AROUND_POWER_OF_2(i + 1, cap); + if (i == index) return 0; + } + IO_Assert(!"Invalid codepath"); + } + + void insert(uint64_t key, const Value &value) { + if (reached_load_factor(max_load_factor)) { + if (cap == 0) cap = 16; // 32 cause cap*2 + reserve(cap * 2); + } + + uint64_t hash = HashBytes(&key, sizeof(key)); + if (hash == 0) hash += 1; + uint64_t index = WRAP_AROUND_POWER_OF_2(hash, cap); + uint64_t i = index; + Entry to_insert = {hash, key, 0, value}; + for (;;) { + Entry *it = values + i; + if (is_empty(it)) { + *it = to_insert; + len += 1; + // If we have more then 8 consecutive items we try to resize + if (to_insert.distance > 8 && reached_load_factor(min_load_factor)) { + reserve(cap * 2); + } + return; + } + if (it->hash == hash && it->key == key) { + *it = to_insert; + // If we have more then 8 consecutive items we try to resize + if (to_insert.distance > 8 && reached_load_factor(min_load_factor)) { + reserve(cap * 2); + } + return; + } + + // Robin hood hashing + if (to_insert.distance > it->distance) { + Entry temp = to_insert; + to_insert = *it; + *it = temp; + } + + to_insert.distance += 1; + i = WRAP_AROUND_POWER_OF_2(i + 1, cap); + IO_Assert(i != index && "Did a full 360 through a hash table, no good :( that shouldnt be possible"); + } + IO_Assert(!"Invalid codepath"); + } + + void remove(uint64_t key) { + Entry *entry = get_table_entry(key); + entry->hash = 0; + entry->distance = 0; + len -= 1; + } + + Value *get(uint64_t key) { + Entry *v = get_table_entry(key); + if (!v) return 0; + return &v->value; + } + + Value get(uint64_t key, Value default_value) { + Entry *v = get_table_entry(key); + if (!v) return default_value; + return v->value; + } + + Value *gets(char *str) { + int len = S8_Length(str); + uint64_t hash = HashBytes(str, len); + return get(hash); + } + + Value gets(char *str, Value default_value) { + int len = S8_Length(str); + uint64_t hash = HashBytes(str, len); + return get(hash, default_value); + } + + Value *get(S8_String s) { + uint64_t hash = HashBytes(s.str, (unsigned)s.len); + return get(hash); + } + + Value get(S8_String s, Value default_value) { + uint64_t hash = HashBytes(s.str, (unsigned)s.len); + return get(hash, default_value); + } + + void put(S8_String s, const Value &value) { + uint64_t hash = HashBytes(s.str, (unsigned)s.len); + insert(hash, value); + } + + void puts(char *str, const Value &value) { + int len = S8_Length(str); + uint64_t hash = HashBytes(str, len); + insert(hash, value); + } + + void reset() { + len = 0; + for (size_t i = 0; i < cap; i += 1) { + Entry *it = values + i; + it->hash = 0; + } + } + + void dealloc() { + M_Dealloc(allocator, values); + len = 0; + cap = 0; + values = 0; + } +}; diff --git a/src/profiler/profiler.c b/src/profiler/profiler.c new file mode 100644 index 0000000..8728848 --- /dev/null +++ b/src/profiler/profiler.c @@ -0,0 +1,62 @@ +#if defined(LC_ENABLE_PROFILER) + #include "spall.h" +static SpallProfile spall_ctx; +static SpallBuffer spall_buffer; + +LC_FUNCTION void LC_BeginProfiling() { + spall_ctx = spall_init_file("lc.spall", 1); + + int buffer_size = 1 * 1024 * 1024 * 4; + unsigned char *buffer = (unsigned char *)malloc(buffer_size); + + spall_buffer.length = buffer_size; + spall_buffer.data = buffer; + spall_buffer_init(&spall_ctx, &spall_buffer); +} + +LC_FUNCTION void LC_EndProfiling() { + spall_buffer_quit(&spall_ctx, &spall_buffer); + free(spall_buffer.data); + spall_quit(&spall_ctx); +} + + #if _WIN32 + #include +double LC_GetTime(void) { + static double invfreq; + if (!invfreq) { + LARGE_INTEGER frequency; + QueryPerformanceFrequency(&frequency); + invfreq = 1000000.0 / frequency.QuadPart; + } + LARGE_INTEGER counter; + QueryPerformanceCounter(&counter); + return counter.QuadPart * invfreq; +} + #else + #include +double LC_GetTime(void) { + struct timespec spec; + clock_gettime(CLOCK_MONOTONIC, &spec); + return (((double)spec.tv_sec) * 1000000) + (((double)spec.tv_nsec) / 1000); +} + #endif + +struct LC_ProfileScope { + LC_ProfileScope(const char *fn, int size) { + spall_buffer_begin(&spall_ctx, &spall_buffer, fn, size - 1, LC_GetTime()); + } + ~LC_ProfileScope() { + spall_buffer_end(&spall_ctx, &spall_buffer, LC_GetTime()); + } +}; + + #define LC_ProfileScope() \ + LC_ProfileScope TIME_SCOPE_(__FUNCTION__, sizeof(__FUNCTION__)) +#else + #define LC_ProfileScope() +LC_FUNCTION void LC_BeginProfiling() { +} +LC_FUNCTION void LC_EndProfiling() { +} +#endif \ No newline at end of file diff --git a/src/profiler/spall.h b/src/profiler/spall.h new file mode 100644 index 0000000..45b7ce0 --- /dev/null +++ b/src/profiler/spall.h @@ -0,0 +1,448 @@ +// SPDX-FileCopyrightText: © 2023 Phillip Trudeau-Tavara +// SPDX-License-Identifier: MIT + +/* + +TODO: Optional Helper APIs: + + - Compression API: would require a mutexed lockable context (yuck...) + - Either using a ZIP library, a name cache + TIDPID cache, or both (but ZIP is likely more than enough!!!) + - begin()/end() writes compressed chunks to a caller-determined destination + - The destination can be the buffered-writing API or a custom user destination + - Ultimately need to take a lock with some granularity... can that be the caller's responsibility? + + - Counter Event: should allow tracking arbitrary named values with a single event, for memory and frame profiling + + - Ring-buffer API + spall_ring_init + spall_ring_emit_begin + spall_ring_emit_end + spall_ring_flush +*/ + +#ifndef SPALL_H +#define SPALL_H + +#if !defined(_MSC_VER) || defined(__clang__) + #define SPALL_NOINSTRUMENT __attribute__((no_instrument_function)) + #define SPALL_FORCEINLINE __attribute__((always_inline)) +#else + #define _CRT_SECURE_NO_WARNINGS + #define SPALL_NOINSTRUMENT // Can't noinstrument on MSVC! + #define SPALL_FORCEINLINE __forceinline +#endif + +#include +#include +#include +#include + +#define SPALL_FN static inline SPALL_NOINSTRUMENT + +#define SPALL_MIN(a, b) (((a) < (b)) ? (a) : (b)) + +#pragma pack(push, 1) + +typedef struct SpallHeader { + uint64_t magic_header; // = 0x0BADF00D + uint64_t version; // = 1 + double timestamp_unit; + uint64_t must_be_0; +} SpallHeader; + +enum { + SpallEventType_Invalid = 0, + SpallEventType_Custom_Data = 1, // Basic readers can skip this. + SpallEventType_StreamOver = 2, + + SpallEventType_Begin = 3, + SpallEventType_End = 4, + SpallEventType_Instant = 5, + + SpallEventType_Overwrite_Timestamp = 6, // Retroactively change timestamp units - useful for incrementally improving RDTSC frequency. + SpallEventType_Pad_Skip = 7, +}; + +typedef struct SpallBeginEvent { + uint8_t type; // = SpallEventType_Begin + uint8_t category; + + uint32_t pid; + uint32_t tid; + double when; + + uint8_t name_length; + uint8_t args_length; +} SpallBeginEvent; + +typedef struct SpallBeginEventMax { + SpallBeginEvent event; + char name_bytes[255]; + char args_bytes[255]; +} SpallBeginEventMax; + +typedef struct SpallEndEvent { + uint8_t type; // = SpallEventType_End + uint32_t pid; + uint32_t tid; + double when; +} SpallEndEvent; + +typedef struct SpallPadSkipEvent { + uint8_t type; // = SpallEventType_Pad_Skip + uint32_t size; +} SpallPadSkipEvent; + +#pragma pack(pop) + +typedef struct SpallProfile SpallProfile; + +// Important!: If you define your own callbacks, mark them SPALL_NOINSTRUMENT! +typedef bool (*SpallWriteCallback)(SpallProfile *self, const void *data, size_t length); +typedef bool (*SpallFlushCallback)(SpallProfile *self); +typedef void (*SpallCloseCallback)(SpallProfile *self); + +struct SpallProfile { + double timestamp_unit; + bool is_json; + SpallWriteCallback write; + SpallFlushCallback flush; + SpallCloseCallback close; + void *data; +}; + +// Important!: If you are writing Begin/End events, then do NOT write +// events for the same PID + TID pair on different buffers!!! +typedef struct SpallBuffer { + void *data; + size_t length; + + // Internal data - don't assign this + size_t head; + SpallProfile *ctx; +} SpallBuffer; + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(SPALL_BUFFER_PROFILING) && !defined(SPALL_BUFFER_PROFILING_GET_TIME) + #error "You must #define SPALL_BUFFER_PROFILING_GET_TIME() to profile buffer flushes." +#endif + +SPALL_FN SPALL_FORCEINLINE void spall__buffer_profile(SpallProfile *ctx, SpallBuffer *wb, double spall_time_begin, double spall_time_end, const char *name, int name_len); +#ifdef SPALL_BUFFER_PROFILING + #define SPALL_BUFFER_PROFILE_BEGIN() double spall_time_begin = (SPALL_BUFFER_PROFILING_GET_TIME()) + // Don't call this with anything other than a string literal + #define SPALL_BUFFER_PROFILE_END(name) spall__buffer_profile(ctx, wb, spall_time_begin, (SPALL_BUFFER_PROFILING_GET_TIME()), "" name "", sizeof("" name "") - 1) +#else + #define SPALL_BUFFER_PROFILE_BEGIN() + #define SPALL_BUFFER_PROFILE_END(name) +#endif + +SPALL_FN SPALL_FORCEINLINE bool spall__file_write(SpallProfile *ctx, const void *p, size_t n) { + if (!ctx->data) return false; +#ifdef SPALL_DEBUG + if (feof((FILE *)ctx->data)) return false; + if (ferror((FILE *)ctx->data)) return false; +#endif + + if (fwrite(p, n, 1, (FILE *)ctx->data) != 1) return false; + return true; +} +SPALL_FN bool spall__file_flush(SpallProfile *ctx) { + if (!ctx->data) return false; + if (fflush((FILE *)ctx->data)) return false; + return true; +} +SPALL_FN void spall__file_close(SpallProfile *ctx) { + if (!ctx->data) return; + + if (ctx->is_json) { +#ifdef SPALL_DEBUG + if (!feof((FILE *)ctx->data) && !ferror((FILE *)ctx->data)) +#endif + { + fseek((FILE *)ctx->data, -2, SEEK_CUR); // seek back to overwrite trailing comma + fwrite("\n]}\n", sizeof("\n]}\n") - 1, 1, (FILE *)ctx->data); + } + } + fflush((FILE *)ctx->data); + fclose((FILE *)ctx->data); + ctx->data = NULL; +} + +SPALL_FN SPALL_FORCEINLINE bool spall__buffer_flush(SpallProfile *ctx, SpallBuffer *wb) { + // precon: wb + // precon: wb->data + // precon: wb->head <= wb->length + // precon: !ctx || ctx->write +#ifdef SPALL_DEBUG + if (wb->ctx != ctx) return false; // Buffer must be bound to this context (or to NULL) +#endif + + if (wb->head && ctx) { + SPALL_BUFFER_PROFILE_BEGIN(); + if (!ctx->write) return false; + if (ctx->write == spall__file_write) { + if (!spall__file_write(ctx, wb->data, wb->head)) return false; + } + else { + if (!ctx->write(ctx, wb->data, wb->head)) return false; + } + SPALL_BUFFER_PROFILE_END("Buffer Flush"); + } + wb->head = 0; + return true; +} + +SPALL_FN SPALL_FORCEINLINE bool spall__buffer_write(SpallProfile *ctx, SpallBuffer *wb, void *p, size_t n) { + // precon: !wb || wb->head < wb->length + // precon: !ctx || ctx->write + if (!wb) return ctx->write && ctx->write(ctx, p, n); +#ifdef SPALL_DEBUG + if (wb->ctx != ctx) return false; // Buffer must be bound to this context (or to NULL) +#endif + if (wb->head + n > wb->length && !spall__buffer_flush(ctx, wb)) return false; + if (n > wb->length) { + SPALL_BUFFER_PROFILE_BEGIN(); + if (!ctx->write || !ctx->write(ctx, p, n)) return false; + SPALL_BUFFER_PROFILE_END("Unbuffered Write"); + return true; + } + memcpy((char *)wb->data + wb->head, p, n); + wb->head += n; + return true; +} + +SPALL_FN bool spall_buffer_flush(SpallProfile *ctx, SpallBuffer *wb) { +#ifdef SPALL_DEBUG + if (!wb) return false; + if (!wb->data) return false; +#endif + + if (!spall__buffer_flush(ctx, wb)) return false; + return true; +} + +SPALL_FN bool spall_buffer_init(SpallProfile *ctx, SpallBuffer *wb) { + if (!spall_buffer_flush(NULL, wb)) return false; + wb->ctx = ctx; + return true; +} +SPALL_FN bool spall_buffer_quit(SpallProfile *ctx, SpallBuffer *wb) { + if (!spall_buffer_flush(ctx, wb)) return false; + wb->ctx = NULL; + return true; +} + +SPALL_FN bool spall_buffer_abort(SpallBuffer *wb) { + if (!wb) return false; + wb->ctx = NULL; + if (!spall__buffer_flush(NULL, wb)) return false; + return true; +} + +SPALL_FN size_t spall_build_header(void *buffer, size_t rem_size, double timestamp_unit) { + size_t header_size = sizeof(SpallHeader); + if (header_size > rem_size) { + return 0; + } + + SpallHeader *header = (SpallHeader *)buffer; + header->magic_header = 0x0BADF00D; + header->version = 1; + header->timestamp_unit = timestamp_unit; + header->must_be_0 = 0; + return header_size; +} +SPALL_FN SPALL_FORCEINLINE size_t spall_build_begin(void *buffer, size_t rem_size, const char *name, signed long name_len, const char *args, signed long args_len, double when, uint32_t tid, uint32_t pid) { + SpallBeginEventMax *ev = (SpallBeginEventMax *)buffer; + uint8_t trunc_name_len = (uint8_t)SPALL_MIN(name_len, 255); // will be interpreted as truncated in the app (?) + uint8_t trunc_args_len = (uint8_t)SPALL_MIN(args_len, 255); // will be interpreted as truncated in the app (?) + + size_t ev_size = sizeof(SpallBeginEvent) + trunc_name_len + trunc_args_len; + if (ev_size > rem_size) { + return 0; + } + + ev->event.type = SpallEventType_Begin; + ev->event.category = 0; + ev->event.pid = pid; + ev->event.tid = tid; + ev->event.when = when; + ev->event.name_length = trunc_name_len; + ev->event.args_length = trunc_args_len; + memcpy(ev->name_bytes, name, trunc_name_len); + memcpy(ev->name_bytes + trunc_name_len, args, trunc_args_len); + + return ev_size; +} +SPALL_FN SPALL_FORCEINLINE size_t spall_build_end(void *buffer, size_t rem_size, double when, uint32_t tid, uint32_t pid) { + size_t ev_size = sizeof(SpallEndEvent); + if (ev_size > rem_size) { + return 0; + } + + SpallEndEvent *ev = (SpallEndEvent *)buffer; + ev->type = SpallEventType_End; + ev->pid = pid; + ev->tid = tid; + ev->when = when; + + return ev_size; +} + +SPALL_FN void spall_quit(SpallProfile *ctx) { + if (!ctx) return; + if (ctx->close) ctx->close(ctx); + + memset(ctx, 0, sizeof(*ctx)); +} + +SPALL_FN SpallProfile spall_init_callbacks(double timestamp_unit, + SpallWriteCallback write, + SpallFlushCallback flush, + SpallCloseCallback close, + void *userdata, + bool is_json) { + SpallProfile ctx; + memset(&ctx, 0, sizeof(ctx)); + if (timestamp_unit < 0) return ctx; + ctx.timestamp_unit = timestamp_unit; + ctx.is_json = is_json; + ctx.data = userdata; + ctx.write = write; + ctx.flush = flush; + ctx.close = close; + + if (ctx.is_json) { + if (!ctx.write(&ctx, "{\"traceEvents\":[\n", sizeof("{\"traceEvents\":[\n") - 1)) { + spall_quit(&ctx); + return ctx; + } + } + else { + SpallHeader header; + size_t len = spall_build_header(&header, sizeof(header), timestamp_unit); + if (!ctx.write(&ctx, &header, len)) { + spall_quit(&ctx); + return ctx; + } + } + + return ctx; +} + +SPALL_FN SpallProfile spall_init_file_ex(const char *filename, double timestamp_unit, bool is_json) { + SpallProfile ctx; + memset(&ctx, 0, sizeof(ctx)); + if (!filename) return ctx; + ctx.data = fopen(filename, "wb"); // TODO: handle utf8 and long paths on windows + if (ctx.data) { // basically freopen() but we don't want to force users to lug along another macro define + fclose((FILE *)ctx.data); + ctx.data = fopen(filename, "ab"); + } + if (!ctx.data) { + spall_quit(&ctx); + return ctx; + } + ctx = spall_init_callbacks(timestamp_unit, spall__file_write, spall__file_flush, spall__file_close, ctx.data, is_json); + return ctx; +} + +SPALL_FN SpallProfile spall_init_file(const char *filename, double timestamp_unit) { return spall_init_file_ex(filename, timestamp_unit, false); } +SPALL_FN SpallProfile spall_init_file_json(const char *filename, double timestamp_unit) { return spall_init_file_ex(filename, timestamp_unit, true); } + +SPALL_FN bool spall_flush(SpallProfile *ctx) { +#ifdef SPALL_DEBUG + if (!ctx) return false; +#endif + + if (!ctx->flush || !ctx->flush(ctx)) return false; + return true; +} + +SPALL_FN SPALL_FORCEINLINE bool spall_buffer_begin_args(SpallProfile *ctx, SpallBuffer *wb, const char *name, signed long name_len, const char *args, signed long args_len, double when, uint32_t tid, uint32_t pid) { +#ifdef SPALL_DEBUG + if (!ctx) return false; + if (!name) return false; + if (name_len <= 0) return false; + if (!wb) return false; +#endif + + if (ctx->is_json) { + char buf[1024]; + int buf_len = snprintf(buf, sizeof(buf), + "{\"ph\":\"B\",\"ts\":%f,\"pid\":%u,\"tid\":%u,\"name\":\"%.*s\",\"args\":\"%.*s\"},\n", + when * ctx->timestamp_unit, pid, tid, (int)(uint8_t)name_len, name, (int)(uint8_t)args_len, args); + if (buf_len <= 0) return false; + if (buf_len >= sizeof(buf)) return false; + if (!spall__buffer_write(ctx, wb, buf, buf_len)) return false; + } + else { + if ((wb->head + sizeof(SpallBeginEventMax)) > wb->length) { + if (!spall__buffer_flush(ctx, wb)) { + return false; + } + } + + wb->head += spall_build_begin((char *)wb->data + wb->head, wb->length - wb->head, name, name_len, args, args_len, when, tid, pid); + } + + return true; +} + +SPALL_FN SPALL_FORCEINLINE bool spall_buffer_begin_ex(SpallProfile *ctx, SpallBuffer *wb, const char *name, signed long name_len, double when, uint32_t tid, uint32_t pid) { + return spall_buffer_begin_args(ctx, wb, name, name_len, "", 0, when, tid, pid); +} + +SPALL_FN bool spall_buffer_begin(SpallProfile *ctx, SpallBuffer *wb, const char *name, signed long name_len, double when) { + return spall_buffer_begin_args(ctx, wb, name, name_len, "", 0, when, 0, 0); +} + +SPALL_FN SPALL_FORCEINLINE bool spall_buffer_end_ex(SpallProfile *ctx, SpallBuffer *wb, double when, uint32_t tid, uint32_t pid) { +#ifdef SPALL_DEBUG + if (!ctx) return false; + if (!wb) return false; +#endif + + if (ctx->is_json) { + char buf[512]; + int buf_len = snprintf(buf, sizeof(buf), + "{\"ph\":\"E\",\"ts\":%f,\"pid\":%u,\"tid\":%u},\n", + when * ctx->timestamp_unit, pid, tid); + if (buf_len <= 0) return false; + if (buf_len >= sizeof(buf)) return false; + if (!spall__buffer_write(ctx, wb, buf, buf_len)) return false; + } + else { + if ((wb->head + sizeof(SpallEndEvent)) > wb->length) { + if (!spall__buffer_flush(ctx, wb)) { + return false; + } + } + + wb->head += spall_build_end((char *)wb->data + wb->head, wb->length - wb->head, when, tid, pid); + } + + return true; +} + +SPALL_FN bool spall_buffer_end(SpallProfile *ctx, SpallBuffer *wb, double when) { return spall_buffer_end_ex(ctx, wb, when, 0, 0); } + +SPALL_FN SPALL_FORCEINLINE void spall__buffer_profile(SpallProfile *ctx, SpallBuffer *wb, double spall_time_begin, double spall_time_end, const char *name, int name_len) { + // precon: ctx + // precon: ctx->write + char temp_buffer_data[2048]; + SpallBuffer temp_buffer = {temp_buffer_data, sizeof(temp_buffer_data)}; + if (!spall_buffer_begin_ex(ctx, &temp_buffer, name, name_len, spall_time_begin, (uint32_t)(uintptr_t)wb->data, 4222222222)) return; + if (!spall_buffer_end_ex(ctx, &temp_buffer, spall_time_end, (uint32_t)(uintptr_t)wb->data, 4222222222)) return; + if (ctx->write) ctx->write(ctx, temp_buffer_data, temp_buffer.head); +} + +#ifdef __cplusplus +} +#endif + +#endif // SPALL_H \ No newline at end of file diff --git a/src/standalone_libraries/arena.c b/src/standalone_libraries/arena.c new file mode 100644 index 0000000..2a1db92 --- /dev/null +++ b/src/standalone_libraries/arena.c @@ -0,0 +1,366 @@ +#include "arena.h" +#ifndef MA_Assertf + #include + #define MA_Assertf(x, ...) assert(x) +#endif + +#ifndef MA_StaticFunc + #if defined(__GNUC__) || defined(__clang__) + #define MA_StaticFunc __attribute__((unused)) static + #else + #define MA_StaticFunc static + #endif +#endif + +#if defined(MA_USE_ADDRESS_SANITIZER) + #include +#endif + +#if !defined(ASAN_POISON_MEMORY_REGION) + #define MA_ASAN_POISON_MEMORY_REGION(addr, size) ((void)(addr), (void)(size)) + #define MA_ASAN_UNPOISON_MEMORY_REGION(addr, size) ((void)(addr), (void)(size)) +#else + #define MA_ASAN_POISON_MEMORY_REGION(addr, size) ASAN_POISON_MEMORY_REGION(addr, size) + #define MA_ASAN_UNPOISON_MEMORY_REGION(addr, size) ASAN_UNPOISON_MEMORY_REGION(addr, size) +#endif + +MA_THREAD_LOCAL MA_SourceLoc MA_SavedSourceLoc; +MA_API void MA_SaveSourceLocEx(const char *file, int line) { + MA_SavedSourceLoc.file = file; + MA_SavedSourceLoc.line = line; +} + +MA_API size_t MA_GetAlignOffset(size_t size, size_t align) { + size_t mask = align - 1; + size_t val = size & mask; + if (val) { + val = align - val; + } + return val; +} + +MA_API size_t MA_AlignUp(size_t size, size_t align) { + size_t result = size + MA_GetAlignOffset(size, align); + return result; +} + +MA_API size_t MA_AlignDown(size_t size, size_t align) { + size += 1; // Make sure when align is 8 doesn't get rounded down to 0 + size_t result = size - (align - MA_GetAlignOffset(size, align)); + return result; +} + +MA_StaticFunc uint8_t *MV__AdvanceCommit(MV_Memory *m, size_t *commit_size, size_t page_size) { + size_t aligned_up_commit = MA_AlignUp(*commit_size, page_size); + size_t to_be_total_commited_size = aligned_up_commit + m->commit; + size_t to_be_total_commited_size_clamped_to_reserve = MA_CLAMP_TOP(to_be_total_commited_size, m->reserve); + size_t adjusted_to_boundary_commit = to_be_total_commited_size_clamped_to_reserve - m->commit; + MA_Assertf(adjusted_to_boundary_commit, "Reached the virtual memory reserved boundary"); + *commit_size = adjusted_to_boundary_commit; + + if (adjusted_to_boundary_commit == 0) { + return 0; + } + uint8_t *result = m->data + m->commit; + return result; +} + +MA_API void MA_PopToPos(MA_Arena *arena, size_t pos) { + MA_Assertf(arena->len >= arena->base_len, "Bug: arena->len shouldn't ever be smaller then arena->base_len"); + pos = MA_CLAMP(pos, arena->base_len, arena->len); + size_t size = arena->len - pos; + arena->len = pos; + MA_ASAN_POISON_MEMORY_REGION(arena->memory.data + arena->len, size); +} + +MA_API void MA_PopSize(MA_Arena *arena, size_t size) { + MA_PopToPos(arena, arena->len - size); +} + +MA_API void MA_DeallocateArena(MA_Arena *arena) { + MV_Deallocate(&arena->memory); +} + +MA_API void MA_Reset(MA_Arena *arena) { + MA_PopToPos(arena, 0); +} + +MA_StaticFunc size_t MA__AlignLen(MA_Arena *a) { + size_t align_offset = a->alignment ? MA_GetAlignOffset((uintptr_t)a->memory.data + (uintptr_t)a->len, a->alignment) : 0; + size_t aligned = a->len + align_offset; + return aligned; +} + +MA_API void MA_SetAlignment(MA_Arena *arena, int alignment) { + arena->alignment = alignment; +} + +MA_API uint8_t *MA_GetTop(MA_Arena *a) { + MA_Assertf(a->memory.data, "Arena needs to be inited, there is no top to get!"); + return a->memory.data + a->len; +} + +MA_API void *MA__PushSizeNonZeroed(MA_Arena *a, size_t size) { + size_t align_offset = a->alignment ? MA_GetAlignOffset((uintptr_t)a->memory.data + (uintptr_t)a->len, a->alignment) : 0; + size_t aligned_len = a->len + align_offset; + size_t size_with_alignment = size + align_offset; + + if (a->len + size_with_alignment > a->memory.commit) { + if (a->memory.reserve == 0) { +#if MA_ZERO_IS_INITIALIZATION + MA_Init(a); +#else + MA_Assertf(0, "Pushing on uninitialized arena with zero initialization turned off"); +#endif + } + bool result = MV_Commit(&a->memory, size_with_alignment + MA_COMMIT_ADD_SIZE); + MA_Assertf(result, "%s(%d): Failed to commit memory more memory! reserve: %zu commit: %zu len: %zu size_with_alignment: %zu", MA_SavedSourceLoc.file, MA_SavedSourceLoc.line, a->memory.reserve, a->memory.commit, a->len, size_with_alignment); + (void)result; + } + + uint8_t *result = a->memory.data + aligned_len; + a->len += size_with_alignment; + MA_Assertf(a->len <= a->memory.commit, "%s(%d): Reached commit boundary! reserve: %zu commit: %zu len: %zu base_len: %zu alignment: %d size_with_alignment: %zu", MA_SavedSourceLoc.file, MA_SavedSourceLoc.line, a->memory.reserve, a->memory.commit, a->len, a->base_len, a->alignment, size_with_alignment); + MA_ASAN_UNPOISON_MEMORY_REGION(result, size); + return (void *)result; +} + +MA_API void *MA__PushSize(MA_Arena *arena, size_t size) { + void *result = MA__PushSizeNonZeroed(arena, size); + MA_MemoryZero(result, size); + return result; +} + +MA_API char *MA__PushStringCopy(MA_Arena *arena, char *p, size_t size) { + char *copy_buffer = (char *)MA__PushSizeNonZeroed(arena, size + 1); + MA_MemoryCopy(copy_buffer, p, size); + copy_buffer[size] = 0; + return copy_buffer; +} + +MA_API void *MA__PushCopy(MA_Arena *arena, void *p, size_t size) { + void *copy_buffer = MA__PushSizeNonZeroed(arena, size); + MA_MemoryCopy(copy_buffer, p, size); + return copy_buffer; +} + +MA_API MA_Arena MA_PushArena(MA_Arena *arena, size_t size) { + MA_Arena result; + MA_MemoryZero(&result, sizeof(result)); + result.memory.data = MA_PushArrayNonZeroed(arena, uint8_t, size); + result.memory.commit = size; + result.memory.reserve = size; + result.alignment = arena->alignment; + return result; +} + +MA_API MA_Arena *MA_PushArenaP(MA_Arena *arena, size_t size) { + MA_Arena *result = MA_PushStruct(arena, MA_Arena); + *result = MA_PushArena(arena, size); + return result; +} + +MA_API void MA_InitEx(MA_Arena *a, size_t reserve) { + a->memory = MV_Reserve(reserve); + MA_ASAN_POISON_MEMORY_REGION(a->memory.data, a->memory.reserve); + a->alignment = MA_DEFAULT_ALIGNMENT; +} + +MA_API void MA_Init(MA_Arena *a) { + MA_InitEx(a, MA_DEFAULT_RESERVE_SIZE); +} + +MA_API void MA_MakeSureInitialized(MA_Arena *a) { + if (a->memory.data == 0) { + MA_Init(a); + } +} + +MA_API MA_Arena *MA_Bootstrap(void) { + MA_Arena bootstrap_arena = {0}; + MA_Arena *arena = MA_PushStruct(&bootstrap_arena, MA_Arena); + *arena = bootstrap_arena; + arena->base_len = arena->len; + return arena; +} + +MA_API void MA_InitFromBuffer(MA_Arena *arena, void *buffer, size_t size) { + arena->memory.data = (uint8_t *)buffer; + arena->memory.commit = size; + arena->memory.reserve = size; + arena->alignment = MA_DEFAULT_ALIGNMENT; + MA_ASAN_POISON_MEMORY_REGION(arena->memory.data, arena->memory.reserve); +} + +MA_API MA_Arena MA_MakeFromBuffer(void *buffer, size_t size) { + MA_Arena arena; + MA_MemoryZero(&arena, sizeof(arena)); + MA_InitFromBuffer(&arena, buffer, size); + return arena; +} + +MA_API MA_Arena MA_Create() { + MA_Arena arena = {0}; + MA_Init(&arena); + return arena; +} + +MA_API bool MA_IsPointerInside(MA_Arena *arena, void *p) { + uintptr_t pointer = (uintptr_t)p; + uintptr_t start = (uintptr_t)arena->memory.data; + uintptr_t stop = start + (uintptr_t)arena->len; + bool result = pointer >= start && pointer < stop; + return result; +} + +MA_API MA_Temp MA_BeginTemp(MA_Arena *arena) { + MA_Temp result; + result.pos = arena->len; + result.arena = arena; + return result; +} + +MA_API void MA_EndTemp(MA_Temp checkpoint) { + MA_PopToPos(checkpoint.arena, checkpoint.pos); +} + +MA_THREAD_LOCAL MA_Arena *MA_ScratchArenaPool[4]; + +MA_API void MA_InitScratch(void) { + for (int i = 0; i < MA_Lengthof(MA_ScratchArenaPool); i += 1) { + MA_ScratchArenaPool[i] = MA_Bootstrap(); + } +} + +MA_API MA_Temp MA_GetScratchEx(MA_Arena **conflicts, int conflict_count) { + MA_Arena *unoccupied = 0; + for (int i = 0; i < MA_Lengthof(MA_ScratchArenaPool); i += 1) { + MA_Arena *from_pool = MA_ScratchArenaPool[i]; + unoccupied = from_pool; + for (int conflict_i = 0; conflict_i < conflict_count; conflict_i += 1) { + MA_Arena *from_conflict = conflicts[conflict_i]; + if (from_pool == from_conflict) { + unoccupied = 0; + break; + } + } + + if (unoccupied) { + break; + } + } + + MA_Assertf(unoccupied, "Failed to get free scratch memory, this is a fatal error, this shouldnt happen"); + MA_Temp result = MA_BeginTemp(unoccupied); + return result; +} + +MA_API MA_Temp MA_GetScratch(void) { + MA_Temp result = MA_BeginTemp(MA_ScratchArenaPool[0]); + return result; +} + +MA_API MA_Temp MA_GetScratch1(MA_Arena *conflict) { + MA_Arena *conflicts[] = {conflict}; + return MA_GetScratchEx(conflicts, 1); +} + +#ifdef _WIN32 + #ifndef NOMINMAX + #define NOMINMAX + #endif + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + +const size_t MV__WIN32_PAGE_SIZE = 4096; + +MA_API MV_Memory MV_Reserve(size_t size) { + MV_Memory result; + MA_MemoryZero(&result, sizeof(result)); + size_t adjusted_size = MA_AlignUp(size, MV__WIN32_PAGE_SIZE); + result.data = (uint8_t *)VirtualAlloc(0, adjusted_size, MEM_RESERVE, PAGE_READWRITE); + MA_Assertf(result.data, "Failed to reserve virtual memory"); + result.reserve = adjusted_size; + return result; +} + +MA_API bool MV_Commit(MV_Memory *m, size_t commit) { + uint8_t *pointer = MV__AdvanceCommit(m, &commit, MV__WIN32_PAGE_SIZE); + if (pointer) { + void *result = VirtualAlloc(pointer, commit, MEM_COMMIT, PAGE_READWRITE); + MA_Assertf(result, "Failed to commit more memory"); + if (result) { + m->commit += commit; + return true; + } + } + return false; +} + +MA_API void MV_Deallocate(MV_Memory *m) { + BOOL result = VirtualFree(m->data, 0, MEM_RELEASE); + MA_Assertf(result != 0, "Failed to release MV_Memory"); +} + +MA_API bool MV_DecommitPos(MV_Memory *m, size_t pos) { + size_t aligned = MA_AlignDown(pos, MV__WIN32_PAGE_SIZE); + size_t adjusted_pos = MA_CLAMP_TOP(aligned, m->commit); + size_t size_to_decommit = m->commit - adjusted_pos; + if (size_to_decommit) { + uint8_t *base_address = m->data + adjusted_pos; + BOOL result = VirtualFree(base_address, size_to_decommit, MEM_DECOMMIT); + if (result) { + m->commit -= size_to_decommit; + return true; + } + } + return false; +} + +#elif __unix__ || __linux__ || __APPLE__ + #include + #define MV__UNIX_PAGE_SIZE 4096 +MA_API MV_Memory MV_Reserve(size_t size) { + MV_Memory result = {}; + size_t size_aligned = MA_AlignUp(size, MV__UNIX_PAGE_SIZE); + result.data = (uint8_t *)mmap(0, size_aligned, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + MA_Assertf(result.data, "Failed to reserve memory using mmap!!"); + if (result.data) { + result.reserve = size_aligned; + } + return result; +} + +MA_API bool MV_Commit(MV_Memory *m, size_t commit) { + uint8_t *pointer = MV__AdvanceCommit(m, &commit, MV__UNIX_PAGE_SIZE); + if (pointer) { + int mprotect_result = mprotect(pointer, commit, PROT_READ | PROT_WRITE); + MA_Assertf(mprotect_result == 0, "Failed to commit more memory using mmap"); + if (mprotect_result == 0) { + m->commit += commit; + return true; + } + } + return false; +} + +MA_API void MV_Deallocate(MV_Memory *m) { + int result = munmap(m->data, m->reserve); + MA_Assertf(result == 0, "Failed to release virtual memory using munmap"); +} +#else +MA_API MV_Memory MV_Reserve(size_t size) { + MV_Memory result = {0}; + return result; +} + +MA_API bool MV_Commit(MV_Memory *m, size_t commit) { + return false; +} + +MA_API void MV_Deallocate(MV_Memory *m) { +} + +#endif \ No newline at end of file diff --git a/src/standalone_libraries/arena.h b/src/standalone_libraries/arena.h new file mode 100644 index 0000000..a78eac0 --- /dev/null +++ b/src/standalone_libraries/arena.h @@ -0,0 +1,179 @@ +#ifndef MA_HEADER +#define MA_HEADER +#include +#include +#include + +#define MA_KIB(x) ((x##ull) * 1024ull) +#define MA_MIB(x) (MA_KIB(x) * 1024ull) +#define MA_GIB(x) (MA_MIB(x) * 1024ull) +#define MA_TIB(x) (MA_GIB(x) * 1024ull) + +typedef struct MV_Memory MV_Memory; +typedef struct MA_Temp MA_Temp; +typedef struct MA_Arena MA_Arena; +typedef struct MA_SourceLoc MA_SourceLoc; + +#ifndef MA_DEFAULT_RESERVE_SIZE + #define MA_DEFAULT_RESERVE_SIZE MA_GIB(1) +#endif + +#ifndef MA_DEFAULT_ALIGNMENT + #define MA_DEFAULT_ALIGNMENT 8 +#endif + +#ifndef MA_COMMIT_ADD_SIZE + #define MA_COMMIT_ADD_SIZE MA_MIB(4) +#endif + +#ifndef MA_ZERO_IS_INITIALIZATION + #define MA_ZERO_IS_INITIALIZATION 1 +#endif + +#ifndef MA_API + #ifdef __cplusplus + #define MA_API extern "C" + #else + #define MA_API + #endif +#endif + +#ifndef MA_THREAD_LOCAL + #if defined(__cplusplus) && __cplusplus >= 201103L + #define MA_THREAD_LOCAL thread_local + #elif defined(__GNUC__) + #define MA_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define MA_THREAD_LOCAL __declspec(thread) + #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) + #define MA_THREAD_LOCAL _Thread_local + #elif defined(__TINYC__) + #define MA_THREAD_LOCAL _Thread_local + #else + #error Couldnt figure out thread local, needs to be provided manually + #endif +#endif + +#ifndef MA_MemoryZero + #include + #define MA_MemoryZero(p, size) memset(p, 0, size) +#endif + +#ifndef MA_MemoryCopy + #include + #define MA_MemoryCopy(dst, src, size) memcpy(dst, src, size); +#endif + +struct MV_Memory { + size_t commit; + size_t reserve; + uint8_t *data; +}; + +struct MA_Arena { + MV_Memory memory; + int alignment; + size_t len; + size_t base_len; // When popping to 0 this is the minimum "len" value + // It's so that Bootstrapped arena won't delete itself when Reseting. +}; + +struct MA_Temp { + MA_Arena *arena; + size_t pos; +}; + +struct MA_SourceLoc { + const char *file; + int line; +}; + +extern MA_THREAD_LOCAL MA_SourceLoc MA_SavedSourceLoc; +#define MA_SaveSourceLoc() MA_SaveSourceLocEx(__FILE__, __LINE__) +MA_API void MA_SaveSourceLocEx(const char *file, int line); + +#define MA_PushSize(a, size) MA__PushSize(a, size) +#define MA_PushSizeNonZeroed(a, size) MA__PushSizeNonZeroed(a, size) +#define MA_PushCopy(a, p, size) MA__PushCopy(a, p, size) +#define MA_PushStringCopy(a, p, size) MA__PushStringCopy(a, p, size) + +#define MA_PushArrayNonZeroed(a, T, c) (T *)MA__PushSizeNonZeroed(a, sizeof(T) * (c)) +#define MA_PushStructNonZeroed(a, T) (T *)MA__PushSizeNonZeroed(a, sizeof(T)) +#define MA_PushStruct(a, T) (T *)MA__PushSize(a, sizeof(T)) +#define MA_PushArray(a, T, c) (T *)MA__PushSize(a, sizeof(T) * (c)) +#define MA_PushStructCopy(a, T, p) (T *)MA__PushCopy(a, (p), sizeof(T)) + +// clang-format off +MA_API void MA_InitEx(MA_Arena *a, size_t reserve); +MA_API void MA_Init(MA_Arena *a); +MA_API MA_Arena MA_Create(); +MA_API void MA_MakeSureInitialized(MA_Arena *a); +MA_API void MA_InitFromBuffer(MA_Arena *arena, void *buffer, size_t size); +MA_API MA_Arena MA_MakeFromBuffer(void *buffer, size_t size); +MA_API MA_Arena * MA_Bootstrap(void); +MA_API MA_Arena MA_PushArena(MA_Arena *arena, size_t size); +MA_API MA_Arena * MA_PushArenaP(MA_Arena *arena, size_t size); + +MA_API void * MA__PushSizeNonZeroed(MA_Arena *a, size_t size); +MA_API void * MA__PushSize(MA_Arena *arena, size_t size); +MA_API char * MA__PushStringCopy(MA_Arena *arena, char *p, size_t size); +MA_API void * MA__PushCopy(MA_Arena *arena, void *p, size_t size); +MA_API MA_Temp MA_BeginTemp(MA_Arena *arena); +MA_API void MA_EndTemp(MA_Temp checkpoint); + +MA_API void MA_PopToPos(MA_Arena *arena, size_t pos); +MA_API void MA_PopSize(MA_Arena *arena, size_t size); +MA_API void MA_DeallocateArena(MA_Arena *arena); +MA_API void MA_Reset(MA_Arena *arena); + +MA_API size_t MA_GetAlignOffset(size_t size, size_t align); +MA_API size_t MA_AlignUp(size_t size, size_t align); +MA_API size_t MA_AlignDown(size_t size, size_t align); + +MA_API bool MA_IsPointerInside(MA_Arena *arena, void *p); +MA_API void MA_SetAlignment(MA_Arena *arena, int alignment); +MA_API uint8_t * MA_GetTop(MA_Arena *a); + +MA_API MV_Memory MV_Reserve(size_t size); +MA_API bool MV_Commit(MV_Memory *m, size_t commit); +MA_API void MV_Deallocate(MV_Memory *m); +MA_API bool MV_DecommitPos(MV_Memory *m, size_t pos); +// clang-format on + +extern MA_THREAD_LOCAL MA_Arena *MA_ScratchArenaPool[4]; +#define MA_CheckpointScope(name, InArena) for (MA_Temp name = MA_BeginTemp(InArena); name.arena; (MA_EndTemp(name), name.arena = 0)) +#define MA_ScratchScope(x) for (MA_Temp x = MA_GetScratch(); x.arena; (MA_ReleaseScratch(x), x.arena = 0)) +#define MA_ReleaseScratch MA_EndTemp +MA_API MA_Temp MA_GetScratchEx(MA_Arena **conflicts, int conflict_count); +MA_API MA_Temp MA_GetScratch(void); +MA_API MA_Temp MA_GetScratch1(MA_Arena *conflict); + +#if defined(__cplusplus) +struct MA_Scratch { + MA_Temp checkpoint; + MA_Scratch() { this->checkpoint = MA_GetScratch(); } + MA_Scratch(MA_Temp conflict) { this->checkpoint = MA_GetScratch1(conflict.arena); } + MA_Scratch(MA_Temp c1, MA_Temp c2) { + MA_Arena *conflicts[] = {c1.arena, c2.arena}; + this->checkpoint = MA_GetScratchEx(conflicts, 2); + } + ~MA_Scratch() { MA_EndTemp(checkpoint); } + operator MA_Arena *() { return checkpoint.arena; } + + private: // @Note: Disable copy constructors, cause its error prone + MA_Scratch(MA_Scratch &arena); + MA_Scratch(MA_Scratch &arena, MA_Scratch &a2); +}; +#endif // __cplusplus + +#define MA_IS_POW2(x) (((x) & ((x)-1)) == 0) +#define MA_MIN(x, y) ((x) <= (y) ? (x) : (y)) +#define MA_MAX(x, y) ((x) >= (y) ? (x) : (y)) +#define MA_Lengthof(x) ((int64_t)((sizeof(x) / sizeof((x)[0])))) + +#define MA_CLAMP_TOP(x, max) ((x) >= (max) ? (max) : (x)) +#define MA_CLAMP_BOT(x, min) ((x) <= (min) ? (min) : (x)) +#define MA_CLAMP(x, min, max) ((x) >= (max) ? (max) : (x) <= (min) ? (min) \ + : (x)) + +#endif // MA_HEADER \ No newline at end of file diff --git a/src/standalone_libraries/clexer.c b/src/standalone_libraries/clexer.c new file mode 100644 index 0000000..d8fac92 --- /dev/null +++ b/src/standalone_libraries/clexer.c @@ -0,0 +1,1549 @@ +#include "clexer.h" +#include + +/* +- I'm pretty sure I can remove allocations for most of the current functions. +- I also can fix ResolvePath stuff so that it uses string+len and doesn't need allocations +- Add lexing options like in stb_c_lexer.h + +Instead of AND_CL_STRING_TERMINATE_ON_NEW_LINE he is doing some weird cool stuff with redefining +https://github.com/nothings/stb/blob/master/stb_c_lexer.h + +CL_MULTILINE_SSTRINGS +CL_DOLLAR_IDENT + +- Add proper string parsing, as additional function, CL_ParseString() or something, this is the only one that would need allocations + +*/ + +#ifndef CL_PRIVATE_FUNCTION + #if defined(__GNUC__) || defined(__clang__) + #define CL_PRIVATE_FUNCTION __attribute__((unused)) static + #else + #define CL_PRIVATE_FUNCTION static + #endif +#endif + +#ifndef CL_Allocate + #include + #define CL_Allocate(allocator, size) malloc(size) +#endif + +#ifndef CL_STRING_TO_DOUBLE + #include + #define CL_STRING_TO_DOUBLE(str, len) strtod(str, 0) +#endif + +#ifndef CL_ASSERT + #include + #define CL_ASSERT(x) assert(x) +#endif + +#ifndef CL_VSNPRINTF + #include + #define CL_VSNPRINTF vsnprintf +#endif + +#ifndef CL_SNPRINTF + #include + #define CL_SNPRINTF snprintf +#endif + +#ifndef CL__MemoryCopy + #include + #define CL__MemoryCopy(dst, src, s) memcpy(dst, src, s) +#endif + +#ifndef CL_MemoryZero + #include + #define CL_MemoryZero(p, size) memset(p, 0, size) +#endif + +#ifndef CL_FileExists + #define CL_FileExists CL__FileExists + #include +CL_PRIVATE_FUNCTION bool CL_FileExists(char *name) { + bool result = false; + FILE *f = fopen(name, "rb"); + if (f) { + result = true; + fclose(f); + } + return result; +} +#endif + +CL_PRIVATE_FUNCTION void CL_ReportError(CL_Lexer *T, CL_Token *token, const char *string, ...); + +CL_PRIVATE_FUNCTION char *CL_PushStringCopy(CL_Allocator arena, char *p, int size) { + char *copy_buffer = (char *)CL_Allocate(arena, size + 1); + CL__MemoryCopy(copy_buffer, p, size); + copy_buffer[size] = 0; + return copy_buffer; +} + +CL_INLINE void CL_Advance(CL_Lexer *T) { + if (*T->stream == '\n') { + T->line += 1; + T->column = 0; + } + else if (*T->stream == ' ') { + T->column += 1; + } + else if (*T->stream == '\t') { + T->column += 1; + } + else if (*T->stream == 0) { + return; + } + T->stream += 1; +} + +CL_INLINE bool CL_IsAlphabetic(char c) { + bool result = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); + return result; +} + +CL_INLINE bool CL_IsNumeric(char c) { + bool result = (c >= '0' && c <= '9'); + return result; +} + +CL_INLINE bool CL_IsHexNumeric(char c) { + bool result = (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); + return result; +} + +CL_INLINE bool CL_IsWhitespace(char c) { + bool result = c == ' ' || c == '\n' || c == '\r' || c == '\t'; + return result; +} + +CL_INLINE bool CL_IsAlphanumeric(char c) { + bool result = CL_IsAlphabetic(c) || CL_IsNumeric(c); + return result; +} + +CL_API_FUNCTION void CL_SetTokenLength(CL_Lexer *T, CL_Token *token) { + intptr_t diff = T->stream - token->str; + CL_ASSERT(diff < 2147483647); + token->len = (int)diff; +} + +CL_PRIVATE_FUNCTION uint64_t CL_CharMapToNumber(char c) { + switch (c) { + case '0': return 0; break; + case '1': return 1; break; + case '2': return 2; break; + case '3': return 3; break; + case '4': return 4; break; + case '5': return 5; break; + case '6': return 6; break; + case '7': return 7; break; + case '8': return 8; break; + case '9': return 9; break; + case 'a': + case 'A': return 10; break; + case 'b': + case 'B': return 11; break; + case 'c': + case 'C': return 12; break; + case 'd': + case 'D': return 13; break; + case 'e': + case 'E': return 14; break; + case 'f': + case 'F': return 15; break; + default: return 255; + } +} + +CL_PRIVATE_FUNCTION uint64_t CL_ParseInteger(CL_Lexer *T, CL_Token *token, char *string, uint64_t len, uint64_t base) { + CL_ASSERT(base >= 2 && base <= 16); + uint64_t acc = 0; + for (uint64_t i = 0; i < len; i++) { + uint64_t num = CL_CharMapToNumber(string[i]); + if (num >= base) { + CL_ReportError(T, token, "Internal compiler error! Failed to parse a number"); + break; + } + acc *= base; + acc += num; + } + return acc; +} + +typedef struct CL_UTF32Result { + uint32_t out_str; + int advance; + int error; +} CL_UTF32Result; + +CL_PRIVATE_FUNCTION CL_UTF32Result CL_UTF8ToUTF32(char *c, int max_advance) { + CL_UTF32Result result = {0}; + + if ((c[0] & 0x80) == 0) { // Check if leftmost zero of first byte is unset + if (max_advance >= 1) { + result.out_str = c[0]; + result.advance = 1; + } + else result.error = 1; + } + + else if ((c[0] & 0xe0) == 0xc0) { + if ((c[1] & 0xc0) == 0x80) { // Continuation byte required + if (max_advance >= 2) { + result.out_str = (uint32_t)(c[0] & 0x1f) << 6u | (c[1] & 0x3f); + result.advance = 2; + } + else result.error = 2; + } + else result.error = 2; + } + + else if ((c[0] & 0xf0) == 0xe0) { + if ((c[1] & 0xc0) == 0x80 && (c[2] & 0xc0) == 0x80) { // Two continuation bytes required + if (max_advance >= 3) { + result.out_str = (uint32_t)(c[0] & 0xf) << 12u | (uint32_t)(c[1] & 0x3f) << 6u | (c[2] & 0x3f); + result.advance = 3; + } + else result.error = 3; + } + else result.error = 3; + } + + else if ((c[0] & 0xf8) == 0xf0) { + if ((c[1] & 0xc0) == 0x80 && (c[2] & 0xc0) == 0x80 && (c[3] & 0xc0) == 0x80) { // Three continuation bytes required + if (max_advance >= 4) { + result.out_str = (uint32_t)(c[0] & 0xf) << 18u | (uint32_t)(c[1] & 0x3f) << 12u | (uint32_t)(c[2] & 0x3f) << 6u | (uint32_t)(c[3] & 0x3f); + result.advance = 4; + } + else result.error = 4; + } + else result.error = 4; + } + else result.error = 4; + + return result; +} + +// @todo I think I should look at this again +CL_PRIVATE_FUNCTION void CL_ParseCharLiteral(CL_Lexer *T, CL_Token *token) { + token->kind = CL_CHARLIT; + token->str = T->stream; + while (*T->stream != '\'') { + if (*T->stream == '\\') { + CL_Advance(T); + } + if (*T->stream == 0) { + CL_ReportError(T, token, "Unclosed character literal!"); + return; + } + CL_Advance(T); + } + CL_SetTokenLength(T, token); + + if (token->str[0] == '\\') { + switch (token->str[1]) { + case '\\': token->u64 = '\\'; break; + case '\'': token->u64 = '\''; break; + case '"': token->u64 = '"'; break; + case 't': token->u64 = '\t'; break; + case 'v': token->u64 = '\v'; break; + case 'f': token->u64 = '\f'; break; + case 'n': token->u64 = '\n'; break; + case 'r': token->u64 = '\r'; break; + case 'a': token->u64 = '\a'; break; + case 'b': token->u64 = '\b'; break; + case '0': token->u64 = '\0'; break; + case 'x': + case 'X': CL_ASSERT(!"Not implemented"); break; // Hex constant + case 'u': CL_ASSERT(!"Not implemented"); break; // Unicode constant + default: { + CL_ReportError(T, token, "Unknown escape code"); + } + } + } + + else { + if (token->len > 4) { + CL_ReportError(T, token, "This character literal has invalid format, it's too big"); + goto skip_utf_encode; + } + + token->u64 = 0; + int i = 0; + + for (; i < token->len;) { + CL_UTF32Result result = CL_UTF8ToUTF32(token->str + i, (int)token->len); + i += result.advance; + token->u64 |= result.out_str << (8 * (token->len - i)); + if (result.error) { + CL_ReportError(T, token, "This character literal couldnt be parsed as utf8"); + break; + } + } + if (i != token->len) { + CL_ReportError(T, token, "Character literal decode error"); + } + } + +skip_utf_encode: + CL_Advance(T); +} + +// It combines strings, verifies the escape sequences but doesn't do any allocations +// so the final string actually needs additional transformation pass. A pass +// that will combine the string snippets, replace escape sequences with actual values etc. +// +// @warning: @not_sure: we are not setting token->string_literal +// +// "String 1" "String 2" - those strings snippets are combined +// @todo: look at this again +// @todo: make a manual correct version that user can execute if he needs to +CL_PRIVATE_FUNCTION void CL_CheckString(CL_Lexer *T, CL_Token *token) { + token->kind = CL_STRINGLIT; +combine_next_string_literal: + while (*T->stream != '"' && *T->stream != 0 AND_CL_STRING_TERMINATE_ON_NEW_LINE) { + if (*T->stream == '\\') { + CL_Advance(T); + switch (*T->stream) { + case 'a': + case 'b': + case 'e': + case 'f': + case 'n': + case 'r': + case 't': + case 'v': + case '\\': + case '\'': + case '?': + case '"': + case 'x': + case 'X': // Hex constant + case 'u': // Unicode constant + case 'U': + break; + case '0': // octal numbers or null + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + break; + default: { + CL_ReportError(T, token, "Invalid escape sequence"); + return; + } + } + } + CL_Advance(T); + } + CL_Advance(T); + + // Try to seek if there is a consecutive string. + // If there is such string we try to combine it. + { + char *seek_for_next_string = T->stream; + while (CL_IsWhitespace(*seek_for_next_string)) { + seek_for_next_string += 1; + } + + if (*seek_for_next_string == '"') { + seek_for_next_string += 1; + while (T->stream != seek_for_next_string) CL_Advance(T); + goto combine_next_string_literal; + } + } + CL_SetTokenLength(T, token); +} + +CL_PRIVATE_FUNCTION void CL_IsIdentifierKeyword(CL_Token *token) { + if (token->len == 1) return; + char *c = token->str; + switch (c[0]) { + case 'v': { + switch (c[1]) { + case 'o': { + if (CL_StringsAreEqual(token->str, token->len, "void", 4)) { + token->kind = CL_KEYWORD_VOID; + } + else if (CL_StringsAreEqual(token->str, token->len, "volatile", 8)) { + token->kind = CL_KEYWORD_VOLATILE; + } + } break; + } + } break; + case 'i': { + switch (c[1]) { + case 'n': { + if (CL_StringsAreEqual(token->str, token->len, "int", 3)) { + token->kind = CL_KEYWORD_INT; + } + else if (CL_StringsAreEqual(token->str, token->len, "inline", 6)) { + token->kind = CL_KEYWORD_INLINE; + } + } break; + case 'f': { + if (CL_StringsAreEqual(token->str, token->len, "if", 2)) { + token->kind = CL_KEYWORD_IF; + } + } break; + } + } break; + case 'c': { + switch (c[1]) { + case 'h': { + if (CL_StringsAreEqual(token->str, token->len, "char", 4)) { + token->kind = CL_KEYWORD_CHAR; + } + } break; + case 'o': { + if (CL_StringsAreEqual(token->str, token->len, "const", 5)) { + token->kind = CL_KEYWORD_CONST; + } + else if (CL_StringsAreEqual(token->str, token->len, "continue", 8)) { + token->kind = CL_KEYWORD_CONTINUE; + } + } break; + case 'a': { + if (CL_StringsAreEqual(token->str, token->len, "case", 4)) { + token->kind = CL_KEYWORD_CASE; + } + } break; + } + } break; + case 'u': { + switch (c[1]) { + case 'n': { + if (CL_StringsAreEqual(token->str, token->len, "unsigned", 8)) { + token->kind = CL_KEYWORD_UNSIGNED; + } + else if (CL_StringsAreEqual(token->str, token->len, "union", 5)) { + token->kind = CL_KEYWORD_UNION; + } + } break; + } + } break; + case 's': { + switch (c[1]) { + case 'i': { + if (CL_StringsAreEqual(token->str, token->len, "signed", 6)) { + token->kind = CL_KEYWORD_SIGNED; + } + else if (CL_StringsAreEqual(token->str, token->len, "sizeof", 6)) { + token->kind = CL_KEYWORD_SIZEOF; + } + } break; + case 'h': { + if (CL_StringsAreEqual(token->str, token->len, "short", 5)) { + token->kind = CL_KEYWORD_SHORT; + } + } break; + case 't': { + if (CL_StringsAreEqual(token->str, token->len, "static", 6)) { + token->kind = CL_KEYWORD_STATIC; + } + else if (CL_StringsAreEqual(token->str, token->len, "struct", 6)) { + token->kind = CL_KEYWORD_STRUCT; + } + } break; + case 'w': { + if (CL_StringsAreEqual(token->str, token->len, "switch", 6)) { + token->kind = CL_KEYWORD_SWITCH; + } + } break; + } + } break; + case 'l': { + switch (c[1]) { + case 'o': { + if (CL_StringsAreEqual(token->str, token->len, "long", 4)) { + token->kind = CL_KEYWORD_LONG; + } + } break; + } + } break; + case 'd': { + switch (c[1]) { + case 'o': { + if (CL_StringsAreEqual(token->str, token->len, "double", 6)) { + token->kind = CL_KEYWORD_DOUBLE; + } + else if (CL_StringsAreEqual(token->str, token->len, "do", 2)) { + token->kind = CL_KEYWORD_DO; + } + } break; + case 'e': { + if (CL_StringsAreEqual(token->str, token->len, "default", 7)) { + token->kind = CL_KEYWORD_DEFAULT; + } + } break; + } + } break; + case 'f': { + switch (c[1]) { + case 'l': { + if (CL_StringsAreEqual(token->str, token->len, "float", 5)) { + token->kind = CL_KEYWORD_FLOAT; + } + } break; + case 'o': { + if (CL_StringsAreEqual(token->str, token->len, "for", 3)) { + token->kind = CL_KEYWORD_FOR; + } + } break; + } + } break; + case '_': { + switch (c[1]) { + case 'B': { + if (CL_StringsAreEqual(token->str, token->len, "_Bool", 5)) { + token->kind = CL_KEYWORD__BOOL; + } + } break; + case 'C': { + if (CL_StringsAreEqual(token->str, token->len, "_Complex", 8)) { + token->kind = CL_KEYWORD__COMPLEX; + } + } break; + case 'I': { + if (CL_StringsAreEqual(token->str, token->len, "_Imaginary", 10)) { + token->kind = CL_KEYWORD__IMAGINARY; + } + } break; + case 'T': { + if (CL_StringsAreEqual(token->str, token->len, "_Thread_local", 13)) { + token->kind = CL_KEYWORD__THREAD_LOCAL; + } + } break; + case 'A': { + if (CL_StringsAreEqual(token->str, token->len, "_Atomic", 7)) { + token->kind = CL_KEYWORD__ATOMIC; + } + else if (CL_StringsAreEqual(token->str, token->len, "_Alignas", 8)) { + token->kind = CL_KEYWORD__ALIGNAS; + } + else if (CL_StringsAreEqual(token->str, token->len, "_Alignof", 8)) { + token->kind = CL_KEYWORD__ALIGNOF; + } + } break; + case 'N': { + if (CL_StringsAreEqual(token->str, token->len, "_Noreturn", 9)) { + token->kind = CL_KEYWORD__NORETURN; + } + } break; + case 'S': { + if (CL_StringsAreEqual(token->str, token->len, "_Static_assert", 14)) { + token->kind = CL_KEYWORD__STATIC_ASSERT; + } + } break; + case 'G': { + if (CL_StringsAreEqual(token->str, token->len, "_Generic", 8)) { + token->kind = CL_KEYWORD__GENERIC; + } + } break; + } + } break; + case 'a': { + switch (c[1]) { + case 'u': { + if (CL_StringsAreEqual(token->str, token->len, "auto", 4)) { + token->kind = CL_KEYWORD_AUTO; + } + } break; + } + } break; + case 'e': { + switch (c[1]) { + case 'x': { + if (CL_StringsAreEqual(token->str, token->len, "extern", 6)) { + token->kind = CL_KEYWORD_EXTERN; + } + } break; + case 'n': { + if (CL_StringsAreEqual(token->str, token->len, "enum", 4)) { + token->kind = CL_KEYWORD_ENUM; + } + } break; + case 'l': { + if (CL_StringsAreEqual(token->str, token->len, "else", 4)) { + token->kind = CL_KEYWORD_ELSE; + } + } break; + } + } break; + case 'r': { + switch (c[1]) { + case 'e': { + if (CL_StringsAreEqual(token->str, token->len, "register", 8)) { + token->kind = CL_KEYWORD_REGISTER; + } + else if (CL_StringsAreEqual(token->str, token->len, "restrict", 8)) { + token->kind = CL_KEYWORD_RESTRICT; + } + else if (CL_StringsAreEqual(token->str, token->len, "return", 6)) { + token->kind = CL_KEYWORD_RETURN; + } + } break; + } + } break; + case 't': { + switch (c[1]) { + case 'y': { + if (CL_StringsAreEqual(token->str, token->len, "typedef", 7)) { + token->kind = CL_KEYWORD_TYPEDEF; + } + } break; + } + } break; + case 'b': { + switch (c[1]) { + case 'r': { + if (CL_StringsAreEqual(token->str, token->len, "break", 5)) { + token->kind = CL_KEYWORD_BREAK; + } + } break; + } + } break; + case 'w': { + switch (c[1]) { + case 'h': { + if (CL_StringsAreEqual(token->str, token->len, "while", 5)) { + token->kind = CL_KEYWORD_WHILE; + } + } break; + } + } break; + case 'g': { + switch (c[1]) { + case 'o': { + if (CL_StringsAreEqual(token->str, token->len, "goto", 4)) { + token->kind = CL_KEYWORD_GOTO; + } + } break; + } + } break; + } +} + +CL_PRIVATE_FUNCTION void CL_EatMacroWhitespace(CL_Lexer *T) { + while (T->stream[0] == ' ' || T->stream[0] == '\t') CL_Advance(T); +} + +CL_PRIVATE_FUNCTION void CL_EatUntil(CL_Lexer *T, char c) { + while (T->stream[0] != c && T->stream[0] != 0) CL_Advance(T); +} + +CL_PRIVATE_FUNCTION void CL_LexMacroInclude(CL_Lexer *T, CL_Token *token) { + token->kind = CL_PREPROC_INCLUDE; + CL_EatMacroWhitespace(T); + char end = 0; + if (*T->stream == '"') { + end = '"'; + } + else if (*T->stream == '<') { + end = '>'; + token->is_system_include = true; + } + else { + CL_ReportError(T, token, "Invalid include directive, file not specified"); + return; + } + CL_Advance(T); + + token->str = T->stream; + while (*T->stream != end) { + if (*T->stream == 0) { + CL_ReportError(T, token, "Invalid include directive, reached end of file while reading filename"); + } + if (*T->stream == '\n') { + CL_ReportError(T, token, "Invalid include directive filename, got newline character while reading filename"); + } + CL_Advance(T); + } + CL_SetTokenLength(T, token); + CL_Advance(T); + + // @not_sure: this is because we want null terminated input into path resolution stuff + token->string_literal = CL_PushStringCopy(T->arena, token->str, token->len); +} + +CL_PRIVATE_FUNCTION bool CL_LexMacro(CL_Lexer *T, CL_Token *token) { + CL_EatMacroWhitespace(T); + token->str = T->stream; + while (CL_IsAlphabetic(*T->stream)) CL_Advance(T); + CL_SetTokenLength(T, token); + + switch (*token->str) { + case 'd': + if (CL_StringsAreEqual(token->str, token->len, "define", 6)) { + token->kind = CL_PREPROC_DEFINE; + } + break; + + case 'i': + if (CL_StringsAreEqual(token->str, token->len, "ifdef", 5)) { + token->kind = CL_PREPROC_IFDEF; + } + else if (CL_StringsAreEqual(token->str, token->len, "ifndef", 6)) { + token->kind = CL_PREPROC_IFNDEF; + } + else if (CL_StringsAreEqual(token->str, token->len, "include", 7)) { + token->kind = CL_PREPROC_INCLUDE; + CL_LexMacroInclude(T, token); + } + else if (CL_StringsAreEqual(token->str, token->len, "if", 2)) { + token->kind = CL_PREPROC_IF; + } + break; + + case 'e': + if (CL_StringsAreEqual(token->str, token->len, "endif", 5)) { + token->kind = CL_PREPROC_ENDIF; + } + else if (CL_StringsAreEqual(token->str, token->len, "error", 5)) { + token->kind = CL_PREPROC_ERROR; + CL_EatMacroWhitespace(T); + token->str = T->stream; + CL_EatUntil(T, '\n'); + CL_SetTokenLength(T, token); + } + else if (CL_StringsAreEqual(token->str, token->len, "else", 4)) { + token->kind = CL_PREPROC_ELSE; + } + else if (CL_StringsAreEqual(token->str, token->len, "elif", 4)) { + token->kind = CL_PREPROC_ELIF; + } + break; + + case 'p': + if (CL_StringsAreEqual(token->str, token->len, "pragma", 6)) { + token->kind = CL_PREPROC_PRAGMA; + } + break; + + case 'u': + if (CL_StringsAreEqual(token->str, token->len, "undef", 5)) { + token->kind = CL_PREPROC_UNDEF; + } + break; + default: return false; + } + return true; +} + +// Skipped space here is for case #define Memes (a), this is not a function like macro because of space +static uint32_t CL_TokenID; // @todo: make it read only +CL_PRIVATE_FUNCTION void CL_PrepareToken(CL_Lexer *T, CL_Token *token, bool skipped_space) { + CL_MemoryZero(token, sizeof(*token)); + token->str = T->stream; + token->line = T->line; + token->column = T->column; + token->file = T->file; + token->id = ++CL_TokenID; + if (skipped_space) token->is_there_whitespace_before_token = true; + CL_Advance(T); +} + +CL_PRIVATE_FUNCTION void CL_DefaultTokenize(CL_Lexer *T, CL_Token *token) { + char *c = token->str; + switch (*c) { + case 0: break; + case '(': token->kind = CL_OPENPAREN; break; + case ')': token->kind = CL_CLOSEPAREN; break; + case '{': token->kind = CL_OPENBRACE; break; + case '}': token->kind = CL_CLOSEBRACE; break; + case '[': token->kind = CL_OPENBRACKET; break; + case ']': token->kind = CL_CLOSEBRACKET; break; + case ',': token->kind = CL_COMMA; break; + case '~': token->kind = CL_NEG; break; + case '?': token->kind = CL_QUESTION; break; + case ';': token->kind = CL_SEMICOLON; break; + case ':': token->kind = CL_COLON; break; + case '.': { + token->kind = CL_DOT; + if (T->stream[0] == '.' && T->stream[1] == '.') { + CL_Advance(T); + CL_Advance(T); + token->kind = CL_THREEDOTS; + } + } break; + case '/': { + token->kind = CL_DIV; + if (*T->stream == '/') { + token->kind = CL_COMMENT; + CL_Advance(T); + CL_EatUntil(T, '\n'); + CL_SetTokenLength(T, token); + } + else if (*T->stream == '*') { + token->kind = CL_COMMENT; + CL_Advance(T); + for (;;) { + if (T->stream[0] == '*' && T->stream[1] == '/') { + break; + } + if (T->stream[0] == 0) { + CL_ReportError(T, token, "Unclosed block comment"); + goto error_end_path; + } + CL_Advance(T); + } + token->str += 2; + CL_SetTokenLength(T, token); + CL_Advance(T); + CL_Advance(T); + } + else if (*T->stream == '=') { + token->kind = CL_DIVASSIGN; + CL_Advance(T); + } + } break; + case '#': { + if (*T->stream == '#') { + token->kind = CL_MACRO_CONCAT; + CL_Advance(T); + } + else { + bool is_macro_directive = CL_LexMacro(T, token); + if (is_macro_directive) { + T->inside_of_macro = true; + } + else { + if (!T->inside_of_macro) { + CL_ReportError(T, token, "Invalid preprocessor directive"); + goto error_end_path; + } + + token->kind = CL_PREPROC_STRINGIFY; + token->str = T->stream; + while (*T->stream == '_' || CL_IsAlphanumeric(*T->stream)) + CL_Advance(T); + CL_SetTokenLength(T, token); + } + } + } break; + case '>': { + if (*T->stream == '=') { + token->kind = CL_GREATERTHEN_OR_EQUAL; + CL_Advance(T); + } + else if (*T->stream == '>') { + CL_Advance(T); + if (*T->stream == '=') { + CL_Advance(T); + token->kind = CL_RIGHTSHIFTASSIGN; + } + else { + token->kind = CL_RIGHTSHIFT; + } + } + else { + token->kind = CL_GREATERTHEN; + } + } break; + case '<': { + token->kind = CL_LESSERTHEN; + if (*T->stream == '=') { + token->kind = CL_LESSERTHEN_OR_EQUAL; + CL_Advance(T); + } + else if (*T->stream == '<') { + CL_Advance(T); + if (*T->stream == '=') { + CL_Advance(T); + token->kind = CL_LEFTSHIFTASSIGN; + } + else { + token->kind = CL_LEFTSHIFT; + } + } + } break; + case '&': { + if (*T->stream == '=') { + token->kind = CL_ANDASSIGN; + CL_Advance(T); + } + else if (*T->stream == '&') { + token->kind = CL_AND; + CL_Advance(T); + } + else { + token->kind = CL_BITAND; + } + } break; + case '-': { + if (*T->stream == '-') { + token->kind = CL_DECREMENT; + CL_Advance(T); + } + else if (*T->stream == '=') { + token->kind = CL_SUBASSIGN; + CL_Advance(T); + } + else { + token->kind = CL_SUB; + } + } break; + case '+': { + if (*T->stream == '+') { + token->kind = CL_INCREMENT; + CL_Advance(T); + } + else if (*T->stream == '=') { + token->kind = CL_ADDASSIGN; + CL_Advance(T); + } + else { + token->kind = CL_ADD; + } + } break; + case '|': { + if (*T->stream == '|') { + token->kind = CL_OR; + CL_Advance(T); + } + else if (*T->stream == '=') { + token->kind = CL_ORASSIGN; + CL_Advance(T); + } + else { + token->kind = CL_BITOR; + } + } break; + case '=': { + if (*T->stream != '=') { + token->kind = CL_ASSIGN; + } + else { + CL_Advance(T); + token->kind = CL_EQUALS; + } + } break; + case '!': { + if (*T->stream != '=') { + token->kind = CL_NOT; + } + else { + CL_Advance(T); + token->kind = CL_NOTEQUALS; + } + } break; + case '*': { + token->kind = CL_MUL; + if (*T->stream == '=') { + CL_Advance(T); + token->kind = CL_MULASSIGN; + } + } break; + case '%': { + token->kind = CL_MOD; + if (*T->stream == '=') { + token->kind = CL_MODASSIGN; + CL_Advance(T); + } + } break; + case '^': { + token->kind = CL_BITXOR; + if (*T->stream == '=') { + CL_Advance(T); + token->kind = CL_XORASSIGN; + } + } break; + case '"': { + CL_CheckString(T, token); + } break; + case '\'': { + CL_ParseCharLiteral(T, token); + } break; + case 'U': { // @todo Unicode32 + if (*T->stream == '"') { + token->fix = CL_PREFIX_U32; + CL_Advance(T); + CL_CheckString(T, token); + } + else if (*T->stream == '\'') { + token->fix = CL_PREFIX_U32; + CL_Advance(T); + CL_ParseCharLiteral(T, token); + } + else goto parse_regular_char; + } break; + case 'u': { // Unicode16 + if (*T->stream == '8') { // Unicode8 + if (T->stream[1] == '"') { // U8 STRING + token->fix = CL_PREFIX_U8; + CL_Advance(T); + CL_Advance(T); + CL_CheckString(T, token); + } + else if (T->stream[1] == '\'') { // U8 CHAR + token->fix = CL_PREFIX_U8; + CL_Advance(T); + CL_Advance(T); + CL_ParseCharLiteral(T, token); + } + else goto parse_regular_char; + } + else if (*T->stream == '"') { // U16 STRING + token->fix = CL_PREFIX_U16; + CL_Advance(T); + CL_CheckString(T, token); + } + else if (*T->stream == '\'') { // U16 CHAR + CL_Advance(T); + CL_ParseCharLiteral(T, token); + } + else goto parse_regular_char; + } + case 'L': { // Widechar + if (*T->stream == '"') { + token->fix = CL_PREFIX_L; + CL_Advance(T); + CL_CheckString(T, token); // @todo UTF16 + } + else if (*T->stream == '\'') { + token->fix = CL_PREFIX_L; + CL_Advance(T); + CL_ParseCharLiteral(T, token); + } + else goto parse_regular_char; + } break; + case 'A': + case 'a': + case 'B': + case 'b': + case 'C': + case 'c': + case 'D': + case 'd': + case 'E': + case 'e': + case 'F': + case 'f': + case 'G': + case 'g': + case 'H': + case 'h': + case 'I': + case 'i': + case 'J': + case 'j': + case 'K': + case 'k': + /*case 'L':*/ case 'l': + case 'M': + case 'm': + case 'N': + case 'n': + case 'O': + case 'o': + case 'P': + case 'p': + case 'Q': + case 'q': + case 'R': + case 'r': + case 'S': + case 's': + case 'T': + case 't': + // case 'U': case 'u': + case 'V': + case 'v': + case 'W': + case 'w': + case 'X': + case 'x': + case 'Y': + case 'y': + case 'Z': + case 'z': + case '_': + parse_regular_char : { + token->kind = CL_IDENTIFIER; + while (*T->stream == '_' || CL_IsAlphanumeric(*T->stream)) { + CL_Advance(T); + } + CL_SetTokenLength(T, token); + CL_IsIdentifierKeyword(token); + } break; + case '0': { + if (*T->stream == 'x' || *T->stream == 'X') { + token->kind = CL_INT; + token->is_hex = true; + CL_Advance(T); + while (CL_IsHexNumeric(*T->stream)) { + CL_Advance(T); + } + uint64_t len = T->stream - token->str; + CL_ASSERT(len > 2); + token->u64 = CL_ParseInteger(T, token, token->str + 2, len - 2, 16); + break; + } + } + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': { + token->kind = CL_INT; + for (;;) { + if (*T->stream == '.') { + if (token->kind == CL_FLOAT) { + CL_ReportError(T, token, "Failed to parse a floating point number, invalid format, found multiple '.'"); + } + + if (token->kind == CL_INT) { + token->kind = CL_FLOAT; + } + } + else if (CL_IsNumeric(*T->stream) == false) { + break; + } + CL_Advance(T); + } + + if (token->kind == CL_INT) { + uint64_t len = T->stream - token->str; + CL_ASSERT(len > 0); + token->u64 = CL_ParseInteger(T, token, token->str, len, 10); + } + + else if (token->kind == CL_FLOAT) { + token->f64 = CL_STRING_TO_DOUBLE(token->str, token->len); + } + + else { + CL_ASSERT(token->kind == CL_ERROR); + } + + if (*T->stream == 'f' || *T->stream == 'F') { + CL_Advance(T); + token->fix = CL_SUFFIX_F; + } + + else if (*T->stream == 'l' || *T->stream == 'L') { + CL_Advance(T); + token->fix = CL_SUFFIX_L; + if (*T->stream == 'l' || *T->stream == 'L') { + CL_Advance(T); + token->fix = CL_SUFFIX_LL; + if (*T->stream == 'u' || *T->stream == 'U') { + CL_Advance(T); + token->fix = CL_SUFFIX_ULL; + } + } + else if (*T->stream == 'u' || *T->stream == 'U') { + CL_Advance(T); + token->fix = CL_SUFFIX_UL; + } + } + + else if (*T->stream == 'u' || *T->stream == 'U') { + CL_Advance(T); + token->fix = CL_SUFFIX_U; + if (*T->stream == 'l' || *T->stream == 'L') { + CL_Advance(T); + token->fix = CL_SUFFIX_UL; + if (*T->stream == 'l' || *T->stream == 'L') { + CL_Advance(T); + token->fix = CL_SUFFIX_ULL; + } + } + } + + } break; + + default: { + CL_ReportError(T, token, "Unhandled character, skipping ..."); + } break; + } + +error_end_path:; +} + +CL_PRIVATE_FUNCTION bool CL_EatWhitespace(CL_Lexer *T) { + bool skipped = false; + for (;;) { + if (CL_IsWhitespace(*T->stream)) { + if (*T->stream == '\n') T->inside_of_macro = false; + CL_Advance(T); + skipped = true; + } + else if (T->stream[0] == '\\' && T->stream[1] == '\n') { + CL_Advance(T); + CL_Advance(T); + skipped = true; + } + else if (T->stream[0] == '\\' && T->stream[1] == '\r' && T->stream[2] == '\n') { + CL_Advance(T); + CL_Advance(T); + CL_Advance(T); + skipped = true; + } + else { + break; + } + } + return skipped; +} + +CL_PRIVATE_FUNCTION void CL_TryToFinalizeToken(CL_Lexer *T, CL_Token *token) { + if (!token->len) { + CL_SetTokenLength(T, token); + } + if (T->inside_of_macro) { + token->is_inside_macro = true; + } +} + +CL_PRIVATE_FUNCTION void CL_InitNextToken(CL_Lexer *T, CL_Token *token) { + // Skip comments, comments get allocated on perm and gathered on the Tokenizer. + // First non comment token gets those comments attached. + for (;;) { + bool skipped = CL_EatWhitespace(T); + CL_PrepareToken(T, token, skipped); + CL_DefaultTokenize(T, token); + + if (token->kind == CL_EOF) { + break; + } + + if (T->select_includes) { + if (token->kind != CL_PREPROC_INCLUDE) continue; + } + + if (T->select_macros) { + if (!token->is_inside_macro) continue; + } + + if (T->select_comments) { + if (token->kind != CL_COMMENT) continue; + } + + if (T->skip_comments) { + if (token->kind == CL_COMMENT) continue; + } + + if (T->skip_macros) { + if (token->is_inside_macro) continue; + } + + break; + } + CL_TryToFinalizeToken(T, token); +} + +CL_API_FUNCTION CL_Token CL_Next(CL_Lexer *T) { + CL_Token result; + CL_MemoryZero(&result, sizeof(CL_Token)); + CL_InitNextToken(T, &result); + return result; +} + +CL_API_FUNCTION CL_Lexer CL_Begin(CL_Allocator arena, char *stream, char *filename) { + CL_Lexer lexer = {0}; + lexer.stream = lexer.stream_begin = stream; + lexer.file = filename; + lexer.arena = arena; + lexer.skip_comments = true; + return lexer; +} + +// +// +// + +CL_PRIVATE_FUNCTION char *CL_ChopLastSlash(CL_Allocator arena, char *str) { + int i = 0; + int slash_pos = -1; + while (str[i]) { + if (str[i] == '/') { + slash_pos = i; + } + i += 1; + } + + char *result = str; + if (slash_pos != -1) { + result = CL_PushStringCopy(arena, str, slash_pos); + } + else { + result = (char *)"./"; + } + return result; +} + +CL_PRIVATE_FUNCTION char *CL_JoinPath(CL_Allocator arena, char *a, char *b) { + int alen = CL_StringLength(a); + int blen = CL_StringLength(b); + int additional_len = 0; + + if (alen && a[alen - 1] != '/') additional_len = 1; + char *result = (char *)CL_Allocate(arena, sizeof(char) * (alen + blen + 1 + additional_len)); + CL__MemoryCopy(result, a, alen); + if (additional_len) result[alen++] = '/'; + CL__MemoryCopy(result + alen, b, blen); + result[alen + blen] = 0; + return result; +} + +CL_PRIVATE_FUNCTION bool CL_IsAbsolutePath(char *path) { +#if _WIN32 + bool result = CL_IsAlphabetic(path[0]) && path[1] == ':' && path[2] == '/'; +#else + bool result = path[0] == '/'; +#endif + return result; +} + +CL_PRIVATE_FUNCTION char *CL_SkipToLastSlash(char *p) { + int last_slash = 0; + for (int i = 0; p[i]; i += 1) { + if (p[i] == '/') last_slash = i; + } + return p + last_slash; +} + +CL_API_FUNCTION char *CL_ResolveFilepath(CL_Allocator arena, CL_SearchPaths *search_paths, char *filename, char *parent_file, bool is_system_include) { + CL_SearchPaths null_search_paths = {0}; + if (search_paths == 0) search_paths = &null_search_paths; + + if (search_paths->file_begin_to_ignore) { + char *name = CL_SkipToLastSlash(filename); + int namelen = CL_StringLength(name); + char *ignore = search_paths->file_begin_to_ignore; + int ignorelen = CL_StringLength(ignore); + if (namelen > ignorelen) { + namelen = ignorelen; + } + if (CL_StringsAreEqual(name, namelen, search_paths->file_begin_to_ignore, ignorelen)) { + return 0; + } + } + + if (CL_IsAbsolutePath(filename) && CL_FileExists(filename)) { + return filename; + } + + if (is_system_include) { + for (int path_i = 0; path_i < search_paths->system_include_path_count; path_i += 1) { + char *path_it = search_paths->system_include_path[path_i]; + char *file = CL_JoinPath(arena, path_it, filename); + if (CL_FileExists(file)) { + return file; + } + } + } + else { + if (parent_file) { + char *parent_dir = CL_ChopLastSlash(arena, parent_file); + char *file = CL_JoinPath(arena, parent_dir, filename); + if (CL_FileExists(file)) { + return file; + } + } + + for (int path_i = 0; path_i < search_paths->include_path_count; path_i += 1) { + char *path_it = search_paths->include_path[path_i]; + char *file = CL_JoinPath(arena, path_it, filename); + if (CL_FileExists(file)) { + return file; + } + } + } + return 0; +} + +// +// +// + +const char *CL_FixString[] = { + "SUFFIX_INVALID", + "SUFFIX_U", + "SUFFIX_UL", + "SUFFIX_ULL", + "SUFFIX_L", + "SUFFIX_LL", + "SUFFIX_F", + "SUFFIX_FL", + "PREFIX_U8", + "PREFIX_U16", + "PREFIX_U32", + "PREFIX_L", +}; + +const char *CL_KindString[] = { + "EOF", + "*", + "/", + "%", + "<<", + ">>", + "+", + "-", + "==", + "<", + ">", + "<=", + ">=", + "!=", + "&", + "|", + "^", + "&&", + "||", + "~", + "!", + "--", + "++", + "--", + "++", + "=", + "/=", + "*=", + "%=", + "-=", + "+=", + "&=", + "|=", + "^=", + "<<=", + ">>=", + "(", + ")", + "{", + "}", + "[", + "]", + ",", + "##", + "#Stringify", + "?", + "...", + ";", + ".", + ":", + "TAG", + "->", + "SIZEOF", + "DOCCOMMENT", + "COMMENT", + "IDENTIFIER", + "STRING_LITERAL", + "CHARACTER_LITERAL", + "ERROR TOKEN", + "FLOAT", + "INT", + "PREPROC_NULL", + "PREPROC_DEFINE", + "PREPROC_IFDEF", + "PREPROC_IFNDEF", + "PREPROC_INCLUDE", + "PREPROC_ENDIF", + "PREPROC_IF", + "PREPROC_PRAGMA", + "PREPROC_ERROR", + "PREPROC_ELSE", + "PREPROC_ELIF", + "PREPROC_UNDEF", + "KEYWORD_VOID", + "KEYWORD_INT", + "KEYWORD_CHAR", + "KEYWORD_UNSIGNED", + "KEYWORD_SIGNED", + "KEYWORD_LONG", + "KEYWORD_SHORT", + "KEYWORD_DOUBLE", + "KEYWORD_FLOAT", + "KEYWORD__BOOL", + "KEYWORD__COMPLEX", + "KEYWORD__IMAGINARY", + "KEYWORD_STATIC", + "KEYWORD_AUTO", + "KEYWORD_CONST", + "KEYWORD_EXTERN", + "KEYWORD_INLINE", + "KEYWORD_REGISTER", + "KEYWORD_RESTRICT", + "KEYWORD_VOLATILE", + "KEYWORD__THREAD_LOCAL", + "KEYWORD__ATOMIC", + "KEYWORD__NORETURN", + "KEYWORD_STRUCT", + "KEYWORD_UNION", + "KEYWORD_ENUM", + "KEYWORD_TYPEDEF", + "KEYWORD_DEFAULT", + "KEYWORD_BREAK", + "KEYWORD_RETURN", + "KEYWORD_SWITCH", + "KEYWORD_IF", + "KEYWORD_ELSE", + "KEYWORD_FOR", + "KEYWORD_WHILE", + "KEYWORD_CASE", + "KEYWORD_CONTINUE", + "KEYWORD_DO", + "KEYWORD_GOTO", + "KEYWORD_SIZEOF", + "KEYWORD__ALIGNAS", + "KEYWORD__ALIGNOF", + "KEYWORD__STATIC_ASSERT", + "KEYWORD__GENERIC", +}; + +CL_API_FUNCTION void CL_StringifyMessage(char *buff, int buff_size, CL_Message *msg) { + CL_SNPRINTF(buff, buff_size, "%s(%d,%d): %15s", msg->token.file, msg->token.line + 1, msg->token.column + 1, msg->string); +} + +CL_API_FUNCTION void CL_Stringify(char *buff, int buff_size, CL_Token *token) { + const char *token_kind = "UNKNOWN"; + if (token->kind < CL_COUNT) token_kind = CL_KindString[token->kind]; + CL_SNPRINTF(buff, buff_size, "%s(%d,%d): %15s %15.*s", token->file, token->line + 1, token->column + 1, token_kind, token->len, token->str); +} + +#define CL_SLL_QUEUE_ADD_MOD(f, l, n, next) \ + do { \ + (n)->next = 0; \ + if ((f) == 0) { \ + (f) = (l) = (n); \ + } \ + else { \ + (l) = (l)->next = (n); \ + } \ + } while (0) +#define CL_SLL_QUEUE_ADD(f, l, n) CL_SLL_QUEUE_ADD_MOD(f, l, n, next) + +#define CL__FORMAT(arena, string, result) \ + va_list args1, args2; \ + va_start(args1, string); \ + va_copy(args2, args1); \ + int len = CL_VSNPRINTF(0, 0, string, args2); \ + va_end(args2); \ + char *result = (char *)CL_Allocate((arena), len + 1); \ + CL_VSNPRINTF(result, len + 1, string, args1); \ + va_end(args1) + +CL_PRIVATE_FUNCTION void CL_ReportError(CL_Lexer *T, CL_Token *token, const char *string, ...) { + CL__FORMAT(T->arena, string, message_string); + CL_Message *result = (CL_Message *)CL_Allocate(T->arena, sizeof(CL_Message)); + CL_MemoryZero(result, sizeof(CL_Message)); + CL_SLL_QUEUE_ADD(T->first_message, T->last_message, result); + + result->string = (char *)string; + result->token = *token; + token->kind = CL_ERROR; + token->error = result; + T->errors += 1; +} diff --git a/src/standalone_libraries/clexer.h b/src/standalone_libraries/clexer.h new file mode 100644 index 0000000..47179ee --- /dev/null +++ b/src/standalone_libraries/clexer.h @@ -0,0 +1,302 @@ +#ifndef FIRST_CL_HEADER +#define FIRST_CL_HEADER + +#include +#include +#include + +#ifndef CL_API_FUNCTION + #ifdef __cplusplus + #define CL_API_FUNCTION extern "C" + #else + #define CL_API_FUNCTION + #endif +#endif + +#ifndef CL_INLINE + #ifndef _MSC_VER + #ifdef __cplusplus + #define CL_INLINE inline + #else + #define CL_INLINE + #endif + #else + #define CL_INLINE __forceinline + #endif +#endif + +#ifndef CL_Allocator +struct MA_Arena; + #define CL_Allocator MA_Arena * +#endif + +#ifndef AND_CL_STRING_TERMINATE_ON_NEW_LINE + #define AND_CL_STRING_TERMINATE_ON_NEW_LINE &&*T->stream != '\n' +#endif + +typedef enum CL_Kind { + CL_EOF, + CL_MUL, + CL_DIV, + CL_MOD, + CL_LEFTSHIFT, + CL_RIGHTSHIFT, + CL_ADD, + CL_SUB, + CL_EQUALS, + CL_LESSERTHEN, + CL_GREATERTHEN, + CL_LESSERTHEN_OR_EQUAL, + CL_GREATERTHEN_OR_EQUAL, + CL_NOTEQUALS, + CL_BITAND, + CL_BITOR, + CL_BITXOR, + CL_AND, + CL_OR, + CL_NEG, + CL_NOT, + CL_DECREMENT, + CL_INCREMENT, + CL_POSTDECREMENT, + CL_POSTINCREMENT, + CL_ASSIGN, + CL_DIVASSIGN, + CL_MULASSIGN, + CL_MODASSIGN, + CL_SUBASSIGN, + CL_ADDASSIGN, + CL_ANDASSIGN, + CL_ORASSIGN, + CL_XORASSIGN, + CL_LEFTSHIFTASSIGN, + CL_RIGHTSHIFTASSIGN, + CL_OPENPAREN, + CL_CLOSEPAREN, + CL_OPENBRACE, + CL_CLOSEBRACE, + CL_OPENBRACKET, + CL_CLOSEBRACKET, + CL_COMMA, + CL_MACRO_CONCAT, + CL_PREPROC_STRINGIFY, + CL_QUESTION, + CL_THREEDOTS, + CL_SEMICOLON, + CL_DOT, + CL_COLON, + CL_TAG, + CL_ARROW, + CL_EXPRSIZEOF, + CL_DOCCOMMENT, + CL_COMMENT, + CL_IDENTIFIER, + CL_STRINGLIT, + CL_CHARLIT, + CL_ERROR, + CL_FLOAT, + CL_INT, + CL_PREPROC_NULL, + CL_PREPROC_DEFINE, + CL_PREPROC_IFDEF, + CL_PREPROC_IFNDEF, + CL_PREPROC_INCLUDE, + CL_PREPROC_ENDIF, + CL_PREPROC_IF, + CL_PREPROC_PRAGMA, + CL_PREPROC_ERROR, + CL_PREPROC_ELSE, + CL_PREPROC_ELIF, + CL_PREPROC_UNDEF, + CL_KEYWORD_VOID, + CL_KEYWORD_INT, + CL_KEYWORD_CHAR, + CL_KEYWORD_UNSIGNED, + CL_KEYWORD_SIGNED, + CL_KEYWORD_LONG, + CL_KEYWORD_SHORT, + CL_KEYWORD_DOUBLE, + CL_KEYWORD_FLOAT, + CL_KEYWORD__BOOL, + CL_KEYWORD__COMPLEX, + CL_KEYWORD__IMAGINARY, + CL_KEYWORD_STATIC, + CL_KEYWORD_AUTO, + CL_KEYWORD_CONST, + CL_KEYWORD_EXTERN, + CL_KEYWORD_INLINE, + CL_KEYWORD_REGISTER, + CL_KEYWORD_RESTRICT, + CL_KEYWORD_VOLATILE, + CL_KEYWORD__THREAD_LOCAL, + CL_KEYWORD__ATOMIC, + CL_KEYWORD__NORETURN, + CL_KEYWORD_STRUCT, + CL_KEYWORD_UNION, + CL_KEYWORD_ENUM, + CL_KEYWORD_TYPEDEF, + CL_KEYWORD_DEFAULT, + CL_KEYWORD_BREAK, + CL_KEYWORD_RETURN, + CL_KEYWORD_SWITCH, + CL_KEYWORD_IF, + CL_KEYWORD_ELSE, + CL_KEYWORD_FOR, + CL_KEYWORD_WHILE, + CL_KEYWORD_CASE, + CL_KEYWORD_CONTINUE, + CL_KEYWORD_DO, + CL_KEYWORD_GOTO, + CL_KEYWORD_SIZEOF, + CL_KEYWORD__ALIGNAS, + CL_KEYWORD__ALIGNOF, + CL_KEYWORD__STATIC_ASSERT, + CL_KEYWORD__GENERIC, + CL_COUNT, +} CL_Kind; + +typedef enum CL_Fix { + CL_FIX_NONE, + CL_SUFFIX_U, + CL_SUFFIX_UL, + CL_SUFFIX_ULL, + CL_SUFFIX_L, + CL_SUFFIX_LL, + CL_SUFFIX_F, + CL_SUFFIX_FL, + CL_PREFIX_U8, + CL_PREFIX_U16, + CL_PREFIX_U32, + CL_PREFIX_L, +} CL_Fix; + +typedef struct CL_Token CL_Token; +struct CL_Token { + CL_Kind kind; + CL_Fix fix; + + bool is_hex : 1; + bool is_inside_macro : 1; + bool is_system_include : 1; + bool is_there_whitespace_before_token : 1; + + uint32_t id; + int len; + char *str; + + // Not storing line_begin like I would normally cause the user could + // override the line and file information using directives. + // On error need to do search if I want nice error context. + int line, column; + char *file; + + union { + double f64; + uint64_t u64; + char *intern; + char *string_literal; + struct CL_Message *error; + }; +}; + +typedef struct CL_Message CL_Message; +struct CL_Message { + CL_Message *next; + char *string; + CL_Token token; +}; + +typedef struct CL_Lexer CL_Lexer; +struct CL_Lexer { + CL_Message *first_message; + CL_Message *last_message; + int errors; + + char *stream; + char *stream_begin; + int line; + int column; + char *file; + bool inside_of_macro; + + // filters + bool skip_comments : 1; + bool skip_macros : 1; + bool select_includes : 1; + bool select_comments : 1; + bool select_macros : 1; + + CL_Allocator arena; +}; + +typedef struct CL_SearchPaths CL_SearchPaths; +struct CL_SearchPaths { + char **include_path; + int include_path_count; + + char **system_include_path; + int system_include_path_count; + + char *file_begin_to_ignore; +}; + +CL_API_FUNCTION CL_Token CL_Next(CL_Lexer *T); +CL_API_FUNCTION CL_Lexer CL_Begin(CL_Allocator arena, char *stream, char *filename); +CL_API_FUNCTION char *CL_ResolveFilepath(CL_Allocator arena, CL_SearchPaths *search_paths, char *filename, char *parent_file, bool is_system_include); +CL_API_FUNCTION void CL_StringifyMessage(char *buff, int buff_size, CL_Message *msg); +CL_API_FUNCTION void CL_Stringify(char *buff, int buff_size, CL_Token *token); + +extern const char *CL_FixString[]; +extern const char *CL_KindString[]; + +CL_INLINE int CL_StringLength(char *string) { + int len = 0; + while (*string++ != 0) len++; + return len; +} + +CL_INLINE bool CL_StringsAreEqual(char *a, int64_t alen, const char *b, int64_t blen) { + if (alen != blen) return false; + for (int i = 0; i < alen; i += 1) { + if (a[i] != b[i]) return false; + } + return true; +} + +CL_INLINE bool CL_IsIdentifier(CL_Token *token, char *str) { + int str_len = CL_StringLength(str); + bool result = token->kind == CL_IDENTIFIER && CL_StringsAreEqual(token->str, token->len, str, str_len); + return result; +} + +CL_INLINE bool CL_IsAssign(CL_Kind op) { + bool result = op >= CL_ASSIGN && op <= CL_RIGHTSHIFTASSIGN; + return result; +} + +CL_INLINE bool CL_IsKeywordType(CL_Kind op) { + bool result = op >= CL_KEYWORD_VOID && op <= CL_KEYWORD__IMAGINARY; + return result; +} + +CL_INLINE bool CL_IsKeywordTypeOrSpec(CL_Kind op) { + bool result = op >= CL_KEYWORD_VOID && op <= CL_KEYWORD_TYPEDEF; + return result; +} + +CL_INLINE bool CL_IsMacro(CL_Kind kind) { + bool result = kind >= CL_PREPROC_DEFINE && kind <= CL_PREPROC_UNDEF; + return result; +} + +CL_INLINE bool CL_IsKeyword(CL_Kind kind) { + bool result = kind >= CL_KEYWORD_VOID && kind <= CL_KEYWORD__GENERIC; + return result; +} + +CL_INLINE bool CL_IsKeywordOrIdent(CL_Kind kind) { + bool result = CL_IsKeyword(kind) || kind == CL_IDENTIFIER; + return result; +} + +#endif \ No newline at end of file diff --git a/src/standalone_libraries/defer.hpp b/src/standalone_libraries/defer.hpp new file mode 100644 index 0000000..463ec4a --- /dev/null +++ b/src/standalone_libraries/defer.hpp @@ -0,0 +1,25 @@ +#ifndef FIRST_DEFER_HEADER +#define FIRST_DEFER_HEADER + +template +struct DEFER_ExitScope { + T lambda; + DEFER_ExitScope(T lambda) : lambda(lambda) {} + ~DEFER_ExitScope() { lambda(); } + DEFER_ExitScope(const DEFER_ExitScope &i) : lambda(i.lambda){}; + + private: + DEFER_ExitScope &operator=(const DEFER_ExitScope &); +}; + +class DEFER_ExitScopeHelp { + public: + template + DEFER_ExitScope operator+(T t) { return t; } +}; + +#define DEFER_CONCAT_INTERNAL(x, y) x##y +#define DEFER_CONCAT(x, y) DEFER_CONCAT_INTERNAL(x, y) +#define defer const auto DEFER_CONCAT(defer__, __LINE__) = DEFER_ExitScopeHelp() + [&]() + +#endif \ No newline at end of file diff --git a/src/standalone_libraries/hash.c b/src/standalone_libraries/hash.c new file mode 100644 index 0000000..8b44f00 --- /dev/null +++ b/src/standalone_libraries/hash.c @@ -0,0 +1,53 @@ +#include "hash.h" + +// FNV HASH (1a?) +HASH_API_FUNCTION uint64_t HashBytes(void *data, uint64_t size) { + uint8_t *data8 = (uint8_t *)data; + uint64_t hash = (uint64_t)14695981039346656037ULL; + for (uint64_t i = 0; i < size; i++) { + hash = hash ^ (uint64_t)(data8[i]); + hash = hash * (uint64_t)1099511628211ULL; + } + return hash; +} + +HASH_API_FUNCTION RandomSeed MakeRandomSeed(uint64_t value) { + RandomSeed result; + result.a = value; + return result; +} + +HASH_API_FUNCTION uint64_t GetRandomU64(RandomSeed *state) { + uint64_t x = state->a; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + return state->a = x; +} + +HASH_API_FUNCTION int GetRandomRangeI(RandomSeed *seed, int first, int last_included) { + uint64_t random = GetRandomU64(seed); + int range = (last_included - first + 1); + int mapped = random % range; + int result = mapped + first; + return result; +} + +HASH_API_FUNCTION double GetRandomNormal(RandomSeed *series) { + uint64_t rnd = GetRandomU64(series); + double result = (double)rnd / (double)UINT64_MAX; + return result; +} + +HASH_API_FUNCTION double GetRandomNormalRange(RandomSeed *seed, double min, double max) { + double value = GetRandomNormal(seed); + double result = value * (max - min) + min; + return result; +} + +HASH_API_FUNCTION uint64_t HashMix(uint64_t x, uint64_t y) { + x ^= y; + x *= 0xff51afd7ed558ccd; + x ^= x >> 32; + return x; +} diff --git a/src/standalone_libraries/hash.h b/src/standalone_libraries/hash.h new file mode 100644 index 0000000..073a9d2 --- /dev/null +++ b/src/standalone_libraries/hash.h @@ -0,0 +1,28 @@ +#ifndef FIRST_HASH_HEADER +#define FIRST_HASH_HEADER +#include + +#ifndef HASH_API_FUNCTION + #ifdef __cplusplus + #define HASH_API_FUNCTION extern "C" + #else + #define HASH_API_FUNCTION + #endif +#endif + +typedef struct RandomSeed RandomSeed; +struct RandomSeed { + uint64_t a; +}; + +HASH_API_FUNCTION uint64_t HashBytes(void *data, uint64_t size); +HASH_API_FUNCTION RandomSeed MakeRandomSeed(uint64_t value); +HASH_API_FUNCTION uint64_t GetRandomU64(RandomSeed *state); +HASH_API_FUNCTION int GetRandomRangeI(RandomSeed *seed, int first, int last_included); +HASH_API_FUNCTION double GetRandomNormal(RandomSeed *series); +HASH_API_FUNCTION double GetRandomNormalRange(RandomSeed *seed, double min, double max); +HASH_API_FUNCTION uint64_t HashMix(uint64_t x, uint64_t y); + +#define WRAP_AROUND_POWER_OF_2(x, pow2) (((x) & ((pow2)-1llu))) +static inline float GetRandomNormalF(RandomSeed *series) { return (float)GetRandomNormal(series); } +#endif \ No newline at end of file diff --git a/src/standalone_libraries/io.c b/src/standalone_libraries/io.c new file mode 100644 index 0000000..6f194ab --- /dev/null +++ b/src/standalone_libraries/io.c @@ -0,0 +1,236 @@ +#include "io.h" +#include + +#ifndef IO_SNPRINTF + #include + #define IO_SNPRINTF snprintf +#endif + +#ifndef IO_VSNPRINTF + #include + #define IO_VSNPRINTF vsnprintf +#endif + +#ifndef IO_ALLOCATE + #include + #define IO_ALLOCATE(x) malloc(x) + #define IO_FREE(x) free(x) +#endif + +#ifndef IO_StaticFunc + #if defined(__GNUC__) || defined(__clang__) + #define IO_StaticFunc __attribute__((unused)) static + #else + #define IO_StaticFunc static + #endif +#endif + +IO_StaticFunc int IO_Strlen(char *string) { + int len = 0; + while (*string++ != 0) len++; + return len; +} + +IO_THREAD_LOCAL void (*IO_User_OutputMessage)(int kind, const char *file, int line, char *str, int len); + +IO_API bool IO__FatalErrorf(const char *file, int line, const char *msg, ...) { + va_list args1; + va_list args2; + char buff[2048]; + + va_start(args1, msg); + va_copy(args2, args1); + int size = IO_VSNPRINTF(buff, sizeof(buff), msg, args2); + va_end(args2); + + char *new_buffer = 0; + char *user_message = buff; + if (size >= sizeof(buff)) { + size += 4; + new_buffer = (char *)IO_ALLOCATE(size); + IO_VSNPRINTF(new_buffer, size, msg, args1); + user_message = new_buffer; + } + va_end(args1); + + IO_ErrorResult ret = IO_ErrorResult_Continue; + { + char buff2[2048]; + char *result = buff2; + char *b = 0; + int size2 = IO_SNPRINTF(buff2, sizeof(buff2), "%s(%d): error: %s \n", file, line, user_message); + if (size2 >= sizeof(buff2)) { + size2 += 4; + b = (char *)IO_ALLOCATE(size2); + size2 = IO_SNPRINTF(b, size2, "%s(%d): error: %s \n", file, line, user_message); + result = b; + } + + ret = IO_OutputError(result, size2); + if (ret == IO_ErrorResult_Exit) { + IO_Exit(1); + } + + if (b) { + IO_FREE(b); + } + } + + if (new_buffer) { + IO_FREE(new_buffer); + } + + return ret == IO_ErrorResult_Break; +} + +IO_API void IO__Printf(int kind, const char *file, int line, const char *msg, ...) { + // First try to use a static buffer. That can fail because the message + // can be bigger then the buffer. Allocate enough memory to fit in that + // case. + va_list args1; + va_list args2; + char buff[2048]; + + va_start(args1, msg); + va_copy(args2, args1); + int size = IO_VSNPRINTF(buff, sizeof(buff), msg, args2); + va_end(args2); + + char *new_buffer = 0; + char *result = buff; + if (size >= sizeof(buff)) { + size += 4; + new_buffer = (char *)IO_ALLOCATE(size); + IO_VSNPRINTF(new_buffer, size, msg, args1); + result = new_buffer; + } + va_end(args1); + + if (IO_User_OutputMessage) { + IO_User_OutputMessage(kind, file, line, result, size); + } else { + IO_OutputMessage(result, size); + } + + if (new_buffer) { + IO_FREE(new_buffer); + } +} + +IO_API bool IO__FatalError(const char *msg) { + int len = IO_Strlen((char *)msg); + IO_ErrorResult result = IO_OutputError((char *)msg, len); + if (result == IO_ErrorResult_Exit) { + IO_Exit(1); + } + return result == IO_ErrorResult_Break; +} + +IO_API void IO_Print(int kind, const char *file, int line, char *msg, int len) { + if (IO_User_OutputMessage) { + IO_User_OutputMessage(kind, file, line, msg, len); + } else { + IO_OutputMessage(msg, len); + } +} +#ifdef _WIN32 + #ifndef NOMINMAX + #define NOMINMAX + #endif + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + + #pragma comment(lib, "user32") + + #include + +IO_API bool IO_IsDebuggerPresent(void) { + return IsDebuggerPresent(); +} + +IO_API void IO_OutputMessage(char *str, int len) { + if (IsDebuggerPresent()) { + OutputDebugStringA(str); + } + printf("%.*s", len, str); + fflush(stdout); +} + +IO_API IO_ErrorResult IO_OutputError(char *str, int len) { + IO_ErrorResult result = IO_ErrorResult_Continue; + IO_OutputMessage(str, len); + + char *msg = str; + if (str[len] != 0) { + msg = (char *)IO_ALLOCATE(len + 1); + for (int i = 0; i < len; i += 1) msg[i] = str[i]; + msg[len] = 0; + } + + OutputDebugStringA(msg); + if (!IsDebuggerPresent()) { + + // Limit size of error output message + char tmp = 0; + if (len > 4096) { + tmp = str[4096]; + str[4096] = 0; + } + + MessageBoxA(0, msg, "Error!", 0); + + if (tmp != 0) { + str[4096] = tmp; + } + + result = IO_ErrorResult_Exit; + } else { + result = IO_ErrorResult_Break; + } + + if (msg != str) { + IO_FREE(msg); + } + + return result; +} + +IO_API void IO_Exit(int error_code) { + ExitProcess(error_code); +} +#elif __linux__ || __unix__ || __APPLE__ + #include +IO_API IO_ErrorResult IO_OutputError(char *str, int len) { + fprintf(stderr, "%.*s", len, str); + return IO_ErrorResult_Exit; +} + +IO_API void IO_OutputMessage(char *str, int len) { + fprintf(stdout, "%.*s", len, str); +} + +IO_API void IO_Exit(int error_code) { + exit(error_code); +} + +IO_API bool IO_IsDebuggerPresent(void) { + return false; +} +#else +IO_API IO_ErrorResult IO_OutputError(char *str, int len) { + return IO_ErrorResult_Exit; +} + +IO_API void IO_OutputMessage(char *str, int len) { +} + +IO_API void IO_Exit(int error_code) { +} + +IO_API bool IO_IsDebuggerPresent(void) { + return false; +} + +#endif // LIBC diff --git a/src/standalone_libraries/io.h b/src/standalone_libraries/io.h new file mode 100644 index 0000000..70f8bb8 --- /dev/null +++ b/src/standalone_libraries/io.h @@ -0,0 +1,108 @@ +#ifndef FIRST_IO_HEADER +#define FIRST_IO_HEADER +#include + +#ifndef IO_API + #ifdef __cplusplus + #define IO_API extern "C" + #else + #define IO_API + #endif +#endif + +typedef enum IO_ErrorResult { + IO_ErrorResult_Continue, + IO_ErrorResult_Break, + IO_ErrorResult_Exit, +} IO_ErrorResult; + +#if defined(_MSC_VER) + #define IO_DebugBreak() (__debugbreak(), 0) +#else + #define IO_DebugBreak() (__builtin_trap(), 0) +#endif + +#ifndef IO_THREAD_LOCAL + #if defined(__cplusplus) && __cplusplus >= 201103L + #define IO_THREAD_LOCAL thread_local + #elif defined(__GNUC__) + #define IO_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define IO_THREAD_LOCAL __declspec(thread) + #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) + #define IO_THREAD_LOCAL _Thread_local + #elif defined(__TINYC__) + #define IO_THREAD_LOCAL _Thread_local + #else + #error Couldnt figure out thread local, needs to be provided manually + #endif +#endif + +#if defined(__has_attribute) + #if __has_attribute(format) + #define IO__PrintfFormat(fmt, va) __attribute__((format(printf, fmt, va))) + #endif +#endif + +#ifndef IO__PrintfFormat + #define IO__PrintfFormat(fmt, va) +#endif + +typedef void IO_MessageHandler(int kind, const char *file, int line, char *str, int len); +extern IO_THREAD_LOCAL void (*IO_User_OutputMessage)(int kind, const char *file, int line, char *str, int len); + +#define IO__STRINGIFY(x) #x +#define IO__TOSTRING(x) IO__STRINGIFY(x) +#define IO_LINE IO__TOSTRING(__LINE__) + +#define IO_Assert(x) !(x) && IO__FatalError((__FILE__ "(" IO_LINE "): " \ + "error: " #x "\n")) && \ + IO_DebugBreak() +#define IO_FatalErrorf(...) \ + do { \ + bool result = IO__FatalErrorf(__FILE__, __LINE__, __VA_ARGS__); \ + if (result) IO_DebugBreak(); \ + } while (0) +#define IO_FatalError(...) \ + do { \ + bool result = IO__FatalError(__FILE__ "(" IO_LINE "): error - " __VA_ARGS__); \ + if (result) IO_DebugBreak(); \ + } while (0) +#define IO_Assertf(x, ...) \ + do { \ + if (!(x)) { \ + bool result = IO__FatalErrorf(__FILE__, __LINE__, __VA_ARGS__); \ + if (result) IO_DebugBreak(); \ + } \ + } while (0) + +#define IO_InvalidElseIf(c) \ + else if (c) { \ + IO_InvalidCodepath(); \ + } +#define IO_InvalidElse() \ + else { \ + IO_InvalidCodepath(); \ + } +#define IO_InvalidCodepath() IO_FatalError("This codepath is invalid") +#define IO_InvalidDefaultCase() \ +default: { \ + IO_FatalError("Entered invalid switch statement case"); \ +} +#define IO_Todo() IO_FatalError("This codepath is not implemented yet") + +IO_API bool IO__FatalErrorf(const char *file, int line, const char *msg, ...) IO__PrintfFormat(3, 4); +IO_API void IO__Printf(int kind, const char *file, int line, const char *msg, ...) IO__PrintfFormat(4, 5); +IO_API bool IO__FatalError(const char *msg); +IO_API void IO_Print(int kind, const char *file, int line, char *msg, int len); +IO_API void IO_OutputMessage(char *str, int len); +IO_API IO_ErrorResult IO_OutputError(char *str, int len); +IO_API void IO_Exit(int error_code); +IO_API bool IO_IsDebuggerPresent(void); + +static const int IO_KindPrintf = 1; +static const int IO_KindWarningf = 2; + +#define IO_Printf(...) IO__Printf(IO_KindPrintf, __FILE__, __LINE__, __VA_ARGS__) +#define IO_Warningf(...) IO__Printf(IO_KindWarningf, __FILE__, __LINE__, __VA_ARGS__) +#endif \ No newline at end of file diff --git a/src/standalone_libraries/linked_list.h b/src/standalone_libraries/linked_list.h new file mode 100644 index 0000000..7ae9625 --- /dev/null +++ b/src/standalone_libraries/linked_list.h @@ -0,0 +1,119 @@ +#ifndef FIRST_LL_HEADER +#define FIRST_LL_HEADER +#define SLL_QUEUE_ADD_MOD(f, l, n, next) \ + do { \ + (n)->next = 0; \ + if ((f) == 0) { \ + (f) = (l) = (n); \ + } else { \ + (l) = (l)->next = (n); \ + } \ + } while (0) +#define SLL_QUEUE_ADD(f, l, n) SLL_QUEUE_ADD_MOD(f, l, n, next) + +#define SLL_QUEUE_POP_FIRST_MOD(f, l, next) \ + do { \ + if ((f) == (l)) { \ + (f) = (l) = 0; \ + } else { \ + (f) = (f)->next; \ + } \ + } while (0) +#define SLL_QUEUE_POP_FIRST(f, l) SLL_QUEUE_POP_FIRST_MOD(f, l, next) + +#define SLL_STACK_ADD_MOD(stack_base, new_stack_base, next) \ + do { \ + (new_stack_base)->next = (stack_base); \ + (stack_base) = (new_stack_base); \ + } while (0) +#define SLL_STACK_ADD(stack_base, new_stack_base) \ + SLL_STACK_ADD_MOD(stack_base, new_stack_base, next) + +#define SLL_STACK_POP_AND_STORE(stack_base, out_node) \ + do { \ + if (stack_base) { \ + (out_node) = (stack_base); \ + (stack_base) = (stack_base)->next; \ + (out_node)->next = 0; \ + } \ + } while (0) + +#define DLL_QUEUE_ADD_MOD(f, l, node, next, prev) \ + do { \ + if ((f) == 0) { \ + (f) = (l) = (node); \ + (node)->prev = 0; \ + (node)->next = 0; \ + } else { \ + (l)->next = (node); \ + (node)->prev = (l); \ + (node)->next = 0; \ + (l) = (node); \ + } \ + } while (0) +#define DLL_QUEUE_ADD(f, l, node) DLL_QUEUE_ADD_MOD(f, l, node, next, prev) +#define DLL_QUEUE_ADD_FRONT(f, l, node) DLL_QUEUE_ADD_MOD(l, f, node, prev, next) +#define DLL_QUEUE_REMOVE_MOD(first, last, node, next, prev) \ + do { \ + if ((first) == (last)) { \ + (first) = (last) = 0; \ + } else if ((last) == (node)) { \ + (last) = (last)->prev; \ + (last)->next = 0; \ + } else if ((first) == (node)) { \ + (first) = (first)->next; \ + (first)->prev = 0; \ + } else { \ + (node)->prev->next = (node)->next; \ + (node)->next->prev = (node)->prev; \ + } \ + if (node) { \ + (node)->prev = 0; \ + (node)->next = 0; \ + } \ + } while (0) +#define DLL_QUEUE_REMOVE(first, last, node) DLL_QUEUE_REMOVE_MOD(first, last, node, next, prev) + +#define DLL_STACK_ADD_MOD(first, node, next, prev) \ + do { \ + (node)->next = (first); \ + if ((first)) \ + (first)->prev = (node); \ + (first) = (node); \ + (node)->prev = 0; \ + } while (0) +#define DLL_STACK_ADD(first, node) DLL_STACK_ADD_MOD(first, node, next, prev) +#define DLL_STACK_REMOVE_MOD(first, node, next, prev) \ + do { \ + if ((node) == (first)) { \ + (first) = (first)->next; \ + if ((first)) \ + (first)->prev = 0; \ + } else { \ + (node)->prev->next = (node)->next; \ + if ((node)->next) \ + (node)->next->prev = (node)->prev; \ + } \ + if (node) { \ + (node)->prev = 0; \ + (node)->next = 0; \ + } \ + } while (0) +#define DLL_STACK_REMOVE(first, node) DLL_STACK_REMOVE_MOD(first, node, next, prev) + +#define DLL_INSERT_NEXT_MOD(base, new, next, prev) \ + do { \ + if ((base) == 0) { \ + (base) = (new); \ + (new)->next = 0; \ + (new)->prev = 0; \ + } else { \ + (new)->next = (base)->next; \ + (base)->next = (new); \ + (new)->prev = (base); \ + if ((new)->next) (new)->next->prev = (new); \ + } \ + } while (0) +#define DLL_INSERT_NEXT(base, new) DLL_INSERT_NEXT_MOD(base, new, next, prev) +#define DLL_INSERT_PREV(base, new) DLL_INSERT_NEXT_MOD(base, new, next, prev) +#endif \ No newline at end of file diff --git a/src/standalone_libraries/load_library.c b/src/standalone_libraries/load_library.c new file mode 100644 index 0000000..eda26be --- /dev/null +++ b/src/standalone_libraries/load_library.c @@ -0,0 +1,26 @@ +#include "load_library.h" +#ifdef _WIN32 + #ifndef NOMINMAX + #define NOMINMAX + #endif + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + +LIB_Library LIB_LoadLibrary(char *str) { + HMODULE module = LoadLibraryA(str); + return (LIB_Library)module; +} + +void *LIB_LoadSymbol(LIB_Library lib, char *symbol) { + void *result = (void *)GetProcAddress((HMODULE)lib, symbol); + return result; +} + +bool LIB_UnloadLibrary(LIB_Library lib) { + BOOL result = FreeLibrary((HMODULE)lib); + if (result == 0) return false; + return true; +} +#endif // _WIN32 diff --git a/src/standalone_libraries/load_library.h b/src/standalone_libraries/load_library.h new file mode 100644 index 0000000..3c98bbd --- /dev/null +++ b/src/standalone_libraries/load_library.h @@ -0,0 +1,12 @@ +#ifndef FIRST_LIB_HEADER +#define FIRST_LIB_HEADER +typedef void *LIB_Library; + +LIB_Library LIB_LoadLibrary(char *str); +void *LIB_LoadSymbol(LIB_Library lib, char *symbol); +bool LIB_UnloadLibrary(LIB_Library lib); + +#ifndef LIB_EXPORT + #define LIB_EXPORT __declspec(dllexport) +#endif +#endif \ No newline at end of file diff --git a/src/standalone_libraries/multimedia.c b/src/standalone_libraries/multimedia.c new file mode 100644 index 0000000..1b49cc1 --- /dev/null +++ b/src/standalone_libraries/multimedia.c @@ -0,0 +1,1740 @@ +#include "multimedia.h" + +#ifndef MU_StaticFunc + #if defined(__GNUC__) || defined(__clang__) + #define MU_StaticFunc __attribute__((unused)) static + #else + #define MU_StaticFunc static + #endif +#endif + +#ifndef MU_PRIVATE_VAR + #define MU_PRIVATE_VAR MU_StaticFunc +#endif + +#ifdef _WIN32 + #ifndef NOMINMAX + #define NOMINMAX + #endif + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #include + #include // for handling dropped files + + #define INITGUID + #define CINTERFACE + #define COBJMACROS + #define CONST_VTABLE + #include + #include + #include + #include + + // + // Automatically linking with the libraries + // + #pragma comment(lib, "gdi32.lib") + #pragma comment(lib, "user32.lib") + #pragma comment(lib, "shell32.lib") // For handling dropping files into the app +#endif +MU_StaticFunc void *MU_PushSize(MU_Arena *ar, size_t size); +MU_StaticFunc MU_UTF32Result MU_UTF16ToUTF32(uint16_t *c, int max_advance); +MU_StaticFunc MU_UTF8Result MU_UTF32ToUTF8(uint32_t codepoint); +MU_StaticFunc int64_t MU_CreateCharFromWidechar(char *buffer, int64_t buffer_size, wchar_t *in, int64_t inlen); +MU_StaticFunc void MU_WIN32_UpdateFocusedWindowBasedOnHandle(MU_Context *mu, HWND handle); +MU_StaticFunc void MU_WIN32_UpdateFocusedWindow(MU_Context *mu); +MU_StaticFunc void MU_Win32_GetWindowSize(HWND window, int *x, int *y); +MU_StaticFunc void MU_WIN32_GetWindowPos(HWND window, int *x, int *y); +MU_StaticFunc MU_Int2 MU_WIN32_GetMousePosition(HWND window); +MU_StaticFunc MU_Int2 MU_WIN32_GetMousePositionInverted(HWND window, int y); +MU_StaticFunc void MU_WIN32_CreateCanvas(MU_Window *window); +MU_StaticFunc void MU_WIN32_DestroyCanvas(MU_Window *window); +MU_StaticFunc void MU_WIN32_DrawCanvas(MU_Window *window); +MU_StaticFunc void MU__MemoryCopy(void *dst, const void *src, size_t size); +MU_StaticFunc void MU_PushDroppedFile(MU_Context *mu, MU_Window *window, char *str, int size); +MU_StaticFunc void MU_UpdateWindowState(MU_Window *window); +MU_StaticFunc int MU__AreStringsEqual(const char *src, const char *dst, size_t dstlen); +MU_StaticFunc void *MU_Win32_GLGetWindowProcAddressForGlad(const char *proc); +MU_StaticFunc void MU_WIN32_GetWGLFunctions(MU_Context *mu); +MU_StaticFunc void MU_WIN32_TryToInitGLContextForWindow(MU_Context *mu, MU_Win32_Window *w32_window); +MU_StaticFunc void MU_WIN32_DeinitSound(MU_Context *mu); +MU_StaticFunc void MU_WIN32_LoadCOM(MU_Context *mu); +MU_StaticFunc DWORD MU_WIN32_SoundThread(void *parameter); +MU_StaticFunc void MU_WIN32_InitWasapi(MU_Context *mu); + +#ifndef MU_GL_ENABLE_MULTISAMPLING + #define MU_GL_ENABLE_MULTISAMPLING 1 +#endif + +#ifndef MU_GL_BUILD_DEBUG + #define MU_GL_BUILD_DEBUG 1 +#endif + +#ifndef MU_ASSERT_CODE + #define MU_ASSERT_CODE(x) x +#endif + +#ifndef MU_ASSERT + #include + #define MU_ASSERT(x) assert(x) +#endif + +/* Quake uses this to sleep when user is not interacting with app + void SleepUntilInput (int time) + { + MsgWaitForMultipleObjects(1, &tevent, FALSE, time, QS_ALLINPUT); + } + + if ((cl.paused && (!ActiveApp && !DDActive)) || Minimized || block_drawing) + { + SleepUntilInput (PAUSE_SLEEP); + scr_skipupdate = 1; // no point in bothering to draw + } + else if (!ActiveApp && !DDActive) + { + SleepUntilInput (NOT_FOCUS_SLEEP); + } + */ +// @! Add native handle to MU_Context for Directx 11 initialize +// @! Add option to manually blit, some manual blit param and manual blit function +// @! Add ram info? https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-globalmemorystatusex +// @! Maybe make the library friendly to people who dont use debuggers +// @! Set window title +// @! Good defaults for multiple windows ?? + +struct MU_UTF32Result { + uint32_t out_str; + int advance; + int error; +}; + +struct MU_UTF8Result { + char out_str[4]; + int len; + int error; +}; + +#define MU_ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) +#define MU_STACK_ADD_MOD(stack_base, new_stack_base, next) \ + do { \ + (new_stack_base)->next = (stack_base); \ + (stack_base) = (new_stack_base); \ + } while (0) +#define MU_STACK_ADD(stack_base, new_stack_base) \ + MU_STACK_ADD_MOD(stack_base, new_stack_base, next) + +MU_API void MU_Quit(MU_Context *mu) { + mu->quit = true; +} + +MU_API void MU_DefaultSoundCallback(MU_Context *mu, uint16_t *buffer, uint32_t samples_to_fill) { +} + +MU_INLINE void MU__WriteChar8(MU_Window *window, char *c, int len) { + if (window->user_text8_count + len < MU_ARRAY_SIZE(window->user_text8)) { + for (int i = 0; i < len; i += 1) { + window->user_text8[window->user_text8_count++] = c[i]; + } + } +} + +MU_INLINE void MU__WriteChar32(MU_Window *window, uint32_t c) { + if (window->user_text32_count + 1 < MU_ARRAY_SIZE(window->user_text32)) { + window->user_text32[window->user_text32_count++] = c; + } +} + +MU_INLINE void MU__KeyDown(MU_Window *window, MU_Key key) { + if (window->key[key].down == false) + window->key[key].press = true; + window->key[key].down = true; + window->key[key].raw_press = true; +} + +MU_INLINE void MU__ZeroMemory(void *p, size_t size) { + uint8_t *p8 = (uint8_t *)p; + for (size_t i = 0; i < size; i += 1) { + p8[i] = 0; + } +} + +MU_INLINE size_t MU__GetAlignOffset(size_t size, size_t align) { + size_t mask = align - 1; + size_t val = size & mask; + if (val) { + val = align - val; + } + return val; +} + +MU_INLINE void MU__KeyUP(MU_Window *window, MU_Key key) { + if (window->key[key].down == true) + window->key[key].unpress = true; + window->key[key].down = false; +} + +MU_INLINE bool MU_DoesSizeFit(MU_Arena *ar, size_t size) { + const size_t alignment = 16; + size_t align = MU__GetAlignOffset((uintptr_t)ar->memory + ar->len, alignment); + size_t cursor = ar->len + align; + bool result = cursor + size <= ar->cap; + return result; +} + +#define MU_PUSH_STRUCT(mu, T) (T *)MU_PushSize(mu, sizeof(T)) +MU_StaticFunc void *MU_PushSize(MU_Arena *ar, size_t size) { + const size_t alignment = 16; + + ar->len += MU__GetAlignOffset((uintptr_t)ar->memory + ar->len, alignment); + if (ar->len + size > ar->cap) { + MU_ASSERT(!"MU_Context has not enough memory for what you are trying to do!"); + } + + void *result = (void *)(ar->memory + ar->len); + ar->len += size; + MU_ASSERT(ar->len < ar->cap); + MU__ZeroMemory(result, size); + return result; +} + +MU_StaticFunc MU_UTF32Result MU_UTF16ToUTF32(uint16_t *c, int max_advance) { + MU_UTF32Result result; + MU__ZeroMemory(&result, sizeof(result)); + if (max_advance >= 1) { + result.advance = 1; + result.out_str = c[0]; + if (c[0] >= 0xD800 && c[0] <= 0xDBFF && c[1] >= 0xDC00 && c[1] <= 0xDFFF) { + if (max_advance >= 2) { + result.out_str = 0x10000; + result.out_str += (uint32_t)(c[0] & 0x03FF) << 10u | (c[1] & 0x03FF); + result.advance = 2; + } + else + result.error = 2; + } + } + else { + result.error = 1; + } + return result; +} + +MU_StaticFunc MU_UTF8Result MU_UTF32ToUTF8(uint32_t codepoint) { + MU_UTF8Result result; + MU__ZeroMemory(&result, sizeof(result)); + if (codepoint <= 0x7F) { + result.len = 1; + result.out_str[0] = (char)codepoint; + } + else if (codepoint <= 0x7FF) { + result.len = 2; + result.out_str[0] = 0xc0 | (0x1f & (codepoint >> 6)); + result.out_str[1] = 0x80 | (0x3f & codepoint); + } + else if (codepoint <= 0xFFFF) { // 16 bit word + result.len = 3; + result.out_str[0] = 0xe0 | (0xf & (codepoint >> 12)); // 4 bits + result.out_str[1] = 0x80 | (0x3f & (codepoint >> 6)); // 6 bits + result.out_str[2] = 0x80 | (0x3f & codepoint); // 6 bits + } + else if (codepoint <= 0x10FFFF) { // 21 bit word + result.len = 4; + result.out_str[0] = 0xf0 | (0x7 & (codepoint >> 18)); // 3 bits + result.out_str[1] = 0x80 | (0x3f & (codepoint >> 12)); // 6 bits + result.out_str[2] = 0x80 | (0x3f & (codepoint >> 6)); // 6 bits + result.out_str[3] = 0x80 | (0x3f & codepoint); // 6 bits + } + else { + result.error = true; + } + + return result; +} + +// @warning: this function is a little different from usual, returns -1 on decode errors +MU_StaticFunc int64_t MU_CreateCharFromWidechar(char *buffer, int64_t buffer_size, wchar_t *in, int64_t inlen) { + int64_t outlen = 0; + for (int64_t i = 0; i < inlen && in[i] != 0;) { + MU_UTF32Result decode = MU_UTF16ToUTF32((uint16_t *)(in + i), (int)(inlen - i)); + if (!decode.error) { + i += decode.advance; + MU_UTF8Result encode = MU_UTF32ToUTF8(decode.out_str); + if (!encode.error) { + for (int64_t j = 0; j < encode.len; j++) { + if (outlen >= buffer_size) { + outlen = -1; + goto failed_to_decode; + } + buffer[outlen++] = encode.out_str[j]; + } + } + else { + outlen = -1; + goto failed_to_decode; + } + } + else { + outlen = -1; + goto failed_to_decode; + } + } + + buffer[outlen] = 0; +failed_to_decode:; + return outlen; +} + +#ifdef _WIN32 + #define MU_DEFAULT_MEMORY_SIZE (1024 * 4) + +// Typedefines for the COM functions which are going to be loaded currently only required for sound +typedef HRESULT CoCreateInstanceFunction(REFCLSID rclsid, LPUNKNOWN *pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv); +typedef HRESULT CoInitializeExFunction(LPVOID pvReserved, DWORD dwCoInit); + +struct MU_Win32 { + WNDCLASSW wc; + bool good_scheduling; + MU_glGetProcAddress *wgl_get_proc_address; + HMODULE opengl32; + + HCURSOR cursor_hand; + HCURSOR cursor_arrow; + + // Sound + IMMDevice *device; + IAudioClient *audio_client; + IMMDeviceEnumerator *device_enum; + IAudioRenderClient *audio_render_client; + + uint32_t buffer_frame_count; + // IAudioCaptureClient *audio_capture_client; + + // Pointers to the functions from the dll + CoCreateInstanceFunction *CoCreateInstanceFunctionPointer; + CoInitializeExFunction *CoInitializeExFunctionPointer; +}; + +struct MU_Win32_Window { + HDC handle_dc; + HDC canvas_dc; + HBITMAP canvas_dib; + + // for fullscreen + WINDOWPLACEMENT prev_placement; + DWORD style; +}; + +MU_API double MU_GetTime(void) { + static int64_t counts_per_second; + if (counts_per_second == 0) { + LARGE_INTEGER freq; + QueryPerformanceFrequency(&freq); + counts_per_second = freq.QuadPart; + } + + LARGE_INTEGER time; + QueryPerformanceCounter(&time); + double result = (double)time.QuadPart / (double)counts_per_second; + return result; +} + +MU_StaticFunc void MU_WIN32_UpdateFocusedWindowBasedOnHandle(MU_Context *mu, HWND handle) { + if (mu->all_windows == 0) return; + for (MU_Window *it = mu->all_windows; it; it = it->next) { + if (it->handle == handle) { + mu->window = it; + return; + } + } +} + +MU_StaticFunc void MU_WIN32_UpdateFocusedWindow(MU_Context *mu) { + HWND handle = GetFocus(); + if (handle) { + MU_WIN32_UpdateFocusedWindowBasedOnHandle(mu, handle); + } +} + +MU_StaticFunc void MU_Win32_GetWindowSize(HWND window, int *x, int *y) { + RECT window_rect; + GetClientRect(window, &window_rect); + *x = window_rect.right - window_rect.left; + *y = window_rect.bottom - window_rect.top; +} + +MU_StaticFunc void MU_WIN32_GetWindowPos(HWND window, int *x, int *y) { + POINT point = {0, 0}; + ClientToScreen(window, &point); + *x = point.x; + *y = point.y; +} + +MU_StaticFunc MU_Int2 MU_WIN32_GetMousePosition(HWND window) { + POINT p; + GetCursorPos(&p); + ScreenToClient(window, &p); + MU_Int2 result = {p.x, p.y}; + return result; +} + +MU_StaticFunc MU_Int2 MU_WIN32_GetMousePositionInverted(HWND window, int y) { + MU_Int2 result = MU_WIN32_GetMousePosition(window); + result.y = y - result.y; + return result; +} + +MU_StaticFunc void MU_WIN32_CreateCanvas(MU_Window *window) { + MU_Win32_Window *w32_window = (MU_Win32_Window *)window->platform; + + MU_ASSERT(window->canvas == 0); + + BITMAPINFO bminfo; + { + MU__ZeroMemory(&bminfo, sizeof(bminfo)); + bminfo.bmiHeader.biSize = sizeof(bminfo.bmiHeader); + bminfo.bmiHeader.biWidth = (LONG)window->size.x; + bminfo.bmiHeader.biHeight = (LONG)window->size.y; + bminfo.bmiHeader.biPlanes = 1; + bminfo.bmiHeader.biBitCount = 32; + bminfo.bmiHeader.biCompression = BI_RGB; // AA RR GG BB + bminfo.bmiHeader.biXPelsPerMeter = 1; + bminfo.bmiHeader.biYPelsPerMeter = 1; + } + w32_window->canvas_dib = CreateDIBSection(w32_window->handle_dc, &bminfo, DIB_RGB_COLORS, (void **)&window->canvas, 0, 0); + w32_window->canvas_dc = CreateCompatibleDC(w32_window->handle_dc); +} + +MU_StaticFunc void MU_WIN32_DestroyCanvas(MU_Window *window) { + MU_Win32_Window *w32_window = (MU_Win32_Window *)window->platform; + if (window->canvas) { + DeleteDC(w32_window->canvas_dc); + DeleteObject(w32_window->canvas_dib); + w32_window->canvas_dc = 0; + w32_window->canvas_dib = 0; + window->canvas = 0; + } +} + +MU_StaticFunc void MU_WIN32_DrawCanvas(MU_Window *window) { + if (window->canvas) { + MU_Win32_Window *w32_window = (MU_Win32_Window *)window->platform; + SelectObject(w32_window->canvas_dc, w32_window->canvas_dib); + BitBlt(w32_window->handle_dc, 0, 0, window->size.x, window->size.y, w32_window->canvas_dc, 0, 0, SRCCOPY); + } +} + +MU_API void MU_ToggleFPSMode(MU_Window *window) { + ShowCursor(window->is_fps_mode); + window->is_fps_mode = !window->is_fps_mode; +} + +MU_API void MU_DisableFPSMode(MU_Window *window) { + if (window->is_fps_mode == true) MU_ToggleFPSMode(window); +} + +MU_API void MU_EnableFPSMode(MU_Window *window) { + if (window->is_fps_mode == false) MU_ToggleFPSMode(window); +} + +MU_StaticFunc void MU__MemoryCopy(void *dst, const void *src, size_t size) { + char *src8 = (char *)src; + char *dst8 = (char *)dst; + while (size--) *dst8++ = *src8++; +} + +// https://devblogs.microsoft.com/oldnewthing/20100412-00/?p=14353 +MU_API void MU_ToggleFullscreen(MU_Window *window) { + MU_Win32_Window *w32_window = (MU_Win32_Window *)window->platform; + DWORD dwStyle = GetWindowLong((HWND)window->handle, GWL_STYLE); + if (window->is_fullscreen == false) { + MONITORINFO mi = {sizeof(mi)}; + if (GetWindowPlacement((HWND)window->handle, &w32_window->prev_placement) && + GetMonitorInfo(MonitorFromWindow((HWND)window->handle, MONITOR_DEFAULTTOPRIMARY), &mi)) { + SetWindowLong((HWND)window->handle, GWL_STYLE, dwStyle & ~WS_OVERLAPPEDWINDOW); + BOOL result = SetWindowPos((HWND)window->handle, HWND_TOP, + mi.rcMonitor.left, mi.rcMonitor.top, + mi.rcMonitor.right - mi.rcMonitor.left, + mi.rcMonitor.bottom - mi.rcMonitor.top, + SWP_NOOWNERZORDER | SWP_FRAMECHANGED); + if (result) window->is_fullscreen = true; + } + } + else { + SetWindowLong((HWND)window->handle, GWL_STYLE, w32_window->style); + SetWindowPlacement((HWND)window->handle, &w32_window->prev_placement); + BOOL result = SetWindowPos((HWND)window->handle, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED); + if (result) window->is_fullscreen = false; + } +} + +MU_StaticFunc void MU_PushDroppedFile(MU_Context *mu, MU_Window *window, char *str, int size) { + if (MU_DoesSizeFit(&mu->frame_arena, sizeof(MU_DroppedFile) + size)) { + MU_DroppedFile *result = MU_PUSH_STRUCT(&mu->frame_arena, MU_DroppedFile); + result->filename = (char *)MU_PushSize(&mu->frame_arena, size + 1); + result->filename_size = size; + MU__MemoryCopy(result->filename, str, size); + result->filename[size] = 0; + + result->next = window->first_dropped_file; + window->first_dropped_file = result; + } +} + +// Should be initialized before processing events +// Should be initialized before initializing opengl functions using GLAD +static MU_Context *MU_WIN32_ContextPointerForEventHandling = 0; +static LRESULT CALLBACK MU_WIN32_WindowProc(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam) { + MU_Context *mu = MU_WIN32_ContextPointerForEventHandling; + MU_Win32 *w32 = (MU_Win32 *)mu->platform; + + MU_WIN32_UpdateFocusedWindowBasedOnHandle(mu, wnd); + MU_Window *window = mu->window ? mu->window : 0; + if (window) window->processed_events_this_frame += 1; + + (void)w32; + switch (msg) { + + case WM_DROPFILES: { + wchar_t buffer[512]; + char buffer8[1024]; + + HDROP hdrop = (HDROP)wparam; + int file_count = (int)DragQueryFileW(hdrop, 0xffffffff, NULL, 0); + bool drop_failed = false; + for (int i = 0; i < file_count; i += 1) { + // UINT num_chars = DragQueryFileW(hdrop, i, NULL, 0) + 1; + // WCHAR* buffer = (WCHAR*) _sapp_malloc_clear(num_chars * sizeof(WCHAR)); + UINT result = DragQueryFileW(hdrop, i, buffer, MU_ARRAY_SIZE(buffer)); + MU_ASSERT(result != 0); + if (result) { + int64_t size = MU_CreateCharFromWidechar(buffer8, MU_ARRAY_SIZE(buffer8), buffer, MU_ARRAY_SIZE(buffer)); + if (size != -1) { + MU_PushDroppedFile(mu, window, buffer8, (int)size); + } + } + } + DragFinish(hdrop); + } break; + + case WM_CLOSE: { + // @! Make sure that focus works + // @! We should find the window and make sure we inform it that the user clicked the close button + PostQuitMessage(0); + mu->quit = true; + } break; + + case WM_LBUTTONDOWN: { + SetCapture(wnd); + if (window->change_cursor_on_mouse_hold) SetCursor(w32->cursor_hand); + if (window->mouse.left.down == false) + window->mouse.left.press = true; + window->mouse.left.down = true; + } break; + + case WM_LBUTTONUP: { + ReleaseCapture(); + if (window->change_cursor_on_mouse_hold) SetCursor(w32->cursor_arrow); + if (window->mouse.left.down == true) + window->mouse.left.unpress = true; + window->mouse.left.down = false; + } break; + + case WM_RBUTTONDOWN: { + SetCapture(wnd); + if (window->mouse.right.down == false) + window->mouse.right.press = true; + window->mouse.right.down = true; + } break; + + case WM_RBUTTONUP: { + ReleaseCapture(); + if (window->mouse.right.down == true) + window->mouse.right.unpress = true; + window->mouse.right.down = false; + } break; + + case WM_MBUTTONDOWN: { + SetCapture(wnd); + if (window->mouse.middle.down == false) + window->mouse.middle.press = true; + window->mouse.middle.down = true; + } break; + + case WM_MBUTTONUP: { + ReleaseCapture(); + if (window->mouse.middle.down == true) + window->mouse.middle.unpress = true; + window->mouse.middle.down = false; + } break; + + case WM_MOUSEWHEEL: { + if ((int)wparam > 0) { + window->mouse.delta_wheel += 1.0f; + } + else { + window->mouse.delta_wheel -= 1.0f; + } + } break; + + case WM_CHAR: { + MU_UTF32Result encode = MU_UTF16ToUTF32((uint16_t *)&wparam, 2); + if (encode.error) { + MU__WriteChar32(window, (uint32_t)'?'); + MU__WriteChar8(window, "?", 1); + } + else { + MU__WriteChar32(window, encode.out_str); + } + + // Utf8 encode + if (encode.error == false) { + MU_UTF8Result encode8 = MU_UTF32ToUTF8(encode.out_str); + if (encode8.error) { + MU__WriteChar8(window, "?", 1); + } + else { + MU__WriteChar8(window, encode8.out_str, encode8.len); + } + } + } break; + + case WM_KEYUP: + case WM_SYSKEYUP: { + switch (wparam) { + case VK_ESCAPE: MU__KeyUP(window, MU_KEY_ESCAPE); break; + case VK_RETURN: MU__KeyUP(window, MU_KEY_ENTER); break; + case VK_TAB: MU__KeyUP(window, MU_KEY_TAB); break; + case VK_BACK: MU__KeyUP(window, MU_KEY_BACKSPACE); break; + case VK_INSERT: MU__KeyUP(window, MU_KEY_INSERT); break; + case VK_DELETE: MU__KeyUP(window, MU_KEY_DELETE); break; + case VK_RIGHT: MU__KeyUP(window, MU_KEY_RIGHT); break; + case VK_LEFT: MU__KeyUP(window, MU_KEY_LEFT); break; + case VK_DOWN: MU__KeyUP(window, MU_KEY_DOWN); break; + case VK_UP: MU__KeyUP(window, MU_KEY_UP); break; + case VK_PRIOR: MU__KeyUP(window, MU_KEY_PAGE_UP); break; + case VK_NEXT: MU__KeyUP(window, MU_KEY_PAGE_DOWN); break; + case VK_END: MU__KeyUP(window, MU_KEY_HOME); break; + case VK_HOME: MU__KeyUP(window, MU_KEY_END); break; + case VK_F1: MU__KeyUP(window, MU_KEY_F1); break; + case VK_F2: MU__KeyUP(window, MU_KEY_F2); break; + case VK_F3: MU__KeyUP(window, MU_KEY_F3); break; + case VK_F4: MU__KeyUP(window, MU_KEY_F4); break; + case VK_F5: MU__KeyUP(window, MU_KEY_F5); break; + case VK_F6: MU__KeyUP(window, MU_KEY_F6); break; + case VK_F7: MU__KeyUP(window, MU_KEY_F7); break; + case VK_F8: MU__KeyUP(window, MU_KEY_F8); break; + case VK_F9: MU__KeyUP(window, MU_KEY_F9); break; + case VK_F10: MU__KeyUP(window, MU_KEY_F10); break; + case VK_F11: MU__KeyUP(window, MU_KEY_F11); break; + case VK_F12: MU__KeyUP(window, MU_KEY_F12); break; + case VK_SPACE: MU__KeyUP(window, MU_KEY_SPACE); break; + case VK_OEM_PLUS: MU__KeyUP(window, MU_KEY_PLUS); break; + case VK_OEM_COMMA: MU__KeyUP(window, MU_KEY_COMMA); break; + case VK_OEM_MINUS: MU__KeyUP(window, MU_KEY_MINUS); break; + case VK_OEM_PERIOD: MU__KeyUP(window, MU_KEY_PERIOD); break; + case '0': MU__KeyUP(window, MU_KEY_0); break; + case '1': MU__KeyUP(window, MU_KEY_1); break; + case '2': MU__KeyUP(window, MU_KEY_2); break; + case '3': MU__KeyUP(window, MU_KEY_3); break; + case '4': MU__KeyUP(window, MU_KEY_4); break; + case '5': MU__KeyUP(window, MU_KEY_5); break; + case '6': MU__KeyUP(window, MU_KEY_6); break; + case '7': MU__KeyUP(window, MU_KEY_7); break; + case '8': MU__KeyUP(window, MU_KEY_8); break; + case '9': MU__KeyUP(window, MU_KEY_9); break; + case ';': MU__KeyUP(window, MU_KEY_SEMICOLON); break; + case '=': MU__KeyUP(window, MU_KEY_EQUAL); break; + case 'A': MU__KeyUP(window, MU_KEY_A); break; + case 'B': MU__KeyUP(window, MU_KEY_B); break; + case 'C': MU__KeyUP(window, MU_KEY_C); break; + case 'D': MU__KeyUP(window, MU_KEY_D); break; + case 'E': MU__KeyUP(window, MU_KEY_E); break; + case 'F': MU__KeyUP(window, MU_KEY_F); break; + case 'G': MU__KeyUP(window, MU_KEY_G); break; + case 'H': MU__KeyUP(window, MU_KEY_H); break; + case 'I': MU__KeyUP(window, MU_KEY_I); break; + case 'J': MU__KeyUP(window, MU_KEY_J); break; + case 'K': MU__KeyUP(window, MU_KEY_K); break; + case 'L': MU__KeyUP(window, MU_KEY_L); break; + case 'M': MU__KeyUP(window, MU_KEY_M); break; + case 'N': MU__KeyUP(window, MU_KEY_N); break; + case 'O': MU__KeyUP(window, MU_KEY_O); break; + case 'P': MU__KeyUP(window, MU_KEY_P); break; + case 'Q': MU__KeyUP(window, MU_KEY_Q); break; + case 'R': MU__KeyUP(window, MU_KEY_R); break; + case 'S': MU__KeyUP(window, MU_KEY_S); break; + case 'T': MU__KeyUP(window, MU_KEY_T); break; + case 'U': MU__KeyUP(window, MU_KEY_U); break; + case 'V': MU__KeyUP(window, MU_KEY_V); break; + case 'W': MU__KeyUP(window, MU_KEY_W); break; + case 'X': MU__KeyUP(window, MU_KEY_X); break; + case 'Y': MU__KeyUP(window, MU_KEY_Y); break; + case 'Z': MU__KeyUP(window, MU_KEY_Z); break; + case VK_F13: MU__KeyUP(window, MU_KEY_F13); break; + case VK_F14: MU__KeyUP(window, MU_KEY_F14); break; + case VK_F15: MU__KeyUP(window, MU_KEY_F15); break; + case VK_F16: MU__KeyUP(window, MU_KEY_F16); break; + case VK_F17: MU__KeyUP(window, MU_KEY_F17); break; + case VK_F18: MU__KeyUP(window, MU_KEY_F18); break; + case VK_F19: MU__KeyUP(window, MU_KEY_F19); break; + case VK_F20: MU__KeyUP(window, MU_KEY_F20); break; + case VK_F21: MU__KeyUP(window, MU_KEY_F21); break; + case VK_F22: MU__KeyUP(window, MU_KEY_F22); break; + case VK_F23: MU__KeyUP(window, MU_KEY_F23); break; + case VK_F24: MU__KeyUP(window, MU_KEY_F24); break; + case 0x60: MU__KeyUP(window, MU_KEY_KP_0); break; + case 0x61: MU__KeyUP(window, MU_KEY_KP_1); break; + case 0x62: MU__KeyUP(window, MU_KEY_KP_2); break; + case 0x63: MU__KeyUP(window, MU_KEY_KP_3); break; + case 0x64: MU__KeyUP(window, MU_KEY_KP_4); break; + case 0x65: MU__KeyUP(window, MU_KEY_KP_5); break; + case 0x66: MU__KeyUP(window, MU_KEY_KP_6); break; + case 0x67: MU__KeyUP(window, MU_KEY_KP_7); break; + case 0x68: MU__KeyUP(window, MU_KEY_KP_8); break; + case 0x69: MU__KeyUP(window, MU_KEY_KP_9); break; + case VK_DECIMAL: MU__KeyUP(window, MU_KEY_KP_DECIMAL); break; + case VK_DIVIDE: MU__KeyUP(window, MU_KEY_KP_DIVIDE); break; + case VK_MULTIPLY: MU__KeyUP(window, MU_KEY_KP_MULTIPLY); break; + case VK_SUBTRACT: MU__KeyUP(window, MU_KEY_KP_SUBTRACT); break; + case VK_ADD: MU__KeyUP(window, MU_KEY_KP_ADD); break; + case VK_LMENU: MU__KeyUP(window, MU_KEY_LEFT_ALT); break; + case VK_LWIN: MU__KeyUP(window, MU_KEY_LEFT_SUPER); break; + case VK_CONTROL: MU__KeyUP(window, MU_KEY_CONTROL); break; + case VK_SHIFT: MU__KeyUP(window, MU_KEY_SHIFT); break; + case VK_LSHIFT: MU__KeyUP(window, MU_KEY_LEFT_SHIFT); break; + case VK_LCONTROL: MU__KeyUP(window, MU_KEY_LEFT_CONTROL); break; + case VK_RSHIFT: MU__KeyUP(window, MU_KEY_RIGHT_SHIFT); break; + case VK_RCONTROL: MU__KeyUP(window, MU_KEY_RIGHT_CONTROL); break; + case VK_RMENU: MU__KeyUP(window, MU_KEY_RIGHT_ALT); break; + case VK_RWIN: MU__KeyUP(window, MU_KEY_RIGHT_SUPER); break; + case VK_CAPITAL: MU__KeyUP(window, MU_KEY_CAPS_LOCK); break; + case VK_SCROLL: MU__KeyUP(window, MU_KEY_SCROLL_LOCK); break; + case VK_NUMLOCK: MU__KeyUP(window, MU_KEY_NUM_LOCK); break; + case VK_SNAPSHOT: MU__KeyUP(window, MU_KEY_PRINT_SCREEN); break; + case VK_PAUSE: MU__KeyUP(window, MU_KEY_PAUSE); break; + } + } break; + + case WM_KEYDOWN: + case WM_SYSKEYDOWN: { + switch (wparam) { + case VK_ESCAPE: MU__KeyDown(window, MU_KEY_ESCAPE); break; + case VK_RETURN: MU__KeyDown(window, MU_KEY_ENTER); break; + case VK_TAB: MU__KeyDown(window, MU_KEY_TAB); break; + case VK_BACK: MU__KeyDown(window, MU_KEY_BACKSPACE); break; + case VK_INSERT: MU__KeyDown(window, MU_KEY_INSERT); break; + case VK_DELETE: MU__KeyDown(window, MU_KEY_DELETE); break; + case VK_RIGHT: MU__KeyDown(window, MU_KEY_RIGHT); break; + case VK_LEFT: MU__KeyDown(window, MU_KEY_LEFT); break; + case VK_DOWN: MU__KeyDown(window, MU_KEY_DOWN); break; + case VK_UP: MU__KeyDown(window, MU_KEY_UP); break; + case VK_PRIOR: MU__KeyDown(window, MU_KEY_PAGE_UP); break; + case VK_NEXT: MU__KeyDown(window, MU_KEY_PAGE_DOWN); break; + case VK_END: MU__KeyDown(window, MU_KEY_HOME); break; + case VK_HOME: MU__KeyDown(window, MU_KEY_END); break; + case VK_F1: MU__KeyDown(window, MU_KEY_F1); break; + case VK_F2: MU__KeyDown(window, MU_KEY_F2); break; + case VK_F3: MU__KeyDown(window, MU_KEY_F3); break; + case VK_F4: MU__KeyDown(window, MU_KEY_F4); break; + case VK_F5: MU__KeyDown(window, MU_KEY_F5); break; + case VK_F6: MU__KeyDown(window, MU_KEY_F6); break; + case VK_F7: MU__KeyDown(window, MU_KEY_F7); break; + case VK_F8: MU__KeyDown(window, MU_KEY_F8); break; + case VK_F9: MU__KeyDown(window, MU_KEY_F9); break; + case VK_F10: MU__KeyDown(window, MU_KEY_F10); break; + case VK_F11: MU__KeyDown(window, MU_KEY_F11); break; + case VK_F12: MU__KeyDown(window, MU_KEY_F12); break; + case VK_SPACE: MU__KeyDown(window, MU_KEY_SPACE); break; + case VK_OEM_PLUS: MU__KeyDown(window, MU_KEY_PLUS); break; + case VK_OEM_COMMA: MU__KeyDown(window, MU_KEY_COMMA); break; + case VK_OEM_MINUS: MU__KeyDown(window, MU_KEY_MINUS); break; + case VK_OEM_PERIOD: MU__KeyDown(window, MU_KEY_PERIOD); break; + case '0': MU__KeyDown(window, MU_KEY_0); break; + case '1': MU__KeyDown(window, MU_KEY_1); break; + case '2': MU__KeyDown(window, MU_KEY_2); break; + case '3': MU__KeyDown(window, MU_KEY_3); break; + case '4': MU__KeyDown(window, MU_KEY_4); break; + case '5': MU__KeyDown(window, MU_KEY_5); break; + case '6': MU__KeyDown(window, MU_KEY_6); break; + case '7': MU__KeyDown(window, MU_KEY_7); break; + case '8': MU__KeyDown(window, MU_KEY_8); break; + case '9': MU__KeyDown(window, MU_KEY_9); break; + case ';': MU__KeyDown(window, MU_KEY_SEMICOLON); break; + case '=': MU__KeyDown(window, MU_KEY_EQUAL); break; + case 'A': MU__KeyDown(window, MU_KEY_A); break; + case 'B': MU__KeyDown(window, MU_KEY_B); break; + case 'C': MU__KeyDown(window, MU_KEY_C); break; + case 'D': MU__KeyDown(window, MU_KEY_D); break; + case 'E': MU__KeyDown(window, MU_KEY_E); break; + case 'F': MU__KeyDown(window, MU_KEY_F); break; + case 'G': MU__KeyDown(window, MU_KEY_G); break; + case 'H': MU__KeyDown(window, MU_KEY_H); break; + case 'I': MU__KeyDown(window, MU_KEY_I); break; + case 'J': MU__KeyDown(window, MU_KEY_J); break; + case 'K': MU__KeyDown(window, MU_KEY_K); break; + case 'L': MU__KeyDown(window, MU_KEY_L); break; + case 'M': MU__KeyDown(window, MU_KEY_M); break; + case 'N': MU__KeyDown(window, MU_KEY_N); break; + case 'O': MU__KeyDown(window, MU_KEY_O); break; + case 'P': MU__KeyDown(window, MU_KEY_P); break; + case 'Q': MU__KeyDown(window, MU_KEY_Q); break; + case 'R': MU__KeyDown(window, MU_KEY_R); break; + case 'S': MU__KeyDown(window, MU_KEY_S); break; + case 'T': MU__KeyDown(window, MU_KEY_T); break; + case 'U': MU__KeyDown(window, MU_KEY_U); break; + case 'V': MU__KeyDown(window, MU_KEY_V); break; + case 'W': MU__KeyDown(window, MU_KEY_W); break; + case 'X': MU__KeyDown(window, MU_KEY_X); break; + case 'Y': MU__KeyDown(window, MU_KEY_Y); break; + case 'Z': MU__KeyDown(window, MU_KEY_Z); break; + case VK_F13: MU__KeyDown(window, MU_KEY_F13); break; + case VK_F14: MU__KeyDown(window, MU_KEY_F14); break; + case VK_F15: MU__KeyDown(window, MU_KEY_F15); break; + case VK_F16: MU__KeyDown(window, MU_KEY_F16); break; + case VK_F17: MU__KeyDown(window, MU_KEY_F17); break; + case VK_F18: MU__KeyDown(window, MU_KEY_F18); break; + case VK_F19: MU__KeyDown(window, MU_KEY_F19); break; + case VK_F20: MU__KeyDown(window, MU_KEY_F20); break; + case VK_F21: MU__KeyDown(window, MU_KEY_F21); break; + case VK_F22: MU__KeyDown(window, MU_KEY_F22); break; + case VK_F23: MU__KeyDown(window, MU_KEY_F23); break; + case VK_F24: MU__KeyDown(window, MU_KEY_F24); break; + case 0x60: MU__KeyDown(window, MU_KEY_KP_0); break; + case 0x61: MU__KeyDown(window, MU_KEY_KP_1); break; + case 0x62: MU__KeyDown(window, MU_KEY_KP_2); break; + case 0x63: MU__KeyDown(window, MU_KEY_KP_3); break; + case 0x64: MU__KeyDown(window, MU_KEY_KP_4); break; + case 0x65: MU__KeyDown(window, MU_KEY_KP_5); break; + case 0x66: MU__KeyDown(window, MU_KEY_KP_6); break; + case 0x67: MU__KeyDown(window, MU_KEY_KP_7); break; + case 0x68: MU__KeyDown(window, MU_KEY_KP_8); break; + case 0x69: MU__KeyDown(window, MU_KEY_KP_9); break; + case VK_CONTROL: MU__KeyDown(window, MU_KEY_CONTROL); break; + case VK_SHIFT: MU__KeyDown(window, MU_KEY_SHIFT); break; + case VK_DECIMAL: MU__KeyDown(window, MU_KEY_KP_DECIMAL); break; + case VK_DIVIDE: MU__KeyDown(window, MU_KEY_KP_DIVIDE); break; + case VK_MULTIPLY: MU__KeyDown(window, MU_KEY_KP_MULTIPLY); break; + case VK_SUBTRACT: MU__KeyDown(window, MU_KEY_KP_SUBTRACT); break; + case VK_ADD: MU__KeyDown(window, MU_KEY_KP_ADD); break; + case VK_LSHIFT: MU__KeyDown(window, MU_KEY_LEFT_SHIFT); break; + case VK_LCONTROL: MU__KeyDown(window, MU_KEY_LEFT_CONTROL); break; + case VK_LMENU: MU__KeyDown(window, MU_KEY_LEFT_ALT); break; + case VK_LWIN: MU__KeyDown(window, MU_KEY_LEFT_SUPER); break; + case VK_RSHIFT: MU__KeyDown(window, MU_KEY_RIGHT_SHIFT); break; + case VK_RCONTROL: MU__KeyDown(window, MU_KEY_RIGHT_CONTROL); break; + case VK_RMENU: MU__KeyDown(window, MU_KEY_RIGHT_ALT); break; + case VK_RWIN: MU__KeyDown(window, MU_KEY_RIGHT_SUPER); break; + case VK_CAPITAL: MU__KeyDown(window, MU_KEY_CAPS_LOCK); break; + case VK_SCROLL: MU__KeyDown(window, MU_KEY_SCROLL_LOCK); break; + case VK_NUMLOCK: MU__KeyDown(window, MU_KEY_NUM_LOCK); break; + case VK_SNAPSHOT: MU__KeyDown(window, MU_KEY_PRINT_SCREEN); break; + case VK_PAUSE: MU__KeyDown(window, MU_KEY_PAUSE); break; + } + } break; + + default: { + return DefWindowProcW(wnd, msg, wparam, lparam); + } + } + return 0; +} + +MU_API void MU_Init(MU_Context *mu, MU_Params params, size_t len) { + MU_ASSERT(params.memory && params.cap && "Expected any kind of memory"); + + MU__ZeroMemory(mu, sizeof(*mu)); + mu->perm_arena.memory = (char *)params.memory; + mu->perm_arena.cap = params.cap; + mu->perm_arena.len = len; + MU_WIN32_ContextPointerForEventHandling = mu; + + mu->platform = MU_PUSH_STRUCT(&mu->perm_arena, MU_Win32); + MU_Win32 *w32 = (MU_Win32 *)mu->platform; + + mu->frame_arena.cap = (mu->perm_arena.cap - mu->perm_arena.len) / 2; + mu->frame_arena.memory = (char *)MU_PushSize(&mu->perm_arena, mu->frame_arena.cap); + + mu->time.delta = params.delta_time == 0.0 ? 0.0166666 : params.delta_time; + + mu->sound.callback = params.sound_callback; + mu->params = params; + + if (mu->sound.callback) { + MU_WIN32_InitWasapi(mu); + MU_ASSERT(mu->sound.initialized); + } + + typedef enum MU_PROCESS_DPI_AWARENESS { + MU_PROCESS_DPI_UNAWARE = 0, + MU_PROCESS_SYSTEM_DPI_AWARE = 1, + MU_PROCESS_PER_MONITOR_DPI_AWARE = 2 + } MU_PROCESS_DPI_AWARENESS; + typedef unsigned MU_TimeBeginPeriod(unsigned); + typedef HRESULT MU_SetProcessDpiAwareness(MU_PROCESS_DPI_AWARENESS); + + HMODULE shcore = LoadLibraryA("Shcore.dll"); + if (shcore) { + MU_SetProcessDpiAwareness *set_dpi_awr = (MU_SetProcessDpiAwareness *)GetProcAddress(shcore, "SetProcessDpiAwareness"); + if (set_dpi_awr) { + HRESULT hr = set_dpi_awr(MU_PROCESS_PER_MONITOR_DPI_AWARE); + MU_ASSERT(SUCCEEDED(hr) && "Failed to set dpi awareness"); + } + } + + HMODULE winmm = LoadLibraryA("winmm.dll"); + if (winmm) { + MU_TimeBeginPeriod *timeBeginPeriod = (MU_TimeBeginPeriod *)GetProcAddress(winmm, "timeBeginPeriod"); + if (timeBeginPeriod) { + if (timeBeginPeriod(1) == 0) { + w32->good_scheduling = true; + } + } + } + + WNDCLASSW wc; + { + MU__ZeroMemory(&wc, sizeof(wc)); + wc.lpfnWndProc = MU_WIN32_WindowProc; + wc.hInstance = GetModuleHandleW(NULL); + wc.lpszClassName = L"Multimedia_Start"; + wc.hCursor = LoadCursor(0, IDC_ARROW); + wc.hIcon = NULL; // LoadIcon(wc.hInstance, IDI_APPLICATION); + wc.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW; + MU_ASSERT_CODE(ATOM result =) + RegisterClassW(&wc); + MU_ASSERT(result != 0); + w32->wc = wc; + } + + mu->primary_monitor_size.x = GetSystemMetrics(SM_CXSCREEN); + mu->primary_monitor_size.y = GetSystemMetrics(SM_CYSCREEN); + + w32->cursor_hand = LoadCursor(0, IDC_SIZEALL); + w32->cursor_arrow = LoadCursor(0, IDC_ARROW); + + mu->time.app_start = MU_GetTime(); + mu->first_frame = true; +} + +MU_StaticFunc void MU_UpdateWindowState(MU_Window *window) { + MU_Win32_Window *w32_window = (MU_Win32_Window *)window->platform; + + UINT dpi = GetDpiForWindow((HWND)window->handle); + MU_ASSERT(dpi != 0 && "Failed to get dpi for window"); + window->dpi_scale = (float)dpi / 96.f; + + MU_Int2 size; + MU_WIN32_GetWindowPos((HWND)window->handle, &window->pos.x, &window->pos.y); + MU_Win32_GetWindowSize((HWND)window->handle, &size.x, &size.y); + + if (window->canvas_enabled == false || window->size.x != size.x || window->size.y != size.y) { + MU_WIN32_DestroyCanvas(window); + } + + window->size = size; + window->sizef.x = (float)window->size.x; + window->sizef.y = (float)window->size.y; + + window->posf.x = (float)window->pos.x; + window->posf.y = (float)window->pos.y; + + if (window->canvas_enabled && window->canvas == 0) { + MU_WIN32_CreateCanvas(window); + } +} + +MU_API MU_Window *MU_AddWindow(MU_Context *mu, MU_Window_Params params) { + MU_Window *window = MU_PUSH_STRUCT(&mu->perm_arena, MU_Window); + MU_InitWindow(mu, window, params); + return window; +} + +MU_API void MU_InitWindow(MU_Context *mu, MU_Window *window, MU_Window_Params params) { + window->platform = MU_PUSH_STRUCT(&mu->perm_arena, MU_Win32_Window); + + MU_Win32 *w32 = (MU_Win32 *)mu->platform; + MU_Win32_Window *w32_window = (MU_Win32_Window *)window->platform; + + if (params.pos.x == 0) params.pos.x = (int)((double)mu->primary_monitor_size.x * 0.1); + if (params.pos.y == 0) params.pos.y = (int)((double)mu->primary_monitor_size.y * 0.1); + if (params.size.x == 0) params.size.x = (int)((double)mu->primary_monitor_size.x * 0.8); + if (params.size.y == 0) params.size.y = (int)((double)mu->primary_monitor_size.y * 0.8); + window->canvas_enabled = params.enable_canvas; + + w32_window->style = WS_OVERLAPPEDWINDOW; + if (!params.resizable) { + w32_window->style &= ~WS_THICKFRAME & ~WS_MAXIMIZEBOX; + } + if (params.borderless) { + w32_window->style = WS_POPUP | WS_VISIBLE | WS_SYSMENU; + } + + RECT window_rect; + window_rect.left = (LONG)params.pos.x; + window_rect.top = (LONG)params.pos.y; + window_rect.right = (LONG)params.size.x + window_rect.left; + window_rect.bottom = (LONG)params.size.y + window_rect.top; + AdjustWindowRectEx(&window_rect, w32_window->style, false, 0); + + HWND handle = CreateWindowW(w32->wc.lpszClassName, L"Zzz... Window, hello!", w32_window->style, window_rect.left, window_rect.top, window_rect.right - window_rect.left, window_rect.bottom - window_rect.top, NULL, NULL, w32->wc.hInstance, NULL); + MU_ASSERT(handle); + + window->handle = handle; + w32_window->handle_dc = GetDC(handle); + MU_ASSERT(w32_window->handle_dc); + + DragAcceptFiles(handle, TRUE); + + MU_WIN32_TryToInitGLContextForWindow(mu, w32_window); + + ShowWindow(handle, SW_SHOW); + MU_UpdateWindowState(window); + MU_STACK_ADD(mu->all_windows, window); + MU_WIN32_UpdateFocusedWindow(mu); +} + +MU_API MU_Context *MU_Start(MU_Params params) { + // Bootstrap the context from user memory + // If the user didnt provide memory, allocate it ourselves + if (!params.memory) { + HANDLE process_heap = GetProcessHeap(); + params.cap = MU_DEFAULT_MEMORY_SIZE; + params.memory = HeapAlloc(process_heap, 0, params.cap); + MU_ASSERT(params.memory); + } + MU_Context *mu = (MU_Context *)params.memory; + MU_Init(mu, params, sizeof(MU_Context)); + mu->window = MU_AddWindow(mu, params.window); + + return mu; +} + +MU_API bool MU_Update(MU_Context *mu) { + MU_Win32 *w32 = (MU_Win32 *)mu->platform; + + // Since this is meant to be called in while loop + // first MU_Update happens before first frame + // therfore start of second MU_Update is end of first frame + mu->_MU_Update_count += 1; + if (mu->_MU_Update_count == 2) mu->first_frame = false; + mu->frame_arena.len = 0; + + MU_WIN32_UpdateFocusedWindow(mu); + for (MU_Window *it = mu->all_windows; it; it = it->next) { + if (it->should_render == true && mu->first_frame == false && mu->opengl_initialized) { + MU_Win32_Window *w32_window = (MU_Win32_Window *)it->platform; + MU_ASSERT_CODE(BOOL result =) + SwapBuffers(w32_window->handle_dc); + MU_ASSERT(result); + } + it->should_render = true; + + it->first_dropped_file = 0; + MU_WIN32_DrawCanvas(it); + it->processed_events_this_frame = 0; + it->user_text8_count = 0; + it->user_text32_count = 0; + it->mouse.delta_wheel = 0.0; + it->mouse.left.press = 0; + it->mouse.right.press = 0; + it->mouse.middle.press = 0; + it->mouse.left.unpress = 0; + it->mouse.right.unpress = 0; + it->mouse.middle.unpress = 0; + for (int i = 0; i < MU_KEY_COUNT; i += 1) { + it->key[i].press = 0; + it->key[i].unpress = 0; + it->key[i].raw_press = 0; + } + } + + MSG msg; + MU_WIN32_ContextPointerForEventHandling = mu; + while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + + for (MU_Window *it = mu->all_windows; it; it = it->next) { + MU_UpdateWindowState(it); + } + + mu->window->user_text8[mu->window->user_text8_count] = 0; + mu->window->user_text32[mu->window->user_text32_count] = 0; + + MU_Win32_Window *w32_window = (MU_Win32_Window *)mu->window->platform; + HWND focused_window = GetFocus(); + mu->window->is_focused = focused_window == (HWND)mu->window->handle; + + // We only need to update the mouse position of a currently focused window? + { + + MU_Int2 mouse_pos = MU_WIN32_GetMousePositionInverted((HWND)mu->window->handle, mu->window->size.y); + + if (mu->window->is_focused) { + if (mu->first_frame == false) { + mu->window->mouse.delta_pos.x = mouse_pos.x - mu->window->mouse.pos.x; + mu->window->mouse.delta_pos.y = mouse_pos.y - mu->window->mouse.pos.y; + mu->window->mouse.delta_pos_normalized.x = (float)mu->window->mouse.delta_pos.x / (float)mu->window->size.x; + mu->window->mouse.delta_pos_normalized.y = (float)mu->window->mouse.delta_pos.y / (float)mu->window->size.y; + } + if (mu->window->is_fps_mode) { + SetCursorPos(mu->window->size.x / 2, mu->window->size.y / 2); + mouse_pos = MU_WIN32_GetMousePositionInverted((HWND)mu->window->handle, mu->window->size.y); + } + } + mu->window->mouse.pos = mouse_pos; + mu->window->mouse.posf.x = (float)mouse_pos.x; + mu->window->mouse.posf.y = (float)mouse_pos.y; + } + + // Timming + if (mu->first_frame == false) { + mu->time.update = MU_GetTime() - mu->time.frame_start; + if (mu->time.update < mu->time.delta) { + mu->consecutive_missed_frames = 0; + + // Try to use the Sleep, if we dont have good scheduler priority + // then we can miss framerate so need to busy loop instead + if (w32->good_scheduling) { + double time_to_sleep = mu->time.delta - mu->time.update; + double time_to_sleep_in_ms = time_to_sleep * 1000.0 - 1; + if (time_to_sleep > 0.0) { + DWORD time_to_sleep_uint = (DWORD)time_to_sleep_in_ms; + if (time_to_sleep_uint) { + Sleep(time_to_sleep_uint); + } + } + } + + // Busy loop if we dont have good scheduling + // or we woke up early + double update_time = MU_GetTime() - mu->time.frame_start; + while (update_time < mu->time.delta) { + update_time = MU_GetTime() - mu->time.frame_start; + } + } + else { + mu->consecutive_missed_frames += 1; + mu->total_missed_frames += 1; + } + + mu->frame += 1; + mu->time.update_total = MU_GetTime() - mu->time.frame_start; + mu->time.total += mu->time.delta; + } + mu->time.frame_start = MU_GetTime(); + + mu->time.deltaf = (float)mu->time.delta; + mu->time.totalf = (float)mu->time.total; + + return !mu->quit; +} + +// +// Opengl context setup +// +// @! Cleanup OpenGL - Should the user be cappable of detecting that opengl couldnt load? +// Should the layer automatically downscale? +// Should the layer inform and allow for a response? +/* + MU_Context *mu = MU_Start((MU_Params){ + .enable_opengl = true, + }); + if (mu->opengl_initialized == false) { + mu_opengl_try_initializng_context_for_window(mu->window, 3, 3); + } + if (mu->opengl_initialized == false) { + // directx + } + + + */ + +// Symbols taken from GLFW +// +// Executables (but not DLLs) exporting this symbol with this value will be +// automatically directed to the high-performance GPU on Nvidia Optimus systems +// with up-to-date drivers +// +__declspec(dllexport) DWORD NvOptimusEnablement = 1; + +// Executables (but not DLLs) exporting this symbol with this value will be +// automatically directed to the high-performance GPU on AMD PowerXpress systems +// with up-to-date drivers +// +__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; + +typedef HGLRC MU_wglCreateContext(HDC unnamedParam1); +typedef BOOL MU_wglMakeCurrent(HDC unnamedParam1, HGLRC unnamedParam2); +typedef BOOL MU_wglDeleteContext(HGLRC unnamedParam1); +HGLRC(*mu_wglCreateContext) +(HDC unnamedParam1); +BOOL(*mu_wglMakeCurrent) +(HDC unnamedParam1, HGLRC unnamedParam2); +BOOL(*mu_wglDeleteContext) +(HGLRC unnamedParam1); + +typedef const char *MU_wglGetExtensionsStringARB(HDC hdc); +typedef BOOL MU_wglChoosePixelFormatARB(HDC hdc, const int *piAttribIList, const float *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats); +typedef HGLRC MU_wglCreateContextAttribsARB(HDC hDC, HGLRC hshareContext, const int *attribList); +typedef BOOL MU_wglSwapIntervalEXT(int interval); +MU_wglChoosePixelFormatARB *wglChoosePixelFormatARB; +MU_wglCreateContextAttribsARB *wglCreateContextAttribsARB; +MU_wglSwapIntervalEXT *wglSwapIntervalEXT; + + #define WGL_DRAW_TO_WINDOW_ARB 0x2001 + #define WGL_SUPPORT_OPENGL_ARB 0x2010 + #define WGL_DOUBLE_BUFFER_ARB 0x2011 + #define WGL_PIXEL_TYPE_ARB 0x2013 + #define WGL_TYPE_RGBA_ARB 0x202B + #define WGL_COLOR_BITS_ARB 0x2014 + #define WGL_DEPTH_BITS_ARB 0x2022 + #define WGL_STENCIL_BITS_ARB 0x2023 + + #define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091 + #define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092 + #define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126 + #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001 + #define WGL_CONTEXT_FLAGS_ARB 0x2094 + #define WGL_CONTEXT_DEBUG_BIT_ARB 0x00000001 + + #define WGL_SAMPLE_BUFFERS_ARB 0x2041 + #define WGL_SAMPLES_ARB 0x2042 + +// +// Below loading part largely taken from github gist of Martins Mozeiko +// + +// compares src string with dstlen characters from dst, returns 1 if they are equal, 0 if not +MU_StaticFunc int MU__AreStringsEqual(const char *src, const char *dst, size_t dstlen) { + while (*src && dstlen-- && *dst) { + if (*src++ != *dst++) { + return 0; + } + } + + return (dstlen && *src == *dst) || (!dstlen && *src == 0); +} + +MU_StaticFunc void *MU_Win32_GLGetWindowProcAddressForGlad(const char *proc) { + MU_Win32 *w32 = (MU_Win32 *)MU_WIN32_ContextPointerForEventHandling->platform; + void *func; + + func = w32->wgl_get_proc_address(proc); + if (!func) { + func = GetProcAddress(w32->opengl32, proc); + } + return func; +} + +MU_StaticFunc void MU_WIN32_GetWGLFunctions(MU_Context *mu) { + MU_Win32 *w32 = (MU_Win32 *)mu->platform; + HMODULE opengl32 = LoadLibraryA("opengl32"); + MU_ASSERT(opengl32); + if (opengl32) { + w32->opengl32 = opengl32; + w32->wgl_get_proc_address = (MU_glGetProcAddress *)GetProcAddress(opengl32, "wglGetProcAddress"); + mu->gl_get_proc_address = MU_Win32_GLGetWindowProcAddressForGlad; + mu_wglCreateContext = (MU_wglCreateContext *)GetProcAddress(opengl32, "wglCreateContext"); + mu_wglMakeCurrent = (MU_wglMakeCurrent *)GetProcAddress(opengl32, "wglMakeCurrent"); + mu_wglDeleteContext = (MU_wglDeleteContext *)GetProcAddress(opengl32, "wglDeleteContext"); + } + if (opengl32 == NULL || mu_wglCreateContext == NULL || mu->gl_get_proc_address == NULL || mu_wglMakeCurrent == NULL || mu_wglDeleteContext == NULL) { + MU_ASSERT(!"Failed to load Opengl wgl functions from opengl32.lib"); + return; + } + + // to get WGL functions we need valid GL context, so create dummy window for dummy GL contetx + HWND dummy = CreateWindowExW( + 0, L"STATIC", L"DummyWindow", WS_OVERLAPPED, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, + NULL, NULL, NULL, NULL); + MU_ASSERT(dummy && "Failed to create dummy window"); + + HDC dc = GetDC(dummy); + MU_ASSERT(dc && "Failed to get device context for dummy window"); + + PIXELFORMATDESCRIPTOR desc; + MU__ZeroMemory(&desc, sizeof(desc)); + { + desc.nSize = sizeof(desc); + desc.nVersion = 1; + desc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; + desc.iPixelType = PFD_TYPE_RGBA; + desc.cColorBits = 24; + }; + + int format = ChoosePixelFormat(dc, &desc); + if (!format) { + MU_ASSERT(!"Cannot choose OpenGL pixel format for dummy window!"); + } + + int ok = DescribePixelFormat(dc, format, sizeof(desc), &desc); + MU_ASSERT(ok && "Failed to describe OpenGL pixel format"); + + // reason to create dummy window is that SetPixelFormat can be called only once for the window + if (!SetPixelFormat(dc, format, &desc)) { + MU_ASSERT(!"Cannot set OpenGL pixel format for dummy window!"); + } + + HGLRC rc = mu_wglCreateContext(dc); + MU_ASSERT(rc && "Failed to create OpenGL context for dummy window"); + + ok = mu_wglMakeCurrent(dc, rc); + MU_ASSERT(ok && "Failed to make current OpenGL context for dummy window"); + + // https://www.khronos.org/registry/OpenGL/extensions/ARB/WGL_ARB_extensions_string.txt + MU_wglGetExtensionsStringARB *wglGetExtensionsStringARB = (MU_wglGetExtensionsStringARB *)mu->gl_get_proc_address("wglGetExtensionsStringARB"); + if (!wglGetExtensionsStringARB) { + MU_ASSERT(!"OpenGL does not support WGL_ARB_extensions_string extension!"); + } + + const char *ext = wglGetExtensionsStringARB(dc); + MU_ASSERT(ext && "Failed to get OpenGL WGL extension string"); + + const char *start = ext; + for (;;) { + while (*ext != 0 && *ext != ' ') { + ext++; + } + size_t length = ext - start; + if (MU__AreStringsEqual("WGL_ARB_pixel_format", start, length)) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/WGL_ARB_pixel_format.txt + wglChoosePixelFormatARB = (MU_wglChoosePixelFormatARB *)mu->gl_get_proc_address("wglChoosePixelFormatARB"); + } + else if (MU__AreStringsEqual("WGL_ARB_create_context", start, length)) { + // https://www.khronos.org/registry/OpenGL/extensions/ARB/WGL_ARB_create_context.txt + wglCreateContextAttribsARB = (MU_wglCreateContextAttribsARB *)mu->gl_get_proc_address("wglCreateContextAttribsARB"); + } + else if (MU__AreStringsEqual("WGL_EXT_swap_control", start, length)) { + // https://www.khronos.org/registry/OpenGL/extensions/EXT/WGL_EXT_swap_control.txt + wglSwapIntervalEXT = (MU_wglSwapIntervalEXT *)mu->gl_get_proc_address("wglSwapIntervalEXT"); + } + + if (*ext == 0) { + break; + } + + ext++; + start = ext; + } + + if (!wglChoosePixelFormatARB || !wglCreateContextAttribsARB || !wglSwapIntervalEXT) { + MU_ASSERT(!"OpenGL does not support required WGL extensions for modern context!"); + } + + mu_wglMakeCurrent(NULL, NULL); + mu_wglDeleteContext(rc); + ReleaseDC(dummy, dc); + DestroyWindow(dummy); + + mu->opengl_initialized = true; +} + +MU_StaticFunc void MU_WIN32_TryToInitGLContextForWindow(MU_Context *mu, MU_Win32_Window *w32_window) { + if (mu->opengl_initialized == false && mu->params.enable_opengl) { + MU_WIN32_GetWGLFunctions(mu); + if (mu->opengl_initialized) { + mu->opengl_major = mu->params.opengl_major ? mu->params.opengl_major : 4; + mu->opengl_minor = mu->params.opengl_minor ? mu->params.opengl_minor : 5; + } + } + + if (mu->opengl_initialized) { + // set pixel format for OpenGL context + int attrib[] = + { + WGL_DRAW_TO_WINDOW_ARB, + true, + WGL_SUPPORT_OPENGL_ARB, + true, + WGL_DOUBLE_BUFFER_ARB, + true, + WGL_PIXEL_TYPE_ARB, + WGL_TYPE_RGBA_ARB, + WGL_COLOR_BITS_ARB, + 32, + WGL_DEPTH_BITS_ARB, + 24, + WGL_STENCIL_BITS_ARB, + 8, + + // uncomment for sRGB framebuffer, from WGL_ARB_framebuffer_sRGB extension + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_framebuffer_sRGB.txt + // WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, GL_TRUE, + + // uncomment for multisampeld framebuffer, from WGL_ARB_multisample extension + // https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_multisample.txt + #if MU_GL_ENABLE_MULTISAMPLING + WGL_SAMPLE_BUFFERS_ARB, + 1, + WGL_SAMPLES_ARB, + 4, // 4x MSAA + #endif + + 0, + }; + + int format; + UINT formats; + if (!wglChoosePixelFormatARB(w32_window->handle_dc, attrib, 0, 1, &format, &formats) || formats == 0) { + MU_ASSERT(!"OpenGL does not support required pixel format!"); + } + + PIXELFORMATDESCRIPTOR desc; + MU__ZeroMemory(&desc, sizeof(desc)); + desc.nSize = sizeof(desc); + int ok = DescribePixelFormat(w32_window->handle_dc, format, sizeof(desc), &desc); + MU_ASSERT(ok && "Failed to describe OpenGL pixel format"); + + if (!SetPixelFormat(w32_window->handle_dc, format, &desc)) { + MU_ASSERT(!"Cannot set OpenGL selected pixel format!"); + } + + // create modern OpenGL context + { + int attrib[] = + { + WGL_CONTEXT_MAJOR_VERSION_ARB, + mu->opengl_major, + WGL_CONTEXT_MINOR_VERSION_ARB, + mu->opengl_minor, + WGL_CONTEXT_PROFILE_MASK_ARB, + WGL_CONTEXT_CORE_PROFILE_BIT_ARB, + + #if MU_GL_BUILD_DEBUG + WGL_CONTEXT_FLAGS_ARB, + WGL_CONTEXT_DEBUG_BIT_ARB, + #endif + + 0, + }; + + HGLRC rc = wglCreateContextAttribsARB(w32_window->handle_dc, 0, attrib); + if (!rc) { + MU_ASSERT(!"Cannot create modern OpenGL context! OpenGL version 4.5 not supported?"); + } + + BOOL ok = mu_wglMakeCurrent(w32_window->handle_dc, rc); + MU_ASSERT(ok && "Failed to make current OpenGL context"); + } + } +} + +// +// Sound using WASAPI +// @! Sound: Comeback to it later! I dont really know what I should expect from a sound system +// What actually in reality errors out in WASAPI, what is important when working with sound. +// As such I'm not really currently equiped to make something good / reliable. +// Probably would be nice to work with it a bit more. +// +// Sound params should probably be configurable +// but I dont really understand what I should want to expect +// from this sort of system +// +// Not sure if I should in the future implement some different non threaded api. +// +// +// Below GUID stuff taken from libsoundio +// reference: https://github.com/andrewrk/libsoundio/blob/master/src/wasapi.c +// + +// And some GUID are never implemented (Ignoring the INITGUID define) +MU_PRIVATE_VAR const CLSID MU_CLSID_MMDeviceEnumerator = { + 0xbcde0395, 0xe52f, 0x467c, {0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e} +}; +MU_PRIVATE_VAR const IID MU_IID_IMMDeviceEnumerator = { + // MIDL_INTERFACE("A95664D2-9614-4F35-A746-DE8DB63617E6") + 0xa95664d2, + 0x9614, + 0x4f35, + {0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6} +}; +MU_PRIVATE_VAR const IID MU_IID_IMMNotificationClient = { + // MIDL_INTERFACE("7991EEC9-7E89-4D85-8390-6C703CEC60C0") + 0x7991eec9, + 0x7e89, + 0x4d85, + {0x83, 0x90, 0x6c, 0x70, 0x3c, 0xec, 0x60, 0xc0} +}; +MU_PRIVATE_VAR const IID MU_IID_IAudioClient = { + // MIDL_INTERFACE("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2") + 0x1cb9ad4c, + 0xdbfa, + 0x4c32, + {0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2} +}; +MU_PRIVATE_VAR const IID MU_IID_IAudioRenderClient = { + // MIDL_INTERFACE("F294ACFC-3146-4483-A7BF-ADDCA7C260E2") + 0xf294acfc, + 0x3146, + 0x4483, + {0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2} +}; +MU_PRIVATE_VAR const IID MU_IID_IAudioSessionControl = { + // MIDL_INTERFACE("F4B1A599-7266-4319-A8CA-E70ACB11E8CD") + 0xf4b1a599, + 0x7266, + 0x4319, + {0xa8, 0xca, 0xe7, 0x0a, 0xcb, 0x11, 0xe8, 0xcd} +}; +MU_PRIVATE_VAR const IID MU_IID_IAudioSessionEvents = { + // MIDL_INTERFACE("24918ACC-64B3-37C1-8CA9-74A66E9957A8") + 0x24918acc, + 0x64b3, + 0x37c1, + {0x8c, 0xa9, 0x74, 0xa6, 0x6e, 0x99, 0x57, 0xa8} +}; +MU_PRIVATE_VAR const IID MU_IID_IMMEndpoint = { + // MIDL_INTERFACE("1BE09788-6894-4089-8586-9A2A6C265AC5") + 0x1be09788, + 0x6894, + 0x4089, + {0x85, 0x86, 0x9a, 0x2a, 0x6c, 0x26, 0x5a, 0xc5} +}; +MU_PRIVATE_VAR const IID MU_IID_IAudioClockAdjustment = { + // MIDL_INTERFACE("f6e4c0a0-46d9-4fb8-be21-57a3ef2b626c") + 0xf6e4c0a0, + 0x46d9, + 0x4fb8, + {0xbe, 0x21, 0x57, 0xa3, 0xef, 0x2b, 0x62, 0x6c} +}; +MU_PRIVATE_VAR const IID MU_IID_IAudioCaptureClient = { + // MIDL_INTERFACE("C8ADBD64-E71E-48a0-A4DE-185C395CD317") + 0xc8adbd64, + 0xe71e, + 0x48a0, + {0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17} +}; +MU_PRIVATE_VAR const IID MU_IID_ISimpleAudioVolume = { + // MIDL_INTERFACE("87ce5498-68d6-44e5-9215-6da47ef883d8") + 0x87ce5498, + 0x68d6, + 0x44e5, + {0x92, 0x15, 0x6d, 0xa4, 0x7e, 0xf8, 0x83, 0xd8} +}; + + #ifdef __cplusplus + // In C++ mode, IsEqualGUID() takes its arguments by reference + #define IS_EQUAL_GUID(a, b) IsEqualGUID(*(a), *(b)) + #define IS_EQUAL_IID(a, b) IsEqualIID((a), *(b)) + + // And some constants are passed by reference + #define MU_IID_IAUDIOCLIENT (MU_IID_IAudioClient) + #define MU_IID_IMMENDPOINT (MU_IID_IMMEndpoint) + #define MU_IID_IAUDIOCLOCKADJUSTMENT (MU_IID_IAudioClockAdjustment) + #define MU_IID_IAUDIOSESSIONCONTROL (MU_IID_IAudioSessionControl) + #define MU_IID_IAUDIORENDERCLIENT (MU_IID_IAudioRenderClient) + #define MU_IID_IMMDEVICEENUMERATOR (MU_IID_IMMDeviceEnumerator) + #define MU_IID_IAUDIOCAPTURECLIENT (MU_IID_IAudioCaptureClient) + #define MU_IID_ISIMPLEAUDIOVOLUME (MU_IID_ISimpleAudioVolume) + #define MU_CLSID_MMDEVICEENUMERATOR (MU_CLSID_MMDeviceEnumerator) + #define MU_PKEY_DEVICE_FRIENDLYNAME (PKEY_Device_FriendlyName) + #define MU_PKEY_AUDIOENGINE_DEVICEFORMAT (PKEY_AudioEngine_DeviceFormat) + + #else + #define IS_EQUAL_GUID(a, b) IsEqualGUID((a), (b)) + #define IS_EQUAL_IID(a, b) IsEqualIID((a), (b)) + + #define MU_IID_IAUDIOCLIENT (&MU_IID_IAudioClient) + #define MU_IID_IMMENDPOINT (&MU_IID_IMMEndpoint) + #define MU_PKEY_DEVICE_FRIENDLYNAME (&PKEY_Device_FriendlyName) + #define MU_PKEY_AUDIOENGINE_DEVICEFORMAT (&PKEY_AudioEngine_DeviceFormat) + #define MU_CLSID_MMDEVICEENUMERATOR (&MU_CLSID_MMDeviceEnumerator) + #define MU_IID_IAUDIOCLOCKADJUSTMENT (&MU_IID_IAudioClockAdjustment) + #define MU_IID_IAUDIOSESSIONCONTROL (&MU_IID_IAudioSessionControl) + #define MU_IID_IAUDIORENDERCLIENT (&MU_IID_IAudioRenderClient) + #define MU_IID_IMMDEVICEENUMERATOR (&MU_IID_IMMDeviceEnumerator) + #define MU_IID_IAUDIOCAPTURECLIENT (&MU_IID_IAudioCaptureClient) + #define MU_IID_ISIMPLEAUDIOVOLUME (&MU_IID_ISimpleAudioVolume) + #endif + + // Number of REFERENCE_TIME units per second + // One unit is equal to 100 nano seconds + #define MU_REF_TIMES_PER_SECOND 10000000 + #define MU_REF_TIMES_PER_MSECOND 10000 + +// Empty functions(stubs) which are used when library fails to load +static HRESULT CoCreateInstanceStub(REFCLSID rclsid, LPUNKNOWN *pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv) { + (void)(rclsid); + (void)(pUnkOuter); + (void)(dwClsContext); + (void)(riid); + (void)(ppv); + return S_FALSE; +} + +static HRESULT CoInitializeExStub(LPVOID pvReserved, DWORD dwCoInit) { + (void)(pvReserved); + (void)(dwCoInit); + return S_FALSE; +} + +MU_StaticFunc void MU_WIN32_DeinitSound(MU_Context *mu) { + MU_Win32 *w32 = (MU_Win32 *)mu->platform; + if (w32->audio_client) w32->audio_client->lpVtbl->Stop(w32->audio_client); + if (w32->audio_client) w32->audio_client->lpVtbl->Release(w32->audio_client); + if (w32->device_enum) w32->device_enum->lpVtbl->Release(w32->device_enum); + if (w32->device) w32->device->lpVtbl->Release(w32->device); + if (w32->audio_render_client) w32->audio_render_client->lpVtbl->Release(w32->audio_render_client); + mu->sound.initialized = false; +} + +// Load COM Library functions dynamically, +// this way sound is not necessary to run the game +MU_StaticFunc void MU_WIN32_LoadCOM(MU_Context *mu) { + MU_Win32 *w32 = (MU_Win32 *)mu->platform; + + HMODULE ole32_lib = LoadLibraryA("ole32.dll"); + if (ole32_lib) { + w32->CoCreateInstanceFunctionPointer = (CoCreateInstanceFunction *)GetProcAddress(ole32_lib, "CoCreateInstance"); + w32->CoInitializeExFunctionPointer = (CoInitializeExFunction *)GetProcAddress(ole32_lib, "CoInitializeEx"); + mu->sound.initialized = true; + } + + if (ole32_lib == 0 || w32->CoCreateInstanceFunctionPointer == 0 || w32->CoInitializeExFunctionPointer == 0) { + w32->CoCreateInstanceFunctionPointer = CoCreateInstanceStub; + w32->CoInitializeExFunctionPointer = CoInitializeExStub; + mu->sound.initialized = false; + } +} + +MU_StaticFunc DWORD MU_WIN32_SoundThread(void *parameter) { + MU_Context *mu = (MU_Context *)parameter; + MU_Win32 *w32 = (MU_Win32 *)mu->platform; + + HANDLE thread_handle = GetCurrentThread(); + SetThreadPriority(thread_handle, THREAD_PRIORITY_HIGHEST); + HANDLE buffer_ready_event = CreateEvent(0, 0, 0, 0); + if (!buffer_ready_event) { + MU_ASSERT(!"Sound thread failed"); + goto error_cleanup; + } + if (FAILED(IAudioClient_SetEventHandle(w32->audio_client, buffer_ready_event))) { + MU_ASSERT(!"Sound thread failed"); + goto error_cleanup; + } + + if (FAILED(IAudioClient_Start(w32->audio_client))) { + MU_ASSERT(!"Sound thread failed"); + goto error_cleanup; + } + for (;;) { + if (WaitForSingleObject(buffer_ready_event, INFINITE) != WAIT_OBJECT_0) { + MU_ASSERT(!"Sound thread failed"); + goto error_cleanup; + } + uint32_t padding_frame_count; + if (FAILED(IAudioClient_GetCurrentPadding(w32->audio_client, &padding_frame_count))) { + MU_ASSERT(!"Sound thread failed"); + goto error_cleanup; + } + uint32_t *samples; + uint32_t fill_frame_count = w32->buffer_frame_count - padding_frame_count; + if (FAILED(IAudioRenderClient_GetBuffer(w32->audio_render_client, fill_frame_count, (BYTE **)&samples))) { + MU_ASSERT(!"Sound thread failed"); + goto error_cleanup; + } + + // Call user callback + uint32_t sample_count_to_fill = fill_frame_count * mu->sound.number_of_channels; + mu->sound.callback((MU_Context *)mu, (uint16_t *)samples, sample_count_to_fill); + + if (FAILED(IAudioRenderClient_ReleaseBuffer(w32->audio_render_client, fill_frame_count, 0))) { + MU_ASSERT(!"Sound thread failed"); + goto error_cleanup; + } + } + return 0; +error_cleanup: + MU_WIN32_DeinitSound(mu); + return -1; +} + +MU_StaticFunc void MU_WIN32_InitWasapi(MU_Context *mu) { + REFERENCE_TIME requested_buffer_duration = MU_REF_TIMES_PER_MSECOND * 40; + MU_Win32 *w32 = (MU_Win32 *)mu->platform; + + MU_WIN32_LoadCOM(mu); + MU_ASSERT(mu->sound.initialized); + if (mu->sound.initialized == false) { + return; + } + + mu->sound.bytes_per_sample = 2; + mu->sound.number_of_channels = 2; + mu->sound.samples_per_second = 44100; + + HANDLE thread_handle; + + HRESULT hr = w32->CoInitializeExFunctionPointer(0, COINITBASE_MULTITHREADED); + if (FAILED(hr)) { + MU_ASSERT(!"Failed to initialize sound"); + goto failure_path; + } + + hr = w32->CoCreateInstanceFunctionPointer(MU_CLSID_MMDEVICEENUMERATOR, NULL, CLSCTX_ALL, MU_IID_IMMDEVICEENUMERATOR, (void **)&w32->device_enum); + if (FAILED(hr)) { + MU_ASSERT(!"Failed to initialize sound"); + goto failure_path; + } + + hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(w32->device_enum, eRender, eMultimedia, &w32->device); + if (FAILED(hr)) { + MU_ASSERT(!"Failed to initialize sound"); + goto failure_path; + } + + hr = IMMDevice_Activate(w32->device, MU_IID_IAUDIOCLIENT, CLSCTX_ALL, NULL, (void **)&w32->audio_client); + if (FAILED(hr)) { + MU_ASSERT(!"Failed to initialize sound"); + goto failure_path; + } + + WAVEFORMATEX fmt; + { + MU__ZeroMemory(&fmt, sizeof(fmt)); + fmt.wFormatTag = WAVE_FORMAT_PCM; + fmt.nChannels = mu->sound.number_of_channels; + fmt.nSamplesPerSec = mu->sound.samples_per_second; + fmt.wBitsPerSample = mu->sound.bytes_per_sample * 8; + fmt.nBlockAlign = fmt.nChannels * fmt.wBitsPerSample / 8; + fmt.nAvgBytesPerSec = fmt.nSamplesPerSec * fmt.nBlockAlign; + } + + hr = IAudioClient_Initialize( + w32->audio_client, AUDCLNT_SHAREMODE_SHARED, + AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_RATEADJUST | + AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, + requested_buffer_duration, 0, &fmt, 0); + if (FAILED(hr)) { + MU_ASSERT(!"Failed to initialize sound"); + goto failure_path; + } + + hr = IAudioClient_GetService(w32->audio_client, MU_IID_IAUDIORENDERCLIENT, (void **)&w32->audio_render_client); + if (FAILED(hr)) { + MU_ASSERT(!"Failed to initialize sound"); + goto failure_path; + } + + hr = IAudioClient_GetBufferSize(w32->audio_client, &w32->buffer_frame_count); + if (FAILED(hr)) { + MU_ASSERT(!"Failed to initialize sound"); + goto failure_path; + } + + thread_handle = CreateThread(0, 0, MU_WIN32_SoundThread, mu, 0, 0); + if (thread_handle == INVALID_HANDLE_VALUE) { + MU_ASSERT(!"Failed to create a sound thread"); + goto failure_path; + } + + return; +failure_path: + MU_WIN32_DeinitSound(mu); +} + +#endif // _WIN32 \ No newline at end of file diff --git a/src/standalone_libraries/multimedia.h b/src/standalone_libraries/multimedia.h new file mode 100644 index 0000000..241bf09 --- /dev/null +++ b/src/standalone_libraries/multimedia.h @@ -0,0 +1,370 @@ +#ifndef FIRST_MU_HEADER +#define FIRST_MU_HEADER +#include +#include +#include +#ifndef MU_API + #ifdef __cplusplus + #define MU_API extern "C" + #else + #define MU_API + #endif +#endif + +#ifndef MU_INLINE + #ifndef _MSC_VER + #ifdef __cplusplus + #define MU_INLINE inline + #else + #define MU_INLINE + #endif + #else + #define MU_INLINE __forceinline + #endif +#endif + +#ifndef MU_Float2 + #define MU_Float2 MU__Float2 +typedef struct MU__Float2 { + float x; + float y; +} MU__Float2; +#endif + +#ifndef MU_Int2 + #define MU_Int2 MU__Int2 +typedef struct MU__Int2 { + int x; + int y; +} MU__Int2; +#endif + +//@begin gen_structs +typedef struct MU_UTF32Result MU_UTF32Result; +typedef struct MU_UTF8Result MU_UTF8Result; +typedef struct MU_Win32 MU_Win32; +typedef struct MU_Win32_Window MU_Win32_Window; +typedef struct MU_Window_Params MU_Window_Params; +typedef struct MU_Params MU_Params; +typedef struct MU_Key_State MU_Key_State; +typedef struct MU_Mouse_State MU_Mouse_State; +typedef struct MU_DroppedFile MU_DroppedFile; +typedef struct MU_Arena MU_Arena; +typedef struct MU_Window MU_Window; +typedef struct MU_Time MU_Time; +typedef struct MU_Sound MU_Sound; +typedef struct MU_Context MU_Context; +//@end gen_structs + +typedef void *MU_glGetProcAddress(const char *); + +struct MU_Window_Params { + MU_Int2 size; + MU_Int2 pos; + char *title; + bool enable_canvas; + bool resizable; + bool borderless; + bool fps_cursor; +}; + +struct MU_Params { + void *memory; + size_t cap; + + bool enable_opengl; + int opengl_major; + int opengl_minor; + + double delta_time; + MU_Window_Params window; // this controls window when calling MU_Start + void (*sound_callback)(MU_Context *mu, uint16_t *buffer, uint32_t samples_to_fill); +}; + +struct MU_Key_State { + bool down; + bool press; + bool unpress; + bool raw_press; +}; + +typedef enum MU_Key { + MU_KEY_INVALID, + MU_KEY_ESCAPE, + MU_KEY_ENTER, + MU_KEY_TAB, + MU_KEY_BACKSPACE, + MU_KEY_INSERT, + MU_KEY_DELETE, + MU_KEY_RIGHT, + MU_KEY_LEFT, + MU_KEY_DOWN, + MU_KEY_UP, + MU_KEY_PAGE_UP, + MU_KEY_PAGE_DOWN, + MU_KEY_HOME, + MU_KEY_END, + MU_KEY_F1, + MU_KEY_F2, + MU_KEY_F3, + MU_KEY_F4, + MU_KEY_F5, + MU_KEY_F6, + MU_KEY_F7, + MU_KEY_F8, + MU_KEY_F9, + MU_KEY_F10, + MU_KEY_F11, + MU_KEY_F12, + MU_KEY_SPACE = 32, + MU_KEY_APOSTROPHE = 39, + MU_KEY_PLUS = 43, + MU_KEY_COMMA = 44, + MU_KEY_MINUS = 45, + MU_KEY_PERIOD = 46, + MU_KEY_SLASH = 47, + MU_KEY_0 = 48, + MU_KEY_1 = 49, + MU_KEY_2 = 50, + MU_KEY_3 = 51, + MU_KEY_4 = 52, + MU_KEY_5 = 53, + MU_KEY_6 = 54, + MU_KEY_7 = 55, + MU_KEY_8 = 56, + MU_KEY_9 = 57, + MU_KEY_SEMICOLON = 59, + MU_KEY_EQUAL = 61, + MU_KEY_A = 65, + MU_KEY_B = 66, + MU_KEY_C = 67, + MU_KEY_D = 68, + MU_KEY_E = 69, + MU_KEY_F = 70, + MU_KEY_G = 71, + MU_KEY_H = 72, + MU_KEY_I = 73, + MU_KEY_J = 74, + MU_KEY_K = 75, + MU_KEY_L = 76, + MU_KEY_M = 77, + MU_KEY_N = 78, + MU_KEY_O = 79, + MU_KEY_P = 80, + MU_KEY_Q = 81, + MU_KEY_R = 82, + MU_KEY_S = 83, + MU_KEY_T = 84, + MU_KEY_U = 85, + MU_KEY_V = 86, + MU_KEY_W = 87, + MU_KEY_X = 88, + MU_KEY_Y = 89, + MU_KEY_Z = 90, + MU_KEY_LEFT_BRACKET = 91, + MU_KEY_BACKSLASH = 92, + MU_KEY_RIGHT_BRACKET = 93, + MU_KEY_GRAVE_ACCENT = 96, + MU_KEY_F13, + MU_KEY_F14, + MU_KEY_F15, + MU_KEY_F16, + MU_KEY_F17, + MU_KEY_F18, + MU_KEY_F19, + MU_KEY_F20, + MU_KEY_F21, + MU_KEY_F22, + MU_KEY_F23, + MU_KEY_F24, + MU_KEY_KP_0, + MU_KEY_KP_1, + MU_KEY_KP_2, + MU_KEY_KP_3, + MU_KEY_KP_4, + MU_KEY_KP_5, + MU_KEY_KP_6, + MU_KEY_KP_7, + MU_KEY_KP_8, + MU_KEY_KP_9, + MU_KEY_KP_DECIMAL, + MU_KEY_KP_DIVIDE, + MU_KEY_KP_MULTIPLY, + MU_KEY_KP_SUBTRACT, + MU_KEY_KP_ADD, + MU_KEY_KP_ENTER, + MU_KEY_LEFT_SHIFT, + MU_KEY_LEFT_CONTROL, + MU_KEY_LEFT_ALT, + MU_KEY_LEFT_SUPER, + MU_KEY_RIGHT_SHIFT, + MU_KEY_RIGHT_CONTROL, + MU_KEY_RIGHT_ALT, + MU_KEY_RIGHT_SUPER, + MU_KEY_CAPS_LOCK, + MU_KEY_SCROLL_LOCK, + MU_KEY_NUM_LOCK, + MU_KEY_PRINT_SCREEN, + MU_KEY_PAUSE, + MU_KEY_SHIFT, + MU_KEY_CONTROL, + MU_KEY_COUNT, +} MU_Key; + +struct MU_Mouse_State { + MU_Int2 pos; + MU_Float2 posf; + MU_Int2 delta_pos; + MU_Float2 delta_pos_normalized; + MU_Key_State left; + MU_Key_State middle; + MU_Key_State right; + float delta_wheel; // @todo: add smooth delta? +}; + +struct MU_DroppedFile { + MU_DroppedFile *next; + char *filename; // null terminated + int filename_size; +}; + +struct MU_Arena { + char *memory; + size_t len; + size_t cap; +}; + +// Most of the fields in the window struct are read only. They are updated +// in appropriate update functions. The window should belong to the MU_Context +// but you get access to the information. +struct MU_Window { + MU_Int2 size; + MU_Float2 sizef; + MU_Int2 pos; + MU_Float2 posf; + float dpi_scale; + bool is_fullscreen; + bool is_fps_mode; + bool is_focused; + bool change_cursor_on_mouse_hold; // @in @out + uint64_t processed_events_this_frame; + bool should_render; // @in @out this is false on first frame but it doesn't matter cause it shouldnt be rendered + + MU_DroppedFile *first_dropped_file; + + uint32_t *canvas; + bool canvas_enabled; // @in @out + + MU_Mouse_State mouse; + MU_Key_State key[MU_KEY_COUNT]; + + uint32_t user_text32[32]; + int user_text32_count; + + char user_text8[32]; + int user_text8_count; + + MU_Window *next; + void *handle; + void *platform; +}; + +struct MU_Time { + double app_start; + double frame_start; + + double update; + double update_total; + + double delta; + float deltaf; + double total; + float totalf; +}; + +struct MU_Sound { + bool initialized; + unsigned samples_per_second; + unsigned number_of_channels; + unsigned bytes_per_sample; + void (*callback)(MU_Context *mu, uint16_t *buffer, uint32_t samples_to_fill); +}; + +struct MU_Context { + bool quit; + + MU_Sound sound; + MU_Time time; + bool first_frame; + int _MU_Update_count; + size_t frame; + size_t consecutive_missed_frames; + size_t total_missed_frames; + + MU_Int2 primary_monitor_size; + bool opengl_initialized; + int opengl_major; + int opengl_minor; + void *(*gl_get_proc_address)(const char *str); + + MU_Params params; + MU_Window *window; + MU_Window *all_windows; + MU_Arena perm_arena; + MU_Arena frame_arena; // Reset at beginning of MU_Update + void *platform; +}; + +//@begin gen_api_funcs +MU_API void MU_Quit(MU_Context *mu); +MU_API void MU_DefaultSoundCallback(MU_Context *mu, uint16_t *buffer, uint32_t samples_to_fill); +MU_API double MU_GetTime(void); +MU_API void MU_ToggleFPSMode(MU_Window *window); +MU_API void MU_DisableFPSMode(MU_Window *window); +MU_API void MU_EnableFPSMode(MU_Window *window); +MU_API void MU_ToggleFullscreen(MU_Window *window); +MU_API void MU_Init(MU_Context *mu, MU_Params params, size_t len); +MU_API MU_Window *MU_AddWindow(MU_Context *mu, MU_Window_Params params); +MU_API void MU_InitWindow(MU_Context *mu, MU_Window *window, MU_Window_Params params); +MU_API MU_Context *MU_Start(MU_Params params); +MU_API bool MU_Update(MU_Context *mu); +//@end gen_api_funcs + +/* @! In the future, api for processing messages manually + + while(true) { + MU_Event event; + while (mu_get_event_blocking(&event)) { + switch(event.kind) { + + } + } + } + +typedef int MU_Modifier; +enum MU_Modifier { + MU_MODIFIER_SHIFT = 0x1, // left or right shift key + MU_MODIFIER_CTRL = 0x2, // left or right control key + MU_MODIFIER_ALT = 0x4, // left or right alt key + MU_MODIFIER_SUPER = 0x8, // left or right 'super' key + MU_MODIFIER_LMB = 0x100, // left mouse button + MU_MODIFIER_RMB = 0x200, // right mouse button + MU_MODIFIER_MMB = 0x400, // middle mouse button +}; + +typedef enum MU_Event_Kind { + MU_EVENT_KIND_INVALID, + MU_EVENT_KIND_KEY_DOWN, + MU_EVENT_KIND_KEY_UP, + MU_EVENT_KIND_MOUSE_MOVE, +} MU_Event_Kind; + +typedef struct MU_Event { + MU_Event_Kind kind; + MU_Modifier modifier; + MU_Key key; +} MU_Event; + + + */ +#endif \ No newline at end of file diff --git a/src/standalone_libraries/preproc_env.h b/src/standalone_libraries/preproc_env.h new file mode 100644 index 0000000..77b8084 --- /dev/null +++ b/src/standalone_libraries/preproc_env.h @@ -0,0 +1,119 @@ +#ifndef FIRST_ENV_HEADER +#define FIRST_ENV_HEADER +#ifndef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS +#endif + +#if defined(__APPLE__) && defined(__MACH__) + #define OS_MAC 1 +#elif defined(_WIN32) + #define OS_WINDOWS 1 +#elif defined(__linux__) + #define OS_POSIX 1 + #define OS_LINUX 1 +#elif OS_WASM +#else + #error Unsupported platform +#endif + +#if defined(__clang__) + #define COMPILER_CLANG 1 +#elif defined(__GNUC__) || defined(__GNUG__) + #define COMPILER_GCC 1 +#elif defined(_MSC_VER) + #define COMPILER_MSVC 1 +#elif defined(__TINYC__) + #define COMPILER_TCC 1 +#else + #error Unsupported compiler +#endif + +#ifdef __cplusplus + #define LANG_CPP 1 +#else + #define LANG_C 1 +#endif + +#ifndef OS_MAC + #define OS_MAC 0 +#endif + +#ifndef OS_WINDOWS + #define OS_WINDOWS 0 +#endif + +#ifndef OS_LINUX + #define OS_LINUX 0 +#endif + +#ifndef OS_POSIX + #define OS_POSIX 0 +#endif + +#ifndef COMPILER_MSVC + #define COMPILER_MSVC 0 +#endif + +#ifndef COMPILER_CLANG + #define COMPILER_CLANG 0 +#endif + +#ifndef COMPILER_GCC + #define COMPILER_GCC 0 +#endif + +#ifndef COMPILER_TCC + #define COMPILER_TCC 0 +#endif + +#ifndef LANG_CPP + #define LANG_CPP 0 +#endif + +#ifndef LANG_C + #define LANG_C 0 +#endif + +#if COMPILER_MSVC + #define FORCE_INLINE __forceinline +#elif COMPILER_GCC || COMPILER_CLANG + #define FORCE_INLINE __attribute__((always_inline)) inline +#else + #define FORCE_INLINE inline +#endif + +#if OS_MAC + #define IF_MAC(x) x +#else + #define IF_MAC(x) +#endif + +#if OS_WINDOWS + #define IF_WINDOWS(x) x + #define IF_WINDOWS_ELSE(x, y) x +#else + #define IF_WINDOWS(x) + #define IF_WINDOWS_ELSE(x, y) y +#endif + +#if OS_LINUX + #define IF_LINUX(x) x + #define IF_LINUX_ELSE(x, y) x +#else + #define IF_LINUX(x) + #define IF_LINUX_ELSE(x, y) y +#endif + +#if OS_WINDOWS + #define OS_NAME "windows" +#elif OS_LINUX + #define OS_NAME "linux" +#elif OS_MAC + #define OS_NAME "mac_os" +#elif OS_WASM + #define OS_NAME "wasm" +#else + #error couldnt figure out OS +#endif + +#endif \ No newline at end of file diff --git a/src/standalone_libraries/regex.c b/src/standalone_libraries/regex.c new file mode 100644 index 0000000..3fd3e4e --- /dev/null +++ b/src/standalone_libraries/regex.c @@ -0,0 +1,558 @@ +#include "regex.h" + +#ifndef RE_ASSERT + #include + #define RE_ASSERT(x) assert(x) +#endif + +#ifndef RE_STRICT_ASSERT + #define RE_STRICT_ASSERT RE_ASSERT +#endif + +#ifndef RE_MemoryZero + #include + #define RE_MemoryZero(p, size) memset(p, 0, size) +#endif + +typedef struct RE__Arena { + char *buff; + RE_Int len; + RE_Int cap; +} RE_Arena; + +struct RE_String { + char *str; + RE_Int len; +}; + +struct RE_Utf32Result { + uint32_t out_str; + int advance; + int error; +}; +static RE_Regex RE_NullRegex; +static char RE_NullChar; + +struct RE_Parser { + RE_String string; + RE_Int i; + RE_Regex *first; + RE_Regex *last; +}; +RE_API RE_Regex *RE1_ParseEx(RE_Arena *arena, char *string); +RE_API RE_Regex *RE2_ParseEx(RE_Arena *arena, char *string, RE_Int len); + +RE_StaticFunc void *RE_PushSize(RE_Arena *arena, RE_Int size) { + if (arena->len + size > arena->cap) { + RE_ASSERT(!"RE_Regex: Not enough memory passed for this regex"); + } + void *result = arena->buff + arena->len; + arena->len += size; + return result; +} + +RE_StaticFunc RE_Arena RE_ArenaFromBuffer(char *buff, RE_Int size) { + RE_Arena result; + result.len = 0; + result.cap = size; + result.buff = buff; + return result; +} + +RE_StaticFunc RE_String RE_Skip(RE_String string, RE_Int len) { + if (len > string.len) len = string.len; + RE_Int remain = string.len - len; + RE_String result; + result.str = string.str + len; + result.len = remain; + return result; +} + +RE_StaticFunc RE_Int RE_StringLength(char *string) { + RE_Int len = 0; + while (*string++ != 0) len++; + return len; +} + +RE_StaticFunc RE_Utf32Result RE_ConvertUTF8ToUTF32(char *c, int max_advance) { + RE_Utf32Result result; + RE_MemoryZero(&result, sizeof(result)); + + if ((c[0] & 0x80) == 0) { // Check if leftmost zero of first byte is unset + if (max_advance >= 1) { + result.out_str = c[0]; + result.advance = 1; + } + else result.error = 1; + } + + else if ((c[0] & 0xe0) == 0xc0) { + if ((c[1] & 0xc0) == 0x80) { // Continuation byte required + if (max_advance >= 2) { + result.out_str = (uint32_t)(c[0] & 0x1f) << 6u | (c[1] & 0x3f); + result.advance = 2; + } + else result.error = 2; + } + else result.error = 2; + } + + else if ((c[0] & 0xf0) == 0xe0) { + if ((c[1] & 0xc0) == 0x80 && (c[2] & 0xc0) == 0x80) { // Two continuation bytes required + if (max_advance >= 3) { + result.out_str = (uint32_t)(c[0] & 0xf) << 12u | (uint32_t)(c[1] & 0x3f) << 6u | (c[2] & 0x3f); + result.advance = 3; + } + else result.error = 3; + } + else result.error = 3; + } + + else if ((c[0] & 0xf8) == 0xf0) { + if ((c[1] & 0xc0) == 0x80 && (c[2] & 0xc0) == 0x80 && (c[3] & 0xc0) == 0x80) { // Three continuation bytes required + if (max_advance >= 4) { + result.out_str = (uint32_t)(c[0] & 0xf) << 18u | (uint32_t)(c[1] & 0x3f) << 12u | (uint32_t)(c[2] & 0x3f) << 6u | (uint32_t)(c[3] & 0x3f); + result.advance = 4; + } + else result.error = 4; + } + else result.error = 4; + } + else result.error = 4; + + return result; +} + +#define RE_DLL_QUEUE_REMOVE(first, last, node) \ + do { \ + if ((first) == (last)) { \ + (first) = (last) = 0; \ + } \ + else if ((last) == (node)) { \ + (last) = (last)->prev; \ + (last)->next = 0; \ + } \ + else if ((first) == (node)) { \ + (first) = (first)->next; \ + (first)->prev = 0; \ + } \ + else { \ + (node)->prev->next = (node)->next; \ + (node)->next->prev = (node)->prev; \ + } \ + if (node) (node)->prev = 0; \ + } while (0) + +#define RE_DLL_QUEUE_ADD(f, l, node) \ + do { \ + if ((f) == 0) { \ + (f) = (l) = (node); \ + (node)->prev = 0; \ + (node)->next = 0; \ + } \ + else { \ + (l)->next = (node); \ + (node)->prev = (l); \ + (node)->next = 0; \ + (l) = (node); \ + } \ + } while (0) + +RE_StaticFunc char *RE_GetP(RE_Parser *P) { + if (P->i >= P->string.len) return &RE_NullChar; + return P->string.str + P->i; +} + +RE_StaticFunc char RE_Get(RE_Parser *P) { + if (P->i >= P->string.len) return 0; + return P->string.str[P->i]; +} + +RE_StaticFunc char RE_Get1(RE_Parser *P) { + if ((P->i + 1) >= P->string.len || P->i >= P->string.len) return 0; + return P->string.str[P->i + 1]; +} + +RE_StaticFunc void RE_Advance(RE_Parser *P) { + if (P->i >= P->string.len) return; + P->i += 1; +} + +RE_StaticFunc RE_Regex *RE_ParseSingle(RE_Parser *P, RE_Arena *arena, RE_Regex **first, RE_Regex **last) { + RE_Regex *regex = (RE_Regex *)RE_PushSize(arena, sizeof(RE_Regex)); + RE_MemoryZero(regex, sizeof(*regex)); + char *c = RE_GetP(P); + RE_Int size_left = P->string.len - P->i; + RE_Advance(P); + switch (*c) { + case ')': RE_STRICT_ASSERT(regex->kind != RE_MATCH_NULL && "Invalid regex syntax, ')' appeared without matching '('"); break; + case '\0': RE_STRICT_ASSERT(regex->kind != RE_MATCH_NULL && "Invalid regex syntax, reached end of string obruptly"); break; + case '.': regex->kind = RE_MATCH_ANY; break; + case '^': regex->kind = RE_MATCH_FRONT; break; + case '$': regex->kind = RE_MATCH_BACK; break; + + case '*': { + if (*last) { + regex->kind = RE_MATCH_ZERO_OR_MORE; + RE_Regex *prev = *last; + RE_DLL_QUEUE_REMOVE(*first, *last, *last); + regex->child = prev; + } + else { + RE_STRICT_ASSERT(!"Invalid regex syntax, '*' is not attached to anything"); + } + } break; + + case '+': { + if (*last) { + regex->kind = RE_MATCH_ONE_OR_MORE; + RE_Regex *prev = *last; + RE_DLL_QUEUE_REMOVE(*first, *last, *last); + regex->child = prev; + } + else { + RE_STRICT_ASSERT(!"Invalid regex syntax, '+' is not attached to anything"); + } + } break; + + case '?': { + if (*last) { + regex->kind = RE_MATCH_ZERO_OR_ONE; + RE_Regex *prev = *last; + RE_DLL_QUEUE_REMOVE(*first, *last, *last); + regex->child = prev; + } + else { + RE_STRICT_ASSERT(!"Invalid regex syntax, '?' is not attached to anything"); + } + } break; + + case '[': { + regex->kind = RE_MATCH_SELECTED; + if (RE_Get(P) == '^') { + regex->kind = RE_MATCH_NOT_SELECTED; + RE_Advance(P); + } + while (RE_Get(P) != 0 && RE_Get(P) != ']') { + RE_Regex *r = RE_ParseSingle(P, arena, ®ex->group.first, ®ex->group.last); + if (r->kind == RE_MATCH_NULL) { + regex->kind = RE_MATCH_NULL; + break; + } + if (r->kind == RE_MATCH_WORD && RE_Get(P) == '-') { + char word = RE_Get1(P); + if (word >= '!' && word <= '~') { + RE_Advance(P); + RE_Regex *right = RE_ParseSingle(P, arena, 0, 0); + if (right->kind == RE_MATCH_NULL) { + regex->kind = RE_MATCH_NULL; + break; + } + RE_ASSERT(right->kind == RE_MATCH_WORD); + RE_ASSERT(right->word == word); + r->word_min = word > r->word ? r->word : word; + r->word_max = word > r->word ? word : r->word; + r->kind = RE_MATCH_RANGE; + } + } + RE_DLL_QUEUE_ADD(regex->group.first, regex->group.last, r); + } + RE_Advance(P); + } break; + + case '(': { + regex->kind = RE_MATCH_GROUP; + while (RE_Get(P) != 0 && RE_Get(P) != ')') { + RE_Regex *r = RE_ParseSingle(P, arena, ®ex->group.first, ®ex->group.last); + if (r->kind == RE_MATCH_NULL) { + regex->kind = RE_MATCH_NULL; + break; + } + RE_DLL_QUEUE_ADD(regex->group.first, regex->group.last, r); + } + RE_Advance(P); + } break; + + case '|': { + if (*last) { + regex->kind = RE_MATCH_OR; + RE_Regex *left = *last; + RE_Regex *right = RE_ParseSingle(P, arena, first, last); + if (right->kind == RE_MATCH_NULL) { + regex->kind = RE_MATCH_NULL; + RE_STRICT_ASSERT(!"Invalid regex syntax, '|' appeared but it's right option is invalid"); + } + else { + RE_DLL_QUEUE_REMOVE(*first, *last, left); + regex->left = left; + regex->right = right; + } + } + } break; + + case '\\': { + regex->kind = RE_MATCH_WORD; + regex->word = RE_Get(P); + switch (regex->word) { + case 'n': regex->word = '\n'; break; + case 't': regex->word = '\t'; break; + case 'r': regex->word = '\r'; break; + case 'w': regex->kind = RE_MATCH_ANY_WORD; break; + case 'd': regex->kind = RE_MATCH_ANY_DIGIT; break; + case 's': regex->kind = RE_MATCH_ANY_WHITESPACE; break; + case '\0': { + regex->kind = RE_MATCH_NULL; + RE_STRICT_ASSERT(!"Invalid regex syntax, escape '\\' followed by end of string"); + } break; + } + RE_Advance(P); + } break; + + default: { + regex->kind = RE_MATCH_WORD; + RE_Utf32Result decode = RE_ConvertUTF8ToUTF32(c, (int)size_left); + if (decode.error) { + regex->kind = RE_MATCH_NULL; + RE_STRICT_ASSERT(!"Invalid regex syntax, string is an invalid utf8"); + } + else { + regex->word32 = decode.out_str; + for (int i = 0; i < decode.advance - 1; i += 1) + RE_Advance(P); + } + } + } + + return regex; +} + +RE_StaticFunc RE_Int RE_MatchSingle(RE_Regex *regex, RE_String string) { + switch (regex->kind) { + case RE_MATCH_ZERO_OR_MORE: { + RE_Int result = 0; + for (; string.len;) { + // @idea + // In this case (asd)*(asd) we just quit with 0 + // when we meet asd + // Maybe this should be collapsed in parsing stage/ + // asd should be combined with *asd etc. cause + // now it's a bit weird but I dont know why you would + // type that in the first place + if (RE_MatchSingle(regex->next, string) != -1) break; + RE_Int index = RE_MatchSingle(regex->child, string); + if (index == -1) break; + string = RE_Skip(string, index); + result += index; + } + return result; + } break; + + case RE_MATCH_ONE_OR_MORE: { + RE_Int result = 0; + for (; string.len;) { + RE_Int index = RE_MatchSingle(regex->child, string); + if (index == -1) break; + string = RE_Skip(string, index); + result += index; + } + + if (result == 0) return -1; + return result; + } break; + + case RE_MATCH_OR: { + RE_Int right = RE_MatchSingle(regex->right, string); + RE_Int left = RE_MatchSingle(regex->left, string); + if (left > right) return left; + else return right; + } break; + + case RE_MATCH_GROUP: { + RE_Int result = 0; + for (RE_Regex *it = regex->group.first; it; it = it->next) { + if (string.len == 0) return -1; + RE_Int index = RE_MatchSingle(it, string); + if (index == -1) return -1; + result += index; + string = RE_Skip(string, index); + } + return result; + } break; + + case RE_MATCH_NOT_SELECTED: { + for (RE_Regex *it = regex->group.first; it; it = it->next) { + RE_Int index = RE_MatchSingle(it, string); + if (index != -1) return -1; + } + RE_Utf32Result decode = RE_ConvertUTF8ToUTF32(string.str, (int)string.len); + if (decode.error) return -1; + return decode.advance; + } break; + + case RE_MATCH_SELECTED: { + for (RE_Regex *it = regex->group.first; it; it = it->next) { + RE_Int index = RE_MatchSingle(it, string); + if (index != -1) return index; + } + return -1; + } break; + + case RE_MATCH_RANGE: { + if (string.str[0] >= regex->word_min && string.str[0] <= regex->word_max) + return 1; + return -1; + } + + case RE_MATCH_ANY_WORD: { + if ((string.str[0] >= 'a' && string.str[0] <= 'z') || (string.str[0] >= 'A' && string.str[0] <= 'Z')) + return 1; + return -1; + } break; + + case RE_MATCH_ANY_DIGIT: { + if (string.str[0] >= '0' && string.str[0] <= '9') + return 1; + return -1; + } break; + + case RE_MATCH_ANY_WHITESPACE: { + if (string.str[0] == ' ' || string.str[0] == '\n' || string.str[0] == '\t' || string.str[0] == '\r') + return 1; + return -1; + } break; + + case RE_MATCH_ANY: { + if (string.str[0] != '\n') { + return 1; + } + return -1; + } break; + + case RE_MATCH_ZERO_OR_ONE: { + RE_Int index = RE_MatchSingle(regex->child, string); + if (index == -1) index = 0; + return index; + } break; + + case RE_MATCH_WORD: { + RE_Utf32Result decode = RE_ConvertUTF8ToUTF32(string.str, (int)string.len); + if (decode.error) return -1; + if (decode.out_str == regex->word32) return decode.advance; + return -1; + } break; + + case RE_MATCH_BACK: + case RE_MATCH_NULL: return -1; + + default: RE_ASSERT(!"Invalid codepath"); + } + return -1; +} + +RE_API bool RE1_AreEqual(char *regex, char *string) { + char buff[4096]; + RE_Regex *re = RE1_Parse(buff, sizeof(buff), regex); + bool result = RE3_AreEqual(re, string, RE_StringLength(string)); + return result; +} + +RE_API bool RE2_AreEqual(RE_Regex *regex, char *string) { + return RE3_AreEqual(regex, string, RE_StringLength(string)); +} + +RE_API bool RE3_AreEqual(RE_Regex *regex, char *string, RE_Int len) { + RE_Int result = RE3_MatchFront(regex, string, len, string); + return result == len ? true : false; +} + +RE_API RE_Match RE1_Find(char *regex, char *string) { + char buff[4096]; + RE_Regex *re = RE1_Parse(buff, sizeof(buff), regex); + RE_Match result = RE2_Find(re, string); + return result; +} + +RE_API RE_Match RE2_Find(RE_Regex *regex, char *string) { + return RE3_Find(regex, string, RE_StringLength(string)); +} + +RE_API RE_Match RE3_Find(RE_Regex *regex, char *string, RE_Int len) { + RE_Match result; + for (RE_Int i = 0; i < len; i += 1) { + result.size = RE3_MatchFront(regex, string + i, len - i, string); + if (result.size != -1) { + result.pos = i; + return result; + } + } + + result.size = 0; + result.pos = -1; + return result; +} + +RE_API RE_Match RE2_FindAgain(RE_Regex *regex, char *string, RE_Match prev_match) { + return RE2_Find(regex, string + prev_match.pos); +} + +RE_API RE_Match RE3_FindAgain(RE_Regex *regex, char *string, RE_Int len, RE_Match prev_match) { + return RE3_Find(regex, string + prev_match.pos, len - prev_match.pos); +} + +RE_API RE_Int RE3_MatchFront(RE_Regex *regex, char *string, RE_Int len, char *string_front) { + RE_String re_string; + re_string.str = string; + re_string.len = len; + RE_Int submatch_len = 0; + for (RE_Regex *it = regex; it; it = it->next) { + if (it->kind == RE_MATCH_FRONT) { + if (re_string.str == string_front) + continue; + return -1; + } + if (it->kind == RE_MATCH_BACK) { + if (re_string.len == 0) + continue; + return -1; + } + + RE_Int index = RE_MatchSingle(it, re_string); + if (index == -1) return -1; + re_string = RE_Skip(re_string, index); + submatch_len += index; + } + return submatch_len; +} + +RE_API RE_Regex *RE1_ParseEx(RE_Arena *arena, char *string) { + return RE2_ParseEx(arena, string, RE_StringLength(string)); +} + +RE_API RE_Regex *RE2_ParseEx(RE_Arena *arena, char *string, RE_Int len) { + RE_Parser P; + RE_MemoryZero(&P, sizeof(P)); + P.string.str = string; + P.string.len = len; + + for (; P.i < P.string.len;) { + RE_Regex *regex = RE_ParseSingle(&P, arena, &P.first, &P.last); + RE_DLL_QUEUE_ADD(P.first, P.last, regex); + if (regex->kind == RE_MATCH_NULL) { + P.first = &RE_NullRegex; + break; + } + } + return P.first; +} + +RE_API RE_Regex *RE1_Parse(char *buff, RE_Int buffsize, char *string) { + RE_Arena arena = RE_ArenaFromBuffer(buff, buffsize); + RE_Regex *result = RE1_ParseEx(&arena, string); + return result; +} + +RE_API RE_Regex *RE2_Parse(char *buff, RE_Int buffsize, char *string, RE_Int len) { + RE_Arena arena = RE_ArenaFromBuffer(buff, buffsize); + RE_Regex *result = RE2_ParseEx(&arena, string, len); + return result; +} diff --git a/src/standalone_libraries/regex.h b/src/standalone_libraries/regex.h new file mode 100644 index 0000000..aca1448 --- /dev/null +++ b/src/standalone_libraries/regex.h @@ -0,0 +1,95 @@ +#ifndef FIRST_REGEX_HEADER +#define FIRST_REGEX_HEADER +#include +#include + +#ifndef RE_Int + #define RE_Int int64_t +#endif + +#ifndef RE_API + #ifdef __cplusplus + #define RE_API extern "C" + #else + #define RE_API + #endif +#endif + +#ifndef RE_StaticFunc + #if defined(__GNUC__) || defined(__clang__) + #define RE_StaticFunc __attribute__((unused)) static + #else + #define RE_StaticFunc static + #endif +#endif + +typedef struct RE_String RE_String; +typedef struct RE_Utf32Result RE_Utf32Result; +typedef struct RE_Parser RE_Parser; +typedef struct RE_Regex RE_Regex; +typedef struct RE_Match RE_Match; + +/* @todo +Add \W \D \S oppsites +*/ + +typedef enum RE_MatchKind { + RE_MATCH_NULL, + RE_MATCH_FRONT, + RE_MATCH_BACK, + RE_MATCH_WORD, + RE_MATCH_OR, + RE_MATCH_GROUP, + RE_MATCH_SELECTED, + RE_MATCH_NOT_SELECTED, + RE_MATCH_RANGE, + RE_MATCH_ANY, + RE_MATCH_ANY_WORD, + RE_MATCH_ANY_DIGIT, + RE_MATCH_ANY_WHITESPACE, + RE_MATCH_ONE_OR_MORE, + RE_MATCH_ZERO_OR_MORE, + RE_MATCH_ZERO_OR_ONE, +} RE_MatchKind; + +struct RE_Regex { + RE_MatchKind kind; + RE_Regex *next; + RE_Regex *prev; + + union { + struct { + char word_min; + char word_max; + }; + char word; + uint32_t word32; + RE_Regex *child; + struct { + RE_Regex *left; + RE_Regex *right; + }; + struct { + RE_Regex *first; + RE_Regex *last; + } group; + }; +}; + +struct RE_Match { + RE_Int pos; + RE_Int size; +}; + +RE_API bool RE1_AreEqual(char *regex, char *string); +RE_API bool RE2_AreEqual(RE_Regex *regex, char *string); +RE_API bool RE3_AreEqual(RE_Regex *regex, char *string, RE_Int len); +RE_API RE_Match RE1_Find(char *regex, char *string); +RE_API RE_Match RE2_Find(RE_Regex *regex, char *string); +RE_API RE_Match RE3_Find(RE_Regex *regex, char *string, RE_Int len); +RE_API RE_Match RE2_FindAgain(RE_Regex *regex, char *string, RE_Match prev_match); +RE_API RE_Match RE3_FindAgain(RE_Regex *regex, char *string, RE_Int len, RE_Match prev_match); +RE_API RE_Int RE3_MatchFront(RE_Regex *regex, char *string, RE_Int len, char *string_front); +RE_API RE_Regex *RE1_Parse(char *buff, RE_Int buffsize, char *string); +RE_API RE_Regex *RE2_Parse(char *buff, RE_Int buffsize, char *string, RE_Int len); +#endif \ No newline at end of file diff --git a/src/standalone_libraries/stb_sprintf.c b/src/standalone_libraries/stb_sprintf.c new file mode 100644 index 0000000..c6b7a25 --- /dev/null +++ b/src/standalone_libraries/stb_sprintf.c @@ -0,0 +1,1669 @@ + +#define stbsp__uint32 unsigned int +#define stbsp__int32 signed int + +#ifdef _MSC_VER + #define stbsp__uint64 unsigned __int64 + #define stbsp__int64 signed __int64 +#else + #define stbsp__uint64 unsigned long long + #define stbsp__int64 signed long long +#endif +#define stbsp__uint16 unsigned short + +#ifndef stbsp__uintptr + #if defined(__ppc64__) || defined(__powerpc64__) || defined(__aarch64__) || defined(_M_X64) || defined(__x86_64__) || defined(__x86_64) || defined(__s390x__) + #define stbsp__uintptr stbsp__uint64 + #else + #define stbsp__uintptr stbsp__uint32 + #endif +#endif + +#ifndef STB_SPRINTF_MSVC_MODE // used for MSVC2013 and earlier (MSVC2015 matches GCC) + #if defined(_MSC_VER) && (_MSC_VER < 1900) + #define STB_SPRINTF_MSVC_MODE + #endif +#endif + +#ifdef STB_SPRINTF_NOUNALIGNED // define this before inclusion to force stbsp_sprintf to always use aligned accesses + #define STBSP__UNALIGNED(code) +#else + #define STBSP__UNALIGNED(code) code +#endif + +#ifndef STB_SPRINTF_NOFLOAT +// internal float utility functions +static stbsp__int32 stbsp__real_to_str(char const **start, stbsp__uint32 *len, char *out, stbsp__int32 *decimal_pos, double value, stbsp__uint32 frac_digits); +static stbsp__int32 stbsp__real_to_parts(stbsp__int64 *bits, stbsp__int32 *expo, double value); + #define STBSP__SPECIAL 0x7000 +#endif + +static char stbsp__period = '.'; +static char stbsp__comma = ','; +static struct +{ + short temp; // force next field to be 2-byte aligned + char pair[201]; +} stbsp__digitpair = + { + 0, + "00010203040506070809101112131415161718192021222324" + "25262728293031323334353637383940414243444546474849" + "50515253545556575859606162636465666768697071727374" + "75767778798081828384858687888990919293949596979899"}; + +STBSP__PUBLICDEF void STB_SPRINTF_DECORATE(set_separators)(char pcomma, char pperiod) { + stbsp__period = pperiod; + stbsp__comma = pcomma; +} + +#define STBSP__LEFTJUST 1 +#define STBSP__LEADINGPLUS 2 +#define STBSP__LEADINGSPACE 4 +#define STBSP__LEADING_0X 8 +#define STBSP__LEADINGZERO 16 +#define STBSP__INTMAX 32 +#define STBSP__TRIPLET_COMMA 64 +#define STBSP__NEGATIVE 128 +#define STBSP__METRIC_SUFFIX 256 +#define STBSP__HALFWIDTH 512 +#define STBSP__METRIC_NOSPACE 1024 +#define STBSP__METRIC_1024 2048 +#define STBSP__METRIC_JEDEC 4096 + +static void stbsp__lead_sign(stbsp__uint32 fl, char *sign) { + sign[0] = 0; + if (fl & STBSP__NEGATIVE) { + sign[0] = 1; + sign[1] = '-'; + } + else if (fl & STBSP__LEADINGSPACE) { + sign[0] = 1; + sign[1] = ' '; + } + else if (fl & STBSP__LEADINGPLUS) { + sign[0] = 1; + sign[1] = '+'; + } +} + +static STBSP__ASAN stbsp__uint32 stbsp__strlen_limited(char const *s, stbsp__uint32 limit) { + char const *sn = s; + + // get up to 4-byte alignment + for (;;) { + if (((stbsp__uintptr)sn & 3) == 0) + break; + + if (!limit || *sn == 0) + return (stbsp__uint32)(sn - s); + + ++sn; + --limit; + } + + // scan over 4 bytes at a time to find terminating 0 + // this will intentionally scan up to 3 bytes past the end of buffers, + // but becase it works 4B aligned, it will never cross page boundaries + // (hence the STBSP__ASAN markup; the over-read here is intentional + // and harmless) + while (limit >= 4) { + stbsp__uint32 v = *(stbsp__uint32 *)sn; + // bit hack to find if there's a 0 byte in there + if ((v - 0x01010101) & (~v) & 0x80808080UL) + break; + + sn += 4; + limit -= 4; + } + + // handle the last few characters to find actual size + while (limit && *sn) { + ++sn; + --limit; + } + + return (stbsp__uint32)(sn - s); +} + +STBSP__PUBLICDEF int STB_SPRINTF_DECORATE(vsprintfcb)(STBSP_SPRINTFCB *callback, void *user, char *buf, char const *fmt, va_list va) { + static char hex[] = "0123456789abcdefxp"; + static char hexu[] = "0123456789ABCDEFXP"; + char *bf; + char const *f; + int tlen = 0; + + bf = buf; + f = fmt; + for (;;) { + stbsp__int32 fw, pr, tz; + stbsp__uint32 fl; + + // macros for the callback buffer stuff +#define stbsp__chk_cb_bufL(bytes) \ + { \ + int len = (int)(bf - buf); \ + if ((len + (bytes)) >= STB_SPRINTF_MIN) { \ + tlen += len; \ + if (0 == (bf = buf = callback(buf, user, len))) \ + goto done; \ + } \ + } +#define stbsp__chk_cb_buf(bytes) \ + { \ + if (callback) { \ + stbsp__chk_cb_bufL(bytes); \ + } \ + } +#define stbsp__flush_cb() \ + { \ + stbsp__chk_cb_bufL(STB_SPRINTF_MIN - 1); \ + } // flush if there is even one byte in the buffer +#define stbsp__cb_buf_clamp(cl, v) \ + cl = v; \ + if (callback) { \ + int lg = STB_SPRINTF_MIN - (int)(bf - buf); \ + if (cl > lg) \ + cl = lg; \ + } + + // fast copy everything up to the next % (or end of string) + for (;;) { + while (((stbsp__uintptr)f) & 3) { + schk1: + if (f[0] == '%') + goto scandd; + schk2: + if (f[0] == 0) + goto endfmt; + stbsp__chk_cb_buf(1); + *bf++ = f[0]; + ++f; + } + for (;;) { + // Check if the next 4 bytes contain %(0x25) or end of string. + // Using the 'hasless' trick: + // https://graphics.stanford.edu/~seander/bithacks.html#HasLessInWord + stbsp__uint32 v, c; + v = *(stbsp__uint32 *)f; + c = (~v) & 0x80808080; + if (((v ^ 0x25252525) - 0x01010101) & c) + goto schk1; + if ((v - 0x01010101) & c) + goto schk2; + if (callback) + if ((STB_SPRINTF_MIN - (int)(bf - buf)) < 4) + goto schk1; +#ifdef STB_SPRINTF_NOUNALIGNED + if (((stbsp__uintptr)bf) & 3) { + bf[0] = f[0]; + bf[1] = f[1]; + bf[2] = f[2]; + bf[3] = f[3]; + } + else +#endif + { + *(stbsp__uint32 *)bf = v; + } + bf += 4; + f += 4; + } + } + scandd: + + ++f; + + // ok, we have a percent, read the modifiers first + fw = 0; + pr = -1; + fl = 0; + tz = 0; + + // flags + for (;;) { + switch (f[0]) { + // if we have left justify + case '-': + fl |= STBSP__LEFTJUST; + ++f; + continue; + // if we have leading plus + case '+': + fl |= STBSP__LEADINGPLUS; + ++f; + continue; + // if we have leading space + case ' ': + fl |= STBSP__LEADINGSPACE; + ++f; + continue; + // if we have leading 0x + case '#': + fl |= STBSP__LEADING_0X; + ++f; + continue; + // if we have thousand commas + case '\'': + fl |= STBSP__TRIPLET_COMMA; + ++f; + continue; + // if we have kilo marker (none->kilo->kibi->jedec) + case '$': + if (fl & STBSP__METRIC_SUFFIX) { + if (fl & STBSP__METRIC_1024) { + fl |= STBSP__METRIC_JEDEC; + } + else { + fl |= STBSP__METRIC_1024; + } + } + else { + fl |= STBSP__METRIC_SUFFIX; + } + ++f; + continue; + // if we don't want space between metric suffix and number + case '_': + fl |= STBSP__METRIC_NOSPACE; + ++f; + continue; + // if we have leading zero + case '0': + fl |= STBSP__LEADINGZERO; + ++f; + goto flags_done; + default: goto flags_done; + } + } + flags_done: + + // get the field width + if (f[0] == '*') { + fw = va_arg(va, stbsp__uint32); + ++f; + } + else { + while ((f[0] >= '0') && (f[0] <= '9')) { + fw = fw * 10 + f[0] - '0'; + f++; + } + } + // get the precision + if (f[0] == '.') { + ++f; + if (f[0] == '*') { + pr = va_arg(va, stbsp__uint32); + ++f; + } + else { + pr = 0; + while ((f[0] >= '0') && (f[0] <= '9')) { + pr = pr * 10 + f[0] - '0'; + f++; + } + } + } + + // handle integer size overrides + switch (f[0]) { + // are we halfwidth? + case 'h': + fl |= STBSP__HALFWIDTH; + ++f; + if (f[0] == 'h') + ++f; // QUARTERWIDTH + break; + // are we 64-bit (unix style) + case 'l': + fl |= ((sizeof(long) == 8) ? STBSP__INTMAX : 0); + ++f; + if (f[0] == 'l') { + fl |= STBSP__INTMAX; + ++f; + } + break; + // are we 64-bit on intmax? (c99) + case 'j': + fl |= (sizeof(size_t) == 8) ? STBSP__INTMAX : 0; + ++f; + break; + // are we 64-bit on size_t or ptrdiff_t? (c99) + case 'z': + fl |= (sizeof(ptrdiff_t) == 8) ? STBSP__INTMAX : 0; + ++f; + break; + case 't': + fl |= (sizeof(ptrdiff_t) == 8) ? STBSP__INTMAX : 0; + ++f; + break; + // are we 64-bit (msft style) + case 'I': + if ((f[1] == '6') && (f[2] == '4')) { + fl |= STBSP__INTMAX; + f += 3; + } + else if ((f[1] == '3') && (f[2] == '2')) { + f += 3; + } + else { + fl |= ((sizeof(void *) == 8) ? STBSP__INTMAX : 0); + ++f; + } + break; + default: break; + } + + // handle each replacement + switch (f[0]) { +#define STBSP__NUMSZ 512 // big enough for e308 (with commas) or e-307 + char num[STBSP__NUMSZ]; + char lead[8]; + char tail[8]; + char *s; + char const *h; + stbsp__uint32 l, n, cs; + stbsp__uint64 n64; +#ifndef STB_SPRINTF_NOFLOAT + double fv; +#endif + stbsp__int32 dp; + char const *sn; + struct STB_STRING { + char *str; + int64_t len; + }; + struct STB_STRING str; + + case 'Q': + str = va_arg(va, struct STB_STRING); + if (str.str == 0 && str.len != 0) { + str.str = (char *)"null"; + str.len = 4; + } + pr = (int)str.len; + s = (char *)str.str; + l = stbsp__strlen_limited(s, (pr >= 0) ? pr : ~0u); + lead[0] = 0; + tail[0] = 0; + pr = 0; + dp = 0; + cs = 0; + goto scopy; + + case 's': + // get the string + s = va_arg(va, char *); + if (s == 0) + s = (char *)"null"; + // get the length, limited to desired precision + // always limit to ~0u chars since our counts are 32b + l = stbsp__strlen_limited(s, (pr >= 0) ? pr : ~0u); + lead[0] = 0; + tail[0] = 0; + pr = 0; + dp = 0; + cs = 0; + // copy the string in + goto scopy; + + case 'c': // char + // get the character + s = num + STBSP__NUMSZ - 1; + *s = (char)va_arg(va, int); + l = 1; + lead[0] = 0; + tail[0] = 0; + pr = 0; + dp = 0; + cs = 0; + goto scopy; + + case 'n': // weird write-bytes specifier + { + int *d = va_arg(va, int *); + *d = tlen + (int)(bf - buf); + } break; + +#ifdef STB_SPRINTF_NOFLOAT + case 'A': // float + case 'a': // hex float + case 'G': // float + case 'g': // float + case 'E': // float + case 'e': // float + case 'f': // float + va_arg(va, double); // eat it + s = (char *)"No float"; + l = 8; + lead[0] = 0; + tail[0] = 0; + pr = 0; + cs = 0; + STBSP__NOTUSED(dp); + goto scopy; +#else + case 'A': // hex float + case 'a': // hex float + h = (f[0] == 'A') ? hexu : hex; + fv = va_arg(va, double); + if (pr == -1) + pr = 6; // default is 6 + // read the double into a string + if (stbsp__real_to_parts((stbsp__int64 *)&n64, &dp, fv)) + fl |= STBSP__NEGATIVE; + + s = num + 64; + + stbsp__lead_sign(fl, lead); + + if (dp == -1023) + dp = (n64) ? -1022 : 0; + else + n64 |= (((stbsp__uint64)1) << 52); + n64 <<= (64 - 56); + if (pr < 15) + n64 += ((((stbsp__uint64)8) << 56) >> (pr * 4)); + // add leading chars + + #ifdef STB_SPRINTF_MSVC_MODE + *s++ = '0'; + *s++ = 'x'; + #else + lead[1 + lead[0]] = '0'; + lead[2 + lead[0]] = 'x'; + lead[0] += 2; + #endif + *s++ = h[(n64 >> 60) & 15]; + n64 <<= 4; + if (pr) + *s++ = stbsp__period; + sn = s; + + // print the bits + n = pr; + if (n > 13) + n = 13; + if (pr > (stbsp__int32)n) + tz = pr - n; + pr = 0; + while (n--) { + *s++ = h[(n64 >> 60) & 15]; + n64 <<= 4; + } + + // print the expo + tail[1] = h[17]; + if (dp < 0) { + tail[2] = '-'; + dp = -dp; + } + else + tail[2] = '+'; + n = (dp >= 1000) ? 6 : ((dp >= 100) ? 5 : ((dp >= 10) ? 4 : 3)); + tail[0] = (char)n; + for (;;) { + tail[n] = '0' + dp % 10; + if (n <= 3) + break; + --n; + dp /= 10; + } + + dp = (int)(s - sn); + l = (int)(s - (num + 64)); + s = num + 64; + cs = 1 + (3 << 24); + goto scopy; + + case 'G': // float + case 'g': // float + h = (f[0] == 'G') ? hexu : hex; + fv = va_arg(va, double); + if (pr == -1) + pr = 6; + else if (pr == 0) + pr = 1; // default is 6 + // read the double into a string + if (stbsp__real_to_str(&sn, &l, num, &dp, fv, (pr - 1) | 0x80000000)) + fl |= STBSP__NEGATIVE; + + // clamp the precision and delete extra zeros after clamp + n = pr; + if (l > (stbsp__uint32)pr) + l = pr; + while ((l > 1) && (pr) && (sn[l - 1] == '0')) { + --pr; + --l; + } + + // should we use %e + if ((dp <= -4) || (dp > (stbsp__int32)n)) { + if (pr > (stbsp__int32)l) + pr = l - 1; + else if (pr) + --pr; // when using %e, there is one digit before the decimal + goto doexpfromg; + } + // this is the insane action to get the pr to match %g semantics for %f + if (dp > 0) { + pr = (dp < (stbsp__int32)l) ? l - dp : 0; + } + else { + pr = -dp + ((pr > (stbsp__int32)l) ? (stbsp__int32)l : pr); + } + goto dofloatfromg; + + case 'E': // float + case 'e': // float + h = (f[0] == 'E') ? hexu : hex; + fv = va_arg(va, double); + if (pr == -1) + pr = 6; // default is 6 + // read the double into a string + if (stbsp__real_to_str(&sn, &l, num, &dp, fv, pr | 0x80000000)) + fl |= STBSP__NEGATIVE; + doexpfromg: + tail[0] = 0; + stbsp__lead_sign(fl, lead); + if (dp == STBSP__SPECIAL) { + s = (char *)sn; + cs = 0; + pr = 0; + goto scopy; + } + s = num + 64; + // handle leading chars + *s++ = sn[0]; + + if (pr) + *s++ = stbsp__period; + + // handle after decimal + if ((l - 1) > (stbsp__uint32)pr) + l = pr + 1; + for (n = 1; n < l; n++) + *s++ = sn[n]; + // trailing zeros + tz = pr - (l - 1); + pr = 0; + // dump expo + tail[1] = h[0xe]; + dp -= 1; + if (dp < 0) { + tail[2] = '-'; + dp = -dp; + } + else + tail[2] = '+'; + #ifdef STB_SPRINTF_MSVC_MODE + n = 5; + #else + n = (dp >= 100) ? 5 : 4; + #endif + tail[0] = (char)n; + for (;;) { + tail[n] = '0' + dp % 10; + if (n <= 3) + break; + --n; + dp /= 10; + } + cs = 1 + (3 << 24); // how many tens + goto flt_lead; + + case 'f': // float + fv = va_arg(va, double); + doafloat: + // do kilos + if (fl & STBSP__METRIC_SUFFIX) { + double divisor; + divisor = 1000.0f; + if (fl & STBSP__METRIC_1024) + divisor = 1024.0; + while (fl < 0x4000000) { + if ((fv < divisor) && (fv > -divisor)) + break; + fv /= divisor; + fl += 0x1000000; + } + } + if (pr == -1) + pr = 6; // default is 6 + // read the double into a string + if (stbsp__real_to_str(&sn, &l, num, &dp, fv, pr)) + fl |= STBSP__NEGATIVE; + dofloatfromg: + tail[0] = 0; + stbsp__lead_sign(fl, lead); + if (dp == STBSP__SPECIAL) { + s = (char *)sn; + cs = 0; + pr = 0; + goto scopy; + } + s = num + 64; + + // handle the three decimal varieties + if (dp <= 0) { + stbsp__int32 i; + // handle 0.000*000xxxx + *s++ = '0'; + if (pr) + *s++ = stbsp__period; + n = -dp; + if ((stbsp__int32)n > pr) + n = pr; + i = n; + while (i) { + if ((((stbsp__uintptr)s) & 3) == 0) + break; + *s++ = '0'; + --i; + } + while (i >= 4) { + *(stbsp__uint32 *)s = 0x30303030; + s += 4; + i -= 4; + } + while (i) { + *s++ = '0'; + --i; + } + if ((stbsp__int32)(l + n) > pr) + l = pr - n; + i = l; + while (i) { + *s++ = *sn++; + --i; + } + tz = pr - (n + l); + cs = 1 + (3 << 24); // how many tens did we write (for commas below) + } + else { + cs = (fl & STBSP__TRIPLET_COMMA) ? ((600 - (stbsp__uint32)dp) % 3) : 0; + if ((stbsp__uint32)dp >= l) { + // handle xxxx000*000.0 + n = 0; + for (;;) { + if ((fl & STBSP__TRIPLET_COMMA) && (++cs == 4)) { + cs = 0; + *s++ = stbsp__comma; + } + else { + *s++ = sn[n]; + ++n; + if (n >= l) + break; + } + } + if (n < (stbsp__uint32)dp) { + n = dp - n; + if ((fl & STBSP__TRIPLET_COMMA) == 0) { + while (n) { + if ((((stbsp__uintptr)s) & 3) == 0) + break; + *s++ = '0'; + --n; + } + while (n >= 4) { + *(stbsp__uint32 *)s = 0x30303030; + s += 4; + n -= 4; + } + } + while (n) { + if ((fl & STBSP__TRIPLET_COMMA) && (++cs == 4)) { + cs = 0; + *s++ = stbsp__comma; + } + else { + *s++ = '0'; + --n; + } + } + } + cs = (int)(s - (num + 64)) + (3 << 24); // cs is how many tens + if (pr) { + *s++ = stbsp__period; + tz = pr; + } + } + else { + // handle xxxxx.xxxx000*000 + n = 0; + for (;;) { + if ((fl & STBSP__TRIPLET_COMMA) && (++cs == 4)) { + cs = 0; + *s++ = stbsp__comma; + } + else { + *s++ = sn[n]; + ++n; + if (n >= (stbsp__uint32)dp) + break; + } + } + cs = (int)(s - (num + 64)) + (3 << 24); // cs is how many tens + if (pr) + *s++ = stbsp__period; + if ((l - dp) > (stbsp__uint32)pr) + l = pr + dp; + while (n < l) { + *s++ = sn[n]; + ++n; + } + tz = pr - (l - dp); + } + } + pr = 0; + + // handle k,m,g,t + if (fl & STBSP__METRIC_SUFFIX) { + char idx; + idx = 1; + if (fl & STBSP__METRIC_NOSPACE) + idx = 0; + tail[0] = idx; + tail[1] = ' '; + { + if (fl >> 24) { // SI kilo is 'k', JEDEC and SI kibits are 'K'. + if (fl & STBSP__METRIC_1024) + tail[idx + 1] = "_KMGT"[fl >> 24]; + else + tail[idx + 1] = "_kMGT"[fl >> 24]; + idx++; + // If printing kibits and not in jedec, add the 'i'. + if (fl & STBSP__METRIC_1024 && !(fl & STBSP__METRIC_JEDEC)) { + tail[idx + 1] = 'i'; + idx++; + } + tail[0] = idx; + } + } + }; + + flt_lead: + // get the length that we copied + l = (stbsp__uint32)(s - (num + 64)); + s = num + 64; + goto scopy; +#endif + + case 'B': // upper binary + case 'b': // lower binary + h = (f[0] == 'B') ? hexu : hex; + lead[0] = 0; + if (fl & STBSP__LEADING_0X) { + lead[0] = 2; + lead[1] = '0'; + lead[2] = h[0xb]; + } + l = (8 << 4) | (1 << 8); + goto radixnum; + + case 'o': // octal + h = hexu; + lead[0] = 0; + if (fl & STBSP__LEADING_0X) { + lead[0] = 1; + lead[1] = '0'; + } + l = (3 << 4) | (3 << 8); + goto radixnum; + + case 'p': // pointer + fl |= (sizeof(void *) == 8) ? STBSP__INTMAX : 0; + pr = sizeof(void *) * 2; + fl &= ~STBSP__LEADINGZERO; // 'p' only prints the pointer with zeros + // fall through - to X + + case 'X': // upper hex + case 'x': // lower hex + h = (f[0] == 'X') ? hexu : hex; + l = (4 << 4) | (4 << 8); + lead[0] = 0; + if (fl & STBSP__LEADING_0X) { + lead[0] = 2; + lead[1] = '0'; + lead[2] = h[16]; + } + radixnum: + // get the number + if (fl & STBSP__INTMAX) + n64 = va_arg(va, stbsp__uint64); + else + n64 = va_arg(va, stbsp__uint32); + + s = num + STBSP__NUMSZ; + dp = 0; + // clear tail, and clear leading if value is zero + tail[0] = 0; + if (n64 == 0) { + lead[0] = 0; + if (pr == 0) { + l = 0; + cs = 0; + goto scopy; + } + } + // convert to string + for (;;) { + *--s = h[n64 & ((1 << (l >> 8)) - 1)]; + n64 >>= (l >> 8); + if (!((n64) || ((stbsp__int32)((num + STBSP__NUMSZ) - s) < pr))) + break; + if (fl & STBSP__TRIPLET_COMMA) { + ++l; + if ((l & 15) == ((l >> 4) & 15)) { + l &= ~15; + *--s = stbsp__comma; + } + } + }; + // get the tens and the comma pos + cs = (stbsp__uint32)((num + STBSP__NUMSZ) - s) + ((((l >> 4) & 15)) << 24); + // get the length that we copied + l = (stbsp__uint32)((num + STBSP__NUMSZ) - s); + // copy it + goto scopy; + + case 'u': // unsigned + case 'i': + case 'd': // integer + // get the integer and abs it + if (fl & STBSP__INTMAX) { + stbsp__int64 i64 = va_arg(va, stbsp__int64); + n64 = (stbsp__uint64)i64; + if ((f[0] != 'u') && (i64 < 0)) { + n64 = (stbsp__uint64)-i64; + fl |= STBSP__NEGATIVE; + } + } + else { + stbsp__int32 i = va_arg(va, stbsp__int32); + n64 = (stbsp__uint32)i; + if ((f[0] != 'u') && (i < 0)) { + n64 = (stbsp__uint32)-i; + fl |= STBSP__NEGATIVE; + } + } + +#ifndef STB_SPRINTF_NOFLOAT + if (fl & STBSP__METRIC_SUFFIX) { + if (n64 < 1024) + pr = 0; + else if (pr == -1) + pr = 1; + fv = (double)(stbsp__int64)n64; + goto doafloat; + } +#endif + + // convert to string + s = num + STBSP__NUMSZ; + l = 0; + + for (;;) { + // do in 32-bit chunks (avoid lots of 64-bit divides even with constant denominators) + char *o = s - 8; + if (n64 >= 100000000) { + n = (stbsp__uint32)(n64 % 100000000); + n64 /= 100000000; + } + else { + n = (stbsp__uint32)n64; + n64 = 0; + } + if ((fl & STBSP__TRIPLET_COMMA) == 0) { + do { + s -= 2; + *(stbsp__uint16 *)s = *(stbsp__uint16 *)&stbsp__digitpair.pair[(n % 100) * 2]; + n /= 100; + } while (n); + } + while (n) { + if ((fl & STBSP__TRIPLET_COMMA) && (l++ == 3)) { + l = 0; + *--s = stbsp__comma; + --o; + } + else { + *--s = (char)(n % 10) + '0'; + n /= 10; + } + } + if (n64 == 0) { + if ((s[0] == '0') && (s != (num + STBSP__NUMSZ))) + ++s; + break; + } + while (s != o) + if ((fl & STBSP__TRIPLET_COMMA) && (l++ == 3)) { + l = 0; + *--s = stbsp__comma; + --o; + } + else { + *--s = '0'; + } + } + + tail[0] = 0; + stbsp__lead_sign(fl, lead); + + // get the length that we copied + l = (stbsp__uint32)((num + STBSP__NUMSZ) - s); + if (l == 0) { + *--s = '0'; + l = 1; + } + cs = l + (3 << 24); + if (pr < 0) + pr = 0; + + scopy: + // get fw=leading/trailing space, pr=leading zeros + if (pr < (stbsp__int32)l) + pr = l; + n = pr + lead[0] + tail[0] + tz; + if (fw < (stbsp__int32)n) + fw = n; + fw -= n; + pr -= l; + + // handle right justify and leading zeros + if ((fl & STBSP__LEFTJUST) == 0) { + if (fl & STBSP__LEADINGZERO) // if leading zeros, everything is in pr + { + pr = (fw > pr) ? fw : pr; + fw = 0; + } + else { + fl &= ~STBSP__TRIPLET_COMMA; // if no leading zeros, then no commas + } + } + + // copy the spaces and/or zeros + if (fw + pr) { + stbsp__int32 i; + stbsp__uint32 c; + + // copy leading spaces (or when doing %8.4d stuff) + if ((fl & STBSP__LEFTJUST) == 0) + while (fw > 0) { + stbsp__cb_buf_clamp(i, fw); + fw -= i; + while (i) { + if ((((stbsp__uintptr)bf) & 3) == 0) + break; + *bf++ = ' '; + --i; + } + while (i >= 4) { + *(stbsp__uint32 *)bf = 0x20202020; + bf += 4; + i -= 4; + } + while (i) { + *bf++ = ' '; + --i; + } + stbsp__chk_cb_buf(1); + } + + // copy leader + sn = lead + 1; + while (lead[0]) { + stbsp__cb_buf_clamp(i, lead[0]); + lead[0] -= (char)i; + while (i) { + *bf++ = *sn++; + --i; + } + stbsp__chk_cb_buf(1); + } + + // copy leading zeros + c = cs >> 24; + cs &= 0xffffff; + cs = (fl & STBSP__TRIPLET_COMMA) ? ((stbsp__uint32)(c - ((pr + cs) % (c + 1)))) : 0; + while (pr > 0) { + stbsp__cb_buf_clamp(i, pr); + pr -= i; + if ((fl & STBSP__TRIPLET_COMMA) == 0) { + while (i) { + if ((((stbsp__uintptr)bf) & 3) == 0) + break; + *bf++ = '0'; + --i; + } + while (i >= 4) { + *(stbsp__uint32 *)bf = 0x30303030; + bf += 4; + i -= 4; + } + } + while (i) { + if ((fl & STBSP__TRIPLET_COMMA) && (cs++ == c)) { + cs = 0; + *bf++ = stbsp__comma; + } + else + *bf++ = '0'; + --i; + } + stbsp__chk_cb_buf(1); + } + } + + // copy leader if there is still one + sn = lead + 1; + while (lead[0]) { + stbsp__int32 i; + stbsp__cb_buf_clamp(i, lead[0]); + lead[0] -= (char)i; + while (i) { + *bf++ = *sn++; + --i; + } + stbsp__chk_cb_buf(1); + } + + // copy the string + n = l; + while (n) { + stbsp__int32 i; + stbsp__cb_buf_clamp(i, n); + n -= i; + STBSP__UNALIGNED(while (i >= 4) { + *(stbsp__uint32 volatile *)bf = *(stbsp__uint32 volatile *)s; + bf += 4; + s += 4; + i -= 4; + }) + while (i) { + *bf++ = *s++; + --i; + } + stbsp__chk_cb_buf(1); + } + + // copy trailing zeros + while (tz) { + stbsp__int32 i; + stbsp__cb_buf_clamp(i, tz); + tz -= i; + while (i) { + if ((((stbsp__uintptr)bf) & 3) == 0) + break; + *bf++ = '0'; + --i; + } + while (i >= 4) { + *(stbsp__uint32 *)bf = 0x30303030; + bf += 4; + i -= 4; + } + while (i) { + *bf++ = '0'; + --i; + } + stbsp__chk_cb_buf(1); + } + + // copy tail if there is one + sn = tail + 1; + while (tail[0]) { + stbsp__int32 i; + stbsp__cb_buf_clamp(i, tail[0]); + tail[0] -= (char)i; + while (i) { + *bf++ = *sn++; + --i; + } + stbsp__chk_cb_buf(1); + } + + // handle the left justify + if (fl & STBSP__LEFTJUST) + if (fw > 0) { + while (fw) { + stbsp__int32 i; + stbsp__cb_buf_clamp(i, fw); + fw -= i; + while (i) { + if ((((stbsp__uintptr)bf) & 3) == 0) + break; + *bf++ = ' '; + --i; + } + while (i >= 4) { + *(stbsp__uint32 *)bf = 0x20202020; + bf += 4; + i -= 4; + } + while (i--) + *bf++ = ' '; + stbsp__chk_cb_buf(1); + } + } + break; + + default: // unknown, just copy code + s = num + STBSP__NUMSZ - 1; + *s = f[0]; + l = 1; + fw = fl = 0; + lead[0] = 0; + tail[0] = 0; + pr = 0; + dp = 0; + cs = 0; + goto scopy; + } + ++f; + } +endfmt: + + if (!callback) + *bf = 0; + else + stbsp__flush_cb(); + +done: + return tlen + (int)(bf - buf); +} + +// cleanup +#undef STBSP__LEFTJUST +#undef STBSP__LEADINGPLUS +#undef STBSP__LEADINGSPACE +#undef STBSP__LEADING_0X +#undef STBSP__LEADINGZERO +#undef STBSP__INTMAX +#undef STBSP__TRIPLET_COMMA +#undef STBSP__NEGATIVE +#undef STBSP__METRIC_SUFFIX +#undef STBSP__NUMSZ +#undef stbsp__chk_cb_bufL +#undef stbsp__chk_cb_buf +#undef stbsp__flush_cb +#undef stbsp__cb_buf_clamp + +// ============================================================================ +// wrapper functions + +STBSP__PUBLICDEF int STB_SPRINTF_DECORATE(sprintf)(char *buf, char const *fmt, ...) { + int result; + va_list va; + va_start(va, fmt); + result = STB_SPRINTF_DECORATE(vsprintfcb)(0, 0, buf, fmt, va); + va_end(va); + return result; +} + +typedef struct stbsp__context { + char *buf; + int count; + int length; + char tmp[STB_SPRINTF_MIN]; +} stbsp__context; + +static char *stbsp__clamp_callback(const char *buf, void *user, int len) { + stbsp__context *c = (stbsp__context *)user; + c->length += len; + + if (len > c->count) + len = c->count; + + if (len) { + if (buf != c->buf) { + const char *s, *se; + char *d; + d = c->buf; + s = buf; + se = buf + len; + do { + *d++ = *s++; + } while (s < se); + } + c->buf += len; + c->count -= len; + } + + if (c->count <= 0) + return c->tmp; + return (c->count >= STB_SPRINTF_MIN) ? c->buf : c->tmp; // go direct into buffer if you can +} + +static char *stbsp__count_clamp_callback(const char *buf, void *user, int len) { + stbsp__context *c = (stbsp__context *)user; + (void)sizeof(buf); + + c->length += len; + return c->tmp; // go direct into buffer if you can +} + +STBSP__PUBLICDEF int STB_SPRINTF_DECORATE(vsnprintf)(char *buf, int count, char const *fmt, va_list va) { + stbsp__context c; + + if ((count == 0) && !buf) { + c.length = 0; + + STB_SPRINTF_DECORATE(vsprintfcb) + (stbsp__count_clamp_callback, &c, c.tmp, fmt, va); + } + else { + int l; + + c.buf = buf; + c.count = count; + c.length = 0; + + STB_SPRINTF_DECORATE(vsprintfcb) + (stbsp__clamp_callback, &c, stbsp__clamp_callback(0, &c, 0), fmt, va); + + // zero-terminate + l = (int)(c.buf - buf); + if (l >= count) // should never be greater, only equal (or less) than count + l = count - 1; + buf[l] = 0; + } + + return c.length; +} + +STBSP__PUBLICDEF int STB_SPRINTF_DECORATE(snprintf)(char *buf, int count, char const *fmt, ...) { + int result; + va_list va; + va_start(va, fmt); + + result = STB_SPRINTF_DECORATE(vsnprintf)(buf, count, fmt, va); + va_end(va); + + return result; +} + +STBSP__PUBLICDEF int STB_SPRINTF_DECORATE(vsprintf)(char *buf, char const *fmt, va_list va) { + return STB_SPRINTF_DECORATE(vsprintfcb)(0, 0, buf, fmt, va); +} + +// ======================================================================= +// low level float utility functions + +#ifndef STB_SPRINTF_NOFLOAT + + // copies d to bits w/ strict aliasing (this compiles to nothing on /Ox) + #define STBSP__COPYFP(dest, src) \ + { \ + int cn; \ + for (cn = 0; cn < 8; cn++) \ + ((char *)&dest)[cn] = ((char *)&src)[cn]; \ + } + +// get float info +static stbsp__int32 stbsp__real_to_parts(stbsp__int64 *bits, stbsp__int32 *expo, double value) { + double d; + stbsp__int64 b = 0; + + // load value and round at the frac_digits + d = value; + + STBSP__COPYFP(b, d); + + *bits = b & ((((stbsp__uint64)1) << 52) - 1); + *expo = (stbsp__int32)(((b >> 52) & 2047) - 1023); + + return (stbsp__int32)((stbsp__uint64)b >> 63); +} + +static double const stbsp__bot[23] = { + 1e+000, 1e+001, 1e+002, 1e+003, 1e+004, 1e+005, 1e+006, 1e+007, 1e+008, 1e+009, 1e+010, 1e+011, + 1e+012, 1e+013, 1e+014, 1e+015, 1e+016, 1e+017, 1e+018, 1e+019, 1e+020, 1e+021, 1e+022}; +static double const stbsp__negbot[22] = { + 1e-001, 1e-002, 1e-003, 1e-004, 1e-005, 1e-006, 1e-007, 1e-008, 1e-009, 1e-010, 1e-011, + 1e-012, 1e-013, 1e-014, 1e-015, 1e-016, 1e-017, 1e-018, 1e-019, 1e-020, 1e-021, 1e-022}; +static double const stbsp__negboterr[22] = { + -5.551115123125783e-018, -2.0816681711721684e-019, -2.0816681711721686e-020, -4.7921736023859299e-021, -8.1803053914031305e-022, 4.5251888174113741e-023, + 4.5251888174113739e-024, -2.0922560830128471e-025, -6.2281591457779853e-026, -3.6432197315497743e-027, 6.0503030718060191e-028, 2.0113352370744385e-029, + -3.0373745563400371e-030, 1.1806906454401013e-032, -7.7705399876661076e-032, 2.0902213275965398e-033, -7.1542424054621921e-034, -7.1542424054621926e-035, + 2.4754073164739869e-036, 5.4846728545790429e-037, 9.2462547772103625e-038, -4.8596774326570872e-039}; +static double const stbsp__top[13] = { + 1e+023, 1e+046, 1e+069, 1e+092, 1e+115, 1e+138, 1e+161, 1e+184, 1e+207, 1e+230, 1e+253, 1e+276, 1e+299}; +static double const stbsp__negtop[13] = { + 1e-023, 1e-046, 1e-069, 1e-092, 1e-115, 1e-138, 1e-161, 1e-184, 1e-207, 1e-230, 1e-253, 1e-276, 1e-299}; +static double const stbsp__toperr[13] = { + 8388608, + 6.8601809640529717e+028, + -7.253143638152921e+052, + -4.3377296974619174e+075, + -1.5559416129466825e+098, + -3.2841562489204913e+121, + -3.7745893248228135e+144, + -1.7356668416969134e+167, + -3.8893577551088374e+190, + -9.9566444326005119e+213, + 6.3641293062232429e+236, + -5.2069140800249813e+259, + -5.2504760255204387e+282}; +static double const stbsp__negtoperr[13] = { + 3.9565301985100693e-040, -2.299904345391321e-063, 3.6506201437945798e-086, 1.1875228833981544e-109, + -5.0644902316928607e-132, -6.7156837247865426e-155, -2.812077463003139e-178, -5.7778912386589953e-201, + 7.4997100559334532e-224, -4.6439668915134491e-247, -6.3691100762962136e-270, -9.436808465446358e-293, + 8.0970921678014997e-317}; + + #if defined(_MSC_VER) && (_MSC_VER <= 1200) +static stbsp__uint64 const stbsp__powten[20] = { + 1, + 10, + 100, + 1000, + 10000, + 100000, + 1000000, + 10000000, + 100000000, + 1000000000, + 10000000000, + 100000000000, + 1000000000000, + 10000000000000, + 100000000000000, + 1000000000000000, + 10000000000000000, + 100000000000000000, + 1000000000000000000, + 10000000000000000000U}; + #define stbsp__tento19th ((stbsp__uint64)1000000000000000000) + #else +static stbsp__uint64 const stbsp__powten[20] = { + 1, + 10, + 100, + 1000, + 10000, + 100000, + 1000000, + 10000000, + 100000000, + 1000000000, + 10000000000ULL, + 100000000000ULL, + 1000000000000ULL, + 10000000000000ULL, + 100000000000000ULL, + 1000000000000000ULL, + 10000000000000000ULL, + 100000000000000000ULL, + 1000000000000000000ULL, + 10000000000000000000ULL}; + #define stbsp__tento19th (1000000000000000000ULL) + #endif + + #define stbsp__ddmulthi(oh, ol, xh, yh) \ + { \ + double ahi = 0, alo, bhi = 0, blo; \ + stbsp__int64 bt; \ + oh = xh * yh; \ + STBSP__COPYFP(bt, xh); \ + bt &= ((~(stbsp__uint64)0) << 27); \ + STBSP__COPYFP(ahi, bt); \ + alo = xh - ahi; \ + STBSP__COPYFP(bt, yh); \ + bt &= ((~(stbsp__uint64)0) << 27); \ + STBSP__COPYFP(bhi, bt); \ + blo = yh - bhi; \ + ol = ((ahi * bhi - oh) + ahi * blo + alo * bhi) + alo * blo; \ + } + + #define stbsp__ddtoS64(ob, xh, xl) \ + { \ + double ahi = 0, alo, vh, t; \ + ob = (stbsp__int64)xh; \ + vh = (double)ob; \ + ahi = (xh - vh); \ + t = (ahi - xh); \ + alo = (xh - (ahi - t)) - (vh + t); \ + ob += (stbsp__int64)(ahi + alo + xl); \ + } + + #define stbsp__ddrenorm(oh, ol) \ + { \ + double s; \ + s = oh + ol; \ + ol = ol - (s - oh); \ + oh = s; \ + } + + #define stbsp__ddmultlo(oh, ol, xh, xl, yh, yl) ol = ol + (xh * yl + xl * yh); + + #define stbsp__ddmultlos(oh, ol, xh, yl) ol = ol + (xh * yl); + +static void stbsp__raise_to_power10(double *ohi, double *olo, double d, stbsp__int32 power) // power can be -323 to +350 +{ + double ph, pl; + if ((power >= 0) && (power <= 22)) { + stbsp__ddmulthi(ph, pl, d, stbsp__bot[power]); + } + else { + stbsp__int32 e, et, eb; + double p2h, p2l; + + e = power; + if (power < 0) + e = -e; + et = (e * 0x2c9) >> 14; /* %23 */ + if (et > 13) + et = 13; + eb = e - (et * 23); + + ph = d; + pl = 0.0; + if (power < 0) { + if (eb) { + --eb; + stbsp__ddmulthi(ph, pl, d, stbsp__negbot[eb]); + stbsp__ddmultlos(ph, pl, d, stbsp__negboterr[eb]); + } + if (et) { + stbsp__ddrenorm(ph, pl); + --et; + stbsp__ddmulthi(p2h, p2l, ph, stbsp__negtop[et]); + stbsp__ddmultlo(p2h, p2l, ph, pl, stbsp__negtop[et], stbsp__negtoperr[et]); + ph = p2h; + pl = p2l; + } + } + else { + if (eb) { + e = eb; + if (eb > 22) + eb = 22; + e -= eb; + stbsp__ddmulthi(ph, pl, d, stbsp__bot[eb]); + if (e) { + stbsp__ddrenorm(ph, pl); + stbsp__ddmulthi(p2h, p2l, ph, stbsp__bot[e]); + stbsp__ddmultlos(p2h, p2l, stbsp__bot[e], pl); + ph = p2h; + pl = p2l; + } + } + if (et) { + stbsp__ddrenorm(ph, pl); + --et; + stbsp__ddmulthi(p2h, p2l, ph, stbsp__top[et]); + stbsp__ddmultlo(p2h, p2l, ph, pl, stbsp__top[et], stbsp__toperr[et]); + ph = p2h; + pl = p2l; + } + } + } + stbsp__ddrenorm(ph, pl); + *ohi = ph; + *olo = pl; +} + +// given a float value, returns the significant bits in bits, and the position of the +// decimal point in decimal_pos. +/-INF and NAN are specified by special values +// returned in the decimal_pos parameter. +// frac_digits is absolute normally, but if you want from first significant digits (got %g and %e), or in 0x80000000 +static stbsp__int32 stbsp__real_to_str(char const **start, stbsp__uint32 *len, char *out, stbsp__int32 *decimal_pos, double value, stbsp__uint32 frac_digits) { + double d; + stbsp__int64 bits = 0; + stbsp__int32 expo, e, ng, tens; + + d = value; + STBSP__COPYFP(bits, d); + expo = (stbsp__int32)((bits >> 52) & 2047); + ng = (stbsp__int32)((stbsp__uint64)bits >> 63); + if (ng) + d = -d; + + if (expo == 2047) // is nan or inf? + { + *start = (bits & ((((stbsp__uint64)1) << 52) - 1)) ? "NaN" : "Inf"; + *decimal_pos = STBSP__SPECIAL; + *len = 3; + return ng; + } + + if (expo == 0) // is zero or denormal + { + if (((stbsp__uint64)bits << 1) == 0) // do zero + { + *decimal_pos = 1; + *start = out; + out[0] = '0'; + *len = 1; + return ng; + } + // find the right expo for denormals + { + stbsp__int64 v = ((stbsp__uint64)1) << 51; + while ((bits & v) == 0) { + --expo; + v >>= 1; + } + } + } + + // find the decimal exponent as well as the decimal bits of the value + { + double ph, pl; + + // log10 estimate - very specifically tweaked to hit or undershoot by no more than 1 of log10 of all expos 1..2046 + tens = expo - 1023; + tens = (tens < 0) ? ((tens * 617) / 2048) : (((tens * 1233) / 4096) + 1); + + // move the significant bits into position and stick them into an int + stbsp__raise_to_power10(&ph, &pl, d, 18 - tens); + + // get full as much precision from double-double as possible + stbsp__ddtoS64(bits, ph, pl); + + // check if we undershot + if (((stbsp__uint64)bits) >= stbsp__tento19th) + ++tens; + } + + // now do the rounding in integer land + frac_digits = (frac_digits & 0x80000000) ? ((frac_digits & 0x7ffffff) + 1) : (tens + frac_digits); + if ((frac_digits < 24)) { + stbsp__uint32 dg = 1; + if ((stbsp__uint64)bits >= stbsp__powten[9]) + dg = 10; + while ((stbsp__uint64)bits >= stbsp__powten[dg]) { + ++dg; + if (dg == 20) + goto noround; + } + if (frac_digits < dg) { + stbsp__uint64 r; + // add 0.5 at the right position and round + e = dg - frac_digits; + if ((stbsp__uint32)e >= 24) + goto noround; + r = stbsp__powten[e]; + bits = bits + (r / 2); + if ((stbsp__uint64)bits >= stbsp__powten[dg]) + ++tens; + bits /= r; + } + noround:; + } + + // kill long trailing runs of zeros + if (bits) { + stbsp__uint32 n; + for (;;) { + if (bits <= 0xffffffff) + break; + if (bits % 1000) + goto donez; + bits /= 1000; + } + n = (stbsp__uint32)bits; + while ((n % 1000) == 0) + n /= 1000; + bits = n; + donez:; + } + + // convert to string + out += 64; + e = 0; + for (;;) { + stbsp__uint32 n; + char *o = out - 8; + // do the conversion in chunks of U32s (avoid most 64-bit divides, worth it, constant denomiators be damned) + if (bits >= 100000000) { + n = (stbsp__uint32)(bits % 100000000); + bits /= 100000000; + } + else { + n = (stbsp__uint32)bits; + bits = 0; + } + while (n) { + out -= 2; + *(stbsp__uint16 *)out = *(stbsp__uint16 *)&stbsp__digitpair.pair[(n % 100) * 2]; + n /= 100; + e += 2; + } + if (bits == 0) { + if ((e) && (out[0] == '0')) { + ++out; + --e; + } + break; + } + while (out != o) { + *--out = '0'; + ++e; + } + } + + *decimal_pos = tens; + *start = out; + *len = e; + return ng; +} + + #undef stbsp__ddmulthi + #undef stbsp__ddrenorm + #undef stbsp__ddmultlo + #undef stbsp__ddmultlos + #undef STBSP__SPECIAL + #undef STBSP__COPYFP + +#endif // STB_SPRINTF_NOFLOAT + +// clean up +#undef stbsp__uint16 +#undef stbsp__uint32 +#undef stbsp__int32 +#undef stbsp__uint64 +#undef stbsp__int64 +#undef STBSP__UNALIGNED diff --git a/src/standalone_libraries/stb_sprintf.h b/src/standalone_libraries/stb_sprintf.h new file mode 100644 index 0000000..0300e84 --- /dev/null +++ b/src/standalone_libraries/stb_sprintf.h @@ -0,0 +1,262 @@ +// stb_sprintf - v1.10 - public domain snprintf() implementation +// originally by Jeff Roberts / RAD Game Tools, 2015/10/20 +// http://github.com/nothings/stb +// +// allowed types: sc uidBboXx p AaGgEef n +// lengths : hh h ll j z t I64 I32 I +// +// Contributors: +// Fabian "ryg" Giesen (reformatting) +// github:aganm (attribute format) +// +// Contributors (bugfixes): +// github:d26435 +// github:trex78 +// github:account-login +// Jari Komppa (SI suffixes) +// Rohit Nirmal +// Marcin Wojdyr +// Leonard Ritter +// Stefano Zanotti +// Adam Allison +// Arvid Gerstmann +// Markus Kolb +// +// LICENSE: +// +// See end of file for license information. + +#ifndef STB_SPRINTF_H_INCLUDE + #define STB_SPRINTF_H_INCLUDE + #include +/* +Single file sprintf replacement. + +Originally written by Jeff Roberts at RAD Game Tools - 2015/10/20. +Hereby placed in public domain. + +This is a full sprintf replacement that supports everything that +the C runtime sprintfs support, including float/double, 64-bit integers, +hex floats, field parameters (%*.*d stuff), length reads backs, etc. + +Why would you need this if sprintf already exists? Well, first off, +it's *much* faster (see below). It's also much smaller than the CRT +versions code-space-wise. We've also added some simple improvements +that are super handy (commas in thousands, callbacks at buffer full, +for example). Finally, the format strings for MSVC and GCC differ +for 64-bit integers (among other small things), so this lets you use +the same format strings in cross platform code. + +It uses the standard single file trick of being both the header file +and the source itself. If you just include it normally, you just get +the header file function definitions. To get the code, you include +it from a C or C++ file and define STB_SPRINTF_IMPLEMENTATION first. + +It only uses va_args macros from the C runtime to do it's work. It +does cast doubles to S64s and shifts and divides U64s, which does +drag in CRT code on most platforms. + +It compiles to roughly 8K with float support, and 4K without. +As a comparison, when using MSVC static libs, calling sprintf drags +in 16K. + +API: +==== +int stbsp_sprintf( char * buf, char const * fmt, ... ) +int stbsp_snprintf( char * buf, int count, char const * fmt, ... ) + Convert an arg list into a buffer. stbsp_snprintf always returns + a zero-terminated string (unlike regular snprintf). + +int stbsp_vsprintf( char * buf, char const * fmt, va_list va ) +int stbsp_vsnprintf( char * buf, int count, char const * fmt, va_list va ) + Convert a va_list arg list into a buffer. stbsp_vsnprintf always returns + a zero-terminated string (unlike regular snprintf). + +int stbsp_vsprintfcb( STBSP_SPRINTFCB * callback, void * user, char * buf, char const * fmt, va_list va ) + typedef char * STBSP_SPRINTFCB( char const * buf, void * user, int len ); + Convert into a buffer, calling back every STB_SPRINTF_MIN chars. + Your callback can then copy the chars out, print them or whatever. + This function is actually the workhorse for everything else. + The buffer you pass in must hold at least STB_SPRINTF_MIN characters. + // you return the next buffer to use or 0 to stop converting + +void stbsp_set_separators( char comma, char period ) + Set the comma and period characters to use. + +FLOATS/DOUBLES: +=============== +This code uses a internal float->ascii conversion method that uses +doubles with error correction (double-doubles, for ~105 bits of +precision). This conversion is round-trip perfect - that is, an atof +of the values output here will give you the bit-exact double back. + +One difference is that our insignificant digits will be different than +with MSVC or GCC (but they don't match each other either). We also +don't attempt to find the minimum length matching float (pre-MSVC15 +doesn't either). + +If you don't need float or doubles at all, define STB_SPRINTF_NOFLOAT +and you'll save 4K of code space. + +64-BIT INTS: +============ +This library also supports 64-bit integers and you can use MSVC style or +GCC style indicators (%I64d or %lld). It supports the C99 specifiers +for size_t and ptr_diff_t (%jd %zd) as well. + +EXTRAS: +======= +Like some GCCs, for integers and floats, you can use a ' (single quote) +specifier and commas will be inserted on the thousands: "%'d" on 12345 +would print 12,345. + +For integers and floats, you can use a "$" specifier and the number +will be converted to float and then divided to get kilo, mega, giga or +tera and then printed, so "%$d" 1000 is "1.0 k", "%$.2d" 2536000 is +"2.53 M", etc. For byte values, use two $:s, like "%$$d" to turn +2536000 to "2.42 Mi". If you prefer JEDEC suffixes to SI ones, use three +$:s: "%$$$d" -> "2.42 M". To remove the space between the number and the +suffix, add "_" specifier: "%_$d" -> "2.53M". + +In addition to octal and hexadecimal conversions, you can print +integers in binary: "%b" for 256 would print 100. + +PERFORMANCE vs MSVC 2008 32-/64-bit (GCC is even slower than MSVC): +=================================================================== +"%d" across all 32-bit ints (4.8x/4.0x faster than 32-/64-bit MSVC) +"%24d" across all 32-bit ints (4.5x/4.2x faster) +"%x" across all 32-bit ints (4.5x/3.8x faster) +"%08x" across all 32-bit ints (4.3x/3.8x faster) +"%f" across e-10 to e+10 floats (7.3x/6.0x faster) +"%e" across e-10 to e+10 floats (8.1x/6.0x faster) +"%g" across e-10 to e+10 floats (10.0x/7.1x faster) +"%f" for values near e-300 (7.9x/6.5x faster) +"%f" for values near e+300 (10.0x/9.1x faster) +"%e" for values near e-300 (10.1x/7.0x faster) +"%e" for values near e+300 (9.2x/6.0x faster) +"%.320f" for values near e-300 (12.6x/11.2x faster) +"%a" for random values (8.6x/4.3x faster) +"%I64d" for 64-bits with 32-bit values (4.8x/3.4x faster) +"%I64d" for 64-bits > 32-bit values (4.9x/5.5x faster) +"%s%s%s" for 64 char strings (7.1x/7.3x faster) +"...512 char string..." ( 35.0x/32.5x faster!) +*/ + + #if defined(__clang__) + #if defined(__has_feature) && defined(__has_attribute) + #if __has_feature(address_sanitizer) + #if __has_attribute(__no_sanitize__) + #define STBSP__ASAN __attribute__((__no_sanitize__("address"))) + #elif __has_attribute(__no_sanitize_address__) + #define STBSP__ASAN __attribute__((__no_sanitize_address__)) + #elif __has_attribute(__no_address_safety_analysis__) + #define STBSP__ASAN __attribute__((__no_address_safety_analysis__)) + #endif + #endif + #endif + #elif defined(__GNUC__) && (__GNUC__ >= 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)) + #if defined(__SANITIZE_ADDRESS__) && __SANITIZE_ADDRESS__ + #define STBSP__ASAN __attribute__((__no_sanitize_address__)) + #endif + #elif defined(_MSC_VER) + #ifdef __SANITIZE_ADDRESS__ + #define STBSP__ASAN __declspec(no_sanitize_address) + #endif + #endif + + #ifndef STBSP__ASAN + #define STBSP__ASAN + #endif + + #ifdef STB_SPRINTF_STATIC + #define STBSP__PUBLICDEC static + #define STBSP__PUBLICDEF static STBSP__ASAN + #else + #ifdef __cplusplus + #define STBSP__PUBLICDEC extern "C" + #define STBSP__PUBLICDEF extern "C" STBSP__ASAN + #else + #define STBSP__PUBLICDEC extern + #define STBSP__PUBLICDEF STBSP__ASAN + #endif + #endif + + #if defined(__has_attribute) + #if __has_attribute(format) + #define STBSP__ATTRIBUTE_FORMAT(fmt, va) __attribute__((format(printf, fmt, va))) + #endif + #endif + + #ifndef STBSP__ATTRIBUTE_FORMAT + #define STBSP__ATTRIBUTE_FORMAT(fmt, va) + #endif + + #ifdef _MSC_VER + #define STBSP__NOTUSED(v) (void)(v) + #else + #define STBSP__NOTUSED(v) (void)sizeof(v) + #endif + + #include // for va_arg(), va_list() + #include // size_t, ptrdiff_t + + #ifndef STB_SPRINTF_MIN + #define STB_SPRINTF_MIN 512 // how many characters per callback + #endif +typedef char *STBSP_SPRINTFCB(const char *buf, void *user, int len); + + #ifndef STB_SPRINTF_DECORATE + #define STB_SPRINTF_DECORATE(name) stbsp_##name // define this before including if you want to change the names + #endif + +STBSP__PUBLICDEC int STB_SPRINTF_DECORATE(vsprintf)(char *buf, char const *fmt, va_list va); +STBSP__PUBLICDEC int STB_SPRINTF_DECORATE(vsnprintf)(char *buf, int count, char const *fmt, va_list va); +STBSP__PUBLICDEC int STB_SPRINTF_DECORATE(sprintf)(char *buf, char const *fmt, ...) STBSP__ATTRIBUTE_FORMAT(2, 3); +STBSP__PUBLICDEC int STB_SPRINTF_DECORATE(snprintf)(char *buf, int count, char const *fmt, ...) STBSP__ATTRIBUTE_FORMAT(3, 4); + +STBSP__PUBLICDEC int STB_SPRINTF_DECORATE(vsprintfcb)(STBSP_SPRINTFCB *callback, void *user, char *buf, char const *fmt, va_list va); +STBSP__PUBLICDEC void STB_SPRINTF_DECORATE(set_separators)(char comma, char period); + +#endif // STB_SPRINTF_H_INCLUDE + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/src/standalone_libraries/string.c b/src/standalone_libraries/string.c new file mode 100644 index 0000000..a9ab569 --- /dev/null +++ b/src/standalone_libraries/string.c @@ -0,0 +1,566 @@ +#include "string.h" +#include + +#ifndef S8_VSNPRINTF + #include + #define S8_VSNPRINTF vsnprintf +#endif + +#ifndef S8_ALLOCATE + #include + #define S8_ALLOCATE(allocator, size) malloc(size) +#endif + +#ifndef S8_ASSERT + #include + #define S8_ASSERT(x) assert(x) +#endif + +#ifndef S8_MemoryCopy + #include + #define S8_MemoryCopy(dst, src, s) memcpy(dst, src, s) +#endif + +#ifndef S8_StaticFunc + #if defined(__GNUC__) || defined(__clang__) + #define S8_StaticFunc __attribute__((unused)) static + #else + #define S8_StaticFunc static + #endif +#endif + +S8_StaticFunc int64_t S8__ClampTop(int64_t val, int64_t max) { + if (val > max) val = max; + return val; +} + +S8_API char CHAR_ToLowerCase(char a) { + if (a >= 'A' && a <= 'Z') a += 32; + return a; +} + +S8_API char CHAR_ToUpperCase(char a) { + if (a >= 'a' && a <= 'z') a -= 32; + return a; +} + +S8_API bool CHAR_IsWhitespace(char w) { + bool result = w == '\n' || w == ' ' || w == '\t' || w == '\v' || w == '\r'; + return result; +} + +S8_API bool CHAR_IsAlphabetic(char a) { + bool result = (a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z'); + return result; +} + +S8_API bool CHAR_IsIdent(char a) { + bool result = (a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z') || a == '_'; + return result; +} + +S8_API bool CHAR_IsDigit(char a) { + bool result = a >= '0' && a <= '9'; + return result; +} + +S8_API bool CHAR_IsAlphanumeric(char a) { + bool result = CHAR_IsDigit(a) || CHAR_IsAlphabetic(a); + return result; +} + +S8_API bool S8_AreEqual(S8_String a, S8_String b, unsigned ignore_case) { + if (a.len != b.len) return false; + for (int64_t i = 0; i < a.len; i++) { + char A = a.str[i]; + char B = b.str[i]; + if (ignore_case) { + A = CHAR_ToLowerCase(A); + B = CHAR_ToLowerCase(B); + } + if (A != B) + return false; + } + return true; +} + +S8_API bool S8_EndsWith(S8_String a, S8_String end, unsigned ignore_case) { + S8_String a_end = S8_GetPostfix(a, end.len); + bool result = S8_AreEqual(end, a_end, ignore_case); + return result; +} + +S8_API bool S8_StartsWith(S8_String a, S8_String start, unsigned ignore_case) { + S8_String a_start = S8_GetPrefix(a, start.len); + bool result = S8_AreEqual(start, a_start, ignore_case); + return result; +} + +S8_API S8_String S8_Make(char *str, int64_t len) { + S8_String result; + result.str = (char *)str; + result.len = len; + return result; +} + +S8_API S8_String S8_Copy(S8_Allocator allocator, S8_String string) { + char *copy = (char *)S8_ALLOCATE(allocator, sizeof(char) * (string.len + 1)); + S8_MemoryCopy(copy, string.str, string.len); + copy[string.len] = 0; + S8_String result = S8_Make(copy, string.len); + return result; +} + +S8_API S8_String S8_CopyChar(S8_Allocator allocator, char *s) { + int64_t len = S8_Length(s); + char *copy = (char *)S8_ALLOCATE(allocator, sizeof(char) * (len + 1)); + S8_MemoryCopy(copy, s, len); + copy[len] = 0; + S8_String result = S8_Make(copy, len); + return result; +} + +S8_API S8_String S8_NormalizePath(S8_Allocator allocator, S8_String s) { + S8_String copy = S8_Copy(allocator, s); + for (int64_t i = 0; i < copy.len; i++) { + if (copy.str[i] == '\\') + copy.str[i] = '/'; + } + return copy; +} + +S8_API void S8_NormalizePathUnsafe(S8_String s) { + for (int64_t i = 0; i < s.len; i++) { + if (s.str[i] == '\\') + s.str[i] = '/'; + } +} + +S8_API S8_String S8_Chop(S8_String string, int64_t len) { + len = S8__ClampTop(len, string.len); + S8_String result = S8_Make(string.str, string.len - len); + return result; +} + +S8_API S8_String S8_Skip(S8_String string, int64_t len) { + len = S8__ClampTop(len, string.len); + int64_t remain = string.len - len; + S8_String result = S8_Make(string.str + len, remain); + return result; +} + +S8_API bool S8_IsPointerInside(S8_String string, char *p) { + uintptr_t pointer = (uintptr_t)p; + uintptr_t start = (uintptr_t)string.str; + uintptr_t stop = start + (uintptr_t)string.len; + bool result = pointer >= start && pointer < stop; + return result; +} + +S8_API S8_String S8_SkipToP(S8_String string, char *p) { + if (S8_IsPointerInside(string, p)) { + S8_String result = S8_Make(p, p - string.str); + return result; + } + return string; +} + +S8_API S8_String S8_SkipPast(S8_String string, S8_String a) { + if (S8_IsPointerInside(string, a.str)) { + S8_String on_p = S8_Make(a.str, a.str - string.str); + S8_String result = S8_Skip(on_p, a.len); + return result; + } + return string; +} + +S8_API S8_String S8_GetPostfix(S8_String string, int64_t len) { + len = S8__ClampTop(len, string.len); + int64_t remain_len = string.len - len; + S8_String result = S8_Make(string.str + remain_len, len); + return result; +} + +S8_API S8_String S8_GetPrefix(S8_String string, int64_t len) { + len = S8__ClampTop(len, string.len); + S8_String result = S8_Make(string.str, len); + return result; +} + +S8_API S8_String S8_GetNameNoExt(S8_String s) { + return S8_SkipToLastSlash(S8_ChopLastPeriod(s)); +} + +S8_API S8_String S8_Slice(S8_String string, int64_t first_index, int64_t one_past_last_index) { + if (one_past_last_index < 0) one_past_last_index = string.len + one_past_last_index + 1; + if (first_index < 0) first_index = string.len + first_index; + S8_ASSERT(first_index < one_past_last_index && "S8_Slice, first_index is bigger then one_past_last_index"); + S8_ASSERT(string.len > 0 && "Slicing string of length 0! Might be an error!"); + S8_String result = string; + if (string.len > 0) { + if (one_past_last_index > first_index) { + first_index = S8__ClampTop(first_index, string.len - 1); + one_past_last_index = S8__ClampTop(one_past_last_index, string.len); + result.str += first_index; + result.len = one_past_last_index - first_index; + } + else { + result.len = 0; + } + } + return result; +} + +S8_API S8_String S8_Trim(S8_String string) { + if (string.len == 0) + return string; + + int64_t whitespace_begin = 0; + for (; whitespace_begin < string.len; whitespace_begin++) { + if (!CHAR_IsWhitespace(string.str[whitespace_begin])) { + break; + } + } + + int64_t whitespace_end = string.len; + for (; whitespace_end != whitespace_begin; whitespace_end--) { + if (!CHAR_IsWhitespace(string.str[whitespace_end - 1])) { + break; + } + } + + if (whitespace_begin == whitespace_end) { + string.len = 0; + } + else { + string = S8_Slice(string, whitespace_begin, whitespace_end); + } + + return string; +} + +S8_API S8_String S8_TrimEnd(S8_String string) { + int64_t whitespace_end = string.len; + for (; whitespace_end != 0; whitespace_end--) { + if (!CHAR_IsWhitespace(string.str[whitespace_end - 1])) { + break; + } + } + + S8_String result = S8_GetPrefix(string, whitespace_end); + return result; +} + +S8_API S8_String S8_ToLowerCase(S8_Allocator allocator, S8_String s) { + S8_String copy = S8_Copy(allocator, s); + for (int64_t i = 0; i < copy.len; i++) { + copy.str[i] = CHAR_ToLowerCase(copy.str[i]); + } + return copy; +} + +S8_API S8_String S8_ToUpperCase(S8_Allocator allocator, S8_String s) { + S8_String copy = S8_Copy(allocator, s); + for (int64_t i = 0; i < copy.len; i++) { + copy.str[i] = CHAR_ToUpperCase(copy.str[i]); + } + return copy; +} + +S8_API bool S8_Seek(S8_String string, S8_String find, S8_FindFlag flags, int64_t *index_out) { + bool ignore_case = flags & S8_FindFlag_IgnoreCase ? true : false; + bool result = false; + if (flags & S8_FindFlag_MatchFindLast) { + for (int64_t i = string.len; i != 0; i--) { + int64_t index = i - 1; + S8_String substring = S8_Slice(string, index, index + find.len); + if (S8_AreEqual(substring, find, ignore_case)) { + if (index_out) + *index_out = index; + result = true; + break; + } + } + } + else { + for (int64_t i = 0; i < string.len; i++) { + S8_String substring = S8_Slice(string, i, i + find.len); + if (S8_AreEqual(substring, find, ignore_case)) { + if (index_out) + *index_out = i; + result = true; + break; + } + } + } + + return result; +} + +S8_API int64_t S8_Find(S8_String string, S8_String find, S8_FindFlag flag) { + int64_t result = -1; + S8_Seek(string, find, flag, &result); + return result; +} + +S8_API S8_List S8_Split(S8_Allocator allocator, S8_String string, S8_String find, S8_SplitFlag flags) { + S8_List result = S8_MakeEmptyList(); + int64_t index = 0; + + S8_FindFlag find_flag = flags & S8_SplitFlag_IgnoreCase ? S8_FindFlag_IgnoreCase : S8_FindFlag_None; + while (S8_Seek(string, find, find_flag, &index)) { + S8_String before_match = S8_Make(string.str, index); + S8_AddNode(allocator, &result, before_match); + if (flags & S8_SplitFlag_SplitInclusive) { + S8_String match = S8_Make(string.str + index, find.len); + S8_AddNode(allocator, &result, match); + } + string = S8_Skip(string, index + find.len); + } + if (string.len) S8_AddNode(allocator, &result, string); + return result; +} + +S8_API S8_String S8_MergeWithSeparator(S8_Allocator allocator, S8_List list, S8_String separator) { + if (list.node_count == 0) return S8_MakeEmpty(); + if (list.char_count == 0) return S8_MakeEmpty(); + + int64_t base_size = (list.char_count + 1); + int64_t sep_size = (list.node_count - 1) * separator.len; + int64_t size = base_size + sep_size; + char *buff = (char *)S8_ALLOCATE(allocator, sizeof(char) * (size + 1)); + S8_String string = S8_Make(buff, 0); + for (S8_Node *it = list.first; it; it = it->next) { + S8_ASSERT(string.len + it->string.len <= size); + S8_MemoryCopy(string.str + string.len, it->string.str, it->string.len); + string.len += it->string.len; + if (it != list.last) { + S8_MemoryCopy(string.str + string.len, separator.str, separator.len); + string.len += separator.len; + } + } + S8_ASSERT(string.len == size - 1); + string.str[size] = 0; + return string; +} + +S8_API S8_String S8_Merge(S8_Allocator allocator, S8_List list) { + return S8_MergeWithSeparator(allocator, list, S8_Lit("")); +} + +S8_API S8_String S8_ReplaceAll(S8_Allocator allocator, S8_String string, S8_String replace, S8_String with, bool ignore_case) { + S8_SplitFlag split_flag = ignore_case ? S8_SplitFlag_IgnoreCase : S8_SplitFlag_None; + S8_List list = S8_Split(allocator, string, replace, split_flag | S8_SplitFlag_SplitInclusive); + for (S8_Node *it = list.first; it; it = it->next) { + if (S8_AreEqual(it->string, replace, ignore_case)) { + S8_ReplaceNodeString(&list, it, with); + } + } + S8_String result = S8_Merge(allocator, list); + return result; +} + +S8_API S8_List S8_FindAll(S8_Allocator allocator, S8_String string, S8_String find, bool ignore_case) { // @untested + S8_List result = S8_MakeEmptyList(); + int64_t index = 0; + + S8_FindFlag find_flag = ignore_case ? S8_FindFlag_IgnoreCase : 0; + while (S8_Seek(string, find, find_flag, &index)) { + S8_String match = S8_Make(string.str + index, find.len); + S8_AddNode(allocator, &result, match); + string = S8_Skip(string, index + find.len); + } + return result; +} + +S8_API S8_String S8_ChopLastSlash(S8_String s) { + S8_String result = s; + S8_Seek(s, S8_Lit("/"), S8_FindFlag_MatchFindLast, &result.len); + return result; +} + +S8_API S8_String S8_ChopLastPeriod(S8_String s) { + S8_String result = s; + S8_Seek(s, S8_Lit("."), S8_FindFlag_MatchFindLast, &result.len); + return result; +} + +S8_API S8_String S8_SkipToLastSlash(S8_String s) { + int64_t pos; + S8_String result = s; + if (S8_Seek(s, S8_Lit("/"), S8_FindFlag_MatchFindLast, &pos)) { + result = S8_Skip(result, pos + 1); + } + return result; +} + +S8_API S8_String S8_SkipToLastPeriod(S8_String s) { + int64_t pos; + S8_String result = s; + if (S8_Seek(s, S8_Lit("."), S8_FindFlag_MatchFindLast, &pos)) { + result = S8_Skip(result, pos + 1); + } + return result; +} + +S8_API int64_t S8_Length(char *string) { + int64_t len = 0; + while (*string++ != 0) + len++; + return len; +} + +S8_API int64_t S8_WideLength(wchar_t *string) { + int64_t len = 0; + while (*string++ != 0) + len++; + return len; +} + +S8_API S8_String S8_MakeFromChar(char *string) { + S8_String result; + result.str = (char *)string; + result.len = S8_Length(string); + return result; +} + +S8_API S8_String S8_MakeEmpty(void) { + return S8_Make(0, 0); +} + +S8_API S8_List S8_MakeEmptyList(void) { + S8_List result; + result.first = 0; + result.last = 0; + result.char_count = 0; + result.node_count = 0; + return result; +} + +S8_API S8_String S8_FormatV(S8_Allocator allocator, const char *str, va_list args1) { + va_list args2; + va_copy(args2, args1); + int64_t len = S8_VSNPRINTF(0, 0, str, args2); + va_end(args2); + + char *result = (char *)S8_ALLOCATE(allocator, sizeof(char) * (len + 1)); + S8_VSNPRINTF(result, (int)(len + 1), str, args1); + S8_String res = S8_Make(result, len); + return res; +} + +S8_API S8_String S8_Format(S8_Allocator allocator, const char *str, ...) { + S8_FORMAT(allocator, str, result); + return result; +} + +S8_API S8_Node *S8_CreateNode(S8_Allocator allocator, S8_String string) { + S8_Node *result = (S8_Node *)S8_ALLOCATE(allocator, sizeof(S8_Node)); + result->string = string; + result->next = 0; + return result; +} + +S8_API void S8_ReplaceNodeString(S8_List *list, S8_Node *node, S8_String new_string) { + list->char_count -= node->string.len; + list->char_count += new_string.len; + node->string = new_string; +} + +S8_API void S8_AddExistingNode(S8_List *list, S8_Node *node) { + if (list->first) { + list->last->next = node; + list->last = list->last->next; + } + else { + list->first = list->last = node; + } + list->node_count += 1; + list->char_count += node->string.len; +} + +S8_API void S8_AddArray(S8_Allocator allocator, S8_List *list, char **array, int count) { + for (int i = 0; i < count; i += 1) { + S8_String s = S8_MakeFromChar(array[i]); + S8_AddNode(allocator, list, s); + } +} + +S8_API void S8_AddArrayWithPrefix(S8_Allocator allocator, S8_List *list, char *prefix, char **array, int count) { + for (int i = 0; i < count; i += 1) { + S8_AddF(allocator, list, "%s%s", prefix, array[i]); + } +} + +S8_API S8_List S8_MakeList(S8_Allocator allocator, S8_String a) { + S8_List result = S8_MakeEmptyList(); + S8_AddNode(allocator, &result, a); + return result; +} + +S8_API S8_List S8_CopyList(S8_Allocator allocator, S8_List a) { + S8_List result = S8_MakeEmptyList(); + for (S8_Node *it = a.first; it; it = it->next) S8_AddNode(allocator, &result, it->string); + return result; +} + +S8_API S8_List S8_ConcatLists(S8_Allocator allocator, S8_List a, S8_List b) { + S8_List result = S8_MakeEmptyList(); + for (S8_Node *it = a.first; it; it = it->next) S8_AddNode(allocator, &result, it->string); + for (S8_Node *it = b.first; it; it = it->next) S8_AddNode(allocator, &result, it->string); + return result; +} + +S8_API S8_Node *S8_AddNode(S8_Allocator allocator, S8_List *list, S8_String string) { + S8_Node *node = S8_CreateNode(allocator, string); + S8_AddExistingNode(list, node); + return node; +} + +S8_API S8_Node *S8_Add(S8_Allocator allocator, S8_List *list, S8_String string) { + S8_String copy = S8_Copy(allocator, string); + S8_Node *node = S8_CreateNode(allocator, copy); + S8_AddExistingNode(list, node); + return node; +} + +S8_API S8_String S8_AddF(S8_Allocator allocator, S8_List *list, const char *str, ...) { + S8_FORMAT(allocator, str, result); + S8_AddNode(allocator, list, result); + return result; +} + +#ifdef FIRST_UTF_HEADER + +S8_API S16_String S8_ToWidecharEx(S8_Allocator allocator, S8_String string) { + S8_ASSERT(sizeof(wchar_t) == 2); + wchar_t *buffer = (wchar_t *)S8_ALLOCATE(allocator, sizeof(wchar_t) * (string.len + 1)); + int64_t size = UTF_CreateWidecharFromChar(buffer, string.len + 1, string.str, string.len); + S16_String result = {buffer, size}; + return result; +} + +S8_API wchar_t *S8_ToWidechar(S8_Allocator allocator, S8_String string) { + S16_String result = S8_ToWidecharEx(allocator, string); + return result.str; +} + +S8_API S8_String S8_FromWidecharEx(S8_Allocator allocator, wchar_t *wstring, int64_t wsize) { + S8_ASSERT(sizeof(wchar_t) == 2); + + int64_t buffer_size = (wsize + 1) * 2; + char *buffer = (char *)S8_ALLOCATE(allocator, buffer_size); + int64_t size = UTF_CreateCharFromWidechar(buffer, buffer_size, wstring, wsize); + S8_String result = S8_Make(buffer, size); + + S8_ASSERT(size < buffer_size); + return result; +} + +S8_API S8_String S8_FromWidechar(S8_Allocator allocator, wchar_t *wstring) { + int64_t size = S8_WideLength(wstring); + S8_String result = S8_FromWidecharEx(allocator, wstring, size); + return result; +} + +#endif \ No newline at end of file diff --git a/src/standalone_libraries/string.h b/src/standalone_libraries/string.h new file mode 100644 index 0000000..76b1d33 --- /dev/null +++ b/src/standalone_libraries/string.h @@ -0,0 +1,197 @@ +#ifndef FIRST_S8_STRING +#define FIRST_S8_STRING +#include +#include +#include + +#ifndef S8_API + #define S8_API +#endif + +#ifdef __cplusplus + #define S8_IF_CPP(x) x +#else + #define S8_IF_CPP(x) +#endif + +#ifndef S8_Allocator +struct MA_Arena; + #define S8_Allocator MA_Arena * +#endif + +typedef struct S8_String S8_String; +typedef struct S8_Node S8_Node; +typedef struct S8_List S8_List; +S8_API int64_t S8_Length(char *string); + +struct S8_String { + char *str; + int64_t len; +#if defined(__cplusplus) + S8_String() = default; + S8_String(char *s) : str(s), len(S8_Length(s)) {} + S8_String(char *s, int64_t l) : str(s), len(l) {} + S8_String(const char *s) : str((char *)s), len(S8_Length((char *)s)) {} + S8_String(const char *s, int64_t l) : str((char *)s), len(l) {} + #if defined(FIRST_UTF_HEADER) + struct Iter { + UTF8_Iter i; + + Iter &operator++() { + UTF8_Advance(&i); + return *this; + } + + friend bool operator!=(const Iter &a, const Iter &b) { return a.i.item != b.i.item; } + UTF8_Iter &operator*() { return i; } + }; + + Iter begin() { return {UTF8_IterateEx(str, (int)len)}; } + Iter end() { return {}; } + #endif // FIRST_UTF_HEADER +#endif // __cplusplus +}; + +struct S8_Node { + S8_Node *next; + S8_String string; +}; + +struct S8_List { + int64_t node_count; + int64_t char_count; + S8_Node *first; + S8_Node *last; + +#if defined(__cplusplus) + struct Iter { + S8_Node *it; + + Iter &operator++() { + it = it->next; + return *this; + } + + friend bool operator!=(const Iter &a, const Iter &b) { return a.it != b.it; } + S8_String &operator*() { return it->string; } + }; + + Iter begin() { return {first}; } + Iter end() { return {0}; } +#endif +}; + +typedef struct S16_String { + wchar_t *str; + int64_t len; +} S16_String; + +typedef int S8_FindFlag; +enum { + S8_FindFlag_None = 0, + S8_FindFlag_IgnoreCase = 1, + S8_FindFlag_MatchFindLast = 2, +}; + +typedef int S8_SplitFlag; +enum { + S8_SplitFlag_None = 0, + S8_SplitFlag_IgnoreCase = 1, + S8_SplitFlag_SplitInclusive = 2, +}; + +static const bool S8_IgnoreCase = true; + +#if defined(__has_attribute) + #if __has_attribute(format) + #define S8__PrintfFormat(fmt, va) __attribute__((format(printf, fmt, va))) + #endif +#endif + +#ifndef S8__PrintfFormat + #define S8__PrintfFormat(fmt, va) +#endif + +#define S8_Lit(string) S8_Make((char *)string, sizeof(string) - 1) +#define S8_ConstLit(string) \ + { string, sizeof(string) - 1 } +#define S8_Expand(string) (int)(string).len, (string).str + +#define S8_FORMAT(allocator, str, result) \ + va_list args1; \ + va_start(args1, str); \ + S8_String result = S8_FormatV(allocator, str, args1); \ + va_end(args1) + +#define S8_For(it, x) for (S8_Node *it = (x).first; it; it = it->next) + +S8_API char CHAR_ToLowerCase(char a); +S8_API char CHAR_ToUpperCase(char a); +S8_API bool CHAR_IsWhitespace(char w); +S8_API bool CHAR_IsAlphabetic(char a); +S8_API bool CHAR_IsIdent(char a); +S8_API bool CHAR_IsDigit(char a); +S8_API bool CHAR_IsAlphanumeric(char a); +S8_API bool S8_AreEqual(S8_String a, S8_String b, unsigned ignore_case S8_IF_CPP(= false)); +S8_API bool S8_EndsWith(S8_String a, S8_String end, unsigned ignore_case S8_IF_CPP(= false)); +S8_API bool S8_StartsWith(S8_String a, S8_String start, unsigned ignore_case S8_IF_CPP(= false)); +S8_API S8_String S8_Make(char *str, int64_t len); +S8_API S8_String S8_Copy(S8_Allocator allocator, S8_String string); +S8_API S8_String S8_CopyChar(S8_Allocator allocator, char *s); +S8_API S8_String S8_NormalizePath(S8_Allocator allocator, S8_String s); +S8_API void S8_NormalizePathUnsafe(S8_String s); // make sure there is no way string is const etc. +S8_API S8_String S8_Chop(S8_String string, int64_t len); +S8_API S8_String S8_Skip(S8_String string, int64_t len); +S8_API S8_String S8_GetPostfix(S8_String string, int64_t len); +S8_API S8_String S8_GetPrefix(S8_String string, int64_t len); +S8_API S8_String S8_Slice(S8_String string, int64_t first_index, int64_t one_past_last_index); +S8_API S8_String S8_Trim(S8_String string); +S8_API S8_String S8_TrimEnd(S8_String string); +S8_API S8_String S8_ToLowerCase(S8_Allocator allocator, S8_String s); +S8_API S8_String S8_ToUpperCase(S8_Allocator allocator, S8_String s); +S8_API bool S8_Seek(S8_String string, S8_String find, S8_FindFlag flags S8_IF_CPP(= S8_FindFlag_None), int64_t *index_out S8_IF_CPP(= 0)); +S8_API int64_t S8_Find(S8_String string, S8_String find, S8_FindFlag flags S8_IF_CPP(= S8_FindFlag_None)); +S8_API S8_String S8_ChopLastSlash(S8_String s); +S8_API S8_String S8_ChopLastPeriod(S8_String s); +S8_API S8_String S8_SkipToLastSlash(S8_String s); +S8_API S8_String S8_SkipToLastPeriod(S8_String s); +S8_API S8_String S8_GetNameNoExt(S8_String s); +S8_API bool S8_IsPointerInside(S8_String string, char *p); +S8_API S8_String S8_SkipToP(S8_String string, char *p); +S8_API S8_String S8_SkipPast(S8_String string, S8_String a); +S8_API int64_t S8_WideLength(wchar_t *string); +S8_API S8_String S8_MakeFromChar(char *string); +S8_API S8_String S8_MakeEmpty(void); +S8_API S8_List S8_MakeEmptyList(void); +S8_API S8_String S8_FormatV(S8_Allocator allocator, const char *str, va_list args1); +S8_API S8_String S8_Format(S8_Allocator allocator, const char *str, ...) S8__PrintfFormat(2, 3); + +S8_API S8_List S8_Split(S8_Allocator allocator, S8_String string, S8_String find, S8_SplitFlag flags S8_IF_CPP(= S8_SplitFlag_None)); +S8_API S8_String S8_MergeWithSeparator(S8_Allocator allocator, S8_List list, S8_String separator S8_IF_CPP(= S8_Lit(" "))); +S8_API S8_String S8_Merge(S8_Allocator allocator, S8_List list); +S8_API S8_String S8_ReplaceAll(S8_Allocator allocator, S8_String string, S8_String replace, S8_String with, bool ignore_case S8_IF_CPP(= false)); +S8_API S8_List S8_FindAll(S8_Allocator allocator, S8_String string, S8_String find, bool ignore_case S8_IF_CPP(= false)); + +S8_API S8_Node *S8_CreateNode(S8_Allocator allocator, S8_String string); +S8_API void S8_ReplaceNodeString(S8_List *list, S8_Node *node, S8_String new_string); +S8_API void S8_AddExistingNode(S8_List *list, S8_Node *node); +S8_API void S8_AddArray(S8_Allocator allocator, S8_List *list, char **array, int count); +S8_API void S8_AddArrayWithPrefix(S8_Allocator allocator, S8_List *list, char *prefix, char **array, int count); +S8_API S8_List S8_MakeList(S8_Allocator allocator, S8_String a); +S8_API S8_List S8_CopyList(S8_Allocator allocator, S8_List a); +S8_API S8_List S8_ConcatLists(S8_Allocator allocator, S8_List a, S8_List b); +S8_API S8_Node *S8_AddNode(S8_Allocator allocator, S8_List *list, S8_String string); +S8_API S8_Node *S8_Add(S8_Allocator allocator, S8_List *list, S8_String string); +S8_API S8_String S8_AddF(S8_Allocator allocator, S8_List *list, const char *str, ...) S8__PrintfFormat(3, 4); + +S8_API S16_String S8_ToWidecharEx(S8_Allocator allocator, S8_String string); +S8_API wchar_t *S8_ToWidechar(S8_Allocator allocator, S8_String string); +S8_API S8_String S8_FromWidecharEx(S8_Allocator allocator, wchar_t *wstring, int64_t wsize); +S8_API S8_String S8_FromWidechar(S8_Allocator allocator, wchar_t *wstring); + +#if defined(__cplusplus) +inline S8_String operator""_s(const char *str, size_t size) { return {(char *)str, (int64_t)size}; } +inline bool operator==(S8_String a, S8_String b) { return S8_AreEqual(a, b, 0); } +inline bool operator!=(S8_String a, S8_String b) { return !S8_AreEqual(a, b, 0); } +#endif +#endif \ No newline at end of file diff --git a/src/standalone_libraries/unicode.c b/src/standalone_libraries/unicode.c new file mode 100644 index 0000000..8cc03ab --- /dev/null +++ b/src/standalone_libraries/unicode.c @@ -0,0 +1,210 @@ +#include "unicode.h" + +#ifndef UTF__MemoryZero + #include + #define UTF__MemoryZero(p, size) memset(p, 0, size) +#endif + +UTF_API UTF32_Result UTF_ConvertUTF16ToUTF32(uint16_t *c, int max_advance) { + UTF32_Result result; + UTF__MemoryZero(&result, sizeof(result)); + if (max_advance >= 1) { + result.advance = 1; + result.out_str = c[0]; + if (c[0] >= 0xD800 && c[0] <= 0xDBFF && c[1] >= 0xDC00 && c[1] <= 0xDFFF) { + if (max_advance >= 2) { + result.out_str = 0x10000; + result.out_str += (uint32_t)(c[0] & 0x03FF) << 10u | (c[1] & 0x03FF); + result.advance = 2; + } + else + result.error = 2; + } + } + else { + result.error = 1; + } + return result; +} + +UTF_API UTF8_Result UTF_ConvertUTF32ToUTF8(uint32_t codepoint) { + UTF8_Result result; + UTF__MemoryZero(&result, sizeof(result)); + + if (codepoint <= 0x7F) { + result.len = 1; + result.out_str[0] = (char)codepoint; + } + else if (codepoint <= 0x7FF) { + result.len = 2; + result.out_str[0] = 0xc0 | (0x1f & (codepoint >> 6)); + result.out_str[1] = 0x80 | (0x3f & codepoint); + } + else if (codepoint <= 0xFFFF) { // 16 bit word + result.len = 3; + result.out_str[0] = 0xe0 | (0xf & (codepoint >> 12)); // 4 bits + result.out_str[1] = 0x80 | (0x3f & (codepoint >> 6)); // 6 bits + result.out_str[2] = 0x80 | (0x3f & codepoint); // 6 bits + } + else if (codepoint <= 0x10FFFF) { // 21 bit word + result.len = 4; + result.out_str[0] = 0xf0 | (0x7 & (codepoint >> 18)); // 3 bits + result.out_str[1] = 0x80 | (0x3f & (codepoint >> 12)); // 6 bits + result.out_str[2] = 0x80 | (0x3f & (codepoint >> 6)); // 6 bits + result.out_str[3] = 0x80 | (0x3f & codepoint); // 6 bits + } + else { + result.error = 1; + } + + return result; +} + +UTF_API UTF32_Result UTF_ConvertUTF8ToUTF32(char *c, int max_advance) { + UTF32_Result result; + UTF__MemoryZero(&result, sizeof(result)); + + if ((c[0] & 0x80) == 0) { // Check if leftmost zero of first byte is unset + if (max_advance >= 1) { + result.out_str = c[0]; + result.advance = 1; + } + else result.error = 1; + } + + else if ((c[0] & 0xe0) == 0xc0) { + if ((c[1] & 0xc0) == 0x80) { // Continuation byte required + if (max_advance >= 2) { + result.out_str = (uint32_t)(c[0] & 0x1f) << 6u | (c[1] & 0x3f); + result.advance = 2; + } + else result.error = 2; + } + else result.error = 2; + } + + else if ((c[0] & 0xf0) == 0xe0) { + if ((c[1] & 0xc0) == 0x80 && (c[2] & 0xc0) == 0x80) { // Two continuation bytes required + if (max_advance >= 3) { + result.out_str = (uint32_t)(c[0] & 0xf) << 12u | (uint32_t)(c[1] & 0x3f) << 6u | (c[2] & 0x3f); + result.advance = 3; + } + else result.error = 3; + } + else result.error = 3; + } + + else if ((c[0] & 0xf8) == 0xf0) { + if ((c[1] & 0xc0) == 0x80 && (c[2] & 0xc0) == 0x80 && (c[3] & 0xc0) == 0x80) { // Three continuation bytes required + if (max_advance >= 4) { + result.out_str = (uint32_t)(c[0] & 0xf) << 18u | (uint32_t)(c[1] & 0x3f) << 12u | (uint32_t)(c[2] & 0x3f) << 6u | (uint32_t)(c[3] & 0x3f); + result.advance = 4; + } + else result.error = 4; + } + else result.error = 4; + } + else result.error = 4; + + return result; +} + +UTF_API UTF16_Result UTF_ConvertUTF32ToUTF16(uint32_t codepoint) { + UTF16_Result result; + UTF__MemoryZero(&result, sizeof(result)); + if (codepoint < 0x10000) { + result.out_str[0] = (uint16_t)codepoint; + result.out_str[1] = 0; + result.len = 1; + } + else if (codepoint <= 0x10FFFF) { + uint32_t code = (codepoint - 0x10000); + result.out_str[0] = (uint16_t)(0xD800 | (code >> 10)); + result.out_str[1] = (uint16_t)(0xDC00 | (code & 0x3FF)); + result.len = 2; + } + else { + result.error = 1; + } + + return result; +} + +#define UTF__HANDLE_DECODE_ERROR(question_mark) \ + { \ + if (outlen < buffer_size - 1) buffer[outlen++] = (question_mark); \ + break; \ + } + +UTF_API int64_t UTF_CreateCharFromWidechar(char *buffer, int64_t buffer_size, wchar_t *in, int64_t inlen) { + int64_t outlen = 0; + for (int64_t i = 0; i < inlen && in[i];) { + UTF32_Result decode = UTF_ConvertUTF16ToUTF32((uint16_t *)(in + i), (int)(inlen - i)); + if (!decode.error) { + i += decode.advance; + UTF8_Result encode = UTF_ConvertUTF32ToUTF8(decode.out_str); + if (!encode.error) { + for (int64_t j = 0; j < encode.len; j++) { + if (outlen < buffer_size - 1) { + buffer[outlen++] = encode.out_str[j]; + } + } + } + else UTF__HANDLE_DECODE_ERROR('?'); + } + else UTF__HANDLE_DECODE_ERROR('?'); + } + + buffer[outlen] = 0; + return outlen; +} + +UTF_API int64_t UTF_CreateWidecharFromChar(wchar_t *buffer, int64_t buffer_size, char *in, int64_t inlen) { + int64_t outlen = 0; + for (int64_t i = 0; i < inlen;) { + UTF32_Result decode = UTF_ConvertUTF8ToUTF32(in + i, (int)(inlen - i)); + if (!decode.error) { + i += decode.advance; + UTF16_Result encode = UTF_ConvertUTF32ToUTF16(decode.out_str); + if (!encode.error) { + for (int64_t j = 0; j < encode.len; j++) { + if (outlen < buffer_size - 1) { + buffer[outlen++] = encode.out_str[j]; + } + } + } + else UTF__HANDLE_DECODE_ERROR(0x003f); + } + else UTF__HANDLE_DECODE_ERROR(0x003f); + } + + buffer[outlen] = 0; + return outlen; +} + +UTF_API void UTF8_Advance(UTF8_Iter *iter) { + iter->i += iter->utf8_codepoint_byte_size; + UTF32_Result r = UTF_ConvertUTF8ToUTF32(iter->str + iter->i, iter->len - iter->i); + if (r.error) { + iter->item = 0; + return; + } + + iter->utf8_codepoint_byte_size = r.advance; + iter->item = r.out_str; +} + +UTF_API UTF8_Iter UTF8_IterateEx(char *str, int len) { + UTF8_Iter result; + UTF__MemoryZero(&result, sizeof(result)); + result.str = str; + result.len = len; + if (len) UTF8_Advance(&result); + return result; +} + +UTF_API UTF8_Iter UTF8_Iterate(char *str) { + int length = 0; + while (str[length]) length += 1; + return UTF8_IterateEx(str, length); +} diff --git a/src/standalone_libraries/unicode.h b/src/standalone_libraries/unicode.h new file mode 100644 index 0000000..0622e83 --- /dev/null +++ b/src/standalone_libraries/unicode.h @@ -0,0 +1,55 @@ +#ifndef FIRST_UTF_HEADER +#define FIRST_UTF_HEADER +#define UTF_HEADER +#include +typedef struct UTF32_Result UTF32_Result; +typedef struct UTF8_Result UTF8_Result; +typedef struct UTF16_Result UTF16_Result; +typedef struct UTF8_Iter UTF8_Iter; + +#ifndef UTF_API + #ifdef __cplusplus + #define UTF_API extern "C" + #else + #define UTF_API + #endif +#endif + +struct UTF32_Result { + uint32_t out_str; + int advance; + int error; +}; + +struct UTF8_Result { + uint8_t out_str[4]; + int len; + int error; +}; + +struct UTF16_Result { + uint16_t out_str[2]; + int len; + int error; +}; + +struct UTF8_Iter { + char *str; + int len; + int utf8_codepoint_byte_size; + int i; + uint32_t item; +}; + +UTF_API UTF32_Result UTF_ConvertUTF16ToUTF32(uint16_t *c, int max_advance); +UTF_API UTF8_Result UTF_ConvertUTF32ToUTF8(uint32_t codepoint); +UTF_API UTF32_Result UTF_ConvertUTF8ToUTF32(char *c, int max_advance); +UTF_API UTF16_Result UTF_ConvertUTF32ToUTF16(uint32_t codepoint); +UTF_API int64_t UTF_CreateCharFromWidechar(char *buffer, int64_t buffer_size, wchar_t *in, int64_t inlen); +UTF_API int64_t UTF_CreateWidecharFromChar(wchar_t *buffer, int64_t buffer_size, char *in, int64_t inlen); +UTF_API void UTF8_Advance(UTF8_Iter *iter); +UTF_API UTF8_Iter UTF8_IterateEx(char *str, int len); +UTF_API UTF8_Iter UTF8_Iterate(char *str); + +#define UTF8_For(name, str, len) for (UTF8_Iter name = UTF8_IterateEx(str, (int)len); name.item; UTF8_Advance(&name)) +#endif \ No newline at end of file diff --git a/src/wasm_playground/01_hello_world.lc b/src/wasm_playground/01_hello_world.lc new file mode 100644 index 0000000..76cf967 --- /dev/null +++ b/src/wasm_playground/01_hello_world.lc @@ -0,0 +1,9 @@ +// You can edit this code! +// Click here and start typing. + +import "libc"; + +main :: proc(): int { + printf("hello world!\n"); + return 0; +} \ No newline at end of file diff --git a/src/wasm_playground/02_conways_game_of_life.lc b/src/wasm_playground/02_conways_game_of_life.lc new file mode 100644 index 0000000..6b2bad1 --- /dev/null +++ b/src/wasm_playground/02_conways_game_of_life.lc @@ -0,0 +1,72 @@ +import c "libc"; + +generation_count :: 5; +board_x :: 20; +board_y :: 10; +board_copy: [board_x * board_y]int; +board: [board_x * board_y]int = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; + +get_neighbor :: proc(xcol: int, yrow: int): int { + x := xcol % board_x; + y := yrow % board_y; + result := board_copy[x + y * board_x]; + return result; +} + +get_neighbor_count :: proc(xcol: int, yrow: int): int { + result := 0; + for dc := -1; dc <= 1; dc += 1 { + for dr := -1; dr <= 1; dr += 1 { + if (dr || dc) result += get_neighbor(xcol + dc, yrow + dr); + } + } + return result; +} + +main :: proc(): int { + for gen := 0; gen < generation_count; gen += 1 { + c.printf("generation: %d\n", gen); + + // show cells + for y := 0; y < board_y; y += 1 { + c.printf("|"); + for x := 0; x < board_x; x += 1 { + cell := board[x + y * board_x]; + if cell { + c.printf("*"); + } else { + c.printf("."); + } + } + c.printf("|\n"); + } + + // update cells + c.memcpy(&board_copy[0], &board[0], sizeof(board)); + for y := 0; y < board_y; y += 1 { + for x := 0; x < board_x; x += 1 { + src_cell := board_copy[x + y * board_x]; + dst_cell := addptr(board, x + y * board_x); + + count := get_neighbor_count(x, y); + birth := !src_cell && count == 3; + survive := src_cell && (count == 3 || count == 2); + dst_cell[0] = birth || survive; + } + } + } + + c.printf("End\n"); + return 0; +} diff --git a/src/wasm_playground/index.html b/src/wasm_playground/index.html new file mode 100644 index 0000000..f39e61e --- /dev/null +++ b/src/wasm_playground/index.html @@ -0,0 +1,110 @@ + + + + + + + + Playground + + + + + + + + + + + \ No newline at end of file diff --git a/src/wasm_playground/run_server.bat b/src/wasm_playground/run_server.bat new file mode 100644 index 0000000..f4e3ade --- /dev/null +++ b/src/wasm_playground/run_server.bat @@ -0,0 +1 @@ +python -m http.server \ No newline at end of file diff --git a/src/wasm_playground/wasm_main.c b/src/wasm_playground/wasm_main.c new file mode 100644 index 0000000..30829b1 --- /dev/null +++ b/src/wasm_playground/wasm_main.c @@ -0,0 +1,132 @@ +#define WASM_IMPORT(name) __attribute__((import_name(#name))) name +#define WASM_EXPORT(name) __attribute__((export_name(#name))) name + +double WASM_IMPORT(JS_ParseFloat)(char *str, int len); +void WASM_IMPORT(JS_ConsoleLog)(char *str, int len); +char *WASM_IMPORT(JS_LoadFile)(void); + +#define LC_ParseFloat(str, len) JS_ParseFloat(str, len) +#define LC_Print(str, len) JS_ConsoleLog(str, len) +#define LC_Exit(x) (*(volatile int *)0 = 0) +#define LC_THREAD_LOCAL +#define LC_MemoryZero(p, size) __builtin_memset(p, 0, size); +#define LC_MemoryCopy(dst, src, size) __builtin_memcpy(dst, src, size) + +#include "../standalone_libraries/stb_sprintf.h" +#include "../standalone_libraries/stb_sprintf.c" +#define LC_vsnprintf stbsp_vsnprintf +#include "../compiler/lib_compiler.c" + +bool LC_IsDir(LC_Arena *temp, LC_String path) { + if (LC_AreEqual(path, LC_Lit("virtual_dir"), false)) return true; + if (LC_AreEqual(path, LC_Lit("virtual_dir/libc"), false)) return true; + return false; +} + +LC_FileIter LC_IterateFiles(LC_Arena *arena, LC_String path) { + LC_FileIter result = {0}; + result.is_valid = true; + result.is_directory = false; + result.filename = LC_Lit("file.lc"); + + if (LC_StartsWith(path, LC_Lit("virtual_dir"), false)) { + result.absolute_path = LC_Format(arena, "%.*s/file.lc", LC_Expand(path)); + result.relative_path = LC_Format(arena, "%.*s/file.lc", LC_Expand(path)); + } + return result; +} + +bool LC_IsValid(LC_FileIter it) { + return it.is_valid; +} + +void LC_Advance(LC_FileIter *it) { + it->is_valid = false; +} + +LC_String LC_ReadFile(LC_Arena *arena, LC_String path) { + LC_String result = LC_Lit("main :: proc(): int { return 0; }"); + return result; +} + +LC_FUNCTION void LC_VDeallocate(LC_VMemory *m) {} +LC_FUNCTION bool LC_VCommit(LC_VMemory *m, size_t commit) { return false; } + +char Memory[64 * 1024 * 24]; +LC_Arena MainArena; + +LC_Lang *Wasm_LC_LangAlloc(LC_Arena *arena) { + LC_Arena *lex_arena = LC_PushStruct(arena, LC_Arena); + *lex_arena = LC_PushArena(arena, 64 * 1024 * 4); + + LC_Arena *ast_arena = LC_PushStruct(arena, LC_Arena); + *ast_arena = LC_PushArena(arena, 64 * 1024 * 4); + + LC_Arena *decl_arena = LC_PushStruct(arena, LC_Arena); + *decl_arena = LC_PushArena(arena, 64 * 1024 * 2); + + LC_Arena *type_arena = LC_PushStruct(arena, LC_Arena); + *type_arena = LC_PushArena(arena, 64 * 1024 * 2); + + LC_Lang *l = LC_PushStruct(arena, LC_Lang); + l->arena = arena; + l->lex_arena = lex_arena; + l->decl_arena = decl_arena; + l->type_arena = type_arena; + l->ast_arena = ast_arena; + + return l; +} + +void Wasm_OnFileLoad(LC_AST *package, LoadedFile *file) { + if (LC_StartsWith(file->path, LC_Lit("virtual_dir/libc/file.lc"), false)) { + file->content = LC_Lit( + " size_t :: typedef ullong; @foreign" + " printf :: proc(format: *char, ...): int; @foreign" + " memset :: proc(s: *void, value: int, n: size_t): *void; @foreign" + " memcpy :: proc(s1: *void, s2: *void, n: size_t): *void; @foreign"); + } else { + file->content.str = JS_LoadFile(); + file->content.len = LC_StrLen(file->content.str); + } +} + +void WASM_EXPORT(test)(void) { + LC_MemoryZero(&MainArena, sizeof(MainArena)); + LC_InitArenaFromBuffer(&MainArena, Memory, sizeof(Memory)); + LC_Lang *lang = Wasm_LC_LangAlloc(&MainArena); + { + lang->on_file_load = Wasm_OnFileLoad; + lang->os = 32; + lang->arch = 32; + } + LC_LangBegin(lang); + { + LC_AddBuiltinConstInt("LC_WASM", 32); + LC_AddBuiltinConstInt("ARCH_WASM", 32); + L->tlong->size = 4; + L->tlong->align = 4; + L->tulong->size = 4; + L->tulong->align = 4; + LC_SetPointerSizeAndAlign(4, 4); + } + + LC_RegisterPackageDir("virtual_dir"); + + LC_Intern name = LC_ILit("file"); + LC_AddSingleFilePackage(name, LC_Lit("file.lc")); + LC_ASTRefList packages = LC_ResolvePackageByName(name); + + if (L->errors == 0) { + LC_BeginStringGen(L->arena); + for (LC_ASTRef *it = packages.first; it; it = it->next) LC_GenCHeader(it->ast); + for (LC_ASTRef *it = packages.first; it; it = it->next) LC_GenCImpl(it->ast); + LC_String result = LC_EndStringGen(L->arena); + + LC_String code_output = LC_Lit("//\n// Code output\n//"); + JS_ConsoleLog(code_output.str, code_output.len); + JS_ConsoleLog(result.str, (int)result.len); + } + + LC_LangEnd(lang); +} diff --git a/src/x64/misc.cpp b/src/x64/misc.cpp new file mode 100644 index 0000000..97b1357 --- /dev/null +++ b/src/x64/misc.cpp @@ -0,0 +1,18 @@ +S8_String GetCodeLine(LC_AST *n) { + LC_Token *token = n->pos; + LC_Lex *x = n->file->afile.x; + S8_String content = S8_MakeFromChar(x->begin); + S8_List lines = S8_Split(L->arena, content, S8_Lit("\n"), 0); + + int line = 1; + S8_For(it, lines) { + if (token->line == line) return it->string; + line += 1; + } + return S8_MakeEmpty(); +} + +void OutASTLine(LC_AST *n) { + S8_String line = GetCodeLine(n); + LC_GenLinef(";%.*s", S8_Expand(line)); +} diff --git a/src/x64/registers.cpp b/src/x64/registers.cpp new file mode 100644 index 0000000..5a2f0dd --- /dev/null +++ b/src/x64/registers.cpp @@ -0,0 +1,28 @@ +#define MAX_REG 3 +bool RegTaken[MAX_REG] = {0, 0, 0}; +Register Regs[MAX_REG] = {R10, R11, R12}; + +Register AllocReg() { + for (int i = 0; i < 3; i += 1) { + if (RegTaken[i] == false) { + RegTaken[i] = true; + return Regs[i]; + } + } + IO_InvalidCodepath(); + return INVALID_REGISTER; +} + +void DeallocReg(Register reg) { + int i = (int)(reg - R10); + RegTaken[i] = false; +} + +const char *Str(Register reg) { + const char *registers[] = { + #define X(x) #x, + REGISTERS + #undef X + }; + return registers[reg]; +} \ No newline at end of file diff --git a/src/x64/tests/array.lc b/src/x64/tests/array.lc new file mode 100644 index 0000000..06c1d21 --- /dev/null +++ b/src/x64/tests/array.lc @@ -0,0 +1,4 @@ +main :: proc(): int { + //i: [8]int; + return 0; +} \ No newline at end of file diff --git a/src/x64/tests/assignop.lc b/src/x64/tests/assignop.lc new file mode 100644 index 0000000..d085496 --- /dev/null +++ b/src/x64/tests/assignop.lc @@ -0,0 +1,10 @@ +main :: proc(): int { + i := 0; + i += 10; + i -= 10; + i += 2; + i *= 2; + i /= 4; + i -= 1; + return i; +} \ No newline at end of file diff --git a/src/x64/tests/expr.lc b/src/x64/tests/expr.lc new file mode 100644 index 0000000..d6d9a6e --- /dev/null +++ b/src/x64/tests/expr.lc @@ -0,0 +1,10 @@ +a1 := 1; +a2 := 2; +a4 := 4; +a5 := 5; +a10 := 10; + +main :: proc(): int { + i := (a1 + a4) / a5 * a10 + (a10 - a5) - 15; + return i; +} \ No newline at end of file diff --git a/src/x64/tests/first.lc b/src/x64/tests/first.lc new file mode 100644 index 0000000..9bb5ba5 --- /dev/null +++ b/src/x64/tests/first.lc @@ -0,0 +1,31 @@ +S :: struct { + a: llong; + b: llong; + c: llong; +} + +main :: proc(): llong { + a: [5]llong; + a[2] = 1; + a[2] -= 1; + s: S; + i4: llong = 4; + i8: llong = i4 + i4; + i12: llong = i4 + i4 + i4; + @unused other_type: llong = 10; + + + p := &i4; + *p -= 1; + *&i4 -= 1; + pp := &p; + **pp += 2; + + @unused ret := second_proc(); + + return i12 - i8 - i4 + s.c + a[2]; +} + +second_proc :: proc(): int { + return 0; +} \ No newline at end of file diff --git a/src/x64/tests/for_loop.lc b/src/x64/tests/for_loop.lc new file mode 100644 index 0000000..890b603 --- /dev/null +++ b/src/x64/tests/for_loop.lc @@ -0,0 +1,18 @@ +main :: proc(): int { + a := 0; + for i := 0; i < 10; i += 1 { + a += 1; + } + + for a > 0; a -= 1 { + c := 20; + c += 1; + } + + a = 10; + for a > 0 { + a -= 1; + } + + return a; +} \ No newline at end of file diff --git a/src/x64/tests/ifreturnvar.lc b/src/x64/tests/ifreturnvar.lc new file mode 100644 index 0000000..47e54b6 --- /dev/null +++ b/src/x64/tests/ifreturnvar.lc @@ -0,0 +1,11 @@ +a := 10; +b := 20; + +main :: proc(): int { + a = 0; + b = 0; + if (a == b) { + return 0; + } + return 1; +} diff --git a/src/x64/tests/pointers.lc b/src/x64/tests/pointers.lc new file mode 100644 index 0000000..f566f03 --- /dev/null +++ b/src/x64/tests/pointers.lc @@ -0,0 +1,25 @@ + +stack_value :: proc(): int { + i := 2; + ip := &i; + return *ip - 2; +} + +I := 2; +glob_value :: proc(): int { + ip := &I; + return *ip - 2; +} + +param_value :: proc(i: int): int { + ip := &i; + ipp := &ip; + return *ip - **ipp; +} + +main :: proc(): int { + i0 := stack_value(); + i1 := glob_value(); + i2 := param_value(i0); + return i0 + i1 + i2; +} \ No newline at end of file diff --git a/src/x64/tests/proc_call.lc b/src/x64/tests/proc_call.lc new file mode 100644 index 0000000..6781d13 --- /dev/null +++ b/src/x64/tests/proc_call.lc @@ -0,0 +1,17 @@ +call :: proc(): int { + return 0; +} + +void_call :: proc() { +} + +args :: proc(a: int, b: int, c: int, d: int): int { + return a + b + c + d; +} + +main :: proc(): int { + void_call(); + val := call() + call() + call() * call(); + result := args(1,2,3,4) - 10; + return result + val; +} \ No newline at end of file diff --git a/src/x64/value.cpp b/src/x64/value.cpp new file mode 100644 index 0000000..9c90d49 --- /dev/null +++ b/src/x64/value.cpp @@ -0,0 +1,15 @@ +const char *Str(Value value) { + if (value.mode == Mode_Reg) { + return LC_Strf("%s", Str(value.reg)); + } else if (value.mode == Mode_Direct) { + return LC_Strf("[%s]", Str(value.reg)); + } else if (value.mode == Mode_Imm) { + return LC_Strf("%llu", value.u); + } else IO_Todo(); + return "INVALID_VALUE"; +} + +void DeallocReg(Value value) { + if (value.mode == Mode_Imm) return; + DeallocReg(value.reg); +} \ No newline at end of file diff --git a/src/x64/x64.h b/src/x64/x64.h new file mode 100644 index 0000000..ee5c42e --- /dev/null +++ b/src/x64/x64.h @@ -0,0 +1,41 @@ +struct X64Decl { + int offset; +}; + +/* +a: int; +a // d lvalue +&a // r not lvalue +*&a // d lvalue +*a // illegal + +b: *int; +*b // d lvalue +b // d lvalue +&b // r not lvalue +**b // illegal +*/ +enum Mode { + Mode_Imm, // Value is a constant and can be folded into instruction + Mode_Reg, // Value is in register + Mode_Direct, // Register that holds address to value, (but this is lvalue, not "*a" but just "a") +}; + +#define REGISTERS\ + X(INVALID_REGISTER)\ + X(RAX) X(RBX) X(RCX) X(RDX) X(RSI) X(RDI) X(RBP) X(RSP)\ + X(R8) X(R9) X(R10) X(R11) X(R12) X(R13) X(R14) X(R15) + +enum Register { + #define X(x) x, + REGISTERS + #undef X +}; + +struct Value { + Mode mode; + Register reg; + uint64_t u; +}; + +Value GenExpr(LC_AST *n); \ No newline at end of file diff --git a/src/x64/x64main.cpp b/src/x64/x64main.cpp new file mode 100644 index 0000000..023c332 --- /dev/null +++ b/src/x64/x64main.cpp @@ -0,0 +1,309 @@ +/* +I assume this is going to be a command line program, so: +- don't care about allocation +- global variables are OK +*/ + +#include "../core/core.c" +#include "../compiler/lib_compiler.c" + +#include "x64.h" +#include "misc.cpp" +#include "registers.cpp" +#include "value.cpp" + +Value GenExprInt(LC_AST *n) { + uint64_t u = LC_Bigint_as_unsigned(&n->eatom.i); + Value result = {Mode_Imm, INVALID_REGISTER, u}; + return result; +} + +Value GenExprIdent(LC_AST *n) { + LC_Decl *decl = n->eident.resolved_decl; + X64Decl *x = decl->x64; + + Register reg = AllocReg(); + + if (decl->ast->kind == LC_ASTKind_StmtVar) { + LC_GenLinef("lea %s, [RBP - %d]", Str(reg), x->offset); + } else IO_Todo(); + + Value result = {Mode_Direct, reg}; + return result; +} + +Value GenExprField(LC_AST *n) { + LC_Decl *resolved_decl = n->efield.resolved_decl; + LC_TypeMember *mem = resolved_decl->type_member; + + Value value = GenExpr(n->efield.left); + IO_Assert(value.mode == Mode_Direct); + + LC_GenLinef("add %s, %d", Str(value.reg), mem->offset); + + return value; +} + +void LoadValueIntoReg(Value *v) { + if (v->mode == Mode_Direct) { + LC_GenLinef("mov %s, %s", Str(v->reg), Str(*v)); + v->mode = Mode_Reg; + } else if (v->mode == Mode_Imm) { + v->reg = AllocReg(); + LC_GenLinef("mov %s, %llu", Str(v->reg), v->u); + v->mode = Mode_Reg; + } +} + +Value GenExprBinary(LC_AST *n) { + Value l = GenExpr(n->ebinary.left); + Value r = GenExpr(n->ebinary.right); + LoadValueIntoReg(&l); + LoadValueIntoReg(&r); + + switch (n->ebinary.op) { + case LC_TokenKind_Add: LC_GenLinef("add %s, %s", Str(l), Str(r)); break; + case LC_TokenKind_Sub: LC_GenLinef("sub %s, %s", Str(l), Str(r)); break; + default: LC_ReportASTError(n, "internal compiler error: unhandled binary op %s in %s", TokenKindString[n->ebinary.op], __FUNCTION__); + } + + DeallocReg(r.reg); + return l; +} + +Value GenExprIndex(LC_AST *n) { + Value index = GenExpr(n->eindex.index); + Value base = GenExpr(n->eindex.base); + + IO_Assert(index.mode != Mode_Direct); + IO_Assert(base.mode == Mode_Direct); + + int esize = n->type->size; + if (index.mode == Mode_Imm) { + index.u *= esize; + } else if (index.mode == Mode_Reg) { + LC_GenLinef("imul %s, %d", Str(index), esize); + } else IO_Todo(); + LC_GenLinef("add %s, %s", Str(base.reg), Str(index)); + + DeallocReg(index); + return base; +} + +Value GenExprGetPointerOfValue(LC_AST *n) { + Value value = GenExpr(n->eunary.expr); + IO_Assert(value.mode == Mode_Direct); + value.mode = Mode_Reg; + return value; +} + +Value GenExprGetValueOfPointer(LC_AST *n) { + Value value = GenExpr(n->eunary.expr); + if (value.mode == Mode_Reg) { + value.mode = Mode_Direct; + } else if (value.mode == Mode_Direct) { + LC_GenLinef("mov %s, %s", Str(value.reg), Str(value)); + } else IO_Todo(); + return value; +} + +Value GenExprCall(LC_AST *n) { + Register abi_regs[] = {RCX, RDX, R8, R9}; + int i = 0; + + LC_ResolvedCompo *com = n->ecompo.resolved_items; + for (LC_ResolvedCompoItem *it = com->first; it; it = it->next) { + IO_Assert(i < 4); + + LC_Type *type = it->t->type; + Value value = GenExpr(it->expr); + Register reg = abi_regs[i++]; + LC_GenLinef("mov %s, %s", Str(reg), Str(value.reg)); + + DeallocReg(value); + } + + LC_GenLinef("call"); + Value result = {0}; + if (n->type->tproc.ret != L->tvoid) { + result.reg = AllocReg(); + result.mode = Mode_Reg; + } + return result; +} + +Value GenExpr(LC_AST *n) { + IO_Assert(LC_IsExpr(n)); + switch (n->kind) { + case LC_ASTKind_ExprIndex: return GenExprIndex(n); break; + case LC_ASTKind_ExprInt: return GenExprInt(n); break; + case LC_ASTKind_ExprIdent: return GenExprIdent(n); break; + case LC_ASTKind_ExprField: return GenExprField(n); break; + case LC_ASTKind_ExprBinary: return GenExprBinary(n); break; + case LC_ASTKind_ExprGetPointerOfValue: return GenExprGetPointerOfValue(n); break; + case LC_ASTKind_ExprGetValueOfPointer: return GenExprGetValueOfPointer(n); break; + case LC_ASTKind_ExprCall: return GenExprCall(n); break; + } + + LC_ReportASTError(n, "internal compiler error: unhandled ast kind %s in %s", ASTKindString[n->kind], __FUNCTION__); + return {}; +} + +void GenEpilogue() { + LC_GenLinef("mov rsp, rbp"); + LC_GenLinef("pop rbp"); +} + +void GenStmtReturn(LC_AST *n) { + if (n->sreturn.expr) { + Value value = GenExpr(n->sreturn.expr); + LC_GenLinef("mov RAX, %s", Str(value)); + DeallocReg(value); + } + + GenEpilogue(); + LC_GenLinef("ret"); +} + +void GenStmtVar(LC_AST *n) { + LC_Decl *decl = n->svar.resolved_decl; + X64Decl *x = decl->x64; + LC_AST *expr = n->svar.expr; + + if (expr) { + Value value = GenExpr(expr); + LC_GenLinef("lea RAX, [RBP - %d]", x->offset); + if (value.mode == Mode_Imm) { + LC_GenLinef("mov qword [RAX], %u", value.u); + } else if (value.mode == Mode_Direct) { + LC_GenLinef("mov RBX, [%s]", Str(value.reg)); + LC_GenLinef("mov qword [RAX], RBX"); + } else if (value.mode == Mode_Reg) { + LC_GenLinef("mov qword [RAX], %s", Str(value.reg)); + } else IO_Todo(); + + DeallocReg(value); + } else { + LC_GenLinef("lea RAX, [RBP - %d]", x->offset); + for (int i = 0; i < n->type->size; i += 1) { + LC_GenLinef("mov byte [RAX+%d], 0", i); + } + } +} + +void GenStmtAssign(LC_AST *n) { + Value l = GenExpr(n->sassign.left); + IO_Assert(l.mode == Mode_Direct); + Value r = GenExpr(n->sassign.right); + + LC_TokenKind op = n->sassign.op; + switch (op) { + case LC_TokenKind_Assign: LC_GenLinef("mov qword %s, %s", Str(l), Str(r)); break; + case LC_TokenKind_AddAssign: LC_GenLinef("add qword %s, %s", Str(l), Str(r)); break; + case LC_TokenKind_SubAssign: LC_GenLinef("sub qword %s, %s", Str(l), Str(r)); break; + default: LC_ReportASTError(n, "internal compiler error: unhandled assign op %s in %s", TokenKindString[n->ebinary.op], __FUNCTION__); + } + + DeallocReg(l); + DeallocReg(r); +} + +void GenStmt(LC_AST *n) { + OutASTLine(n); + IO_Assert(LC_IsStmt(n)); + + switch (n->kind) { + case LC_ASTKind_StmtExpr: + Value val = GenExpr(n->sexpr.expr); + DeallocReg(val); + break; + case LC_ASTKind_StmtVar: GenStmtVar(n); break; + case LC_ASTKind_StmtReturn: GenStmtReturn(n); break; + case LC_ASTKind_StmtAssign: GenStmtAssign(n); break; + default: LC_ReportASTError(n, "internal compiler error: unhandled ast kind %s in %s", ASTKindString[n->kind], __FUNCTION__); + } +} + +void GenStmtBlock(LC_AST *n) { + LC_ASTFor(it, n->sblock.first) { + GenStmt(it); + } +} + +void WalkToComputeStackSize(LC_ASTWalker *w, LC_AST *n) { + int *stack_size = (int *)w->user_data; + if (n->kind == LC_ASTKind_StmtVar) { + LC_Decl *decl = n->svar.resolved_decl; + decl->x64 = MA_PushStruct(L->arena, X64Decl); + + stack_size[0] += n->type->size; + decl->x64->offset = stack_size[0]; // stack goes backwards + stack_size[0] = (int)MA_AlignUp(stack_size[0], 8); + } +} + +void GenProc(LC_Decl *decl) { + LC_AST *n = decl->ast; + OutASTLine(n); + + LC_GenLinef("global %s", decl->foreign_name); + LC_GenLinef("%s:", decl->foreign_name); + + int stack_size = 0; + AST_WalkBreathFirst(MA_GetAllocator(L->arena), WalkToComputeStackSize, n->dproc.body, (void *)&stack_size); + + LC_GenLinef("push rbp"); + LC_GenLinef("mov rbp, rsp"); + + if ((stack_size % 16) == 0) stack_size += 8; + LC_GenLinef("sub rsp, %d", stack_size); + + printer.indent += 1; + for (LC_TypeMember *it = n->type->tproc.args.first; it; it = it->next) { + } + + GenStmtBlock(n->dproc.body); + printer.indent -= 1; + + GenEpilogue(); +} + +void GenPackages(LC_ASTRefList packages) { + LC_GenLinef("BITS 64"); + + LC_GenLinef("section .text"); + for (LC_ASTRef *it = packages.first; it; it = it->next) { + LC_AST *n = it->ast; + + LC_DeclFor(decl, n->apackage.first_ordered) { + if (decl->kind != LC_DeclKind_Proc) continue; + if (decl->is_foreign) continue; + GenProc(decl); + } + } +} + +int main(int argc, char **argv) { + MA_Arena arena = {0}; + for (OS_FileIter iter = OS_IterateFiles(&arena, S8_Lit("../../src/x64/tests")); OS_IsValid(iter); OS_Advance(&iter)) { + if (!S8_EndsWith(iter.filename, S8_Lit("first.lc"))) continue; + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = UseColoredIO; + LC_LangBegin(lang); + LC_ASTRefList package = ParseAndResolveFile(iter.absolute_path.str); + LC_BeginStringGen(L->arena); + GenPackages(package); + S8_String s = LC_EndStringGen(L->arena); + S8_String asmf = S8_Format(L->arena, "%.*s.asm", S8_Expand(iter.filename)); + + OS_WriteFile(asmf, s); + OS_SystemF("..\\..\\tools\\nasm.exe %.*s -o %.*s.obj -gcv8 -f win64 -O0", S8_Expand(asmf), S8_Expand(asmf)); + OS_SystemF("\"C:/Program Files/Microsoft Visual Studio/2022/Community/VC/Tools/MSVC/14.36.32532/bin/Hostx64/x64/link.exe\" %.*s.obj /nologo /subsystem:console /debug /entry:main /out:%.*s.exe", S8_Expand(asmf), S8_Expand(asmf)); + int result = OS_SystemF("%.*s.exe", S8_Expand(asmf)); + IO_Assert(result == 0); + LC_LangEnd(); + } + + IO_DebugBreak(); + return 0; +} diff --git a/tests/any.txt b/tests/any.txt new file mode 100644 index 0000000..3c36377 --- /dev/null +++ b/tests/any.txt @@ -0,0 +1,106 @@ +import "libc"; + +/** + * doc comment test + * +**/ +print :: proc(v: Any) { + switch(v.type) { + case typeof(:int): { + val := :*int(v.data); + assert(*val == 4); + } + default: assert(0); + } +} + +modify_any :: proc(v: Any) { + switch v.type { + case typeof(:int): { + val := :*int(v.data); + val[0] += 1; + } + case typeof(:*int): { + val := *:**int(v.data); + val[0] += 1; + } + default: assert(0); + } +} + +any_vargs :: proc(fmt: *char, ...Any) { + va: va_list; + va_start(va, fmt); + + for i := 0; fmt[i]; i += 1 { + if fmt[i] == '%' { + val := va_arg_any(va); + assert(val.type == typeof(:int) || + val.type == typeof(:float) || + val.type == typeof(:double)|| + val.type == typeof(:*char) || + val.type == typeof(:char) || + val.type == typeof(:String)); + } + } + + va_end(va); +} + +main :: proc(): int { + { + i: int; + modify_any(i); + assert(i == 0); + + modify_any(&i); + assert(i == 1); + } + + { + i: int = 4; + ii: *int = &i; + a: Any = {typeof(&i), &ii}; + b: Any = &i; + c: Any = a; + + assert(*:**int(a.data) == *:**int(b.data)); + assert(a.type == b.type); + + assert(a.data == c.data); + assert(a.type == c.type); + } + + { + a: Any = 32; + b: Any = 33; + + assert(*:*int(a.data) + 1 == *:*int(b.data)); + } + + { + c: Any = "thing"; + d: Any = 32.5232; + e: Any = :float(32); + f: Any = :String("another_thing"); + + assert(c.type == typeof(:*char)); + assert(d.type == typeof(:double)); + assert(e.type == typeof(:float)); + assert(f.type == typeof(:String)); + } + + { + a: String = "asd"; + b: Any = a; + + assert(:*String(b.data).len == 3); + } + + { + any_vargs("% % %", "asd", 32, 32.042); + any_vargs("% % %", :String("asd"), :char(32), :float(32.042)); + } + + return 0; +} diff --git a/tests/any2.txt b/tests/any2.txt new file mode 100644 index 0000000..72391a4 --- /dev/null +++ b/tests/any2.txt @@ -0,0 +1,4 @@ +// #failed: resolve +// #error: non constant global declarations are illegal +global: int = 4; +any_global: Any = global; \ No newline at end of file diff --git a/tests/arrays.txt b/tests/arrays.txt new file mode 100644 index 0000000..c6f9b2f --- /dev/null +++ b/tests/arrays.txt @@ -0,0 +1,25 @@ +import "libc"; + +p :: proc(a: [100]int @unused) { +} +vv: [10]int = {[5] = 4}; + +str := :[]*char{"A", "B", "CD"}; + +#static_assert(1 == 1); +main :: proc(): int { + v: [100]int = {1,2}; + #static_assert(typeof(v) == typeof(:[100]int)); + assert(v[0] == 1); + assert(v[1] == 2); + assert(vv[5] == 4); + assert(vv[6] == 0); + p(v); // disallow? + + assert(str[0][0] == 'A'); + + p0: *int = &v[0]; + p1 := &v[0]; + #static_assert(typeof(p0) == typeof(p1)); + return 0; +} \ No newline at end of file diff --git a/tests/assign.txt b/tests/assign.txt new file mode 100644 index 0000000..2153263 --- /dev/null +++ b/tests/assign.txt @@ -0,0 +1,173 @@ +// #failed: resolve +// #expected_error_count: 41 + +E :: typedef int; +EA :: 0; +EB :: ^; + +S :: struct {a: int;} +Ts :: typedef int; +@weak T :: typedef int; + +main :: proc(): int { + { + a: int; + a = EB; + a /= 1; + a *= 1; + a %= 1; + a -= 1; + a += 1; + a &= 1; + a |= 1; + a <<= 1; + a >>= 1; + } + + { + a: float; + a = 1; + a /= 1; + a *= 1; + a -= 1; + a += 1; + {a %= 1;} + {a &= 1;} + {a |= 1;} + {a <<= 1;} + {a >>= 1;} + } + + { + a: E; + a = 1; + a /= 1; + a *= 1; + a %= 1; + a -= 1; + a += 1; + a &= 1; + a |= 1; + a <<= 1; + a >>= 1; + + a = EB; + a /= EB; + a *= EB; + a %= EB; + a -= EB; + a += EB; + a &= EB; + a |= EB; + a <<= EB; + a >>= EB; + } + + { + b: int; + a: *int; + a = &b; + {a /= &b;} + {a *= &b;} + {a %= &b;} + {a -= &b;} + {a += &b;} + {a &= &b;} + {a |= &b;} + {a <<= &b;} + {a >>= &b;} + } + + { + a: S; + b: S; + a = b; + {a /= b;} + {a *= b;} + {a %= b;} + {a -= b;} + {a += b;} + {a &= b;} + {a |= b;} + {a <<= b;} + {a >>= b;} + } + + { + a: Ts; + b: Ts; + a = 1; + a /= 1; + a *= 1; + a %= 1; + a -= 1; + a += 1; + a &= 1; + a |= 1; + a <<= 1; + a >>= 1; + a = b; + a /= b; + a *= b; + a %= b; + a -= b; + a += b; + a &= b; + a |= b; + a <<= b; + a >>= b; + } + + { + a: T; + b: T; + a = 1; + a /= 1; + a *= 1; + a %= 1; + a -= 1; + a += 1; + a &= 1; + a |= 1; + a <<= 1; + a >>= 1; + a = b; + a /= b; + a *= b; + a %= b; + a -= b; + a += b; + a &= b; + a |= b; + a <<= b; + a >>= b; + } + + { + a: String = "memes"; + b: String = "memes"; + a = "something_else"; + a /= "something_else"; + a *= "something_else"; + a %= "something_else"; + a -= "something_else"; + a += "something_else"; + a &= "something_else"; + a |= "something_else"; + a <<= "something_else"; + a >>= "something_else"; + a = b; + a /= b; + a *= b; + a %= b; + a -= b; + a += b; + a &= b; + a |= b; + a <<= b; + a >>= b; + } + + return 0; +} + diff --git a/tests/assign_void_proc.txt b/tests/assign_void_proc.txt new file mode 100644 index 0000000..b702f4a --- /dev/null +++ b/tests/assign_void_proc.txt @@ -0,0 +1,18 @@ +// #failed: resolve +A :: proc() {} +B :: proc() {} +C :: proc() {} +D :: proc() {} +E :: proc() {} + +main :: proc(): int { + a := A(); + b := +B(); + c := C() + D(); + e := E() + 10; + return 0; +} +// #error: cannot assign void expression to a variable +// #error: invalid unary operation for type 'void' +// #error: cannot perform binary operation, types don't qualify for it, left: 'void' right: 'void' +// #error: cannot perform binary operation, types don't qualify for it, left: 'void' right: 'UntypedInt' \ No newline at end of file diff --git a/tests/break_inside_defer.txt b/tests/break_inside_defer.txt new file mode 100644 index 0000000..e012897 --- /dev/null +++ b/tests/break_inside_defer.txt @@ -0,0 +1,12 @@ +// #failed: resolve +// #error: break inside of defer is illegal + +main :: proc() { + defer { + { + { + for { break; } + } + } + } +} \ No newline at end of file diff --git a/tests/break_outside_loop.txt b/tests/break_outside_loop.txt new file mode 100644 index 0000000..b5f0883 --- /dev/null +++ b/tests/break_outside_loop.txt @@ -0,0 +1,6 @@ +// #failed: resolve +// #error: break outside of a for loop is illegal + +main :: proc() { + break; +} \ No newline at end of file diff --git a/tests/build_if_note.txt b/tests/build_if_note.txt new file mode 100644 index 0000000..f799956 --- /dev/null +++ b/tests/build_if_note.txt @@ -0,0 +1,21 @@ +A :: proc() { +} @build_if(LC_OS == OS_LINUX) + +A :: proc() { +} @build_if(LC_OS == OS_WINDOWS) + +A :: proc() { +} @build_if(LC_OS == OS_MAC) + + +B :: proc() { +} @build_if(0) + +B :: proc() { +} + +main :: proc(): int { + A(); + B(); + return 0; +} \ No newline at end of file diff --git a/tests/builtins.txt b/tests/builtins.txt new file mode 100644 index 0000000..5582176 --- /dev/null +++ b/tests/builtins.txt @@ -0,0 +1,89 @@ +import "libc"; + +main :: proc(): int { + a: int; + d: float; + assert(typeof(:int) == typeof(:int)); + assert(typeof(:int) == typeof(a)); + assert(typeof(:float) != typeof(:int)); + assert(sizeof(:int) == sizeof(a)); + assert(alignof(:int) == alignof(:int)); + assert(sizeof(:int) != sizeof(:*int)); + assert(typeof(:int) != typeof(:*int)); + assert(alignof(:int) != alignof(:*int)); + assert(typeof(:*int) == typeof(&a)); + assert(sizeof(:*int) == sizeof(&a)); + assert(sizeof(a) == sizeof(d)); + + arr: [30]int; + assert(lengthof(arr) == 30); + assert(sizeof(arr) == lengthof(arr) * sizeof(:int)); + assert(typeof(arr) == typeof(:[30]int)); + assert(typeof(:int) != typeof(:[30]int)); + assert(typeof(arr[0]) == typeof(a)); + assert(typeof(:double) != typeof(:int)); + assert(typeof(:double) != typeof(:*double)); + + t := :[]ullong{ + typeof(:char), + typeof(:uchar), + typeof(:short), + typeof(:ushort), + typeof(:bool), + typeof(:int), + typeof(:uint), + typeof(:long), + typeof(:ulong), + typeof(:llong), + typeof(:ullong), + typeof(:float), + typeof(:double), + typeof(:*char), + typeof(:*uchar), + typeof(:*short), + typeof(:*ushort), + typeof(:*bool), + typeof(:*int), + typeof(:*uint), + typeof(:*long), + typeof(:*ulong), + typeof(:*llong), + typeof(:*ullong), + typeof(:*float), + typeof(:*double), + typeof(:[1]char), + typeof(:[1]uchar), + typeof(:[1]short), + typeof(:[1]ushort), + typeof(:[1]bool), + typeof(:[1]int), + typeof(:[1]uint), + typeof(:[1]long), + typeof(:[1]ulong), + typeof(:[1]llong), + typeof(:[1]ullong), + typeof(:[1]float), + typeof(:[1]double), + typeof(:**char), + typeof(:**uchar), + typeof(:**short), + typeof(:**ushort), + typeof(:**bool), + typeof(:**int), + typeof(:**uint), + typeof(:**long), + typeof(:**ulong), + typeof(:**llong), + typeof(:**ullong), + typeof(:**float), + typeof(:**double), + }; + for i := 0; i < lengthof(t); i += 1 { + for j := 0; j < lengthof(t); j += 1 { + if (i==j) continue; + assert(t[i] != t[j]); + } + } + + return 0; +} \ No newline at end of file diff --git a/tests/builtins2.txt b/tests/builtins2.txt new file mode 100644 index 0000000..2dd5698 --- /dev/null +++ b/tests/builtins2.txt @@ -0,0 +1,12 @@ +// #failed: resolve +// #expected_error_count: 6 + +main :: proc(): int { + sizeof(:int, a = 10); + sizeof(a = 10); + sizeof(10); + + alignof(:int, a = 10); + alignof(a = 10); + alignof(10); +} diff --git a/tests/builtins3.txt b/tests/builtins3.txt new file mode 100644 index 0000000..f1dd185 --- /dev/null +++ b/tests/builtins3.txt @@ -0,0 +1,21 @@ +// #failed: resolve + +A :: struct { + a: int; + b: int; +} + +main :: proc(): int { + offsetof(:A, b); + +// #error: first argument should be a type + offsetof(A, b); + +// #error: expected 2 arguments to builtin procedure 'offsetof', got: 3 + offsetof(:A, b, b); + +// #error: named arguments in this builtin procedure are illegal + offsetof(a = :A, b); + + return 0; +} \ No newline at end of file diff --git a/tests/cannot_use_type_as_value.txt b/tests/cannot_use_type_as_value.txt new file mode 100644 index 0000000..b1ad73a --- /dev/null +++ b/tests/cannot_use_type_as_value.txt @@ -0,0 +1,13 @@ +// #failed: resolve +A :: struct { a: int; b: int; } +B :: typedef int; + +main :: proc(): int { +// #error: cannot use type as value + a := :A; +// #error: cannot use type as value + b := :A.i; +// #error: declaration is type, unexpected inside expression + d := B; + return 0; +} \ No newline at end of file diff --git a/tests/compilation/test_compile_header.cpp b/tests/compilation/test_compile_header.cpp new file mode 100644 index 0000000..c0117a1 --- /dev/null +++ b/tests/compilation/test_compile_header.cpp @@ -0,0 +1,4 @@ +#include "../../src/compiler/lib_compiler.h" + +int main() { +} \ No newline at end of file diff --git a/tests/compilation/test_compile_packed.c b/tests/compilation/test_compile_packed.c new file mode 100644 index 0000000..8148b18 --- /dev/null +++ b/tests/compilation/test_compile_packed.c @@ -0,0 +1,40 @@ +#define LIB_COMPILER_IMPLEMENTATION +#include "../../lib_compiler.h" + +int main(int argc, char **argv) { + bool colored = LC_EnableTerminalColors(); + + LC_StringList dirs = {0}; + LC_Arena arena = {0}; + + LC_String package = LC_MakeEmptyString(); + for (int i = 1; i < argc; i += 1) { + LC_String arg = LC_MakeFromChar(argv[i]); + if (LC_StartsWith(arg, LC_Lit("dir="), LC_IgnoreCase)) { + LC_String dir = LC_Skip(arg, 4); + LC_AddNode(&arena, &dirs, dir); + } else { + package = arg; + } + } + + if (package.len == 0) { + printf("package name not passed\n"); + return 0; + } + + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = colored; + LC_LangBegin(lang); + LC_RegisterPackageDir("."); + for (LC_StringNode *it = dirs.first; it; it = it->next) { + LC_RegisterPackageDir(it->string.str); + } + + LC_Intern name = LC_InternStrLen(package.str, (int)package.len); + LC_ASTRefList packages = LC_ResolvePackageByName(name); + if (lang->errors) return 1; + + LC_String code = LC_GenerateUnityBuild(packages); + (void)code; +} \ No newline at end of file diff --git a/tests/compilation/test_compile_packed_cpp.c b/tests/compilation/test_compile_packed_cpp.c new file mode 100644 index 0000000..8148b18 --- /dev/null +++ b/tests/compilation/test_compile_packed_cpp.c @@ -0,0 +1,40 @@ +#define LIB_COMPILER_IMPLEMENTATION +#include "../../lib_compiler.h" + +int main(int argc, char **argv) { + bool colored = LC_EnableTerminalColors(); + + LC_StringList dirs = {0}; + LC_Arena arena = {0}; + + LC_String package = LC_MakeEmptyString(); + for (int i = 1; i < argc; i += 1) { + LC_String arg = LC_MakeFromChar(argv[i]); + if (LC_StartsWith(arg, LC_Lit("dir="), LC_IgnoreCase)) { + LC_String dir = LC_Skip(arg, 4); + LC_AddNode(&arena, &dirs, dir); + } else { + package = arg; + } + } + + if (package.len == 0) { + printf("package name not passed\n"); + return 0; + } + + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = colored; + LC_LangBegin(lang); + LC_RegisterPackageDir("."); + for (LC_StringNode *it = dirs.first; it; it = it->next) { + LC_RegisterPackageDir(it->string.str); + } + + LC_Intern name = LC_InternStrLen(package.str, (int)package.len); + LC_ASTRefList packages = LC_ResolvePackageByName(name); + if (lang->errors) return 1; + + LC_String code = LC_GenerateUnityBuild(packages); + (void)code; +} \ No newline at end of file diff --git a/tests/compilation/test_compile_with_core.c b/tests/compilation/test_compile_with_core.c new file mode 100644 index 0000000..3a27378 --- /dev/null +++ b/tests/compilation/test_compile_with_core.c @@ -0,0 +1,5 @@ +#include "../../src/compiler/lib_compiler.c" +#include "../../src/core/core.c" + +int main() { +} \ No newline at end of file diff --git a/tests/compilation/test_compile_with_core_cpp.cpp b/tests/compilation/test_compile_with_core_cpp.cpp new file mode 100644 index 0000000..3a27378 --- /dev/null +++ b/tests/compilation/test_compile_with_core_cpp.cpp @@ -0,0 +1,5 @@ +#include "../../src/compiler/lib_compiler.c" +#include "../../src/core/core.c" + +int main() { +} \ No newline at end of file diff --git a/tests/compo_cyclic_error.txt b/tests/compo_cyclic_error.txt new file mode 100644 index 0000000..cc3ea33 --- /dev/null +++ b/tests/compo_cyclic_error.txt @@ -0,0 +1,11 @@ +// #failed: resolve +// #error: cyclic dependency +A :: struct { + a: int; + b: int; +} + +AA: A = { + a = 10, + b = AA.a, +}; \ No newline at end of file diff --git a/tests/compos.txt b/tests/compos.txt new file mode 100644 index 0000000..3720624 --- /dev/null +++ b/tests/compos.txt @@ -0,0 +1,55 @@ +import "libc"; + +Node :: struct { + i: int; + l: *Node; + r: *Node; +} + +v: int; +thing :: proc(a:int @unused, b:int @unused, c:int @unused) {} +thingp :: proc(): *int {return &v;} + +default_args :: proc(a: int = 10 @unused, b: int = 10 @unused): int {return 0;} +vargs_proc :: proc(a: int @unused, ...) {} + +// v1 := default_args(v0, v0); // @todo: make error +// v0 := default_args(1,2); +main :: proc(): int { + node: Node = { + i = 1, + l = &:Node{ + i = 2, + }, + r = &:Node{ + i = 3, + l = &:Node{ + i = 4, + } + } + }; + + default_args(); + default_args(a = 1); + default_args(b = 2); + default_args(1, 2); + default_args(a = 1, b = 2); + default_args(1, b = 2); + + vargs_proc(1, 2, 3, 4); + vargs_proc(1); + + assert(node.i == 1); + assert(node.l.i == 2); + assert(node.r.i == 3); + assert(node.r.l.i == 4); + + :Node{2}.i = 2; + assert(:Node{2}.i == 2); + thing(1,2,3); + assert(thingp()[0] == 0); + thingp()[0] = 0; + *thingp() = 0; + + return 0; +} \ No newline at end of file diff --git a/tests/compos2.txt b/tests/compos2.txt new file mode 100644 index 0000000..5a5805d --- /dev/null +++ b/tests/compos2.txt @@ -0,0 +1,4 @@ +// #failed: resolve +// #error: cannot assign, types require explicit cast, variable type: '[6]int' expression type: '[5]int' + +d: [6]int = :[5]int{1, 2, 3, 4}; \ No newline at end of file diff --git a/tests/compos_resolve.txt b/tests/compos_resolve.txt new file mode 100644 index 0000000..e3be3cf --- /dev/null +++ b/tests/compos_resolve.txt @@ -0,0 +1,48 @@ +// #failed: resolve + +Vals :: struct {a:int;b:int;} + +vv0: Vals = {1, 2}; +vv1: Vals = {1}; +vv2: Vals = {a = 1}; +vv3: Vals = {a = 1, b = 2}; +vv4: Vals = {}; + +v0 := :Vals {1, 2}; +v1 := :Vals {1}; +v2 := :Vals {a = 1}; +v3 := :Vals {a = 1, b = 2}; +v4 := :Vals {}; + +// #error: too many struct initializers, expected less then 2 got instead 3 +e0 := :Vals {1, 2, 3}; +// #error: too many struct initializers, expected less then 2 got instead 3 +e1 := :Vals {a = 1, b = 2, c = 3}; +// #error: no matching declaration with name 'c' in type 'Vals' +e2 := :Vals {c = 3}; +// #error: mixing named and positional arguments is illegal +e3 := :Vals {a = 2, 2}; +// #error: mixing named and positional arguments is illegal +e4 := :Vals {b = 2, 2}; +// #error: mixing named and positional arguments is illegal +e5 := :Vals {c = 2, 2}; + +Node :: struct { + l: *Node; + r: *Node; + i: int; +} + +// #error: cannot assign, can assign only const integer equal to 0, variable type: '*Node' expression type: 'UntypedInt' +n0: Node = {i = 10, l = &:Node{1, 2, 3}}; // this is legal, do we do something about this? + +a: int; +// #error: cannot assign, types require explicit cast, variable type: '*Node' expression type: '*int' +ne0: Node = {i = 10, l = &:Node{&a}}; +// #error: too many struct initializers, expected less then 3 got instead 4 +ne1: Node = {i = 10, l = &:Node{1, 2, 3, 4}}; +// #error: no matching declaration with name 'c' in type 'Node' +ne2: Node = {i = 10, l = &:Node{c = 2}}; +// #error: mixing named and positional arguments is illegal +ne3: Node = {i = 10, l = &:Node{l = 0, r = 0, 2}}; + diff --git a/tests/const.txt b/tests/const.txt new file mode 100644 index 0000000..c492e35 --- /dev/null +++ b/tests/const.txt @@ -0,0 +1,4 @@ +// #dont_run +A :: 123 + B + 23 + 123412512 + 123 + B; +B :: 11; +C :: A + B + A + B + 3251; \ No newline at end of file diff --git a/tests/custom_untyped_string.txt b/tests/custom_untyped_string.txt new file mode 100644 index 0000000..927158a --- /dev/null +++ b/tests/custom_untyped_string.txt @@ -0,0 +1,37 @@ +import "libc"; + + +S :: struct { s: String; } + +main :: proc(): int { + using_const: String = "Something"; + str := using_const.str; + len := using_const.len; + + assert(str[0] == 'S'); + assert(typeof(str) == typeof(:*char)); + assert(typeof(len) == typeof(:int)); + + cast_string := :String("Something"); + assert(typeof(cast_string) == typeof(:String)); + assert(cast_string.str[0] == 'S'); + assert(cast_string.len == 9); + + new_line: String = "\n"; + assert(new_line.len == 1); + assert(*new_line.str == '\n'); + + ss: S = { "Thing" }; @unused + ss2: S = { {str = "asd", len = 3} }; @unused + + proc_call("Memes"); + + constant :: "string"; + from_constant: String = constant; @unused + + return 0; +} + +global_string: String = "Something"; +global_s: S = { "Thing" }; +proc_call :: proc(s: String @unused) {} \ No newline at end of file diff --git a/tests/defer_inside_defer.txt b/tests/defer_inside_defer.txt new file mode 100644 index 0000000..271c24c --- /dev/null +++ b/tests/defer_inside_defer.txt @@ -0,0 +1,11 @@ +// #failed: resolve +// #error: defer inside of defer is illegal + +main :: proc(): int { + i := 0; + defer { + defer i += 1; + i += 1; + } + return 0; +} \ No newline at end of file diff --git a/tests/defer_order.txt b/tests/defer_order.txt new file mode 100644 index 0000000..6bb0d6c --- /dev/null +++ b/tests/defer_order.txt @@ -0,0 +1,21 @@ +i := 0; +a: [4]int; +test :: proc() { + defer {a[i] = 1; i += 1;} + defer {a[i] = 2; i += 1;} + defer {a[i] = 3; i += 1;} + defer {a[i] = 4; i += 1;} +} + +main :: proc(): int { + test(); + + i1 := a[0] == 4; + i2 := a[1] == 3; + i3 := a[2] == 2; + i4 := a[3] == 1; + + result := i1 + i2 + i3 + i4; + result -= 4; + return :int(result); +} \ No newline at end of file diff --git a/tests/defer_with_return_inside.txt b/tests/defer_with_return_inside.txt new file mode 100644 index 0000000..f507d35 --- /dev/null +++ b/tests/defer_with_return_inside.txt @@ -0,0 +1,7 @@ +// #failed: resolve +// #error: returning from defer block is illegal + +main :: proc(): int { + defer return 0; + return 0; +} \ No newline at end of file diff --git a/tests/division_by_0.txt b/tests/division_by_0.txt new file mode 100644 index 0000000..ebf58b1 --- /dev/null +++ b/tests/division_by_0.txt @@ -0,0 +1,3 @@ +// #failed: resolve +// #error: division by 0 +a :: 10.0 / 0.0; \ No newline at end of file diff --git a/tests/doc_comment.txt b/tests/doc_comment.txt new file mode 100644 index 0000000..f8f2a32 --- /dev/null +++ b/tests/doc_comment.txt @@ -0,0 +1,36 @@ +// #failed: parse +// #error: got unexpected token: doc comment +// #error: got unexpected token: doc comment + + +/** + * doc comment test + * +**/ +A :: proc() { +} + +/** + * doc comment test + * +**/ + +/** + * doc comment test + * +**/ +B :: proc() { +} + + +/** + * doc comment test + * +**/ + +/** + * doc comment test + * +**/ +C :: proc() { +} \ No newline at end of file diff --git a/tests/doc_comments2.txt b/tests/doc_comments2.txt new file mode 100644 index 0000000..5ddf8af --- /dev/null +++ b/tests/doc_comments2.txt @@ -0,0 +1,17 @@ +/** package +* package doc comment +*/ + +/** file +* file doc comment +*/ + +/** +* normal doc comment +*/ +something :: proc() { +} + +main :: proc(): int { + return 0; +} \ No newline at end of file diff --git a/tests/doc_comments3.txt b/tests/doc_comments3.txt new file mode 100644 index 0000000..76f17fa --- /dev/null +++ b/tests/doc_comments3.txt @@ -0,0 +1,8 @@ +// #failed: parse +// #error: got unexpected token: package doc comment + +/** file +*/ + +/** package +*/ \ No newline at end of file diff --git a/tests/duplicate_package_name/32asd/a.lc b/tests/duplicate_package_name/32asd/a.lc new file mode 100644 index 0000000..535416b --- /dev/null +++ b/tests/duplicate_package_name/32asd/a.lc @@ -0,0 +1,2 @@ +b :: proc() { +} \ No newline at end of file diff --git a/tests/duplicate_package_name/main/main.lc b/tests/duplicate_package_name/main/main.lc new file mode 100644 index 0000000..bb96065 --- /dev/null +++ b/tests/duplicate_package_name/main/main.lc @@ -0,0 +1,6 @@ +import "std_types"; +import "32asd"; + +main :: proc(): int { + return 0; +} \ No newline at end of file diff --git a/tests/duplicate_package_name/std_types/a.lc b/tests/duplicate_package_name/std_types/a.lc new file mode 100644 index 0000000..f7d96f8 --- /dev/null +++ b/tests/duplicate_package_name/std_types/a.lc @@ -0,0 +1,2 @@ +a :: proc() { +} \ No newline at end of file diff --git a/tests/duplicate_package_name/test.txt b/tests/duplicate_package_name/test.txt new file mode 100644 index 0000000..8d576f0 --- /dev/null +++ b/tests/duplicate_package_name/test.txt @@ -0,0 +1,3 @@ +// #failed: package +// #error: found 2 directories with the same name +// #error: invalid package name, please change \ No newline at end of file diff --git a/tests/error_call_proc_in_global_space.txt b/tests/error_call_proc_in_global_space.txt new file mode 100644 index 0000000..4589193 --- /dev/null +++ b/tests/error_call_proc_in_global_space.txt @@ -0,0 +1,10 @@ +// #failed: resolve +// #error: non constant global declarations are illegal +// #error: expected an untyped constant + +thing :: proc(): int { + return 0; +} + +variable := thing(); +constant :: thing(); \ No newline at end of file diff --git a/tests/error_in_global_and_local.txt b/tests/error_in_global_and_local.txt new file mode 100644 index 0000000..5a1bb99 --- /dev/null +++ b/tests/error_in_global_and_local.txt @@ -0,0 +1,9 @@ +// #failed: resolve +// #error: undeclared identifier 'meme' +A: meme; + +main :: proc(): int { +// #error: undeclared identifier 'asd' + a: asd; + return a; +} \ No newline at end of file diff --git a/tests/error_non_const_in_global_scope.txt b/tests/error_non_const_in_global_scope.txt new file mode 100644 index 0000000..1e9559e --- /dev/null +++ b/tests/error_non_const_in_global_scope.txt @@ -0,0 +1,37 @@ +// #failed: resolve + +BUILTIN_sizeof := sizeof(:int); +BUILTIN_alignof := sizeof(:int); +BUILTIN_typedef := typeof(F); +BUILTIN_offsetof := offsetof(:STRUCT, a); + +A: int; +B: *int = &A; +PROC :: proc(): int {return 10;} +ARR: [4]int = {1,2,3,4}; +// #error: non constant global declarations are illegal +ARR_PROC_VAL := :[]int{PROC(),2,3,4}; + +// #error: non constant global declarations are illegal +ARR_VAL := ARR[0]; +// #error: non constant global declarations are illegal +C := *B; +// #error: non constant global declarations are illegal +D := B[0]; +//// #error: non constant global declarations are illegal +//E := B^[0]; +// #error: non constant global declarations are illegal +VAR := PROC(); + +// #error: cannot assign, can assign only const integer equal to 0, variable type: '*int' expression type: 'UntypedInt' +F: *int = 1 - 1; +// #error: cannot assign, can assign only const integer equal to 0, variable type: '*int' expression type: 'UntypedInt' +G: *int = -(1-1); + +STRUCT :: struct { a: int; b: int; } +STRUCT_VAL: STRUCT = { 1, 2 }; + +GG := STRUCT_VAL.a; +// #error: non constant global declarations are illegal +STRUCT_VAL_PROC: STRUCT = {PROC()}; + diff --git a/tests/error_on_shadowing.txt b/tests/error_on_shadowing.txt new file mode 100644 index 0000000..1e76a50 --- /dev/null +++ b/tests/error_on_shadowing.txt @@ -0,0 +1,12 @@ +// #failed: resolve +main :: proc(): int { + +// #error: there are 2 decls with the same name 'a' +// #error: a + a: int; + { + a: int; + } + + return 1; +} \ No newline at end of file diff --git a/tests/error_pointer_arithmetic.txt b/tests/error_pointer_arithmetic.txt new file mode 100644 index 0000000..a13ca9f --- /dev/null +++ b/tests/error_pointer_arithmetic.txt @@ -0,0 +1,20 @@ +// #failed: resolve +// #error: invalid binary operation for type '*int' +// #error: invalid binary operation for type '*int' +// #error: invalid binary operation for type '*int' +// #error: invalid binary operation for type '*int' +// #error: indexing with non integer value of type '*int' + +main :: proc(): int { + a: *int; + b: *int; + val: int; + + c := a - b; + d := a - 4; + e := a * 2; + f := a + val; + g := &a[b]; + + return 0; +} \ No newline at end of file diff --git a/tests/error_proc_invalid_args.txt b/tests/error_proc_invalid_args.txt new file mode 100644 index 0000000..1dc7ff7 --- /dev/null +++ b/tests/error_proc_invalid_args.txt @@ -0,0 +1,41 @@ +// #failed: resolve +// #error: unknown argument to a procedure call, couldn't match it with any of the declared arguments +// #error: unknown argument to a procedure call, couldn't match it with any of the declared arguments +// #error: unknown argument to a procedure call, couldn't match it with any of the declared arguments +// #error: mixing named and positional arguments is illegal +// #error: mixing named and positional arguments is illegal + +// #error: invalid argument count passed in to procedure call +// #error: invalid argument count passed in to procedure call +// #error: invalid argument count passed in to procedure call +// #error: invalid argument count passed in to procedure call +// #error: unknown argument to a procedure call, couldn't match it with any of the declared arguments + +// #error: cannot assign void expression to a variable + +default_args :: proc(a: int = 10, b: int = 10): int { + return a + b; +} + +no_default :: proc(a: int @unused, b: int @unused) { + +} + +main :: proc(): int { + def0 := default_args(1,2,3); + def1 := default_args(c = 10); + def2 := default_args(1, a = 1, b = 2); + def3 := default_args(a = 1, 2); + def4 := default_args(b = 1, 2); + + no_default(); + no_default(1); + no_default(a = 1); + no_default(b = 1); + no_default(a = 2, c = 1); + + assign_void := no_default(1, 2); + + return 0; +} + diff --git a/tests/error_when_assigning_compo_to_global.txt b/tests/error_when_assigning_compo_to_global.txt new file mode 100644 index 0000000..c0b0e28 --- /dev/null +++ b/tests/error_when_assigning_compo_to_global.txt @@ -0,0 +1,8 @@ +a: [2]int; + +main :: proc(): int { + a = {[1] = 2}; + a = {1, 2}; + + return a[1] - 2; +} \ No newline at end of file diff --git a/tests/errors.txt b/tests/errors.txt new file mode 100644 index 0000000..8d2fda9 --- /dev/null +++ b/tests/errors.txt @@ -0,0 +1,43 @@ +// #failed: resolve + +// #error: declaration is type, unexpected inside expression +i0 := typeof(int); +// #error: declaration is type, unexpected inside expression +i1 := sizeof(double); + +p0: *int; +// #error: non constant global declarations are illegal +p1: int = p0[0]; +// #error: invalid binary operation for type '*int' +p2 := p0 + 1; + +Tint :: typedef int; +t0: int; +t1: Tint; +// #error: cannot perform binary operation, types are incompatible, left: 'Tint' right: 'int' +t2 := t1 + t0; + +// #error: #static_assert cant be used as variable initializer +AssertInitializer: int = #static_assert(1 == 1); + +// #error: cannot assign, can assign only const integer equal to 0, variable type: '*int' expression type: 'UntypedInt' +pi0: *int = 1; +pi1: *int = nil; +// #error: cannot assign, can assign only const integer equal to 0, variable type: '*int' expression type: 'UntypedInt' +pi2: *int = 1-1; + +_pi3: *char; +// #error: cannot assign, types require explicit cast, variable type: '*int' expression type: '*char' +pi3: *int = _pi3; + + +_pi4: char; +// #error: cannot assign, types require explicit cast, variable type: '*int' expression type: '*char' +pi4: *int = &_pi4; + +// #error: cannot create a variable of type void +pi5: void = 0; +// #error: cannot create a variable of type void +pi6: void; +// #error: cannot cast, types are incompatible, left: 'void' right: 'UntypedInt' +pi7 := :void(0); diff --git a/tests/errors_proc_vargs.txt b/tests/errors_proc_vargs.txt new file mode 100644 index 0000000..5cd1d51 --- /dev/null +++ b/tests/errors_proc_vargs.txt @@ -0,0 +1,13 @@ +// #failed: resolve +// #error: calling procedure with invalid argument count, expected at least 1 args, got 0 +// #error: variadic procedures cannot have named arguments + +var_proc :: proc(a: int, ...): int { + return a; +} + +main :: proc(): int { + var_proc(); + var_proc(a = 1); + return 0; +} \ No newline at end of file diff --git a/tests/example_ui_and_hot_reloading/build.bat b/tests/example_ui_and_hot_reloading/build.bat new file mode 100644 index 0000000..7622934 --- /dev/null +++ b/tests/example_ui_and_hot_reloading/build.bat @@ -0,0 +1,7 @@ +@echo off +mkdir build +cd build + +clang unity_exe.c -o platform.exe -g -O0 -I"../.." +clang unity_dll.c -o game.dll -O0 -shared -g -I"../.." -Wl,-export:APP_Update + diff --git a/tests/example_ui_and_hot_reloading/dll/app_main.lc b/tests/example_ui_and_hot_reloading/dll/app_main.lc new file mode 100644 index 0000000..fce4086 --- /dev/null +++ b/tests/example_ui_and_hot_reloading/dll/app_main.lc @@ -0,0 +1,78 @@ +import "shared"; +IO_Assertf :: proc(b: bool, s: *char, ...); @foreign +IO_Assert :: proc(b: bool); @foreign +IO_InvalidCodepath :: proc(); @foreign +S8_Lit :: proc(s: *char): S8_String; @foreign +IO_FatalErrorf :: proc(msg: *char, ...); @foreign +IO_FatalError :: proc(msg: *char); @foreign + +HashBytes :: proc(data: *void, data_size: u64): u64; @foreign + +// @todo: hmm ? +SLL_QUEUE_ADD :: proc(first: *void, last: *void, data: *void); @foreign + +Mu: *MU_Context; +Gs: *GameState; +Perm: *MA_Arena; +Temp: *MA_Arena; +R: *R_Render; + +GameState :: struct { + render: R_Render; +} + +activated: bool; +APP_Update :: proc(event: LibraryEvent, mu: *MU_Context, dll_context: *DLL_Context) { + Mu = mu; + Perm = &dll_context.perm; + Temp = dll_context.temp; + Gs = dll_context.context; + + if event == Init { + dll_context.context = MA_PushSize(Perm, :usize(sizeof(:GameState))); + Gs = dll_context.context; + + R_Init(&Gs.render); + return; + } + + if event == Reload { + R_Reload(); + return; + } + + if event == Unload { + return; + } + + UI_Begin(); + Ui.cut = UI_Cut_Top; + UI_PushLayout({}); + { + Ui.cut = UI_Cut_Left; + + if (UI_Checkbox(&activated, "File")) { + } + UI_Button("Edit"); + Ui.cut = UI_Cut_Right; + UI_Button("Memes"); + + Ui.s.cut_size.x += 100000; + UI_Fill(); + UI_PopLayout(); + UI_PopStyle(); + } + UI_End(); + + R_Text2D({ + pos = {100, 100}, + text = S8_Lit("Testing memes"), + color = R_ColorWhite, + do_draw = true, + scale = 1.0, + }); + + R_Rect2D(R2P_SizeF(200, 200, 100, 100), R.atlas.white_texture_bounding_box, R_ColorWhite); + + R_EndFrame(); +} \ No newline at end of file diff --git a/tests/example_ui_and_hot_reloading/dll/math.lc b/tests/example_ui_and_hot_reloading/dll/math.lc new file mode 100644 index 0000000..6a89545 --- /dev/null +++ b/tests/example_ui_and_hot_reloading/dll/math.lc @@ -0,0 +1,122 @@ + +V2 :: struct { x: f32; y: f32; } +V3 :: struct { x: f32; y: f32; z: f32; } +V4 :: struct { x: f32; y: f32; z: f32; w: f32; } +R2P :: struct { min: V2; max: V2; } + +V2I :: struct { x: i32; y: i32; } +V3I :: struct { x: i32; y: i32; z: i32; } +V4I :: struct { x: i32; y: i32; z: i32; w: i32; } + +R2P_SizeF :: proc(px: f32, py: f32, sx: f32, sy: f32): R2P { + result: R2P = {{px, py}, {px + sx, py + sy}}; + return result; +} + +R2P_Size :: proc(pos: V2, size: V2): R2P { + result := :R2P{{pos.x, pos.y}, {pos.x + size.x, pos.y + size.y}}; + return result; +} + +R2P_GetSize :: proc(r: R2P): V2 { + result := :V2{r.max.x - r.min.x, r.max.y - r.min.y}; + return result; +} + +V2_Mul :: proc(a: V2, b: V2): V2 { + result := :V2{a.x * b.x, a.y * b.y}; + return result; +} + +V2_MulF :: proc(a: V2, b: f32): V2 { + result := :V2{a.x * b, a.y * b}; + return result; +} + +V2_FromV2I :: proc(a: V2I): V2 { + result := :V2{:f32(a.x), :f32(a.y)}; + return result; +} + +I32_Max :: proc(a: i32, b: i32): i32 { + if a > b return a; + return b; +} + +I32_Min :: proc(a: i32, b: i32): i32 { + if a > b return b; + return a; +} + +F32_Max :: proc(a: f32, b: f32): f32 { + if a > b return a; + return b; +} + +F32_Min :: proc(a: f32, b: f32): f32 { + if a > b return b; + return a; +} + +F32_Clamp :: proc(val: f32, min: f32, max: f32): f32 { + if (val > max) return max; + if (val < min) return min; + return val; +} + +R2P_CutLeft :: proc(r: *R2P, value: float): R2P { + minx := r.min.x; + r.min.x = F32_Min(r.max.x, r.min.x + value); + return :R2P{ + { minx, r.min.y}, + {r.min.x, r.max.y} + }; +} + +R2P_CutRight :: proc(r: *R2P, value: f32): R2P { + maxx := r.max.x; + r.max.x = F32_Max(r.max.x - value, r.min.x); + return :R2P{ + {r.max.x, r.min.y}, + { maxx, r.max.y} + }; +} + +R2P_CutTop :: proc(r: *R2P, value: f32): R2P { // Y is up + maxy := r.max.y; + r.max.y = F32_Max(r.min.y, r.max.y - value); + return :R2P{ + {r.min.x, r.max.y}, + {r.max.x, maxy} + }; +} + +R2P_CutBottom :: proc(r: *R2P, value: f32): R2P { // Y is up + miny := r.min.y; + r.min.y = F32_Min(r.min.y + value, r.max.y); + return :R2P{ + {r.min.x, miny}, + {r.max.x, r.min.y} + }; +} + +R2P_Shrink :: proc(r: R2P, size: f32): R2P { + return :R2P{ + :V2{r.min.x + size, r.min.y + size}, + :V2{r.max.x - size, r.max.y - size} + }; +} + +R2P_CollidesV2 :: proc(rect: R2P , point: V2): bool { + result := point.x > rect.min.x && point.x < rect.max.x && point.y > rect.min.y && point.y < rect.max.y; + return result; +} + +R2P_CollidesR2P :: proc(a: R2P, b: R2P): bool { + result := a.min.x < b.max.x && a.max.x > b.min.x && a.min.y < b.max.y && a.max.y > b.min.y; + return result; +} + +V2_Add :: proc(a: V2, b: V2): V2 { return {a.x + b.x, a.y + b.y}; } +V2_Sub :: proc(a: V2, b: V2): V2 { return {a.x - b.x, a.y - b.y}; } +V2_DivF :: proc(a: V2, b: f32): V2 { return {a.x / b, a.y / b}; } diff --git a/tests/example_ui_and_hot_reloading/dll/opengl.lc b/tests/example_ui_and_hot_reloading/dll/opengl.lc new file mode 100644 index 0000000..96d12de --- /dev/null +++ b/tests/example_ui_and_hot_reloading/dll/opengl.lc @@ -0,0 +1,3012 @@ + +GLfloat :: typedef float; +GLdouble :: typedef double; +GLchar :: typedef char; +GLenum :: typedef uint; +GLint :: typedef int; +GLuint :: typedef uint; +GLsizei :: typedef int; +GLboolean :: typedef uchar; +GLbitfield :: typedef uint; +GLvoid :: typedef void; +GLbyte :: typedef i8; +GLubyte :: typedef u8; +GLshort :: typedef i16; +GLushort :: typedef u16; + +GL_DEPTH_BUFFER_BIT :: 0x00000100; +GL_STENCIL_BUFFER_BIT :: 0x00000400; +GL_COLOR_BUFFER_BIT :: 0x00004000; +GL_FALSE :: 0; +GL_TRUE :: 1; +GL_POINTS :: 0x0000; +GL_LINES :: 0x0001; +GL_LINE_LOOP :: 0x0002; +GL_LINE_STRIP :: 0x0003; +GL_TRIANGLES :: 0x0004; +GL_TRIANGLE_STRIP :: 0x0005; +GL_TRIANGLE_FAN :: 0x0006; +GL_NEVER :: 0x0200; +GL_LESS :: 0x0201; +GL_EQUAL :: 0x0202; +GL_LEQUAL :: 0x0203; +GL_GREATER :: 0x0204; +GL_NOTEQUAL :: 0x0205; +GL_GEQUAL :: 0x0206; +GL_ALWAYS :: 0x0207; +GL_ZERO :: 0; +GL_ONE :: 1; +GL_SRC_COLOR :: 0x0300; +GL_ONE_MINUS_SRC_COLOR :: 0x0301; +GL_SRC_ALPHA :: 0x0302; +GL_ONE_MINUS_SRC_ALPHA :: 0x0303; +GL_DST_ALPHA :: 0x0304; +GL_ONE_MINUS_DST_ALPHA :: 0x0305; +GL_DST_COLOR :: 0x0306; +GL_ONE_MINUS_DST_COLOR :: 0x0307; +GL_SRC_ALPHA_SATURATE :: 0x0308; +GL_NONE :: 0; +GL_FRONT_LEFT :: 0x0400; +GL_FRONT_RIGHT :: 0x0401; +GL_BACK_LEFT :: 0x0402; +GL_BACK_RIGHT :: 0x0403; +GL_FRONT :: 0x0404; +GL_BACK :: 0x0405; +GL_LEFT :: 0x0406; +GL_RIGHT :: 0x0407; +GL_FRONT_AND_BACK :: 0x0408; +GL_NO_ERROR :: 0; +GL_INVALID_ENUM :: 0x0500; +GL_INVALID_VALUE :: 0x0501; +GL_INVALID_OPERATION :: 0x0502; +GL_OUT_OF_MEMORY :: 0x0505; +GL_CW :: 0x0900; +GL_CCW :: 0x0901; +GL_POINT_SIZE :: 0x0b11; +GL_POINT_SIZE_RANGE :: 0x0b12; +GL_POINT_SIZE_GRANULARITY :: 0x0b13; +GL_LINE_SMOOTH :: 0x0b20; +GL_LINE_WIDTH :: 0x0b21; +GL_LINE_WIDTH_RANGE :: 0x0b22; +GL_LINE_WIDTH_GRANULARITY :: 0x0b23; +GL_POLYGON_MODE :: 0x0b40; +GL_POLYGON_SMOOTH :: 0x0b41; +GL_CULL_FACE :: 0x0b44; +GL_CULL_FACE_MODE :: 0x0b45; +GL_FRONT_FACE :: 0x0b46; +GL_DEPTH_RANGE :: 0x0b70; +GL_DEPTH_TEST :: 0x0b71; +GL_DEPTH_WRITEMASK :: 0x0b72; +GL_DEPTH_CLEAR_VALUE :: 0x0b73; +GL_DEPTH_FUNC :: 0x0b74; +GL_STENCIL_TEST :: 0x0b90; +GL_STENCIL_CLEAR_VALUE :: 0x0b91; +GL_STENCIL_FUNC :: 0x0b92; +GL_STENCIL_VALUE_MASK :: 0x0b93; +GL_STENCIL_FAIL :: 0x0b94; +GL_STENCIL_PASS_DEPTH_FAIL :: 0x0b95; +GL_STENCIL_PASS_DEPTH_PASS :: 0x0b96; +GL_STENCIL_REF :: 0x0b97; +GL_STENCIL_WRITEMASK :: 0x0b98; +GL_VIEWPORT :: 0x0ba2; +GL_DITHER :: 0x0bd0; +GL_BLEND_DST :: 0x0be0; +GL_BLEND_SRC :: 0x0be1; +GL_BLEND :: 0x0be2; +GL_LOGIC_OP_MODE :: 0x0bf0; +GL_DRAW_BUFFER :: 0x0c01; +GL_READ_BUFFER :: 0x0c02; +GL_SCISSOR_BOX :: 0x0c10; +GL_SCISSOR_TEST :: 0x0c11; +GL_COLOR_CLEAR_VALUE :: 0x0c22; +GL_COLOR_WRITEMASK :: 0x0c23; +GL_DOUBLEBUFFER :: 0x0c32; +GL_STEREO :: 0x0c33; +GL_LINE_SMOOTH_HINT :: 0x0c52; +GL_POLYGON_SMOOTH_HINT :: 0x0c53; +GL_UNPACK_SWAP_BYTES :: 0x0cf0; +GL_UNPACK_LSB_FIRST :: 0x0cf1; +GL_UNPACK_ROW_LENGTH :: 0x0cf2; +GL_UNPACK_SKIP_ROWS :: 0x0cf3; +GL_UNPACK_SKIP_PIXELS :: 0x0cf4; +GL_UNPACK_ALIGNMENT :: 0x0cf5; +GL_PACK_SWAP_BYTES :: 0x0d00; +GL_PACK_LSB_FIRST :: 0x0d01; +GL_PACK_ROW_LENGTH :: 0x0d02; +GL_PACK_SKIP_ROWS :: 0x0d03; +GL_PACK_SKIP_PIXELS :: 0x0d04; +GL_PACK_ALIGNMENT :: 0x0d05; +GL_MAX_TEXTURE_SIZE :: 0x0d33; +GL_MAX_VIEWPORT_DIMS :: 0x0d3a; +GL_SUBPIXEL_BITS :: 0x0d50; +GL_TEXTURE_1D :: 0x0de0; +GL_TEXTURE_2D :: 0x0de1; +GL_TEXTURE_WIDTH :: 0x1000; +GL_TEXTURE_HEIGHT :: 0x1001; +GL_TEXTURE_BORDER_COLOR :: 0x1004; +GL_DONT_CARE :: 0x1100; +GL_FASTEST :: 0x1101; +GL_NICEST :: 0x1102; +GL_BYTE :: 0x1400; +GL_UNSIGNED_BYTE :: 0x1401; +GL_SHORT :: 0x1402; +GL_UNSIGNED_SHORT :: 0x1403; +GL_INT :: 0x1404; +GL_UNSIGNED_INT :: 0x1405; +GL_FLOAT :: 0x1406; +GL_CLEAR :: 0x1500; +GL_AND :: 0x1501; +GL_AND_REVERSE :: 0x1502; +GL_COPY :: 0x1503; +GL_AND_INVERTED :: 0x1504; +GL_NOOP :: 0x1505; +GL_XOR :: 0x1506; +GL_OR :: 0x1507; +GL_NOR :: 0x1508; +GL_EQUIV :: 0x1509; +GL_INVERT :: 0x150a; +GL_OR_REVERSE :: 0x150b; +GL_COPY_INVERTED :: 0x150c; +GL_OR_INVERTED :: 0x150d; +GL_NAND :: 0x150e; +GL_SET :: 0x150f; +GL_TEXTURE :: 0x1702; +GL_COLOR :: 0x1800; +GL_DEPTH :: 0x1801; +GL_STENCIL :: 0x1802; +GL_STENCIL_INDEX :: 0x1901; +GL_DEPTH_COMPONENT :: 0x1902; +GL_RED :: 0x1903; +GL_GREEN :: 0x1904; +GL_BLUE :: 0x1905; +GL_ALPHA :: 0x1906; +GL_RGB :: 0x1907; +GL_RGBA :: 0x1908; +GL_POINT :: 0x1b00; +GL_LINE :: 0x1b01; +GL_FILL :: 0x1b02; +GL_KEEP :: 0x1e00; +GL_REPLACE :: 0x1e01; +GL_INCR :: 0x1e02; +GL_DECR :: 0x1e03; +GL_VENDOR :: 0x1f00; +GL_RENDERER :: 0x1f01; +GL_VERSION :: 0x1f02; +GL_EXTENSIONS :: 0x1f03; +GL_NEAREST :: 0x2600; +GL_LINEAR :: 0x2601; +GL_NEAREST_MIPMAP_NEAREST :: 0x2700; +GL_LINEAR_MIPMAP_NEAREST :: 0x2701; +GL_NEAREST_MIPMAP_LINEAR :: 0x2702; +GL_LINEAR_MIPMAP_LINEAR :: 0x2703; +GL_TEXTURE_MAG_FILTER :: 0x2800; +GL_TEXTURE_MIN_FILTER :: 0x2801; +GL_TEXTURE_WRAP_S :: 0x2802; +GL_TEXTURE_WRAP_T :: 0x2803; +GL_REPEAT :: 0x2901; +GL_COLOR_LOGIC_OP :: 0x0bf2; +GL_POLYGON_OFFSET_UNITS :: 0x2a00; +GL_POLYGON_OFFSET_POINT :: 0x2a01; +GL_POLYGON_OFFSET_LINE :: 0x2a02; +GL_POLYGON_OFFSET_FILL :: 0x8037; +GL_POLYGON_OFFSET_FACTOR :: 0x8038; +GL_TEXTURE_BINDING_1D :: 0x8068; +GL_TEXTURE_BINDING_2D :: 0x8069; +GL_TEXTURE_INTERNAL_FORMAT :: 0x1003; +GL_TEXTURE_RED_SIZE :: 0x805c; +GL_TEXTURE_GREEN_SIZE :: 0x805d; +GL_TEXTURE_BLUE_SIZE :: 0x805e; +GL_TEXTURE_ALPHA_SIZE :: 0x805f; +GL_DOUBLE :: 0x140a; +GL_PROXY_TEXTURE_1D :: 0x8063; +GL_PROXY_TEXTURE_2D :: 0x8064; +GL_R3_G3_B2 :: 0x2a10; +GL_RGB4 :: 0x804f; +GL_RGB5 :: 0x8050; +GL_RGB8 :: 0x8051; +GL_RGB10 :: 0x8052; +GL_RGB12 :: 0x8053; +GL_RGB16 :: 0x8054; +GL_RGBA2 :: 0x8055; +GL_RGBA4 :: 0x8056; +GL_RGB5_A1 :: 0x8057; +GL_RGBA8 :: 0x8058; +GL_RGB10_A2 :: 0x8059; +GL_RGBA12 :: 0x805a; +GL_RGBA16 :: 0x805b; +GL_UNSIGNED_BYTE_3_3_2 :: 0x8032; +GL_UNSIGNED_SHORT_4_4_4_4 :: 0x8033; +GL_UNSIGNED_SHORT_5_5_5_1 :: 0x8034; +GL_UNSIGNED_INT_8_8_8_8 :: 0x8035; +GL_UNSIGNED_INT_10_10_10_2 :: 0x8036; +GL_TEXTURE_BINDING_3D :: 0x806a; +GL_PACK_SKIP_IMAGES :: 0x806b; +GL_PACK_IMAGE_HEIGHT :: 0x806c; +GL_UNPACK_SKIP_IMAGES :: 0x806d; +GL_UNPACK_IMAGE_HEIGHT :: 0x806e; +GL_TEXTURE_3D :: 0x806f; +GL_PROXY_TEXTURE_3D :: 0x8070; +GL_TEXTURE_DEPTH :: 0x8071; +GL_TEXTURE_WRAP_R :: 0x8072; +GL_MAX_3D_TEXTURE_SIZE :: 0x8073; +GL_UNSIGNED_BYTE_2_3_3_REV :: 0x8362; +GL_UNSIGNED_SHORT_5_6_5 :: 0x8363; +GL_UNSIGNED_SHORT_5_6_5_REV :: 0x8364; +GL_UNSIGNED_SHORT_4_4_4_4_REV :: 0x8365; +GL_UNSIGNED_SHORT_1_5_5_5_REV :: 0x8366; +GL_UNSIGNED_INT_8_8_8_8_REV :: 0x8367; +GL_UNSIGNED_INT_2_10_10_10_REV :: 0x8368; +GL_BGR :: 0x80e0; +GL_BGRA :: 0x80e1; +GL_MAX_ELEMENTS_VERTICES :: 0x80e8; +GL_MAX_ELEMENTS_INDICES :: 0x80e9; +GL_CLAMP_TO_EDGE :: 0x812f; +GL_TEXTURE_MIN_LOD :: 0x813a; +GL_TEXTURE_MAX_LOD :: 0x813b; +GL_TEXTURE_BASE_LEVEL :: 0x813c; +GL_TEXTURE_MAX_LEVEL :: 0x813d; +GL_SMOOTH_POINT_SIZE_RANGE :: 0x0b12; +GL_SMOOTH_POINT_SIZE_GRANULARITY :: 0x0b13; +GL_SMOOTH_LINE_WIDTH_RANGE :: 0x0b22; +GL_SMOOTH_LINE_WIDTH_GRANULARITY :: 0x0b23; +GL_ALIASED_LINE_WIDTH_RANGE :: 0x846e; +GL_TEXTURE0 :: 0x84c0; +GL_TEXTURE1 :: 0x84c1; +GL_TEXTURE2 :: 0x84c2; +GL_TEXTURE3 :: 0x84c3; +GL_TEXTURE4 :: 0x84c4; +GL_TEXTURE5 :: 0x84c5; +GL_TEXTURE6 :: 0x84c6; +GL_TEXTURE7 :: 0x84c7; +GL_TEXTURE8 :: 0x84c8; +GL_TEXTURE9 :: 0x84c9; +GL_TEXTURE10 :: 0x84ca; +GL_TEXTURE11 :: 0x84cb; +GL_TEXTURE12 :: 0x84cc; +GL_TEXTURE13 :: 0x84cd; +GL_TEXTURE14 :: 0x84ce; +GL_TEXTURE15 :: 0x84cf; +GL_TEXTURE16 :: 0x84d0; +GL_TEXTURE17 :: 0x84d1; +GL_TEXTURE18 :: 0x84d2; +GL_TEXTURE19 :: 0x84d3; +GL_TEXTURE20 :: 0x84d4; +GL_TEXTURE21 :: 0x84d5; +GL_TEXTURE22 :: 0x84d6; +GL_TEXTURE23 :: 0x84d7; +GL_TEXTURE24 :: 0x84d8; +GL_TEXTURE25 :: 0x84d9; +GL_TEXTURE26 :: 0x84da; +GL_TEXTURE27 :: 0x84db; +GL_TEXTURE28 :: 0x84dc; +GL_TEXTURE29 :: 0x84dd; +GL_TEXTURE30 :: 0x84de; +GL_TEXTURE31 :: 0x84df; +GL_ACTIVE_TEXTURE :: 0x84e0; +GL_MULTISAMPLE :: 0x809d; +GL_SAMPLE_ALPHA_TO_COVERAGE :: 0x809e; +GL_SAMPLE_ALPHA_TO_ONE :: 0x809f; +GL_SAMPLE_COVERAGE :: 0x80a0; +GL_SAMPLE_BUFFERS :: 0x80a8; +GL_SAMPLES :: 0x80a9; +GL_SAMPLE_COVERAGE_VALUE :: 0x80aa; +GL_SAMPLE_COVERAGE_INVERT :: 0x80ab; +GL_TEXTURE_CUBE_MAP :: 0x8513; +GL_TEXTURE_BINDING_CUBE_MAP :: 0x8514; +GL_TEXTURE_CUBE_MAP_POSITIVE_X :: 0x8515; +GL_TEXTURE_CUBE_MAP_NEGATIVE_X :: 0x8516; +GL_TEXTURE_CUBE_MAP_POSITIVE_Y :: 0x8517; +GL_TEXTURE_CUBE_MAP_NEGATIVE_Y :: 0x8518; +GL_TEXTURE_CUBE_MAP_POSITIVE_Z :: 0x8519; +GL_TEXTURE_CUBE_MAP_NEGATIVE_Z :: 0x851a; +GL_PROXY_TEXTURE_CUBE_MAP :: 0x851b; +GL_MAX_CUBE_MAP_TEXTURE_SIZE :: 0x851c; +GL_COMPRESSED_RGB :: 0x84ed; +GL_COMPRESSED_RGBA :: 0x84ee; +GL_TEXTURE_COMPRESSION_HINT :: 0x84ef; +GL_TEXTURE_COMPRESSED_IMAGE_SIZE :: 0x86a0; +GL_TEXTURE_COMPRESSED :: 0x86a1; +GL_NUM_COMPRESSED_TEXTURE_FORMATS :: 0x86a2; +GL_COMPRESSED_TEXTURE_FORMATS :: 0x86a3; +GL_CLAMP_TO_BORDER :: 0x812d; +GL_BLEND_DST_RGB :: 0x80c8; +GL_BLEND_SRC_RGB :: 0x80c9; +GL_BLEND_DST_ALPHA :: 0x80ca; +GL_BLEND_SRC_ALPHA :: 0x80cb; +GL_POINT_FADE_THRESHOLD_SIZE :: 0x8128; +GL_DEPTH_COMPONENT16 :: 0x81a5; +GL_DEPTH_COMPONENT24 :: 0x81a6; +GL_DEPTH_COMPONENT32 :: 0x81a7; +GL_MIRRORED_REPEAT :: 0x8370; +GL_MAX_TEXTURE_LOD_BIAS :: 0x84fd; +GL_TEXTURE_LOD_BIAS :: 0x8501; +GL_INCR_WRAP :: 0x8507; +GL_DECR_WRAP :: 0x8508; +GL_TEXTURE_DEPTH_SIZE :: 0x884a; +GL_TEXTURE_COMPARE_MODE :: 0x884c; +GL_TEXTURE_COMPARE_FUNC :: 0x884d; +GL_BLEND_COLOR :: 0x8005; +GL_BLEND_EQUATION :: 0x8009; +GL_CONSTANT_COLOR :: 0x8001; +GL_ONE_MINUS_CONSTANT_COLOR :: 0x8002; +GL_CONSTANT_ALPHA :: 0x8003; +GL_ONE_MINUS_CONSTANT_ALPHA :: 0x8004; +GL_FUNC_ADD :: 0x8006; +GL_FUNC_REVERSE_SUBTRACT :: 0x800b; +GL_FUNC_SUBTRACT :: 0x800a; +GL_MIN :: 0x8007; +GL_MAX :: 0x8008; +GL_BUFFER_SIZE :: 0x8764; +GL_BUFFER_USAGE :: 0x8765; +GL_QUERY_COUNTER_BITS :: 0x8864; +GL_CURRENT_QUERY :: 0x8865; +GL_QUERY_RESULT :: 0x8866; +GL_QUERY_RESULT_AVAILABLE :: 0x8867; +GL_ARRAY_BUFFER :: 0x8892; +GL_ELEMENT_ARRAY_BUFFER :: 0x8893; +GL_ARRAY_BUFFER_BINDING :: 0x8894; +GL_ELEMENT_ARRAY_BUFFER_BINDING :: 0x8895; +GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING :: 0x889f; +GL_READ_ONLY :: 0x88b8; +GL_WRITE_ONLY :: 0x88b9; +GL_READ_WRITE :: 0x88ba; +GL_BUFFER_ACCESS :: 0x88bb; +GL_BUFFER_MAPPED :: 0x88bc; +GL_BUFFER_MAP_POINTER :: 0x88bd; +GL_STREAM_DRAW :: 0x88e0; +GL_STREAM_READ :: 0x88e1; +GL_STREAM_COPY :: 0x88e2; +GL_STATIC_DRAW :: 0x88e4; +GL_STATIC_READ :: 0x88e5; +GL_STATIC_COPY :: 0x88e6; +GL_DYNAMIC_DRAW :: 0x88e8; +GL_DYNAMIC_READ :: 0x88e9; +GL_DYNAMIC_COPY :: 0x88ea; +GL_SAMPLES_PASSED :: 0x8914; +GL_SRC1_ALPHA :: 0x8589; +GL_BLEND_EQUATION_RGB :: 0x8009; +GL_VERTEX_ATTRIB_ARRAY_ENABLED :: 0x8622; +GL_VERTEX_ATTRIB_ARRAY_SIZE :: 0x8623; +GL_VERTEX_ATTRIB_ARRAY_STRIDE :: 0x8624; +GL_VERTEX_ATTRIB_ARRAY_TYPE :: 0x8625; +GL_CURRENT_VERTEX_ATTRIB :: 0x8626; +GL_VERTEX_PROGRAM_POINT_SIZE :: 0x8642; +GL_VERTEX_ATTRIB_ARRAY_POINTER :: 0x8645; +GL_STENCIL_BACK_FUNC :: 0x8800; +GL_STENCIL_BACK_FAIL :: 0x8801; +GL_STENCIL_BACK_PASS_DEPTH_FAIL :: 0x8802; +GL_STENCIL_BACK_PASS_DEPTH_PASS :: 0x8803; +GL_MAX_DRAW_BUFFERS :: 0x8824; +GL_DRAW_BUFFER0 :: 0x8825; +GL_DRAW_BUFFER1 :: 0x8826; +GL_DRAW_BUFFER2 :: 0x8827; +GL_DRAW_BUFFER3 :: 0x8828; +GL_DRAW_BUFFER4 :: 0x8829; +GL_DRAW_BUFFER5 :: 0x882a; +GL_DRAW_BUFFER6 :: 0x882b; +GL_DRAW_BUFFER7 :: 0x882c; +GL_DRAW_BUFFER8 :: 0x882d; +GL_DRAW_BUFFER9 :: 0x882e; +GL_DRAW_BUFFER10 :: 0x882f; +GL_DRAW_BUFFER11 :: 0x8830; +GL_DRAW_BUFFER12 :: 0x8831; +GL_DRAW_BUFFER13 :: 0x8832; +GL_DRAW_BUFFER14 :: 0x8833; +GL_DRAW_BUFFER15 :: 0x8834; +GL_BLEND_EQUATION_ALPHA :: 0x883d; +GL_MAX_VERTEX_ATTRIBS :: 0x8869; +GL_VERTEX_ATTRIB_ARRAY_NORMALIZED :: 0x886a; +GL_MAX_TEXTURE_IMAGE_UNITS :: 0x8872; +GL_FRAGMENT_SHADER :: 0x8b30; +GL_VERTEX_SHADER :: 0x8b31; +GL_MAX_FRAGMENT_UNIFORM_COMPONENTS :: 0x8b49; +GL_MAX_VERTEX_UNIFORM_COMPONENTS :: 0x8b4a; +GL_MAX_VARYING_FLOATS :: 0x8b4b; +GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS :: 0x8b4c; +GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS :: 0x8b4d; +GL_SHADER_TYPE :: 0x8b4f; +GL_FLOAT_VEC2 :: 0x8b50; +GL_FLOAT_VEC3 :: 0x8b51; +GL_FLOAT_VEC4 :: 0x8b52; +GL_INT_VEC2 :: 0x8b53; +GL_INT_VEC3 :: 0x8b54; +GL_INT_VEC4 :: 0x8b55; +GL_BOOL :: 0x8b56; +GL_BOOL_VEC2 :: 0x8b57; +GL_BOOL_VEC3 :: 0x8b58; +GL_BOOL_VEC4 :: 0x8b59; +GL_FLOAT_MAT2 :: 0x8b5a; +GL_FLOAT_MAT3 :: 0x8b5b; +GL_FLOAT_MAT4 :: 0x8b5c; +GL_SAMPLER_1D :: 0x8b5d; +GL_SAMPLER_2D :: 0x8b5e; +GL_SAMPLER_3D :: 0x8b5f; +GL_SAMPLER_CUBE :: 0x8b60; +GL_SAMPLER_1D_SHADOW :: 0x8b61; +GL_SAMPLER_2D_SHADOW :: 0x8b62; +GL_DELETE_STATUS :: 0x8b80; +GL_COMPILE_STATUS :: 0x8b81; +GL_LINK_STATUS :: 0x8b82; +GL_VALIDATE_STATUS :: 0x8b83; +GL_INFO_LOG_LENGTH :: 0x8b84; +GL_ATTACHED_SHADERS :: 0x8b85; +GL_ACTIVE_UNIFORMS :: 0x8b86; +GL_ACTIVE_UNIFORM_MAX_LENGTH :: 0x8b87; +GL_SHADER_SOURCE_LENGTH :: 0x8b88; +GL_ACTIVE_ATTRIBUTES :: 0x8b89; +GL_ACTIVE_ATTRIBUTE_MAX_LENGTH :: 0x8b8a; +GL_FRAGMENT_SHADER_DERIVATIVE_HINT :: 0x8b8b; +GL_SHADING_LANGUAGE_VERSION :: 0x8b8c; +GL_CURRENT_PROGRAM :: 0x8b8d; +GL_POINT_SPRITE_COORD_ORIGIN :: 0x8ca0; +GL_LOWER_LEFT :: 0x8ca1; +GL_UPPER_LEFT :: 0x8ca2; +GL_STENCIL_BACK_REF :: 0x8ca3; +GL_STENCIL_BACK_VALUE_MASK :: 0x8ca4; +GL_STENCIL_BACK_WRITEMASK :: 0x8ca5; +GL_PIXEL_PACK_BUFFER :: 0x88eb; +GL_PIXEL_UNPACK_BUFFER :: 0x88ec; +GL_PIXEL_PACK_BUFFER_BINDING :: 0x88ed; +GL_PIXEL_UNPACK_BUFFER_BINDING :: 0x88ef; +GL_FLOAT_MAT2x3 :: 0x8b65; +GL_FLOAT_MAT2x4 :: 0x8b66; +GL_FLOAT_MAT3x2 :: 0x8b67; +GL_FLOAT_MAT3x4 :: 0x8b68; +GL_FLOAT_MAT4x2 :: 0x8b69; +GL_FLOAT_MAT4x3 :: 0x8b6a; +GL_SRGB :: 0x8c40; +GL_SRGB8 :: 0x8c41; +GL_SRGB_ALPHA :: 0x8c42; +GL_SRGB8_ALPHA8 :: 0x8c43; +GL_COMPRESSED_SRGB :: 0x8c48; +GL_COMPRESSED_SRGB_ALPHA :: 0x8c49; +GL_COMPARE_REF_TO_TEXTURE :: 0x884e; +GL_CLIP_DISTANCE0 :: 0x3000; +GL_CLIP_DISTANCE1 :: 0x3001; +GL_CLIP_DISTANCE2 :: 0x3002; +GL_CLIP_DISTANCE3 :: 0x3003; +GL_CLIP_DISTANCE4 :: 0x3004; +GL_CLIP_DISTANCE5 :: 0x3005; +GL_CLIP_DISTANCE6 :: 0x3006; +GL_CLIP_DISTANCE7 :: 0x3007; +GL_MAX_CLIP_DISTANCES :: 0x0d32; +GL_MAJOR_VERSION :: 0x821b; +GL_MINOR_VERSION :: 0x821c; +GL_NUM_EXTENSIONS :: 0x821d; +GL_CONTEXT_FLAGS :: 0x821e; +GL_COMPRESSED_RED :: 0x8225; +GL_COMPRESSED_RG :: 0x8226; +GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT :: 0x00000001; +GL_RGBA32F :: 0x8814; +GL_RGB32F :: 0x8815; +GL_RGBA16F :: 0x881a; +GL_RGB16F :: 0x881b; +GL_VERTEX_ATTRIB_ARRAY_INTEGER :: 0x88fd; +GL_MAX_ARRAY_TEXTURE_LAYERS :: 0x88ff; +GL_MIN_PROGRAM_TEXEL_OFFSET :: 0x8904; +GL_MAX_PROGRAM_TEXEL_OFFSET :: 0x8905; +GL_CLAMP_READ_COLOR :: 0x891c; +GL_FIXED_ONLY :: 0x891d; +GL_MAX_VARYING_COMPONENTS :: 0x8b4b; +GL_TEXTURE_1D_ARRAY :: 0x8c18; +GL_PROXY_TEXTURE_1D_ARRAY :: 0x8c19; +GL_TEXTURE_2D_ARRAY :: 0x8c1a; +GL_PROXY_TEXTURE_2D_ARRAY :: 0x8c1b; +GL_TEXTURE_BINDING_1D_ARRAY :: 0x8c1c; +GL_TEXTURE_BINDING_2D_ARRAY :: 0x8c1d; +GL_R11F_G11F_B10F :: 0x8c3a; +GL_UNSIGNED_INT_10F_11F_11F_REV :: 0x8c3b; +GL_RGB9_E5 :: 0x8c3d; +GL_UNSIGNED_INT_5_9_9_9_REV :: 0x8c3e; +GL_TEXTURE_SHARED_SIZE :: 0x8c3f; +GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH :: 0x8c76; +GL_TRANSFORM_FEEDBACK_BUFFER_MODE :: 0x8c7f; +GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS :: 0x8c80; +GL_TRANSFORM_FEEDBACK_VARYINGS :: 0x8c83; +GL_TRANSFORM_FEEDBACK_BUFFER_START :: 0x8c84; +GL_TRANSFORM_FEEDBACK_BUFFER_SIZE :: 0x8c85; +GL_PRIMITIVES_GENERATED :: 0x8c87; +GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN :: 0x8c88; +GL_RASTERIZER_DISCARD :: 0x8c89; +GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS :: 0x8c8a; +GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS :: 0x8c8b; +GL_INTERLEAVED_ATTRIBS :: 0x8c8c; +GL_SEPARATE_ATTRIBS :: 0x8c8d; +GL_TRANSFORM_FEEDBACK_BUFFER :: 0x8c8e; +GL_TRANSFORM_FEEDBACK_BUFFER_BINDING :: 0x8c8f; +GL_RGBA32UI :: 0x8d70; +GL_RGB32UI :: 0x8d71; +GL_RGBA16UI :: 0x8d76; +GL_RGB16UI :: 0x8d77; +GL_RGBA8UI :: 0x8d7c; +GL_RGB8UI :: 0x8d7d; +GL_RGBA32I :: 0x8d82; +GL_RGB32I :: 0x8d83; +GL_RGBA16I :: 0x8d88; +GL_RGB16I :: 0x8d89; +GL_RGBA8I :: 0x8d8e; +GL_RGB8I :: 0x8d8f; +GL_RED_INTEGER :: 0x8d94; +GL_GREEN_INTEGER :: 0x8d95; +GL_BLUE_INTEGER :: 0x8d96; +GL_RGB_INTEGER :: 0x8d98; +GL_RGBA_INTEGER :: 0x8d99; +GL_BGR_INTEGER :: 0x8d9a; +GL_BGRA_INTEGER :: 0x8d9b; +GL_SAMPLER_1D_ARRAY :: 0x8dc0; +GL_SAMPLER_2D_ARRAY :: 0x8dc1; +GL_SAMPLER_1D_ARRAY_SHADOW :: 0x8dc3; +GL_SAMPLER_2D_ARRAY_SHADOW :: 0x8dc4; +GL_SAMPLER_CUBE_SHADOW :: 0x8dc5; +GL_UNSIGNED_INT_VEC2 :: 0x8dc6; +GL_UNSIGNED_INT_VEC3 :: 0x8dc7; +GL_UNSIGNED_INT_VEC4 :: 0x8dc8; +GL_INT_SAMPLER_1D :: 0x8dc9; +GL_INT_SAMPLER_2D :: 0x8dca; +GL_INT_SAMPLER_3D :: 0x8dcb; +GL_INT_SAMPLER_CUBE :: 0x8dcc; +GL_INT_SAMPLER_1D_ARRAY :: 0x8dce; +GL_INT_SAMPLER_2D_ARRAY :: 0x8dcf; +GL_UNSIGNED_INT_SAMPLER_1D :: 0x8dd1; +GL_UNSIGNED_INT_SAMPLER_2D :: 0x8dd2; +GL_UNSIGNED_INT_SAMPLER_3D :: 0x8dd3; +GL_UNSIGNED_INT_SAMPLER_CUBE :: 0x8dd4; +GL_UNSIGNED_INT_SAMPLER_1D_ARRAY :: 0x8dd6; +GL_UNSIGNED_INT_SAMPLER_2D_ARRAY :: 0x8dd7; +GL_QUERY_WAIT :: 0x8e13; +GL_QUERY_NO_WAIT :: 0x8e14; +GL_QUERY_BY_REGION_WAIT :: 0x8e15; +GL_QUERY_BY_REGION_NO_WAIT :: 0x8e16; +GL_BUFFER_ACCESS_FLAGS :: 0x911f; +GL_BUFFER_MAP_LENGTH :: 0x9120; +GL_BUFFER_MAP_OFFSET :: 0x9121; +GL_DEPTH_COMPONENT32F :: 0x8cac; +GL_DEPTH32F_STENCIL8 :: 0x8cad; +GL_FLOAT_32_UNSIGNED_INT_24_8_REV :: 0x8dad; +GL_INVALID_FRAMEBUFFER_OPERATION :: 0x0506; +GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING :: 0x8210; +GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE :: 0x8211; +GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE :: 0x8212; +GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE :: 0x8213; +GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE :: 0x8214; +GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE :: 0x8215; +GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE :: 0x8216; +GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE :: 0x8217; +GL_FRAMEBUFFER_DEFAULT :: 0x8218; +GL_FRAMEBUFFER_UNDEFINED :: 0x8219; +GL_DEPTH_STENCIL_ATTACHMENT :: 0x821a; +GL_MAX_RENDERBUFFER_SIZE :: 0x84e8; +GL_DEPTH_STENCIL :: 0x84f9; +GL_UNSIGNED_INT_24_8 :: 0x84fa; +GL_DEPTH24_STENCIL8 :: 0x88f0; +GL_TEXTURE_STENCIL_SIZE :: 0x88f1; +GL_TEXTURE_RED_TYPE :: 0x8c10; +GL_TEXTURE_GREEN_TYPE :: 0x8c11; +GL_TEXTURE_BLUE_TYPE :: 0x8c12; +GL_TEXTURE_ALPHA_TYPE :: 0x8c13; +GL_TEXTURE_DEPTH_TYPE :: 0x8c16; +GL_UNSIGNED_NORMALIZED :: 0x8c17; +GL_FRAMEBUFFER_BINDING :: 0x8ca6; +GL_DRAW_FRAMEBUFFER_BINDING :: 0x8ca6; +GL_RENDERBUFFER_BINDING :: 0x8ca7; +GL_READ_FRAMEBUFFER :: 0x8ca8; +GL_DRAW_FRAMEBUFFER :: 0x8ca9; +GL_READ_FRAMEBUFFER_BINDING :: 0x8caa; +GL_RENDERBUFFER_SAMPLES :: 0x8cab; +GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE :: 0x8cd0; +GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME :: 0x8cd1; +GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL :: 0x8cd2; +GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE :: 0x8cd3; +GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER :: 0x8cd4; +GL_FRAMEBUFFER_COMPLETE :: 0x8cd5; +GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT :: 0x8cd6; +GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT :: 0x8cd7; +GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER :: 0x8cdb; +GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER :: 0x8cdc; +GL_FRAMEBUFFER_UNSUPPORTED :: 0x8cdd; +GL_MAX_COLOR_ATTACHMENTS :: 0x8cdf; +GL_COLOR_ATTACHMENT0 :: 0x8ce0; +GL_COLOR_ATTACHMENT1 :: 0x8ce1; +GL_COLOR_ATTACHMENT2 :: 0x8ce2; +GL_COLOR_ATTACHMENT3 :: 0x8ce3; +GL_COLOR_ATTACHMENT4 :: 0x8ce4; +GL_COLOR_ATTACHMENT5 :: 0x8ce5; +GL_COLOR_ATTACHMENT6 :: 0x8ce6; +GL_COLOR_ATTACHMENT7 :: 0x8ce7; +GL_COLOR_ATTACHMENT8 :: 0x8ce8; +GL_COLOR_ATTACHMENT9 :: 0x8ce9; +GL_COLOR_ATTACHMENT10 :: 0x8cea; +GL_COLOR_ATTACHMENT11 :: 0x8ceb; +GL_COLOR_ATTACHMENT12 :: 0x8cec; +GL_COLOR_ATTACHMENT13 :: 0x8ced; +GL_COLOR_ATTACHMENT14 :: 0x8cee; +GL_COLOR_ATTACHMENT15 :: 0x8cef; +GL_COLOR_ATTACHMENT16 :: 0x8cf0; +GL_COLOR_ATTACHMENT17 :: 0x8cf1; +GL_COLOR_ATTACHMENT18 :: 0x8cf2; +GL_COLOR_ATTACHMENT19 :: 0x8cf3; +GL_COLOR_ATTACHMENT20 :: 0x8cf4; +GL_COLOR_ATTACHMENT21 :: 0x8cf5; +GL_COLOR_ATTACHMENT22 :: 0x8cf6; +GL_COLOR_ATTACHMENT23 :: 0x8cf7; +GL_COLOR_ATTACHMENT24 :: 0x8cf8; +GL_COLOR_ATTACHMENT25 :: 0x8cf9; +GL_COLOR_ATTACHMENT26 :: 0x8cfa; +GL_COLOR_ATTACHMENT27 :: 0x8cfb; +GL_COLOR_ATTACHMENT28 :: 0x8cfc; +GL_COLOR_ATTACHMENT29 :: 0x8cfd; +GL_COLOR_ATTACHMENT30 :: 0x8cfe; +GL_COLOR_ATTACHMENT31 :: 0x8cff; +GL_DEPTH_ATTACHMENT :: 0x8d00; +GL_STENCIL_ATTACHMENT :: 0x8d20; +GL_FRAMEBUFFER :: 0x8d40; +GL_RENDERBUFFER :: 0x8d41; +GL_RENDERBUFFER_WIDTH :: 0x8d42; +GL_RENDERBUFFER_HEIGHT :: 0x8d43; +GL_RENDERBUFFER_INTERNAL_FORMAT :: 0x8d44; +GL_STENCIL_INDEX1 :: 0x8d46; +GL_STENCIL_INDEX4 :: 0x8d47; +GL_STENCIL_INDEX8 :: 0x8d48; +GL_STENCIL_INDEX16 :: 0x8d49; +GL_RENDERBUFFER_RED_SIZE :: 0x8d50; +GL_RENDERBUFFER_GREEN_SIZE :: 0x8d51; +GL_RENDERBUFFER_BLUE_SIZE :: 0x8d52; +GL_RENDERBUFFER_ALPHA_SIZE :: 0x8d53; +GL_RENDERBUFFER_DEPTH_SIZE :: 0x8d54; +GL_RENDERBUFFER_STENCIL_SIZE :: 0x8d55; +GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE :: 0x8d56; +GL_MAX_SAMPLES :: 0x8d57; +GL_FRAMEBUFFER_SRGB :: 0x8db9; +GL_HALF_FLOAT :: 0x140b; +GL_MAP_READ_BIT :: 0x0001; +GL_MAP_WRITE_BIT :: 0x0002; +GL_MAP_INVALIDATE_RANGE_BIT :: 0x0004; +GL_MAP_INVALIDATE_BUFFER_BIT :: 0x0008; +GL_MAP_FLUSH_EXPLICIT_BIT :: 0x0010; +GL_MAP_UNSYNCHRONIZED_BIT :: 0x0020; +GL_COMPRESSED_RED_RGTC1 :: 0x8dbb; +GL_COMPRESSED_SIGNED_RED_RGTC1 :: 0x8dbc; +GL_COMPRESSED_RG_RGTC2 :: 0x8dbd; +GL_COMPRESSED_SIGNED_RG_RGTC2 :: 0x8dbe; +GL_RG :: 0x8227; +GL_RG_INTEGER :: 0x8228; +GL_R8 :: 0x8229; +GL_R16 :: 0x822a; +GL_RG8 :: 0x822b; +GL_RG16 :: 0x822c; +GL_R16F :: 0x822d; +GL_R32F :: 0x822e; +GL_RG16F :: 0x822f; +GL_RG32F :: 0x8230; +GL_R8I :: 0x8231; +GL_R8UI :: 0x8232; +GL_R16I :: 0x8233; +GL_R16UI :: 0x8234; +GL_R32I :: 0x8235; +GL_R32UI :: 0x8236; +GL_RG8I :: 0x8237; +GL_RG8UI :: 0x8238; +GL_RG16I :: 0x8239; +GL_RG16UI :: 0x823a; +GL_RG32I :: 0x823b; +GL_RG32UI :: 0x823c; +GL_VERTEX_ARRAY_BINDING :: 0x85b5; +GL_SAMPLER_2D_RECT :: 0x8b63; +GL_SAMPLER_2D_RECT_SHADOW :: 0x8b64; +GL_SAMPLER_BUFFER :: 0x8dc2; +GL_INT_SAMPLER_2D_RECT :: 0x8dcd; +GL_INT_SAMPLER_BUFFER :: 0x8dd0; +GL_UNSIGNED_INT_SAMPLER_2D_RECT :: 0x8dd5; +GL_UNSIGNED_INT_SAMPLER_BUFFER :: 0x8dd8; +GL_TEXTURE_BUFFER :: 0x8c2a; +GL_MAX_TEXTURE_BUFFER_SIZE :: 0x8c2b; +GL_TEXTURE_BINDING_BUFFER :: 0x8c2c; +GL_TEXTURE_BUFFER_DATA_STORE_BINDING :: 0x8c2d; +GL_TEXTURE_RECTANGLE :: 0x84f5; +GL_TEXTURE_BINDING_RECTANGLE :: 0x84f6; +GL_PROXY_TEXTURE_RECTANGLE :: 0x84f7; +GL_MAX_RECTANGLE_TEXTURE_SIZE :: 0x84f8; +GL_R8_SNORM :: 0x8f94; +GL_RG8_SNORM :: 0x8f95; +GL_RGB8_SNORM :: 0x8f96; +GL_RGBA8_SNORM :: 0x8f97; +GL_R16_SNORM :: 0x8f98; +GL_RG16_SNORM :: 0x8f99; +GL_RGB16_SNORM :: 0x8f9a; +GL_RGBA16_SNORM :: 0x8f9b; +GL_SIGNED_NORMALIZED :: 0x8f9c; +GL_PRIMITIVE_RESTART :: 0x8f9d; +GL_PRIMITIVE_RESTART_INDEX :: 0x8f9e; +GL_COPY_READ_BUFFER :: 0x8f36; +GL_COPY_WRITE_BUFFER :: 0x8f37; +GL_UNIFORM_BUFFER :: 0x8a11; +GL_UNIFORM_BUFFER_BINDING :: 0x8a28; +GL_UNIFORM_BUFFER_START :: 0x8a29; +GL_UNIFORM_BUFFER_SIZE :: 0x8a2a; +GL_MAX_VERTEX_UNIFORM_BLOCKS :: 0x8a2b; +GL_MAX_GEOMETRY_UNIFORM_BLOCKS :: 0x8a2c; +GL_MAX_FRAGMENT_UNIFORM_BLOCKS :: 0x8a2d; +GL_MAX_COMBINED_UNIFORM_BLOCKS :: 0x8a2e; +GL_MAX_UNIFORM_BUFFER_BINDINGS :: 0x8a2f; +GL_MAX_UNIFORM_BLOCK_SIZE :: 0x8a30; +GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS :: 0x8a31; +GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS :: 0x8a32; +GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS :: 0x8a33; +GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT :: 0x8a34; +GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH :: 0x8a35; +GL_ACTIVE_UNIFORM_BLOCKS :: 0x8a36; +GL_UNIFORM_TYPE :: 0x8a37; +GL_UNIFORM_SIZE :: 0x8a38; +GL_UNIFORM_NAME_LENGTH :: 0x8a39; +GL_UNIFORM_BLOCK_INDEX :: 0x8a3a; +GL_UNIFORM_OFFSET :: 0x8a3b; +GL_UNIFORM_ARRAY_STRIDE :: 0x8a3c; +GL_UNIFORM_MATRIX_STRIDE :: 0x8a3d; +GL_UNIFORM_IS_ROW_MAJOR :: 0x8a3e; +GL_UNIFORM_BLOCK_BINDING :: 0x8a3f; +GL_UNIFORM_BLOCK_DATA_SIZE :: 0x8a40; +GL_UNIFORM_BLOCK_NAME_LENGTH :: 0x8a41; +GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS :: 0x8a42; +GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES :: 0x8a43; +GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER :: 0x8a44; +GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER :: 0x8a45; +GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER :: 0x8a46; +GL_INVALID_INDEX :: 0xffffffff; +GL_CONTEXT_CORE_PROFILE_BIT :: 0x00000001; +GL_CONTEXT_COMPATIBILITY_PROFILE_BIT :: 0x00000002; +GL_LINES_ADJACENCY :: 0x000a; +GL_LINE_STRIP_ADJACENCY :: 0x000b; +GL_TRIANGLES_ADJACENCY :: 0x000c; +GL_TRIANGLE_STRIP_ADJACENCY :: 0x000d; +GL_PROGRAM_POINT_SIZE :: 0x8642; +GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS :: 0x8c29; +GL_FRAMEBUFFER_ATTACHMENT_LAYERED :: 0x8da7; +GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS :: 0x8da8; +GL_GEOMETRY_SHADER :: 0x8dd9; +GL_GEOMETRY_VERTICES_OUT :: 0x8916; +GL_GEOMETRY_INPUT_TYPE :: 0x8917; +GL_GEOMETRY_OUTPUT_TYPE :: 0x8918; +GL_MAX_GEOMETRY_UNIFORM_COMPONENTS :: 0x8ddf; +GL_MAX_GEOMETRY_OUTPUT_VERTICES :: 0x8de0; +GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS :: 0x8de1; +GL_MAX_VERTEX_OUTPUT_COMPONENTS :: 0x9122; +GL_MAX_GEOMETRY_INPUT_COMPONENTS :: 0x9123; +GL_MAX_GEOMETRY_OUTPUT_COMPONENTS :: 0x9124; +GL_MAX_FRAGMENT_INPUT_COMPONENTS :: 0x9125; +GL_CONTEXT_PROFILE_MASK :: 0x9126; +GL_DEPTH_CLAMP :: 0x864f; +GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION :: 0x8e4c; +GL_FIRST_VERTEX_CONVENTION :: 0x8e4d; +GL_LAST_VERTEX_CONVENTION :: 0x8e4e; +GL_PROVOKING_VERTEX :: 0x8e4f; +GL_TEXTURE_CUBE_MAP_SEAMLESS :: 0x884f; +GL_MAX_SERVER_WAIT_TIMEOUT :: 0x9111; +GL_OBJECT_TYPE :: 0x9112; +GL_SYNC_CONDITION :: 0x9113; +GL_SYNC_STATUS :: 0x9114; +GL_SYNC_FLAGS :: 0x9115; +GL_SYNC_FENCE :: 0x9116; +GL_SYNC_GPU_COMMANDS_COMPLETE :: 0x9117; +GL_UNSIGNALED :: 0x9118; +GL_SIGNALED :: 0x9119; +GL_ALREADY_SIGNALED :: 0x911a; +GL_TIMEOUT_EXPIRED :: 0x911b; +GL_CONDITION_SATISFIED :: 0x911c; +GL_WAIT_FAILED :: 0x911d; +GL_TIMEOUT_IGNORED :: 0xffffffffffffffff; +GL_SYNC_FLUSH_COMMANDS_BIT :: 0x00000001; +GL_SAMPLE_POSITION :: 0x8e50; +GL_SAMPLE_MASK :: 0x8e51; +GL_SAMPLE_MASK_VALUE :: 0x8e52; +GL_MAX_SAMPLE_MASK_WORDS :: 0x8e59; +GL_TEXTURE_2D_MULTISAMPLE :: 0x9100; +GL_PROXY_TEXTURE_2D_MULTISAMPLE :: 0x9101; +GL_TEXTURE_2D_MULTISAMPLE_ARRAY :: 0x9102; +GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY :: 0x9103; +GL_TEXTURE_BINDING_2D_MULTISAMPLE :: 0x9104; +GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY :: 0x9105; +GL_TEXTURE_SAMPLES :: 0x9106; +GL_TEXTURE_FIXED_SAMPLE_LOCATIONS :: 0x9107; +GL_SAMPLER_2D_MULTISAMPLE :: 0x9108; +GL_INT_SAMPLER_2D_MULTISAMPLE :: 0x9109; +GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE :: 0x910a; +GL_SAMPLER_2D_MULTISAMPLE_ARRAY :: 0x910b; +GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY :: 0x910c; +GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY :: 0x910d; +GL_MAX_COLOR_TEXTURE_SAMPLES :: 0x910e; +GL_MAX_DEPTH_TEXTURE_SAMPLES :: 0x910f; +GL_MAX_INTEGER_SAMPLES :: 0x9110; +GL_VERTEX_ATTRIB_ARRAY_DIVISOR :: 0x88fe; +GL_SRC1_COLOR :: 0x88f9; +GL_ONE_MINUS_SRC1_COLOR :: 0x88fa; +GL_ONE_MINUS_SRC1_ALPHA :: 0x88fb; +GL_MAX_DUAL_SOURCE_DRAW_BUFFERS :: 0x88fc; +GL_ANY_SAMPLES_PASSED :: 0x8c2f; +GL_SAMPLER_BINDING :: 0x8919; +GL_RGB10_A2UI :: 0x906f; +GL_TEXTURE_SWIZZLE_R :: 0x8e42; +GL_TEXTURE_SWIZZLE_G :: 0x8e43; +GL_TEXTURE_SWIZZLE_B :: 0x8e44; +GL_TEXTURE_SWIZZLE_A :: 0x8e45; +GL_TEXTURE_SWIZZLE_RGBA :: 0x8e46; +GL_TIME_ELAPSED :: 0x88bf; +GL_TIMESTAMP :: 0x8e28; +GL_INT_2_10_10_10_REV :: 0x8d9f; +GL_SAMPLE_SHADING :: 0x8c36; +GL_MIN_SAMPLE_SHADING_VALUE :: 0x8c37; +GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET :: 0x8e5e; +GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET :: 0x8e5f; +GL_TEXTURE_CUBE_MAP_ARRAY :: 0x9009; +GL_TEXTURE_BINDING_CUBE_MAP_ARRAY :: 0x900a; +GL_PROXY_TEXTURE_CUBE_MAP_ARRAY :: 0x900b; +GL_SAMPLER_CUBE_MAP_ARRAY :: 0x900c; +GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW :: 0x900d; +GL_INT_SAMPLER_CUBE_MAP_ARRAY :: 0x900e; +GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY :: 0x900f; +GL_DRAW_INDIRECT_BUFFER :: 0x8f3f; +GL_DRAW_INDIRECT_BUFFER_BINDING :: 0x8f43; +GL_GEOMETRY_SHADER_INVOCATIONS :: 0x887f; +GL_MAX_GEOMETRY_SHADER_INVOCATIONS :: 0x8e5a; +GL_MIN_FRAGMENT_INTERPOLATION_OFFSET :: 0x8e5b; +GL_MAX_FRAGMENT_INTERPOLATION_OFFSET :: 0x8e5c; +GL_FRAGMENT_INTERPOLATION_OFFSET_BITS :: 0x8e5d; +GL_MAX_VERTEX_STREAMS :: 0x8e71; +GL_DOUBLE_VEC2 :: 0x8ffc; +GL_DOUBLE_VEC3 :: 0x8ffd; +GL_DOUBLE_VEC4 :: 0x8ffe; +GL_DOUBLE_MAT2 :: 0x8f46; +GL_DOUBLE_MAT3 :: 0x8f47; +GL_DOUBLE_MAT4 :: 0x8f48; +GL_DOUBLE_MAT2x3 :: 0x8f49; +GL_DOUBLE_MAT2x4 :: 0x8f4a; +GL_DOUBLE_MAT3x2 :: 0x8f4b; +GL_DOUBLE_MAT3x4 :: 0x8f4c; +GL_DOUBLE_MAT4x2 :: 0x8f4d; +GL_DOUBLE_MAT4x3 :: 0x8f4e; +GL_ACTIVE_SUBROUTINES :: 0x8de5; +GL_ACTIVE_SUBROUTINE_UNIFORMS :: 0x8de6; +GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS :: 0x8e47; +GL_ACTIVE_SUBROUTINE_MAX_LENGTH :: 0x8e48; +GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH :: 0x8e49; +GL_MAX_SUBROUTINES :: 0x8de7; +GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS :: 0x8de8; +GL_NUM_COMPATIBLE_SUBROUTINES :: 0x8e4a; +GL_COMPATIBLE_SUBROUTINES :: 0x8e4b; +GL_PATCHES :: 0x000e; +GL_PATCH_VERTICES :: 0x8e72; +GL_PATCH_DEFAULT_INNER_LEVEL :: 0x8e73; +GL_PATCH_DEFAULT_OUTER_LEVEL :: 0x8e74; +GL_TESS_CONTROL_OUTPUT_VERTICES :: 0x8e75; +GL_TESS_GEN_MODE :: 0x8e76; +GL_TESS_GEN_SPACING :: 0x8e77; +GL_TESS_GEN_VERTEX_ORDER :: 0x8e78; +GL_TESS_GEN_POINT_MODE :: 0x8e79; +GL_ISOLINES :: 0x8e7a; +GL_QUADS :: 0x0007; +GL_FRACTIONAL_ODD :: 0x8e7b; +GL_FRACTIONAL_EVEN :: 0x8e7c; +GL_MAX_PATCH_VERTICES :: 0x8e7d; +GL_MAX_TESS_GEN_LEVEL :: 0x8e7e; +GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS :: 0x8e7f; +GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS :: 0x8e80; +GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS :: 0x8e81; +GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS :: 0x8e82; +GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS :: 0x8e83; +GL_MAX_TESS_PATCH_COMPONENTS :: 0x8e84; +GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS :: 0x8e85; +GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS :: 0x8e86; +GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS :: 0x8e89; +GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS :: 0x8e8a; +GL_MAX_TESS_CONTROL_INPUT_COMPONENTS :: 0x886c; +GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS :: 0x886d; +GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS :: 0x8e1e; +GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS :: 0x8e1f; +GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER :: 0x84f0; +GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER :: 0x84f1; +GL_TESS_EVALUATION_SHADER :: 0x8e87; +GL_TESS_CONTROL_SHADER :: 0x8e88; +GL_TRANSFORM_FEEDBACK :: 0x8e22; +GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED :: 0x8e23; +GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE :: 0x8e24; +GL_TRANSFORM_FEEDBACK_BINDING :: 0x8e25; +GL_MAX_TRANSFORM_FEEDBACK_BUFFERS :: 0x8e70; +GL_FIXED :: 0x140c; +GL_IMPLEMENTATION_COLOR_READ_TYPE :: 0x8b9a; +GL_IMPLEMENTATION_COLOR_READ_FORMAT :: 0x8b9b; +GL_LOW_FLOAT :: 0x8df0; +GL_MEDIUM_FLOAT :: 0x8df1; +GL_HIGH_FLOAT :: 0x8df2; +GL_LOW_INT :: 0x8df3; +GL_MEDIUM_INT :: 0x8df4; +GL_HIGH_INT :: 0x8df5; +GL_SHADER_COMPILER :: 0x8dfa; +GL_SHADER_BINARY_FORMATS :: 0x8df8; +GL_NUM_SHADER_BINARY_FORMATS :: 0x8df9; +GL_MAX_VERTEX_UNIFORM_VECTORS :: 0x8dfb; +GL_MAX_VARYING_VECTORS :: 0x8dfc; +GL_MAX_FRAGMENT_UNIFORM_VECTORS :: 0x8dfd; +GL_RGB565 :: 0x8d62; +GL_PROGRAM_BINARY_RETRIEVABLE_HINT :: 0x8257; +GL_PROGRAM_BINARY_LENGTH :: 0x8741; +GL_NUM_PROGRAM_BINARY_FORMATS :: 0x87fe; +GL_PROGRAM_BINARY_FORMATS :: 0x87ff; +GL_VERTEX_SHADER_BIT :: 0x00000001; +GL_FRAGMENT_SHADER_BIT :: 0x00000002; +GL_GEOMETRY_SHADER_BIT :: 0x00000004; +GL_TESS_CONTROL_SHADER_BIT :: 0x00000008; +GL_TESS_EVALUATION_SHADER_BIT :: 0x00000010; +GL_ALL_SHADER_BITS :: 0xffffffff; +GL_PROGRAM_SEPARABLE :: 0x8258; +GL_ACTIVE_PROGRAM :: 0x8259; +GL_PROGRAM_PIPELINE_BINDING :: 0x825a; +GL_MAX_VIEWPORTS :: 0x825b; +GL_VIEWPORT_SUBPIXEL_BITS :: 0x825c; +GL_VIEWPORT_BOUNDS_RANGE :: 0x825d; +GL_LAYER_PROVOKING_VERTEX :: 0x825e; +GL_VIEWPORT_INDEX_PROVOKING_VERTEX :: 0x825f; +GL_UNDEFINED_VERTEX :: 0x8260; +GL_COPY_READ_BUFFER_BINDING :: 0x8f36; +GL_COPY_WRITE_BUFFER_BINDING :: 0x8f37; +GL_TRANSFORM_FEEDBACK_ACTIVE :: 0x8e24; +GL_TRANSFORM_FEEDBACK_PAUSED :: 0x8e23; +GL_UNPACK_COMPRESSED_BLOCK_WIDTH :: 0x9127; +GL_UNPACK_COMPRESSED_BLOCK_HEIGHT :: 0x9128; +GL_UNPACK_COMPRESSED_BLOCK_DEPTH :: 0x9129; +GL_UNPACK_COMPRESSED_BLOCK_SIZE :: 0x912a; +GL_PACK_COMPRESSED_BLOCK_WIDTH :: 0x912b; +GL_PACK_COMPRESSED_BLOCK_HEIGHT :: 0x912c; +GL_PACK_COMPRESSED_BLOCK_DEPTH :: 0x912d; +GL_PACK_COMPRESSED_BLOCK_SIZE :: 0x912e; +GL_NUM_SAMPLE_COUNTS :: 0x9380; +GL_MIN_MAP_BUFFER_ALIGNMENT :: 0x90bc; +GL_ATOMIC_COUNTER_BUFFER :: 0x92c0; +GL_ATOMIC_COUNTER_BUFFER_BINDING :: 0x92c1; +GL_ATOMIC_COUNTER_BUFFER_START :: 0x92c2; +GL_ATOMIC_COUNTER_BUFFER_SIZE :: 0x92c3; +GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE :: 0x92c4; +GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS :: 0x92c5; +GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES :: 0x92c6; +GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER :: 0x92c7; +GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER :: 0x92c8; +GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER :: 0x92c9; +GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER :: 0x92ca; +GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER :: 0x92cb; +GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS :: 0x92cc; +GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS :: 0x92cd; +GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS :: 0x92ce; +GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS :: 0x92cf; +GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS :: 0x92d0; +GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS :: 0x92d1; +GL_MAX_VERTEX_ATOMIC_COUNTERS :: 0x92d2; +GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS :: 0x92d3; +GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS :: 0x92d4; +GL_MAX_GEOMETRY_ATOMIC_COUNTERS :: 0x92d5; +GL_MAX_FRAGMENT_ATOMIC_COUNTERS :: 0x92d6; +GL_MAX_COMBINED_ATOMIC_COUNTERS :: 0x92d7; +GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE :: 0x92d8; +GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS :: 0x92dc; +GL_ACTIVE_ATOMIC_COUNTER_BUFFERS :: 0x92d9; +GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX :: 0x92da; +GL_UNSIGNED_INT_ATOMIC_COUNTER :: 0x92db; +GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT :: 0x00000001; +GL_ELEMENT_ARRAY_BARRIER_BIT :: 0x00000002; +GL_UNIFORM_BARRIER_BIT :: 0x00000004; +GL_TEXTURE_FETCH_BARRIER_BIT :: 0x00000008; +GL_SHADER_IMAGE_ACCESS_BARRIER_BIT :: 0x00000020; +GL_COMMAND_BARRIER_BIT :: 0x00000040; +GL_PIXEL_BUFFER_BARRIER_BIT :: 0x00000080; +GL_TEXTURE_UPDATE_BARRIER_BIT :: 0x00000100; +GL_BUFFER_UPDATE_BARRIER_BIT :: 0x00000200; +GL_FRAMEBUFFER_BARRIER_BIT :: 0x00000400; +GL_TRANSFORM_FEEDBACK_BARRIER_BIT :: 0x00000800; +GL_ATOMIC_COUNTER_BARRIER_BIT :: 0x00001000; +GL_ALL_BARRIER_BITS :: 0xffffffff; +GL_MAX_IMAGE_UNITS :: 0x8f38; +GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS :: 0x8f39; +GL_IMAGE_BINDING_NAME :: 0x8f3a; +GL_IMAGE_BINDING_LEVEL :: 0x8f3b; +GL_IMAGE_BINDING_LAYERED :: 0x8f3c; +GL_IMAGE_BINDING_LAYER :: 0x8f3d; +GL_IMAGE_BINDING_ACCESS :: 0x8f3e; +GL_IMAGE_1D :: 0x904c; +GL_IMAGE_2D :: 0x904d; +GL_IMAGE_3D :: 0x904e; +GL_IMAGE_2D_RECT :: 0x904f; +GL_IMAGE_CUBE :: 0x9050; +GL_IMAGE_BUFFER :: 0x9051; +GL_IMAGE_1D_ARRAY :: 0x9052; +GL_IMAGE_2D_ARRAY :: 0x9053; +GL_IMAGE_CUBE_MAP_ARRAY :: 0x9054; +GL_IMAGE_2D_MULTISAMPLE :: 0x9055; +GL_IMAGE_2D_MULTISAMPLE_ARRAY :: 0x9056; +GL_INT_IMAGE_1D :: 0x9057; +GL_INT_IMAGE_2D :: 0x9058; +GL_INT_IMAGE_3D :: 0x9059; +GL_INT_IMAGE_2D_RECT :: 0x905a; +GL_INT_IMAGE_CUBE :: 0x905b; +GL_INT_IMAGE_BUFFER :: 0x905c; +GL_INT_IMAGE_1D_ARRAY :: 0x905d; +GL_INT_IMAGE_2D_ARRAY :: 0x905e; +GL_INT_IMAGE_CUBE_MAP_ARRAY :: 0x905f; +GL_INT_IMAGE_2D_MULTISAMPLE :: 0x9060; +GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY :: 0x9061; +GL_UNSIGNED_INT_IMAGE_1D :: 0x9062; +GL_UNSIGNED_INT_IMAGE_2D :: 0x9063; +GL_UNSIGNED_INT_IMAGE_3D :: 0x9064; +GL_UNSIGNED_INT_IMAGE_2D_RECT :: 0x9065; +GL_UNSIGNED_INT_IMAGE_CUBE :: 0x9066; +GL_UNSIGNED_INT_IMAGE_BUFFER :: 0x9067; +GL_UNSIGNED_INT_IMAGE_1D_ARRAY :: 0x9068; +GL_UNSIGNED_INT_IMAGE_2D_ARRAY :: 0x9069; +GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY :: 0x906a; +GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE :: 0x906b; +GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY :: 0x906c; +GL_MAX_IMAGE_SAMPLES :: 0x906d; +GL_IMAGE_BINDING_FORMAT :: 0x906e; +GL_IMAGE_FORMAT_COMPATIBILITY_TYPE :: 0x90c7; +GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE :: 0x90c8; +GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS :: 0x90c9; +GL_MAX_VERTEX_IMAGE_UNIFORMS :: 0x90ca; +GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS :: 0x90cb; +GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS :: 0x90cc; +GL_MAX_GEOMETRY_IMAGE_UNIFORMS :: 0x90cd; +GL_MAX_FRAGMENT_IMAGE_UNIFORMS :: 0x90ce; +GL_MAX_COMBINED_IMAGE_UNIFORMS :: 0x90cf; +GL_COMPRESSED_RGBA_BPTC_UNORM :: 0x8e8c; +GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM :: 0x8e8d; +GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT :: 0x8e8e; +GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT :: 0x8e8f; +GL_TEXTURE_IMMUTABLE_FORMAT :: 0x912f; +GL_NUM_SHADING_LANGUAGE_VERSIONS :: 0x82e9; +GL_VERTEX_ATTRIB_ARRAY_LONG :: 0x874e; +GL_COMPRESSED_RGB8_ETC2 :: 0x9274; +GL_COMPRESSED_SRGB8_ETC2 :: 0x9275; +GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 :: 0x9276; +GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 :: 0x9277; +GL_COMPRESSED_RGBA8_ETC2_EAC :: 0x9278; +GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC :: 0x9279; +GL_COMPRESSED_R11_EAC :: 0x9270; +GL_COMPRESSED_SIGNED_R11_EAC :: 0x9271; +GL_COMPRESSED_RG11_EAC :: 0x9272; +GL_COMPRESSED_SIGNED_RG11_EAC :: 0x9273; +GL_PRIMITIVE_RESTART_FIXED_INDEX :: 0x8d69; +GL_ANY_SAMPLES_PASSED_CONSERVATIVE :: 0x8d6a; +GL_MAX_ELEMENT_INDEX :: 0x8d6b; +GL_COMPUTE_SHADER :: 0x91b9; +GL_MAX_COMPUTE_UNIFORM_BLOCKS :: 0x91bb; +GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS :: 0x91bc; +GL_MAX_COMPUTE_IMAGE_UNIFORMS :: 0x91bd; +GL_MAX_COMPUTE_SHARED_MEMORY_SIZE :: 0x8262; +GL_MAX_COMPUTE_UNIFORM_COMPONENTS :: 0x8263; +GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS :: 0x8264; +GL_MAX_COMPUTE_ATOMIC_COUNTERS :: 0x8265; +GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS :: 0x8266; +GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS :: 0x90eb; +GL_MAX_COMPUTE_WORK_GROUP_COUNT :: 0x91be; +GL_MAX_COMPUTE_WORK_GROUP_SIZE :: 0x91bf; +GL_COMPUTE_WORK_GROUP_SIZE :: 0x8267; +GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER :: 0x90ec; +GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER :: 0x90ed; +GL_DISPATCH_INDIRECT_BUFFER :: 0x90ee; +GL_DISPATCH_INDIRECT_BUFFER_BINDING :: 0x90ef; +GL_COMPUTE_SHADER_BIT :: 0x00000020; +GL_DEBUG_OUTPUT_SYNCHRONOUS :: 0x8242; +GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH :: 0x8243; +GL_DEBUG_CALLBACK_FUNCTION :: 0x8244; +GL_DEBUG_CALLBACK_USER_PARAM :: 0x8245; +GL_DEBUG_SOURCE_API :: 0x8246; +GL_DEBUG_SOURCE_WINDOW_SYSTEM :: 0x8247; +GL_DEBUG_SOURCE_SHADER_COMPILER :: 0x8248; +GL_DEBUG_SOURCE_THIRD_PARTY :: 0x8249; +GL_DEBUG_SOURCE_APPLICATION :: 0x824a; +GL_DEBUG_SOURCE_OTHER :: 0x824b; +GL_DEBUG_TYPE_ERROR :: 0x824c; +GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR :: 0x824d; +GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR :: 0x824e; +GL_DEBUG_TYPE_PORTABILITY :: 0x824f; +GL_DEBUG_TYPE_PERFORMANCE :: 0x8250; +GL_DEBUG_TYPE_OTHER :: 0x8251; +GL_MAX_DEBUG_MESSAGE_LENGTH :: 0x9143; +GL_MAX_DEBUG_LOGGED_MESSAGES :: 0x9144; +GL_DEBUG_LOGGED_MESSAGES :: 0x9145; +GL_DEBUG_SEVERITY_HIGH :: 0x9146; +GL_DEBUG_SEVERITY_MEDIUM :: 0x9147; +GL_DEBUG_SEVERITY_LOW :: 0x9148; +GL_DEBUG_TYPE_MARKER :: 0x8268; +GL_DEBUG_TYPE_PUSH_GROUP :: 0x8269; +GL_DEBUG_TYPE_POP_GROUP :: 0x826a; +GL_DEBUG_SEVERITY_NOTIFICATION :: 0x826b; +GL_MAX_DEBUG_GROUP_STACK_DEPTH :: 0x826c; +GL_DEBUG_GROUP_STACK_DEPTH :: 0x826d; +GL_BUFFER :: 0x82e0; +GL_SHADER :: 0x82e1; +GL_PROGRAM :: 0x82e2; +GL_VERTEX_ARRAY :: 0x8074; +GL_QUERY :: 0x82e3; +GL_PROGRAM_PIPELINE :: 0x82e4; +GL_SAMPLER :: 0x82e6; +GL_MAX_LABEL_LENGTH :: 0x82e8; +GL_DEBUG_OUTPUT :: 0x92e0; +GL_CONTEXT_FLAG_DEBUG_BIT :: 0x00000002; +GL_MAX_UNIFORM_LOCATIONS :: 0x826e; +GL_FRAMEBUFFER_DEFAULT_WIDTH :: 0x9310; +GL_FRAMEBUFFER_DEFAULT_HEIGHT :: 0x9311; +GL_FRAMEBUFFER_DEFAULT_LAYERS :: 0x9312; +GL_FRAMEBUFFER_DEFAULT_SAMPLES :: 0x9313; +GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS :: 0x9314; +GL_MAX_FRAMEBUFFER_WIDTH :: 0x9315; +GL_MAX_FRAMEBUFFER_HEIGHT :: 0x9316; +GL_MAX_FRAMEBUFFER_LAYERS :: 0x9317; +GL_MAX_FRAMEBUFFER_SAMPLES :: 0x9318; +GL_INTERNALFORMAT_SUPPORTED :: 0x826f; +GL_INTERNALFORMAT_PREFERRED :: 0x8270; +GL_INTERNALFORMAT_RED_SIZE :: 0x8271; +GL_INTERNALFORMAT_GREEN_SIZE :: 0x8272; +GL_INTERNALFORMAT_BLUE_SIZE :: 0x8273; +GL_INTERNALFORMAT_ALPHA_SIZE :: 0x8274; +GL_INTERNALFORMAT_DEPTH_SIZE :: 0x8275; +GL_INTERNALFORMAT_STENCIL_SIZE :: 0x8276; +GL_INTERNALFORMAT_SHARED_SIZE :: 0x8277; +GL_INTERNALFORMAT_RED_TYPE :: 0x8278; +GL_INTERNALFORMAT_GREEN_TYPE :: 0x8279; +GL_INTERNALFORMAT_BLUE_TYPE :: 0x827a; +GL_INTERNALFORMAT_ALPHA_TYPE :: 0x827b; +GL_INTERNALFORMAT_DEPTH_TYPE :: 0x827c; +GL_INTERNALFORMAT_STENCIL_TYPE :: 0x827d; +GL_MAX_WIDTH :: 0x827e; +GL_MAX_HEIGHT :: 0x827f; +GL_MAX_DEPTH :: 0x8280; +GL_MAX_LAYERS :: 0x8281; +GL_MAX_COMBINED_DIMENSIONS :: 0x8282; +GL_COLOR_COMPONENTS :: 0x8283; +GL_DEPTH_COMPONENTS :: 0x8284; +GL_STENCIL_COMPONENTS :: 0x8285; +GL_COLOR_RENDERABLE :: 0x8286; +GL_DEPTH_RENDERABLE :: 0x8287; +GL_STENCIL_RENDERABLE :: 0x8288; +GL_FRAMEBUFFER_RENDERABLE :: 0x8289; +GL_FRAMEBUFFER_RENDERABLE_LAYERED :: 0x828a; +GL_FRAMEBUFFER_BLEND :: 0x828b; +GL_READ_PIXELS :: 0x828c; +GL_READ_PIXELS_FORMAT :: 0x828d; +GL_READ_PIXELS_TYPE :: 0x828e; +GL_TEXTURE_IMAGE_FORMAT :: 0x828f; +GL_TEXTURE_IMAGE_TYPE :: 0x8290; +GL_GET_TEXTURE_IMAGE_FORMAT :: 0x8291; +GL_GET_TEXTURE_IMAGE_TYPE :: 0x8292; +GL_MIPMAP :: 0x8293; +GL_MANUAL_GENERATE_MIPMAP :: 0x8294; +GL_AUTO_GENERATE_MIPMAP :: 0x8295; +GL_COLOR_ENCODING :: 0x8296; +GL_SRGB_READ :: 0x8297; +GL_SRGB_WRITE :: 0x8298; +GL_FILTER :: 0x829a; +GL_VERTEX_TEXTURE :: 0x829b; +GL_TESS_CONTROL_TEXTURE :: 0x829c; +GL_TESS_EVALUATION_TEXTURE :: 0x829d; +GL_GEOMETRY_TEXTURE :: 0x829e; +GL_FRAGMENT_TEXTURE :: 0x829f; +GL_COMPUTE_TEXTURE :: 0x82a0; +GL_TEXTURE_SHADOW :: 0x82a1; +GL_TEXTURE_GATHER :: 0x82a2; +GL_TEXTURE_GATHER_SHADOW :: 0x82a3; +GL_SHADER_IMAGE_LOAD :: 0x82a4; +GL_SHADER_IMAGE_STORE :: 0x82a5; +GL_SHADER_IMAGE_ATOMIC :: 0x82a6; +GL_IMAGE_TEXEL_SIZE :: 0x82a7; +GL_IMAGE_COMPATIBILITY_CLASS :: 0x82a8; +GL_IMAGE_PIXEL_FORMAT :: 0x82a9; +GL_IMAGE_PIXEL_TYPE :: 0x82aa; +GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST :: 0x82ac; +GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST :: 0x82ad; +GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE :: 0x82ae; +GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE :: 0x82af; +GL_TEXTURE_COMPRESSED_BLOCK_WIDTH :: 0x82b1; +GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT :: 0x82b2; +GL_TEXTURE_COMPRESSED_BLOCK_SIZE :: 0x82b3; +GL_CLEAR_BUFFER :: 0x82b4; +GL_TEXTURE_VIEW :: 0x82b5; +GL_VIEW_COMPATIBILITY_CLASS :: 0x82b6; +GL_FULL_SUPPORT :: 0x82b7; +GL_CAVEAT_SUPPORT :: 0x82b8; +GL_IMAGE_CLASS_4_X_32 :: 0x82b9; +GL_IMAGE_CLASS_2_X_32 :: 0x82ba; +GL_IMAGE_CLASS_1_X_32 :: 0x82bb; +GL_IMAGE_CLASS_4_X_16 :: 0x82bc; +GL_IMAGE_CLASS_2_X_16 :: 0x82bd; +GL_IMAGE_CLASS_1_X_16 :: 0x82be; +GL_IMAGE_CLASS_4_X_8 :: 0x82bf; +GL_IMAGE_CLASS_2_X_8 :: 0x82c0; +GL_IMAGE_CLASS_1_X_8 :: 0x82c1; +GL_IMAGE_CLASS_11_11_10 :: 0x82c2; +GL_IMAGE_CLASS_10_10_10_2 :: 0x82c3; +GL_VIEW_CLASS_128_BITS :: 0x82c4; +GL_VIEW_CLASS_96_BITS :: 0x82c5; +GL_VIEW_CLASS_64_BITS :: 0x82c6; +GL_VIEW_CLASS_48_BITS :: 0x82c7; +GL_VIEW_CLASS_32_BITS :: 0x82c8; +GL_VIEW_CLASS_24_BITS :: 0x82c9; +GL_VIEW_CLASS_16_BITS :: 0x82ca; +GL_VIEW_CLASS_8_BITS :: 0x82cb; +GL_VIEW_CLASS_S3TC_DXT1_RGB :: 0x82cc; +GL_VIEW_CLASS_S3TC_DXT1_RGBA :: 0x82cd; +GL_VIEW_CLASS_S3TC_DXT3_RGBA :: 0x82ce; +GL_VIEW_CLASS_S3TC_DXT5_RGBA :: 0x82cf; +GL_VIEW_CLASS_RGTC1_RED :: 0x82d0; +GL_VIEW_CLASS_RGTC2_RG :: 0x82d1; +GL_VIEW_CLASS_BPTC_UNORM :: 0x82d2; +GL_VIEW_CLASS_BPTC_FLOAT :: 0x82d3; +GL_UNIFORM :: 0x92e1; +GL_UNIFORM_BLOCK :: 0x92e2; +GL_PROGRAM_INPUT :: 0x92e3; +GL_PROGRAM_OUTPUT :: 0x92e4; +GL_BUFFER_VARIABLE :: 0x92e5; +GL_SHADER_STORAGE_BLOCK :: 0x92e6; +GL_VERTEX_SUBROUTINE :: 0x92e8; +GL_TESS_CONTROL_SUBROUTINE :: 0x92e9; +GL_TESS_EVALUATION_SUBROUTINE :: 0x92ea; +GL_GEOMETRY_SUBROUTINE :: 0x92eb; +GL_FRAGMENT_SUBROUTINE :: 0x92ec; +GL_COMPUTE_SUBROUTINE :: 0x92ed; +GL_VERTEX_SUBROUTINE_UNIFORM :: 0x92ee; +GL_TESS_CONTROL_SUBROUTINE_UNIFORM :: 0x92ef; +GL_TESS_EVALUATION_SUBROUTINE_UNIFORM :: 0x92f0; +GL_GEOMETRY_SUBROUTINE_UNIFORM :: 0x92f1; +GL_FRAGMENT_SUBROUTINE_UNIFORM :: 0x92f2; +GL_COMPUTE_SUBROUTINE_UNIFORM :: 0x92f3; +GL_TRANSFORM_FEEDBACK_VARYING :: 0x92f4; +GL_ACTIVE_RESOURCES :: 0x92f5; +GL_MAX_NAME_LENGTH :: 0x92f6; +GL_MAX_NUM_ACTIVE_VARIABLES :: 0x92f7; +GL_MAX_NUM_COMPATIBLE_SUBROUTINES :: 0x92f8; +GL_NAME_LENGTH :: 0x92f9; +GL_TYPE :: 0x92fa; +GL_ARRAY_SIZE :: 0x92fb; +GL_OFFSET :: 0x92fc; +GL_BLOCK_INDEX :: 0x92fd; +GL_ARRAY_STRIDE :: 0x92fe; +GL_MATRIX_STRIDE :: 0x92ff; +GL_IS_ROW_MAJOR :: 0x9300; +GL_ATOMIC_COUNTER_BUFFER_INDEX :: 0x9301; +GL_BUFFER_BINDING :: 0x9302; +GL_BUFFER_DATA_SIZE :: 0x9303; +GL_NUM_ACTIVE_VARIABLES :: 0x9304; +GL_ACTIVE_VARIABLES :: 0x9305; +GL_REFERENCED_BY_VERTEX_SHADER :: 0x9306; +GL_REFERENCED_BY_TESS_CONTROL_SHADER :: 0x9307; +GL_REFERENCED_BY_TESS_EVALUATION_SHADER :: 0x9308; +GL_REFERENCED_BY_GEOMETRY_SHADER :: 0x9309; +GL_REFERENCED_BY_FRAGMENT_SHADER :: 0x930a; +GL_REFERENCED_BY_COMPUTE_SHADER :: 0x930b; +GL_TOP_LEVEL_ARRAY_SIZE :: 0x930c; +GL_TOP_LEVEL_ARRAY_STRIDE :: 0x930d; +GL_LOCATION :: 0x930e; +GL_LOCATION_INDEX :: 0x930f; +GL_IS_PER_PATCH :: 0x92e7; +GL_SHADER_STORAGE_BUFFER :: 0x90d2; +GL_SHADER_STORAGE_BUFFER_BINDING :: 0x90d3; +GL_SHADER_STORAGE_BUFFER_START :: 0x90d4; +GL_SHADER_STORAGE_BUFFER_SIZE :: 0x90d5; +GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS :: 0x90d6; +GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS :: 0x90d7; +GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS :: 0x90d8; +GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS :: 0x90d9; +GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS :: 0x90da; +GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS :: 0x90db; +GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS :: 0x90dc; +GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS :: 0x90dd; +GL_MAX_SHADER_STORAGE_BLOCK_SIZE :: 0x90de; +GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT :: 0x90df; +GL_SHADER_STORAGE_BARRIER_BIT :: 0x00002000; +GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES :: 0x8f39; +GL_DEPTH_STENCIL_TEXTURE_MODE :: 0x90ea; +GL_TEXTURE_BUFFER_OFFSET :: 0x919d; +GL_TEXTURE_BUFFER_SIZE :: 0x919e; +GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT :: 0x919f; +GL_TEXTURE_VIEW_MIN_LEVEL :: 0x82db; +GL_TEXTURE_VIEW_NUM_LEVELS :: 0x82dc; +GL_TEXTURE_VIEW_MIN_LAYER :: 0x82dd; +GL_TEXTURE_VIEW_NUM_LAYERS :: 0x82de; +GL_TEXTURE_IMMUTABLE_LEVELS :: 0x82df; +GL_VERTEX_ATTRIB_BINDING :: 0x82d4; +GL_VERTEX_ATTRIB_RELATIVE_OFFSET :: 0x82d5; +GL_VERTEX_BINDING_DIVISOR :: 0x82d6; +GL_VERTEX_BINDING_OFFSET :: 0x82d7; +GL_VERTEX_BINDING_STRIDE :: 0x82d8; +GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET :: 0x82d9; +GL_MAX_VERTEX_ATTRIB_BINDINGS :: 0x82da; +GL_VERTEX_BINDING_BUFFER :: 0x8f4f; +GL_DISPLAY_LIST :: 0x82e7; +GL_STACK_UNDERFLOW :: 0x0504; +GL_STACK_OVERFLOW :: 0x0503; +GL_MAX_VERTEX_ATTRIB_STRIDE :: 0x82e5; +GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED :: 0x8221; +GL_TEXTURE_BUFFER_BINDING :: 0x8c2a; +GL_MAP_PERSISTENT_BIT :: 0x0040; +GL_MAP_COHERENT_BIT :: 0x0080; +GL_DYNAMIC_STORAGE_BIT :: 0x0100; +GL_CLIENT_STORAGE_BIT :: 0x0200; +GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT :: 0x00004000; +GL_BUFFER_IMMUTABLE_STORAGE :: 0x821f; +GL_BUFFER_STORAGE_FLAGS :: 0x8220; +GL_CLEAR_TEXTURE :: 0x9365; +GL_LOCATION_COMPONENT :: 0x934a; +GL_TRANSFORM_FEEDBACK_BUFFER_INDEX :: 0x934b; +GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE :: 0x934c; +GL_QUERY_BUFFER :: 0x9192; +GL_QUERY_BUFFER_BARRIER_BIT :: 0x00008000; +GL_QUERY_BUFFER_BINDING :: 0x9193; +GL_QUERY_RESULT_NO_WAIT :: 0x9194; +GL_MIRROR_CLAMP_TO_EDGE :: 0x8743; +GL_CONTEXT_LOST :: 0x0507; +GL_NEGATIVE_ONE_TO_ONE :: 0x935e; +GL_ZERO_TO_ONE :: 0x935f; +GL_CLIP_ORIGIN :: 0x935c; +GL_CLIP_DEPTH_MODE :: 0x935d; +GL_QUERY_WAIT_INVERTED :: 0x8e17; +GL_QUERY_NO_WAIT_INVERTED :: 0x8e18; +GL_QUERY_BY_REGION_WAIT_INVERTED :: 0x8e19; +GL_QUERY_BY_REGION_NO_WAIT_INVERTED :: 0x8e1a; +GL_MAX_CULL_DISTANCES :: 0x82f9; +GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES :: 0x82fa; +GL_TEXTURE_TARGET :: 0x1006; +GL_QUERY_TARGET :: 0x82ea; +GL_GUILTY_CONTEXT_RESET :: 0x8253; +GL_INNOCENT_CONTEXT_RESET :: 0x8254; +GL_UNKNOWN_CONTEXT_RESET :: 0x8255; +GL_RESET_NOTIFICATION_STRATEGY :: 0x8256; +GL_LOSE_CONTEXT_ON_RESET :: 0x8252; +GL_NO_RESET_NOTIFICATION :: 0x8261; +GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT :: 0x00000004; +GL_COLOR_TABLE :: 0x80d0; +GL_POST_CONVOLUTION_COLOR_TABLE :: 0x80d1; +GL_POST_COLOR_MATRIX_COLOR_TABLE :: 0x80d2; +GL_PROXY_COLOR_TABLE :: 0x80d3; +GL_PROXY_POST_CONVOLUTION_COLOR_TABLE :: 0x80d4; +GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE :: 0x80d5; +GL_CONVOLUTION_1D :: 0x8010; +GL_CONVOLUTION_2D :: 0x8011; +GL_SEPARABLE_2D :: 0x8012; +GL_HISTOGRAM :: 0x8024; +GL_PROXY_HISTOGRAM :: 0x8025; +GL_MINMAX :: 0x802e; +GL_CONTEXT_RELEASE_BEHAVIOR :: 0x82fb; +GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH :: 0x82fc; + +loaded_up_to: [2]int; +loaded_up_to_major := 0; +loaded_up_to_minor := 0; + +Set_Proc_Address_Type :: typedef proc(p: *void, name: *char); + +load_up_to :: proc(major: int, minor: int, set_proc_address: Set_Proc_Address_Type) { + // loaded_up_to = {0, 0}; // @todo + loaded_up_to[0] = major; + loaded_up_to[1] = minor; + loaded_up_to_major = major; + loaded_up_to_minor = minor; + + switch major*10+minor { + case 46: load_4_6(set_proc_address); @fallthrough + case 45: load_4_5(set_proc_address); @fallthrough + case 44: load_4_4(set_proc_address); @fallthrough + case 43: load_4_3(set_proc_address); @fallthrough + case 42: load_4_2(set_proc_address); @fallthrough + case 41: load_4_1(set_proc_address); @fallthrough + case 40: load_4_0(set_proc_address); @fallthrough + case 33: load_3_3(set_proc_address); @fallthrough + case 32: load_3_2(set_proc_address); @fallthrough + case 31: load_3_1(set_proc_address); @fallthrough + case 30: load_3_0(set_proc_address); @fallthrough + case 21: load_2_1(set_proc_address); @fallthrough + case 20: load_2_0(set_proc_address); @fallthrough + case 15: load_1_5(set_proc_address); @fallthrough + case 14: load_1_4(set_proc_address); @fallthrough + case 13: load_1_3(set_proc_address); @fallthrough + case 12: load_1_2(set_proc_address); @fallthrough + case 11: load_1_1(set_proc_address); @fallthrough + case 10: load_1_0(set_proc_address); + } +} + +/* +Type conversion overview: + typedef unsigned int GLenum; : u32 + typedef unsigned char GLboolean;: bool + typedef unsigned int GLbitfield;: u32 + typedef signed char GLbyte; : i8 + typedef short GLshort; : i16 + typedef int GLint; : i32 + typedef unsigned char GLubyte; : u8 + typedef unsigned short GLushort;: u16 + typedef unsigned int GLuint; : u32 + typedef int GLsizei; : i32 + typedef float GLfloat; : f32 + typedef double GLdouble; : f64 + typedef char GLchar; : u8 + typedef ptrdiff_t GLintptr; : int + typedef ptrdiff_t GLsizeiptr; : int + typedef int64_t GLint64; : i64 + typedef uint64_t GLuint64; : u64 + + void* : *void +*/ + +sync_t :: typedef *void; +@weak debug_proc_t :: typedef proc(source: u32, type: u32, id: u32, severity: u32, length: i32, message: *char, userParam: *void); + + +// VERSION_1_0 +glCullFace: proc(mode: u32); +glFrontFace: proc(mode: u32); +glHint: proc(target: u32, mode: u32); +glLineWidth: proc(width: f32); +glPointSize: proc(size: f32); +glPolygonMode: proc(face: u32, mode: u32); +glScissor: proc(x: i32, y: i32, width: i32, height: i32); +glTexParameterf: proc(target: u32, pname: u32, param: f32); +glTexParameterfv: proc(target: u32, pname: u32, params: *f32); +glTexParameteri: proc(target: u32, pname: u32, param: i32); +glTexParameteriv: proc(target: u32, pname: u32, params: *i32); +glTexImage1D: proc(target: u32, level: i32, internalformat: i32, width: i32, border: i32, format: u32, type: u32, pixels: *void); +glTexImage2D: proc(target: u32, level: i32, internalformat: i32, width: i32, height: i32, border: i32, format: u32, type: u32, pixels: *void); +glDrawBuffer: proc(buf: u32); +glClear: proc(mask: u32); +glClearColor: proc(red: f32, green: f32, blue: f32, alpha: f32); +glClearStencil: proc(s: i32); +glClearDepth: proc(depth: f64); +glStencilMask: proc(mask: u32); +glColorMask: proc(red: bool, green: bool, blue: bool, alpha: bool); +glDepthMask: proc(flag: bool); +glDisable: proc(cap: u32); +glEnable: proc(cap: u32); +glFinish: proc(); +glFlush: proc(); +glBlendFunc: proc(sfactor: u32, dfactor: u32); +glLogicOp: proc(opcode: u32); +glStencilFunc: proc(func: u32, ref: i32, mask: u32); +glStencilOp: proc(fail: u32, zfail: u32, zpass: u32); +glDepthFunc: proc(func: u32); +glPixelStoref: proc(pname: u32, param: f32); +glPixelStorei: proc(pname: u32, param: i32); +glReadBuffer: proc(src: u32); +glReadPixels: proc(x: i32, y: i32, width: i32, height: i32, format: u32, type: u32, pixels: *void); +glGetBooleanv: proc(pname: u32, data: *bool); +glGetDoublev: proc(pname: u32, data: *f64); +glGetError: proc(): u32; +glGetFloatv: proc(pname: u32, data: *f32); +glGetIntegerv: proc(pname: u32, data: *i32); +glGetString: proc(name: u32): *char; +glGetTexImage: proc(target: u32, level: i32, format: u32, type: u32, pixels: *void); +glGetTexParameterfv: proc(target: u32, pname: u32, params: *f32); +glGetTexParameteriv: proc(target: u32, pname: u32, params: *i32); +glGetTexLevelParameterfv: proc(target: u32, level: i32, pname: u32, params: *f32); +glGetTexLevelParameteriv: proc(target: u32, level: i32, pname: u32, params: *i32); +glIsEnabled: proc(cap: u32): bool; +glDepthRange: proc(near: f64, far: f64); +glViewport: proc(x: i32, y: i32, width: i32, height: i32); + +load_1_0 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glCullFace, "glCullFace"); + set_proc_address(&glFrontFace, "glFrontFace"); + set_proc_address(&glHint, "glHint"); + set_proc_address(&glLineWidth, "glLineWidth"); + set_proc_address(&glPointSize, "glPointSize"); + set_proc_address(&glPolygonMode, "glPolygonMode"); + set_proc_address(&glScissor, "glScissor"); + set_proc_address(&glTexParameterf, "glTexParameterf"); + set_proc_address(&glTexParameterfv, "glTexParameterfv"); + set_proc_address(&glTexParameteri, "glTexParameteri"); + set_proc_address(&glTexParameteriv, "glTexParameteriv"); + set_proc_address(&glTexImage1D, "glTexImage1D"); + set_proc_address(&glTexImage2D, "glTexImage2D"); + set_proc_address(&glDrawBuffer, "glDrawBuffer"); + set_proc_address(&glClear, "glClear"); + set_proc_address(&glClearColor, "glClearColor"); + set_proc_address(&glClearStencil, "glClearStencil"); + set_proc_address(&glClearDepth, "glClearDepth"); + set_proc_address(&glStencilMask, "glStencilMask"); + set_proc_address(&glColorMask, "glColorMask"); + set_proc_address(&glDepthMask, "glDepthMask"); + set_proc_address(&glDisable, "glDisable"); + set_proc_address(&glEnable, "glEnable"); + set_proc_address(&glFinish, "glFinish"); + set_proc_address(&glFlush, "glFlush"); + set_proc_address(&glBlendFunc, "glBlendFunc"); + set_proc_address(&glLogicOp, "glLogicOp"); + set_proc_address(&glStencilFunc, "glStencilFunc"); + set_proc_address(&glStencilOp, "glStencilOp"); + set_proc_address(&glDepthFunc, "glDepthFunc"); + set_proc_address(&glPixelStoref, "glPixelStoref"); + set_proc_address(&glPixelStorei, "glPixelStorei"); + set_proc_address(&glReadBuffer, "glReadBuffer"); + set_proc_address(&glReadPixels, "glReadPixels"); + set_proc_address(&glGetBooleanv, "glGetBooleanv"); + set_proc_address(&glGetDoublev, "glGetDoublev"); + set_proc_address(&glGetError, "glGetError"); + set_proc_address(&glGetFloatv, "glGetFloatv"); + set_proc_address(&glGetIntegerv, "glGetIntegerv"); + set_proc_address(&glGetString, "glGetString"); + set_proc_address(&glGetTexImage, "glGetTexImage"); + set_proc_address(&glGetTexParameterfv, "glGetTexParameterfv"); + set_proc_address(&glGetTexParameteriv, "glGetTexParameteriv"); + set_proc_address(&glGetTexLevelParameterfv, "glGetTexLevelParameterfv"); + set_proc_address(&glGetTexLevelParameteriv, "glGetTexLevelParameteriv"); + set_proc_address(&glIsEnabled, "glIsEnabled"); + set_proc_address(&glDepthRange, "glDepthRange"); + set_proc_address(&glViewport, "glViewport"); +} + + +// VERSION_1_1 +glDrawArrays: proc(mode: u32, first: i32, count: i32); +glDrawElements: proc(mode: u32, count: i32, type: u32, indices: *void); +glPolygonOffset: proc(factor: f32, units: f32); +glCopyTexImage1D: proc(target: u32, level: i32, internalformat: u32, x: i32, y: i32, width: i32, border: i32); +glCopyTexImage2D: proc(target: u32, level: i32, internalformat: u32, x: i32, y: i32, width: i32, height: i32, border: i32); +glCopyTexSubImage1D: proc(target: u32, level: i32, xoffset: i32, x: i32, y: i32, width: i32); +glCopyTexSubImage2D: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, x: i32, y: i32, width: i32, height: i32); +glTexSubImage1D: proc(target: u32, level: i32, xoffset: i32, width: i32, format: u32, type: u32, pixels: *void); +glTexSubImage2D: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, width: i32, height: i32, format: u32, type: u32, pixels: *void); +glBindTexture: proc(target: u32, texture: u32); +glDeleteTextures: proc(n: i32, textures: *u32); +glGenTextures: proc(n: i32, textures: *u32); +glIsTexture: proc(texture: u32): bool; + +load_1_1 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glDrawArrays, "glDrawArrays"); + set_proc_address(&glDrawElements, "glDrawElements"); + set_proc_address(&glPolygonOffset, "glPolygonOffset"); + set_proc_address(&glCopyTexImage1D, "glCopyTexImage1D"); + set_proc_address(&glCopyTexImage2D, "glCopyTexImage2D"); + set_proc_address(&glCopyTexSubImage1D, "glCopyTexSubImage1D"); + set_proc_address(&glCopyTexSubImage2D, "glCopyTexSubImage2D"); + set_proc_address(&glTexSubImage1D, "glTexSubImage1D"); + set_proc_address(&glTexSubImage2D, "glTexSubImage2D"); + set_proc_address(&glBindTexture, "glBindTexture"); + set_proc_address(&glDeleteTextures, "glDeleteTextures"); + set_proc_address(&glGenTextures, "glGenTextures"); + set_proc_address(&glIsTexture, "glIsTexture"); +} + + +// VERSION_1_2 +glDrawRangeElements: proc(mode: u32, start: u32, end: u32, count: i32, type: u32, indices: *void); +glTexImage3D: proc(target: u32, level: i32, internalformat: i32, width: i32, height: i32, depth: i32, border: i32, format: u32, type: u32, data: *void); +glTexSubImage3D: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, format: u32, type: u32, pixels: *void); +glCopyTexSubImage3D: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, x: i32, y: i32, width: i32, height: i32); + +load_1_2 :: proc(set_proc_address: Set_Proc_Address_Type) { + + set_proc_address(&glDrawRangeElements, "glDrawRangeElements"); + set_proc_address(&glTexImage3D, "glTexImage3D"); + set_proc_address(&glTexSubImage3D, "glTexSubImage3D"); + set_proc_address(&glCopyTexSubImage3D, "glCopyTexSubImage3D"); +} + + +// VERSION_1_3 +glActiveTexture: proc(texture: u32); +glSampleCoverage: proc(value: f32, invert: bool); +glCompressedTexImage3D: proc(target: u32, level: i32, internalformat: u32, width: i32, height: i32, depth: i32, border: i32, imageSize: i32, data: *void); +glCompressedTexImage2D: proc(target: u32, level: i32, internalformat: u32, width: i32, height: i32, border: i32, imageSize: i32, data: *void); +glCompressedTexImage1D: proc(target: u32, level: i32, internalformat: u32, width: i32, border: i32, imageSize: i32, data: *void); +glCompressedTexSubImage3D: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, format: u32, imageSize: i32, data: *void); +glCompressedTexSubImage2D: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, width: i32, height: i32, format: u32, imageSize: i32, data: *void); +glCompressedTexSubImage1D: proc(target: u32, level: i32, xoffset: i32, width: i32, format: u32, imageSize: i32, data: *void); +glGetCompressedTexImage: proc(target: u32, level: i32, img: *void); + +load_1_3 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glActiveTexture, "glActiveTexture"); + set_proc_address(&glSampleCoverage, "glSampleCoverage"); + set_proc_address(&glCompressedTexImage3D, "glCompressedTexImage3D"); + set_proc_address(&glCompressedTexImage2D, "glCompressedTexImage2D"); + set_proc_address(&glCompressedTexImage1D, "glCompressedTexImage1D"); + set_proc_address(&glCompressedTexSubImage3D, "glCompressedTexSubImage3D"); + set_proc_address(&glCompressedTexSubImage2D, "glCompressedTexSubImage2D"); + set_proc_address(&glCompressedTexSubImage1D, "glCompressedTexSubImage1D"); + set_proc_address(&glGetCompressedTexImage, "glGetCompressedTexImage"); +} + + +// VERSION_1_4 +glBlendFuncSeparate: proc(sfactorRGB: u32, dfactorRGB: u32, sfactorAlpha: u32, dfactorAlpha: u32); +glMultiDrawArrays: proc(mode: u32, first: *i32, count: *i32, drawcount: i32); +glMultiDrawElements: proc(mode: u32, count: *i32, type: u32, indices: **void, drawcount: i32); +glPointParameterf: proc(pname: u32, param: f32); +glPointParameterfv: proc(pname: u32, params: *f32); +glPointParameteri: proc(pname: u32, param: i32); +glPointParameteriv: proc(pname: u32, params: *i32); +glBlendColor: proc(red: f32, green: f32, blue: f32, alpha: f32); +glBlendEquation: proc(mode: u32); + + +load_1_4 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glBlendFuncSeparate, "glBlendFuncSeparate"); + set_proc_address(&glMultiDrawArrays, "glMultiDrawArrays"); + set_proc_address(&glMultiDrawElements, "glMultiDrawElements"); + set_proc_address(&glPointParameterf, "glPointParameterf"); + set_proc_address(&glPointParameterfv, "glPointParameterfv"); + set_proc_address(&glPointParameteri, "glPointParameteri"); + set_proc_address(&glPointParameteriv, "glPointParameteriv"); + set_proc_address(&glBlendColor, "glBlendColor"); + set_proc_address(&glBlendEquation, "glBlendEquation"); +} + + +// VERSION_1_5 +glGenQueries: proc(n: i32, ids: *u32); +glDeleteQueries: proc(n: i32, ids: *u32); +glIsQuery: proc(id: u32): bool; +glBeginQuery: proc(target: u32, id: u32); +glEndQuery: proc(target: u32); +glGetQueryiv: proc(target: u32, pname: u32, params: *i32); +glGetQueryObjectiv: proc(id: u32, pname: u32, params: *i32); +glGetQueryObjectuiv: proc(id: u32, pname: u32, params: *u32); +glBindBuffer: proc(target: u32, buffer: u32); +glDeleteBuffers: proc(n: i32, buffers: *u32); +glGenBuffers: proc(n: i32, buffers: *u32); +glIsBuffer: proc(buffer: u32): bool; +glBufferData: proc(target: u32, size: int, data: *void, usage: u32); +glBufferSubData: proc(target: u32, offset: int, size: int, data: *void); +glGetBufferSubData: proc(target: u32, offset: int, size: int, data: *void); +glMapBuffer: proc(target: u32, access: u32): *void; +glUnmapBuffer: proc(target: u32): bool; +glGetBufferParameteriv: proc(target: u32, pname: u32, params: *i32); +glGetBufferPointerv: proc(target: u32, pname: u32, params: **void); + +load_1_5 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glGenQueries, "glGenQueries"); + set_proc_address(&glDeleteQueries, "glDeleteQueries"); + set_proc_address(&glIsQuery, "glIsQuery"); + set_proc_address(&glBeginQuery, "glBeginQuery"); + set_proc_address(&glEndQuery, "glEndQuery"); + set_proc_address(&glGetQueryiv, "glGetQueryiv"); + set_proc_address(&glGetQueryObjectiv, "glGetQueryObjectiv"); + set_proc_address(&glGetQueryObjectuiv, "glGetQueryObjectuiv"); + set_proc_address(&glBindBuffer, "glBindBuffer"); + set_proc_address(&glDeleteBuffers, "glDeleteBuffers"); + set_proc_address(&glGenBuffers, "glGenBuffers"); + set_proc_address(&glIsBuffer, "glIsBuffer"); + set_proc_address(&glBufferData, "glBufferData"); + set_proc_address(&glBufferSubData, "glBufferSubData"); + set_proc_address(&glGetBufferSubData, "glGetBufferSubData"); + set_proc_address(&glMapBuffer, "glMapBuffer"); + set_proc_address(&glUnmapBuffer, "glUnmapBuffer"); + set_proc_address(&glGetBufferParameteriv, "glGetBufferParameteriv"); + set_proc_address(&glGetBufferPointerv, "glGetBufferPointerv"); +} + + +// VERSION_2_0 +glBlendEquationSeparate: proc(modeRGB: u32, modeAlpha: u32); +glDrawBuffers: proc(n: i32, bufs: *u32); +glStencilOpSeparate: proc(face: u32, sfail: u32, dpfail: u32, dppass: u32); +glStencilFuncSeparate: proc(face: u32, func: u32, ref: i32, mask: u32); +glStencilMaskSeparate: proc(face: u32, mask: u32); +glAttachShader: proc(program: u32, shader: u32); +glBindAttribLocation: proc(program: u32, index: u32, name: *char); +glCompileShader: proc(shader: u32); +glCreateProgram: proc(): u32; +glCreateShader: proc(type: u32): u32; +glDeleteProgram: proc(program: u32); +glDeleteShader: proc(shader: u32); +glDetachShader: proc(program: u32, shader: u32); +glDisableVertexAttribArray: proc(index: u32); +glEnableVertexAttribArray: proc(index: u32); +glGetActiveAttrib: proc(program: u32, index: u32, bufSize: i32, length: *i32, size: *i32, type: *u32, name: *u8); +glGetActiveUniform: proc(program: u32, index: u32, bufSize: i32, length: *i32, size: *i32, type: *u32, name: *u8); +glGetAttachedShaders: proc(program: u32, maxCount: i32, count: *i32, shaders: *u32); +glGetAttribLocation: proc(program: u32, name: *char): i32; +glGetProgramiv: proc(program: u32, pname: u32, params: *i32); +glGetProgramInfoLog: proc(program: u32, bufSize: i32, length: *i32, infoLog: *u8); +glGetShaderiv: proc(shader: u32, pname: u32, params: *i32); +glGetShaderInfoLog: proc(shader: u32, bufSize: i32, length: *i32, infoLog: *u8); +glGetShaderSource: proc(shader: u32, bufSize: i32, length: *i32, source: *u8); +glGetUniformLocation: proc(program: u32, name: *char): i32; +glGetUniformfv: proc(program: u32, location: i32, params: *f32); +glGetUniformiv: proc(program: u32, location: i32, params: *i32); +glGetVertexAttribdv: proc(index: u32, pname: u32, params: *f64); +glGetVertexAttribfv: proc(index: u32, pname: u32, params: *f32); +glGetVertexAttribiv: proc(index: u32, pname: u32, params: *i32); +glGetVertexAttribPointerv: proc(index: u32, pname: u32, pointer: *uintptr); +glIsProgram: proc(program: u32): bool; +glIsShader: proc(shader: u32): bool; +glLinkProgram: proc(program: u32); +glShaderSource: proc(shader: u32, count: i32, string: **char, length: *i32); +glUseProgram: proc(program: u32); +glUniform1f: proc(location: i32, v0: f32); +glUniform2f: proc(location: i32, v0: f32, v1: f32); +glUniform3f: proc(location: i32, v0: f32, v1: f32, v2: f32); +glUniform4f: proc(location: i32, v0: f32, v1: f32, v2: f32, v3: f32); +glUniform1i: proc(location: i32, v0: i32); +glUniform2i: proc(location: i32, v0: i32, v1: i32); +glUniform3i: proc(location: i32, v0: i32, v1: i32, v2: i32); +glUniform4i: proc(location: i32, v0: i32, v1: i32, v2: i32, v3: i32); +glUniform1fv: proc(location: i32, count: i32, value: *f32); +glUniform2fv: proc(location: i32, count: i32, value: *f32); +glUniform3fv: proc(location: i32, count: i32, value: *f32); +glUniform4fv: proc(location: i32, count: i32, value: *f32); +glUniform1iv: proc(location: i32, count: i32, value: *i32); +glUniform2iv: proc(location: i32, count: i32, value: *i32); +glUniform3iv: proc(location: i32, count: i32, value: *i32); +glUniform4iv: proc(location: i32, count: i32, value: *i32); +glUniformMatrix2fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix3fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix4fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glValidateProgram: proc(program: u32); +glVertexAttrib1d: proc(index: u32, x: f64); +glVertexAttrib1dv: proc(index: u32, v: *f64); +glVertexAttrib1f: proc(index: u32, x: f32); +glVertexAttrib1fv: proc(index: u32, v: *f32); +glVertexAttrib1s: proc(index: u32, x: i16); +glVertexAttrib1sv: proc(index: u32, v: *i16); +glVertexAttrib2d: proc(index: u32, x: f64, y: f64); +glVertexAttrib2dv: proc(index: u32, v: *[2]f64); +glVertexAttrib2f: proc(index: u32, x: f32, y: f32); +glVertexAttrib2fv: proc(index: u32, v: *[2]f32); +glVertexAttrib2s: proc(index: u32, x: i16, y: i16); +glVertexAttrib2sv: proc(index: u32, v: *[2]i16); +glVertexAttrib3d: proc(index: u32, x: f64, y: f64, z: f64); +glVertexAttrib3dv: proc(index: u32, v: *[3]f64); +glVertexAttrib3f: proc(index: u32, x: f32, y: f32, z: f32); +glVertexAttrib3fv: proc(index: u32, v: *[3]f32); +glVertexAttrib3s: proc(index: u32, x: i16, y: i16, z: i16); +glVertexAttrib3sv: proc(index: u32, v: *[3]i16); +glVertexAttrib4Nbv: proc(index: u32, v: *[4]i8); +glVertexAttrib4Niv: proc(index: u32, v: *[4]i32); +glVertexAttrib4Nsv: proc(index: u32, v: *[4]i16); +glVertexAttrib4Nub: proc(index: u32, x: u8, y: u8, z: u8, w: u8); +glVertexAttrib4Nubv: proc(index: u32, v: *[4]u8); +glVertexAttrib4Nuiv: proc(index: u32, v: *[4]u32); +glVertexAttrib4Nusv: proc(index: u32, v: *[4]u16); +glVertexAttrib4bv: proc(index: u32, v: *[4]i8); +glVertexAttrib4d: proc(index: u32, x: f64, y: f64, z: f64, w: f64); +glVertexAttrib4dv: proc(index: u32, v: *[4]f64); +glVertexAttrib4f: proc(index: u32, x: f32, y: f32, z: f32, w: f32); +glVertexAttrib4fv: proc(index: u32, v: *[4]f32); +glVertexAttrib4iv: proc(index: u32, v: *[4]i32); +glVertexAttrib4s: proc(index: u32, x: i16, y: i16, z: i16, w: i16); +glVertexAttrib4sv: proc(index: u32, v: *[4]i16); +glVertexAttrib4ubv: proc(index: u32, v: *[4]u8); +glVertexAttrib4uiv: proc(index: u32, v: *[4]u32); +glVertexAttrib4usv: proc(index: u32, v: *[4]u16); +glVertexAttribPointer: proc(index: u32, size: i32, type: u32, normalized: bool, stride: i32, pointer: uintptr); + +load_2_0 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glBlendEquationSeparate, "glBlendEquationSeparate"); + set_proc_address(&glDrawBuffers, "glDrawBuffers"); + set_proc_address(&glStencilOpSeparate, "glStencilOpSeparate"); + set_proc_address(&glStencilFuncSeparate, "glStencilFuncSeparate"); + set_proc_address(&glStencilMaskSeparate, "glStencilMaskSeparate"); + set_proc_address(&glAttachShader, "glAttachShader"); + set_proc_address(&glBindAttribLocation, "glBindAttribLocation"); + set_proc_address(&glCompileShader, "glCompileShader"); + set_proc_address(&glCreateProgram, "glCreateProgram"); + set_proc_address(&glCreateShader, "glCreateShader"); + set_proc_address(&glDeleteProgram, "glDeleteProgram"); + set_proc_address(&glDeleteShader, "glDeleteShader"); + set_proc_address(&glDetachShader, "glDetachShader"); + set_proc_address(&glDisableVertexAttribArray, "glDisableVertexAttribArray"); + set_proc_address(&glEnableVertexAttribArray, "glEnableVertexAttribArray"); + set_proc_address(&glGetActiveAttrib, "glGetActiveAttrib"); + set_proc_address(&glGetActiveUniform, "glGetActiveUniform"); + set_proc_address(&glGetAttachedShaders, "glGetAttachedShaders"); + set_proc_address(&glGetAttribLocation, "glGetAttribLocation"); + set_proc_address(&glGetProgramiv, "glGetProgramiv"); + set_proc_address(&glGetProgramInfoLog, "glGetProgramInfoLog"); + set_proc_address(&glGetShaderiv, "glGetShaderiv"); + set_proc_address(&glGetShaderInfoLog, "glGetShaderInfoLog"); + set_proc_address(&glGetShaderSource, "glGetShaderSource"); + set_proc_address(&glGetUniformLocation, "glGetUniformLocation"); + set_proc_address(&glGetUniformfv, "glGetUniformfv"); + set_proc_address(&glGetUniformiv, "glGetUniformiv"); + set_proc_address(&glGetVertexAttribdv, "glGetVertexAttribdv"); + set_proc_address(&glGetVertexAttribfv, "glGetVertexAttribfv"); + set_proc_address(&glGetVertexAttribiv, "glGetVertexAttribiv"); + set_proc_address(&glGetVertexAttribPointerv, "glGetVertexAttribPointerv"); + set_proc_address(&glIsProgram, "glIsProgram"); + set_proc_address(&glIsShader, "glIsShader"); + set_proc_address(&glLinkProgram, "glLinkProgram"); + set_proc_address(&glShaderSource, "glShaderSource"); + set_proc_address(&glUseProgram, "glUseProgram"); + set_proc_address(&glUniform1f, "glUniform1f"); + set_proc_address(&glUniform2f, "glUniform2f"); + set_proc_address(&glUniform3f, "glUniform3f"); + set_proc_address(&glUniform4f, "glUniform4f"); + set_proc_address(&glUniform1i, "glUniform1i"); + set_proc_address(&glUniform2i, "glUniform2i"); + set_proc_address(&glUniform3i, "glUniform3i"); + set_proc_address(&glUniform4i, "glUniform4i"); + set_proc_address(&glUniform1fv, "glUniform1fv"); + set_proc_address(&glUniform2fv, "glUniform2fv"); + set_proc_address(&glUniform3fv, "glUniform3fv"); + set_proc_address(&glUniform4fv, "glUniform4fv"); + set_proc_address(&glUniform1iv, "glUniform1iv"); + set_proc_address(&glUniform2iv, "glUniform2iv"); + set_proc_address(&glUniform3iv, "glUniform3iv"); + set_proc_address(&glUniform4iv, "glUniform4iv"); + set_proc_address(&glUniformMatrix2fv, "glUniformMatrix2fv"); + set_proc_address(&glUniformMatrix3fv, "glUniformMatrix3fv"); + set_proc_address(&glUniformMatrix4fv, "glUniformMatrix4fv"); + set_proc_address(&glValidateProgram, "glValidateProgram"); + set_proc_address(&glVertexAttrib1d, "glVertexAttrib1d"); + set_proc_address(&glVertexAttrib1dv, "glVertexAttrib1dv"); + set_proc_address(&glVertexAttrib1f, "glVertexAttrib1f"); + set_proc_address(&glVertexAttrib1fv, "glVertexAttrib1fv"); + set_proc_address(&glVertexAttrib1s, "glVertexAttrib1s"); + set_proc_address(&glVertexAttrib1sv, "glVertexAttrib1sv"); + set_proc_address(&glVertexAttrib2d, "glVertexAttrib2d"); + set_proc_address(&glVertexAttrib2dv, "glVertexAttrib2dv"); + set_proc_address(&glVertexAttrib2f, "glVertexAttrib2f"); + set_proc_address(&glVertexAttrib2fv, "glVertexAttrib2fv"); + set_proc_address(&glVertexAttrib2s, "glVertexAttrib2s"); + set_proc_address(&glVertexAttrib2sv, "glVertexAttrib2sv"); + set_proc_address(&glVertexAttrib3d, "glVertexAttrib3d"); + set_proc_address(&glVertexAttrib3dv, "glVertexAttrib3dv"); + set_proc_address(&glVertexAttrib3f, "glVertexAttrib3f"); + set_proc_address(&glVertexAttrib3fv, "glVertexAttrib3fv"); + set_proc_address(&glVertexAttrib3s, "glVertexAttrib3s"); + set_proc_address(&glVertexAttrib3sv, "glVertexAttrib3sv"); + set_proc_address(&glVertexAttrib4Nbv, "glVertexAttrib4Nbv"); + set_proc_address(&glVertexAttrib4Niv, "glVertexAttrib4Niv"); + set_proc_address(&glVertexAttrib4Nsv, "glVertexAttrib4Nsv"); + set_proc_address(&glVertexAttrib4Nub, "glVertexAttrib4Nub"); + set_proc_address(&glVertexAttrib4Nubv, "glVertexAttrib4Nubv"); + set_proc_address(&glVertexAttrib4Nuiv, "glVertexAttrib4Nuiv"); + set_proc_address(&glVertexAttrib4Nusv, "glVertexAttrib4Nusv"); + set_proc_address(&glVertexAttrib4bv, "glVertexAttrib4bv"); + set_proc_address(&glVertexAttrib4d, "glVertexAttrib4d"); + set_proc_address(&glVertexAttrib4dv, "glVertexAttrib4dv"); + set_proc_address(&glVertexAttrib4f, "glVertexAttrib4f"); + set_proc_address(&glVertexAttrib4fv, "glVertexAttrib4fv"); + set_proc_address(&glVertexAttrib4iv, "glVertexAttrib4iv"); + set_proc_address(&glVertexAttrib4s, "glVertexAttrib4s"); + set_proc_address(&glVertexAttrib4sv, "glVertexAttrib4sv"); + set_proc_address(&glVertexAttrib4ubv, "glVertexAttrib4ubv"); + set_proc_address(&glVertexAttrib4uiv, "glVertexAttrib4uiv"); + set_proc_address(&glVertexAttrib4usv, "glVertexAttrib4usv"); + set_proc_address(&glVertexAttribPointer, "glVertexAttribPointer"); +} + + +// VERSION_2_1 +glUniformMatrix2x3fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix3x2fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix2x4fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix4x2fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix3x4fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix4x3fv: proc(location: i32, count: i32, transpose: bool, value: *f32); + +load_2_1 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glUniformMatrix2x3fv, "glUniformMatrix2x3fv"); + set_proc_address(&glUniformMatrix3x2fv, "glUniformMatrix3x2fv"); + set_proc_address(&glUniformMatrix2x4fv, "glUniformMatrix2x4fv"); + set_proc_address(&glUniformMatrix4x2fv, "glUniformMatrix4x2fv"); + set_proc_address(&glUniformMatrix3x4fv, "glUniformMatrix3x4fv"); + set_proc_address(&glUniformMatrix4x3fv, "glUniformMatrix4x3fv"); +} + + +// VERSION_3_0 +glColorMaski: proc(index: u32, r: bool, g: bool, b: bool, a: bool); +glGetBooleani_v: proc(target: u32, index: u32, data: *bool); +glGetIntegeri_v: proc(target: u32, index: u32, data: *i32); +glEnablei: proc(target: u32, index: u32); +glDisablei: proc(target: u32, index: u32); +glIsEnabledi: proc(target: u32, index: u32): bool; +glBeginTransformFeedback: proc(primitiveMode: u32); +glEndTransformFeedback: proc(); +glBindBufferRange: proc(target: u32, index: u32, buffer: u32, offset: int, size: int); +glBindBufferBase: proc(target: u32, index: u32, buffer: u32); +glTransformFeedbackVaryings: proc(program: u32, count: i32, varyings: **char, bufferMode: u32); +glGetTransformFeedbackVarying: proc(program: u32, index: u32, bufSize: i32, length: *i32, size: *i32, type: *u32, name: *u8); +glClampColor: proc(target: u32, clamp: u32); +glBeginConditionalRender: proc(id: u32, mode: u32); +glEndConditionalRender: proc(); +glVertexAttribIPointer: proc(index: u32, size: i32, type: u32, stride: i32, pointer: uintptr); +glGetVertexAttribIiv: proc(index: u32, pname: u32, params: *i32); +glGetVertexAttribIuiv: proc(index: u32, pname: u32, params: *u32); +glVertexAttribI1i: proc(index: u32, x: i32); +glVertexAttribI2i: proc(index: u32, x: i32, y: i32); +glVertexAttribI3i: proc(index: u32, x: i32, y: i32, z: i32); +glVertexAttribI4i: proc(index: u32, x: i32, y: i32, z: i32, w: i32); +glVertexAttribI1ui: proc(index: u32, x: u32); +glVertexAttribI2ui: proc(index: u32, x: u32, y: u32); +glVertexAttribI3ui: proc(index: u32, x: u32, y: u32, z: u32); +glVertexAttribI4ui: proc(index: u32, x: u32, y: u32, z: u32, w: u32); +glVertexAttribI1iv: proc(index: u32, v: *i32); +glVertexAttribI2iv: proc(index: u32, v: *i32); +glVertexAttribI3iv: proc(index: u32, v: *i32); +glVertexAttribI4iv: proc(index: u32, v: *i32); +glVertexAttribI1uiv: proc(index: u32, v: *u32); +glVertexAttribI2uiv: proc(index: u32, v: *u32); +glVertexAttribI3uiv: proc(index: u32, v: *u32); +glVertexAttribI4uiv: proc(index: u32, v: *u32); +glVertexAttribI4bv: proc(index: u32, v: *i8); +glVertexAttribI4sv: proc(index: u32, v: *i16); +glVertexAttribI4ubv: proc(index: u32, v: *u8); +glVertexAttribI4usv: proc(index: u32, v: *u16); +glGetUniformuiv: proc(program: u32, location: i32, params: *u32); +glBindFragDataLocation: proc(program: u32, color: u32, name: *char); +glGetFragDataLocation: proc(program: u32, name: *char): i32; +glUniform1ui: proc(location: i32, v0: u32); +glUniform2ui: proc(location: i32, v0: u32, v1: u32); +glUniform3ui: proc(location: i32, v0: u32, v1: u32, v2: u32); +glUniform4ui: proc(location: i32, v0: u32, v1: u32, v2: u32, v3: u32); +glUniform1uiv: proc(location: i32, count: i32, value: *u32); +glUniform2uiv: proc(location: i32, count: i32, value: *u32); +glUniform3uiv: proc(location: i32, count: i32, value: *u32); +glUniform4uiv: proc(location: i32, count: i32, value: *u32); +glTexParameterIiv: proc(target: u32, pname: u32, params: *i32); +glTexParameterIuiv: proc(target: u32, pname: u32, params: *u32); +glGetTexParameterIiv: proc(target: u32, pname: u32, params: *i32); +glGetTexParameterIuiv: proc(target: u32, pname: u32, params: *u32); +glClearBufferiv: proc(buffer: u32, drawbuffer: i32, value: *i32); +glClearBufferuiv: proc(buffer: u32, drawbuffer: i32, value: *u32); +glClearBufferfv: proc(buffer: u32, drawbuffer: i32, value: *f32); +glClearBufferfi: proc(buffer: u32, drawbuffer: i32, depth: f32, stencil: i32): *void; +glGetStringi: proc(name: u32, index: u32): *char; +glIsRenderbuffer: proc(renderbuffer: u32): bool; +glBindRenderbuffer: proc(target: u32, renderbuffer: u32); +glDeleteRenderbuffers: proc(n: i32, renderbuffers: *u32); +glGenRenderbuffers: proc(n: i32, renderbuffers: *u32); +glRenderbufferStorage: proc(target: u32, internalformat: u32, width: i32, height: i32); +glGetRenderbufferParameteriv: proc(target: u32, pname: u32, params: *i32); +glIsFramebuffer: proc(framebuffer: u32): bool; +glBindFramebuffer: proc(target: u32, framebuffer: u32); +glDeleteFramebuffers: proc(n: i32, framebuffers: *u32); +glGenFramebuffers: proc(n: i32, framebuffers: *u32); +glCheckFramebufferStatus: proc(target: u32): u32; +glFramebufferTexture1D: proc(target: u32, attachment: u32, textarget: u32, texture: u32, level: i32); +glFramebufferTexture2D: proc(target: u32, attachment: u32, textarget: u32, texture: u32, level: i32); +glFramebufferTexture3D: proc(target: u32, attachment: u32, textarget: u32, texture: u32, level: i32, zoffset: i32); +glFramebufferRenderbuffer: proc(target: u32, attachment: u32, renderbuffertarget: u32, renderbuffer: u32); +glGetFramebufferAttachmentParameteriv: proc(target: u32, attachment: u32, pname: u32, params: *i32); +glGenerateMipmap: proc(target: u32); +glBlitFramebuffer: proc(srcX0: i32, srcY0: i32, srcX1: i32, srcY1: i32, dstX0: i32, dstY0: i32, dstX1: i32, dstY1: i32, mask: u32, filter: u32); +glRenderbufferStorageMultisample: proc(target: u32, samples: i32, internalformat: u32, width: i32, height: i32); +glFramebufferTextureLayer: proc(target: u32, attachment: u32, texture: u32, level: i32, layer: i32); +glMapBufferRange: proc(target: u32, offset: int, length: int, access: u32): *void; +glFlushMappedBufferRange: proc(target: u32, offset: int, length: int); +glBindVertexArray: proc(array: u32); +glDeleteVertexArrays: proc(n: i32, arrays: *u32); +glGenVertexArrays: proc(n: i32, arrays: *u32); +glIsVertexArray: proc(array: u32): bool; + +load_3_0 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glColorMaski, "glColorMaski"); + set_proc_address(&glGetBooleani_v, "glGetBooleani_v"); + set_proc_address(&glGetIntegeri_v, "glGetIntegeri_v"); + set_proc_address(&glEnablei, "glEnablei"); + set_proc_address(&glDisablei, "glDisablei"); + set_proc_address(&glIsEnabledi, "glIsEnabledi"); + set_proc_address(&glBeginTransformFeedback, "glBeginTransformFeedback"); + set_proc_address(&glEndTransformFeedback, "glEndTransformFeedback"); + set_proc_address(&glBindBufferRange, "glBindBufferRange"); + set_proc_address(&glBindBufferBase, "glBindBufferBase"); + set_proc_address(&glTransformFeedbackVaryings, "glTransformFeedbackVaryings"); + set_proc_address(&glGetTransformFeedbackVarying, "glGetTransformFeedbackVarying"); + set_proc_address(&glClampColor, "glClampColor"); + set_proc_address(&glBeginConditionalRender, "glBeginConditionalRender"); + set_proc_address(&glEndConditionalRender, "glEndConditionalRender"); + set_proc_address(&glVertexAttribIPointer, "glVertexAttribIPointer"); + set_proc_address(&glGetVertexAttribIiv, "glGetVertexAttribIiv"); + set_proc_address(&glGetVertexAttribIuiv, "glGetVertexAttribIuiv"); + set_proc_address(&glVertexAttribI1i, "glVertexAttribI1i"); + set_proc_address(&glVertexAttribI2i, "glVertexAttribI2i"); + set_proc_address(&glVertexAttribI3i, "glVertexAttribI3i"); + set_proc_address(&glVertexAttribI4i, "glVertexAttribI4i"); + set_proc_address(&glVertexAttribI1ui, "glVertexAttribI1ui"); + set_proc_address(&glVertexAttribI2ui, "glVertexAttribI2ui"); + set_proc_address(&glVertexAttribI3ui, "glVertexAttribI3ui"); + set_proc_address(&glVertexAttribI4ui, "glVertexAttribI4ui"); + set_proc_address(&glVertexAttribI1iv, "glVertexAttribI1iv"); + set_proc_address(&glVertexAttribI2iv, "glVertexAttribI2iv"); + set_proc_address(&glVertexAttribI3iv, "glVertexAttribI3iv"); + set_proc_address(&glVertexAttribI4iv, "glVertexAttribI4iv"); + set_proc_address(&glVertexAttribI1uiv, "glVertexAttribI1uiv"); + set_proc_address(&glVertexAttribI2uiv, "glVertexAttribI2uiv"); + set_proc_address(&glVertexAttribI3uiv, "glVertexAttribI3uiv"); + set_proc_address(&glVertexAttribI4uiv, "glVertexAttribI4uiv"); + set_proc_address(&glVertexAttribI4bv, "glVertexAttribI4bv"); + set_proc_address(&glVertexAttribI4sv, "glVertexAttribI4sv"); + set_proc_address(&glVertexAttribI4ubv, "glVertexAttribI4ubv"); + set_proc_address(&glVertexAttribI4usv, "glVertexAttribI4usv"); + set_proc_address(&glGetUniformuiv, "glGetUniformuiv"); + set_proc_address(&glBindFragDataLocation, "glBindFragDataLocation"); + set_proc_address(&glGetFragDataLocation, "glGetFragDataLocation"); + set_proc_address(&glUniform1ui, "glUniform1ui"); + set_proc_address(&glUniform2ui, "glUniform2ui"); + set_proc_address(&glUniform3ui, "glUniform3ui"); + set_proc_address(&glUniform4ui, "glUniform4ui"); + set_proc_address(&glUniform1uiv, "glUniform1uiv"); + set_proc_address(&glUniform2uiv, "glUniform2uiv"); + set_proc_address(&glUniform3uiv, "glUniform3uiv"); + set_proc_address(&glUniform4uiv, "glUniform4uiv"); + set_proc_address(&glTexParameterIiv, "glTexParameterIiv"); + set_proc_address(&glTexParameterIuiv, "glTexParameterIuiv"); + set_proc_address(&glGetTexParameterIiv, "glGetTexParameterIiv"); + set_proc_address(&glGetTexParameterIuiv, "glGetTexParameterIuiv"); + set_proc_address(&glClearBufferiv, "glClearBufferiv"); + set_proc_address(&glClearBufferuiv, "glClearBufferuiv"); + set_proc_address(&glClearBufferfv, "glClearBufferfv"); + set_proc_address(&glClearBufferfi, "glClearBufferfi"); + set_proc_address(&glGetStringi, "glGetStringi"); + set_proc_address(&glIsRenderbuffer, "glIsRenderbuffer"); + set_proc_address(&glBindRenderbuffer, "glBindRenderbuffer"); + set_proc_address(&glDeleteRenderbuffers, "glDeleteRenderbuffers"); + set_proc_address(&glGenRenderbuffers, "glGenRenderbuffers"); + set_proc_address(&glRenderbufferStorage, "glRenderbufferStorage"); + set_proc_address(&glGetRenderbufferParameteriv, "glGetRenderbufferParameteriv"); + set_proc_address(&glIsFramebuffer, "glIsFramebuffer"); + set_proc_address(&glBindFramebuffer, "glBindFramebuffer"); + set_proc_address(&glDeleteFramebuffers, "glDeleteFramebuffers"); + set_proc_address(&glGenFramebuffers, "glGenFramebuffers"); + set_proc_address(&glCheckFramebufferStatus, "glCheckFramebufferStatus"); + set_proc_address(&glFramebufferTexture1D, "glFramebufferTexture1D"); + set_proc_address(&glFramebufferTexture2D, "glFramebufferTexture2D"); + set_proc_address(&glFramebufferTexture3D, "glFramebufferTexture3D"); + set_proc_address(&glFramebufferRenderbuffer, "glFramebufferRenderbuffer"); + set_proc_address(&glGetFramebufferAttachmentParameteriv, "glGetFramebufferAttachmentParameteriv"); + set_proc_address(&glGenerateMipmap, "glGenerateMipmap"); + set_proc_address(&glBlitFramebuffer, "glBlitFramebuffer"); + set_proc_address(&glRenderbufferStorageMultisample, "glRenderbufferStorageMultisample"); + set_proc_address(&glFramebufferTextureLayer, "glFramebufferTextureLayer"); + set_proc_address(&glMapBufferRange, "glMapBufferRange"); + set_proc_address(&glFlushMappedBufferRange, "glFlushMappedBufferRange"); + set_proc_address(&glBindVertexArray, "glBindVertexArray"); + set_proc_address(&glDeleteVertexArrays, "glDeleteVertexArrays"); + set_proc_address(&glGenVertexArrays, "glGenVertexArrays"); + set_proc_address(&glIsVertexArray, "glIsVertexArray"); +} + + +// VERSION_3_1 +glDrawArraysInstanced: proc(mode: u32, first: i32, count: i32, instancecount: i32); +glDrawElementsInstanced: proc(mode: u32, count: i32, type: u32, indices: *void, instancecount: i32); +glTexBuffer: proc(target: u32, internalformat: u32, buffer: u32); +glPrimitiveRestartIndex: proc(index: u32); +glCopyBufferSubData: proc(readTarget: u32, writeTarget: u32, readOffset: int, writeOffset: int, size: int); +glGetUniformIndices: proc(program: u32, uniformCount: i32, uniformNames: **char, uniformIndices: *u32); +glGetActiveUniformsiv: proc(program: u32, uniformCount: i32, uniformIndices: *u32, pname: u32, params: *i32); +glGetActiveUniformName: proc(program: u32, uniformIndex: u32, bufSize: i32, length: *i32, uniformName: *u8); +glGetUniformBlockIndex: proc(program: u32, uniformBlockName: *char): u32; +glGetActiveUniformBlockiv: proc(program: u32, uniformBlockIndex: u32, pname: u32, params: *i32); +glGetActiveUniformBlockName: proc(program: u32, uniformBlockIndex: u32, bufSize: i32, length: *i32, uniformBlockName: *u8); +glUniformBlockBinding: proc(program: u32, uniformBlockIndex: u32, uniformBlockBinding: u32); + +load_3_1 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glDrawArraysInstanced, "glDrawArraysInstanced"); + set_proc_address(&glDrawElementsInstanced, "glDrawElementsInstanced"); + set_proc_address(&glTexBuffer, "glTexBuffer"); + set_proc_address(&glPrimitiveRestartIndex, "glPrimitiveRestartIndex"); + set_proc_address(&glCopyBufferSubData, "glCopyBufferSubData"); + set_proc_address(&glGetUniformIndices, "glGetUniformIndices"); + set_proc_address(&glGetActiveUniformsiv, "glGetActiveUniformsiv"); + set_proc_address(&glGetActiveUniformName, "glGetActiveUniformName"); + set_proc_address(&glGetUniformBlockIndex, "glGetUniformBlockIndex"); + set_proc_address(&glGetActiveUniformBlockiv, "glGetActiveUniformBlockiv"); + set_proc_address(&glGetActiveUniformBlockName, "glGetActiveUniformBlockName"); + set_proc_address(&glUniformBlockBinding, "glUniformBlockBinding"); +} + + +// VERSION_3_2 +glDrawElementsBaseVertex: proc(mode: u32, count: i32, type: u32, indices: *void, basevertex: i32); +glDrawRangeElementsBaseVertex: proc(mode: u32, start: u32, end: u32, count: i32, type: u32, indices: *void, basevertex: i32); +glDrawElementsInstancedBaseVertex: proc(mode: u32, count: i32, type: u32, indices: *void, instancecount: i32, basevertex: i32); +glMultiDrawElementsBaseVertex: proc(mode: u32, count: *i32, type: u32, indices: **void, drawcount: i32, basevertex: *i32); +glProvokingVertex: proc(mode: u32); +glFenceSync: proc(condition: u32, flags: u32): sync_t; +glIsSync: proc(sync: sync_t): bool; +glDeleteSync: proc(sync: sync_t); +glClientWaitSync: proc(sync: sync_t, flags: u32, timeout: u64): u32; +glWaitSync: proc(sync: sync_t, flags: u32, timeout: u64); +glGetInteger64v: proc(pname: u32, data: *i64); +glGetSynciv: proc(sync: sync_t, pname: u32, bufSize: i32, length: *i32, values: *i32); +glGetInteger64i_v: proc(target: u32, index: u32, data: *i64); +glGetBufferParameteri64v: proc(target: u32, pname: u32, params: *i64); +glFramebufferTexture: proc(target: u32, attachment: u32, texture: u32, level: i32); +glTexImage2DMultisample: proc(target: u32, samples: i32, internalformat: u32, width: i32, height: i32, fixedsamplelocations: bool); +glTexImage3DMultisample: proc(target: u32, samples: i32, internalformat: u32, width: i32, height: i32, depth: i32, fixedsamplelocations: bool); +glGetMultisamplefv: proc(pname: u32, index: u32, val: *f32); +glSampleMaski: proc(maskNumber: u32, mask: u32); + +load_3_2 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glDrawElementsBaseVertex, "glDrawElementsBaseVertex"); + set_proc_address(&glDrawRangeElementsBaseVertex, "glDrawRangeElementsBaseVertex"); + set_proc_address(&glDrawElementsInstancedBaseVertex, "glDrawElementsInstancedBaseVertex"); + set_proc_address(&glMultiDrawElementsBaseVertex, "glMultiDrawElementsBaseVertex"); + set_proc_address(&glProvokingVertex, "glProvokingVertex"); + set_proc_address(&glFenceSync, "glFenceSync"); + set_proc_address(&glIsSync, "glIsSync"); + set_proc_address(&glDeleteSync, "glDeleteSync"); + set_proc_address(&glClientWaitSync, "glClientWaitSync"); + set_proc_address(&glWaitSync, "glWaitSync"); + set_proc_address(&glGetInteger64v, "glGetInteger64v"); + set_proc_address(&glGetSynciv, "glGetSynciv"); + set_proc_address(&glGetInteger64i_v, "glGetInteger64i_v"); + set_proc_address(&glGetBufferParameteri64v, "glGetBufferParameteri64v"); + set_proc_address(&glFramebufferTexture, "glFramebufferTexture"); + set_proc_address(&glTexImage2DMultisample, "glTexImage2DMultisample"); + set_proc_address(&glTexImage3DMultisample, "glTexImage3DMultisample"); + set_proc_address(&glGetMultisamplefv, "glGetMultisamplefv"); + set_proc_address(&glSampleMaski, "glSampleMaski"); +} + + +// VERSION_3_3 +glBindFragDataLocationIndexed: proc(program: u32, colorNumber: u32, index: u32, name: *char); +glGetFragDataIndex: proc(program: u32, name: *char): i32; +glGenSamplers: proc(count: i32, samplers: *u32); +glDeleteSamplers: proc(count: i32, samplers: *u32); +glIsSampler: proc(sampler: u32): bool; +glBindSampler: proc(unit: u32, sampler: u32); +glSamplerParameteri: proc(sampler: u32, pname: u32, param: i32); +glSamplerParameteriv: proc(sampler: u32, pname: u32, param: *i32); +glSamplerParameterf: proc(sampler: u32, pname: u32, param: f32); +glSamplerParameterfv: proc(sampler: u32, pname: u32, param: *f32); +glSamplerParameterIiv: proc(sampler: u32, pname: u32, param: *i32); +glSamplerParameterIuiv: proc(sampler: u32, pname: u32, param: *u32); +glGetSamplerParameteriv: proc(sampler: u32, pname: u32, params: *i32); +glGetSamplerParameterIiv: proc(sampler: u32, pname: u32, params: *i32); +glGetSamplerParameterfv: proc(sampler: u32, pname: u32, params: *f32); +glGetSamplerParameterIuiv: proc(sampler: u32, pname: u32, params: *u32); +glQueryCounter: proc(id: u32, target: u32); +glGetQueryObjecti64v: proc(id: u32, pname: u32, params: *i64); +glGetQueryObjectui64v: proc(id: u32, pname: u32, params: *u64); +glVertexAttribDivisor: proc(index: u32, divisor: u32); +glVertexAttribP1ui: proc(index: u32, type: u32, normalized: bool, value: u32); +glVertexAttribP1uiv: proc(index: u32, type: u32, normalized: bool, value: *u32); +glVertexAttribP2ui: proc(index: u32, type: u32, normalized: bool, value: u32); +glVertexAttribP2uiv: proc(index: u32, type: u32, normalized: bool, value: *u32); +glVertexAttribP3ui: proc(index: u32, type: u32, normalized: bool, value: u32); +glVertexAttribP3uiv: proc(index: u32, type: u32, normalized: bool, value: *u32); +glVertexAttribP4ui: proc(index: u32, type: u32, normalized: bool, value: u32); +glVertexAttribP4uiv: proc(index: u32, type: u32, normalized: bool, value: *u32); +glVertexP2ui: proc(type: u32, value: u32); +glVertexP2uiv: proc(type: u32, value: *u32); +glVertexP3ui: proc(type: u32, value: u32); +glVertexP3uiv: proc(type: u32, value: *u32); +glVertexP4ui: proc(type: u32, value: u32); +glVertexP4uiv: proc(type: u32, value: *u32); +glTexCoordP1ui: proc(type: u32, coords: u32); +glTexCoordP1uiv: proc(type: u32, coords: *u32); +glTexCoordP2ui: proc(type: u32, coords: u32); +glTexCoordP2uiv: proc(type: u32, coords: *u32); +glTexCoordP3ui: proc(type: u32, coords: u32); +glTexCoordP3uiv: proc(type: u32, coords: *u32); +glTexCoordP4ui: proc(type: u32, coords: u32); +glTexCoordP4uiv: proc(type: u32, coords: *u32); +glMultiTexCoordP1ui: proc(texture: u32, type: u32, coords: u32); +glMultiTexCoordP1uiv: proc(texture: u32, type: u32, coords: *u32); +glMultiTexCoordP2ui: proc(texture: u32, type: u32, coords: u32); +glMultiTexCoordP2uiv: proc(texture: u32, type: u32, coords: *u32); +glMultiTexCoordP3ui: proc(texture: u32, type: u32, coords: u32); +glMultiTexCoordP3uiv: proc(texture: u32, type: u32, coords: *u32); +glMultiTexCoordP4ui: proc(texture: u32, type: u32, coords: u32); +glMultiTexCoordP4uiv: proc(texture: u32, type: u32, coords: *u32); +glNormalP3ui: proc(type: u32, coords: u32); +glNormalP3uiv: proc(type: u32, coords: *u32); +glColorP3ui: proc(type: u32, color: u32); +glColorP3uiv: proc(type: u32, color: *u32); +glColorP4ui: proc(type: u32, color: u32); +glColorP4uiv: proc(type: u32, color: *u32); +glSecondaryColorP3ui: proc(type: u32, color: u32); +glSecondaryColorP3uiv: proc(type: u32, color: *u32); + +load_3_3 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glBindFragDataLocationIndexed, "glBindFragDataLocationIndexed"); + set_proc_address(&glGetFragDataIndex, "glGetFragDataIndex"); + set_proc_address(&glGenSamplers, "glGenSamplers"); + set_proc_address(&glDeleteSamplers, "glDeleteSamplers"); + set_proc_address(&glIsSampler, "glIsSampler"); + set_proc_address(&glBindSampler, "glBindSampler"); + set_proc_address(&glSamplerParameteri, "glSamplerParameteri"); + set_proc_address(&glSamplerParameteriv, "glSamplerParameteriv"); + set_proc_address(&glSamplerParameterf, "glSamplerParameterf"); + set_proc_address(&glSamplerParameterfv, "glSamplerParameterfv"); + set_proc_address(&glSamplerParameterIiv, "glSamplerParameterIiv"); + set_proc_address(&glSamplerParameterIuiv, "glSamplerParameterIuiv"); + set_proc_address(&glGetSamplerParameteriv, "glGetSamplerParameteriv"); + set_proc_address(&glGetSamplerParameterIiv, "glGetSamplerParameterIiv"); + set_proc_address(&glGetSamplerParameterfv, "glGetSamplerParameterfv"); + set_proc_address(&glGetSamplerParameterIuiv, "glGetSamplerParameterIuiv"); + set_proc_address(&glQueryCounter, "glQueryCounter"); + set_proc_address(&glGetQueryObjecti64v, "glGetQueryObjecti64v"); + set_proc_address(&glGetQueryObjectui64v, "glGetQueryObjectui64v"); + set_proc_address(&glVertexAttribDivisor, "glVertexAttribDivisor"); + set_proc_address(&glVertexAttribP1ui, "glVertexAttribP1ui"); + set_proc_address(&glVertexAttribP1uiv, "glVertexAttribP1uiv"); + set_proc_address(&glVertexAttribP2ui, "glVertexAttribP2ui"); + set_proc_address(&glVertexAttribP2uiv, "glVertexAttribP2uiv"); + set_proc_address(&glVertexAttribP3ui, "glVertexAttribP3ui"); + set_proc_address(&glVertexAttribP3uiv, "glVertexAttribP3uiv"); + set_proc_address(&glVertexAttribP4ui, "glVertexAttribP4ui"); + set_proc_address(&glVertexAttribP4uiv, "glVertexAttribP4uiv"); + set_proc_address(&glVertexP2ui, "glVertexP2ui"); + set_proc_address(&glVertexP2uiv, "glVertexP2uiv"); + set_proc_address(&glVertexP3ui, "glVertexP3ui"); + set_proc_address(&glVertexP3uiv, "glVertexP3uiv"); + set_proc_address(&glVertexP4ui, "glVertexP4ui"); + set_proc_address(&glVertexP4uiv, "glVertexP4uiv"); + set_proc_address(&glTexCoordP1ui, "glTexCoordP1ui"); + set_proc_address(&glTexCoordP1uiv, "glTexCoordP1uiv"); + set_proc_address(&glTexCoordP2ui, "glTexCoordP2ui"); + set_proc_address(&glTexCoordP2uiv, "glTexCoordP2uiv"); + set_proc_address(&glTexCoordP3ui, "glTexCoordP3ui"); + set_proc_address(&glTexCoordP3uiv, "glTexCoordP3uiv"); + set_proc_address(&glTexCoordP4ui, "glTexCoordP4ui"); + set_proc_address(&glTexCoordP4uiv, "glTexCoordP4uiv"); + set_proc_address(&glMultiTexCoordP1ui, "glMultiTexCoordP1ui"); + set_proc_address(&glMultiTexCoordP1uiv, "glMultiTexCoordP1uiv"); + set_proc_address(&glMultiTexCoordP2ui, "glMultiTexCoordP2ui"); + set_proc_address(&glMultiTexCoordP2uiv, "glMultiTexCoordP2uiv"); + set_proc_address(&glMultiTexCoordP3ui, "glMultiTexCoordP3ui"); + set_proc_address(&glMultiTexCoordP3uiv, "glMultiTexCoordP3uiv"); + set_proc_address(&glMultiTexCoordP4ui, "glMultiTexCoordP4ui"); + set_proc_address(&glMultiTexCoordP4uiv, "glMultiTexCoordP4uiv"); + set_proc_address(&glNormalP3ui, "glNormalP3ui"); + set_proc_address(&glNormalP3uiv, "glNormalP3uiv"); + set_proc_address(&glColorP3ui, "glColorP3ui"); + set_proc_address(&glColorP3uiv, "glColorP3uiv"); + set_proc_address(&glColorP4ui, "glColorP4ui"); + set_proc_address(&glColorP4uiv, "glColorP4uiv"); + set_proc_address(&glSecondaryColorP3ui, "glSecondaryColorP3ui"); + set_proc_address(&glSecondaryColorP3uiv, "glSecondaryColorP3uiv"); +} + + +// VERSION_4_0 +DrawArraysIndirectCommand :: struct { + count: u32; + instanceCount: u32; + first: u32; + baseInstance: u32; +} + +DrawElementsIndirectCommand :: struct { + count: u32; + instanceCount: u32; + firstIndex: u32; + baseVertex: u32; + baseInstance: u32; +} + +glMinSampleShading: proc(value: f32); +glBlendEquationi: proc(buf: u32, mode: u32); +glBlendEquationSeparatei: proc(buf: u32, modeRGB: u32, modeAlpha: u32); +glBlendFunci: proc(buf: u32, src: u32, dst: u32); +glBlendFuncSeparatei: proc(buf: u32, srcRGB: u32, dstRGB: u32, srcAlpha: u32, dstAlpha: u32); +glDrawArraysIndirect: proc(mode: u32, indirect: *DrawArraysIndirectCommand); +glDrawElementsIndirect: proc(mode: u32, type: u32, indirect: *DrawElementsIndirectCommand); +glUniform1d: proc(location: i32, x: f64); +glUniform2d: proc(location: i32, x: f64, y: f64); +glUniform3d: proc(location: i32, x: f64, y: f64, z: f64); +glUniform4d: proc(location: i32, x: f64, y: f64, z: f64, w: f64); +glUniform1dv: proc(location: i32, count: i32, value: *f64); +glUniform2dv: proc(location: i32, count: i32, value: *f64); +glUniform3dv: proc(location: i32, count: i32, value: *f64); +glUniform4dv: proc(location: i32, count: i32, value: *f64); +glUniformMatrix2dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix3dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix4dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix2x3dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix2x4dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix3x2dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix3x4dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix4x2dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix4x3dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glGetUniformdv: proc(program: u32, location: i32, params: *f64); +glGetSubroutineUniformLocation: proc(program: u32, shadertype: u32, name: *char): i32; +glGetSubroutineIndex: proc(program: u32, shadertype: u32, name: *char): u32; +glGetActiveSubroutineUniformiv: proc(program: u32, shadertype: u32, index: u32, pname: u32, values: *i32); +glGetActiveSubroutineUniformName: proc(program: u32, shadertype: u32, index: u32, bufsize: i32, length: *i32, name: *u8); +glGetActiveSubroutineName: proc(program: u32, shadertype: u32, index: u32, bufsize: i32, length: *i32, name: *u8); +glUniformSubroutinesuiv: proc(shadertype: u32, count: i32, indices: *u32); +glGetUniformSubroutineuiv: proc(shadertype: u32, location: i32, params: *u32); +glGetProgramStageiv: proc(program: u32, shadertype: u32, pname: u32, values: *i32); +glPatchParameteri: proc(pname: u32, value: i32); +glPatchParameterfv: proc(pname: u32, values: *f32); +glBindTransformFeedback: proc(target: u32, id: u32); +glDeleteTransformFeedbacks: proc(n: i32, ids: *u32); +glGenTransformFeedbacks: proc(n: i32, ids: *u32); +glIsTransformFeedback: proc(id: u32): bool; +glPauseTransformFeedback: proc(); +glResumeTransformFeedback: proc(); +glDrawTransformFeedback: proc(mode: u32, id: u32); +glDrawTransformFeedbackStream: proc(mode: u32, id: u32, stream: u32); +glBeginQueryIndexed: proc(target: u32, index: u32, id: u32); +glEndQueryIndexed: proc(target: u32, index: u32); +glGetQueryIndexediv: proc(target: u32, index: u32, pname: u32, params: *i32); +glGetTextureHandleARB: proc(texture: u32): u64; +glGetTextureSamplerHandleARB: proc(texture: u32, sampler: u32): u64; +glGetImageHandleARB: proc(texture: u32, level: i32, layered: bool, layer: i32, format: u32): u64; +glMakeTextureHandleResidentARB: proc(handle: u64); +glMakeImageHandleResidentARB: proc(handle: u64, access: u32); +glMakeTextureHandleNonResidentARB:proc(handle: u64); +glMakeImageHandleNonResidentARB: proc(handle: u64); + +load_4_0 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glMinSampleShading, "glMinSampleShading"); + set_proc_address(&glBlendEquationi, "glBlendEquationi"); + set_proc_address(&glBlendEquationSeparatei, "glBlendEquationSeparatei"); + set_proc_address(&glBlendFunci, "glBlendFunci"); + set_proc_address(&glBlendFuncSeparatei, "glBlendFuncSeparatei"); + set_proc_address(&glDrawArraysIndirect, "glDrawArraysIndirect"); + set_proc_address(&glDrawElementsIndirect, "glDrawElementsIndirect"); + set_proc_address(&glUniform1d, "glUniform1d"); + set_proc_address(&glUniform2d, "glUniform2d"); + set_proc_address(&glUniform3d, "glUniform3d"); + set_proc_address(&glUniform4d, "glUniform4d"); + set_proc_address(&glUniform1dv, "glUniform1dv"); + set_proc_address(&glUniform2dv, "glUniform2dv"); + set_proc_address(&glUniform3dv, "glUniform3dv"); + set_proc_address(&glUniform4dv, "glUniform4dv"); + set_proc_address(&glUniformMatrix2dv, "glUniformMatrix2dv"); + set_proc_address(&glUniformMatrix3dv, "glUniformMatrix3dv"); + set_proc_address(&glUniformMatrix4dv, "glUniformMatrix4dv"); + set_proc_address(&glUniformMatrix2x3dv, "glUniformMatrix2x3dv"); + set_proc_address(&glUniformMatrix2x4dv, "glUniformMatrix2x4dv"); + set_proc_address(&glUniformMatrix3x2dv, "glUniformMatrix3x2dv"); + set_proc_address(&glUniformMatrix3x4dv, "glUniformMatrix3x4dv"); + set_proc_address(&glUniformMatrix4x2dv, "glUniformMatrix4x2dv"); + set_proc_address(&glUniformMatrix4x3dv, "glUniformMatrix4x3dv"); + set_proc_address(&glGetUniformdv, "glGetUniformdv"); + set_proc_address(&glGetSubroutineUniformLocation, "glGetSubroutineUniformLocation"); + set_proc_address(&glGetSubroutineIndex, "glGetSubroutineIndex"); + set_proc_address(&glGetActiveSubroutineUniformiv, "glGetActiveSubroutineUniformiv"); + set_proc_address(&glGetActiveSubroutineUniformName, "glGetActiveSubroutineUniformName"); + set_proc_address(&glGetActiveSubroutineName, "glGetActiveSubroutineName"); + set_proc_address(&glUniformSubroutinesuiv, "glUniformSubroutinesuiv"); + set_proc_address(&glGetUniformSubroutineuiv, "glGetUniformSubroutineuiv"); + set_proc_address(&glGetProgramStageiv, "glGetProgramStageiv"); + set_proc_address(&glPatchParameteri, "glPatchParameteri"); + set_proc_address(&glPatchParameterfv, "glPatchParameterfv"); + set_proc_address(&glBindTransformFeedback, "glBindTransformFeedback"); + set_proc_address(&glDeleteTransformFeedbacks, "glDeleteTransformFeedbacks"); + set_proc_address(&glGenTransformFeedbacks, "glGenTransformFeedbacks"); + set_proc_address(&glIsTransformFeedback, "glIsTransformFeedback"); + set_proc_address(&glPauseTransformFeedback, "glPauseTransformFeedback"); + set_proc_address(&glResumeTransformFeedback, "glResumeTransformFeedback"); + set_proc_address(&glDrawTransformFeedback, "glDrawTransformFeedback"); + set_proc_address(&glDrawTransformFeedbackStream, "glDrawTransformFeedbackStream"); + set_proc_address(&glBeginQueryIndexed, "glBeginQueryIndexed"); + set_proc_address(&glEndQueryIndexed, "glEndQueryIndexed"); + set_proc_address(&glGetQueryIndexediv, "glGetQueryIndexediv"); + + // Load ARB (architecture review board, vendor specific) extensions that might be available + set_proc_address(&glGetTextureHandleARB, "glGetTextureHandleARB"); + if !glGetTextureHandleARB { + set_proc_address(&glGetTextureHandleARB, "glGetTextureHandleNV"); + } + + set_proc_address(&glGetTextureSamplerHandleARB, "glGetTextureSamplerHandleARB"); + if !glGetTextureSamplerHandleARB { + set_proc_address(&glGetTextureSamplerHandleARB, "glGetTextureSamplerHandleNV"); + } + + set_proc_address(&glGetImageHandleARB, "glGetImageHandleARB"); + if !glGetImageHandleARB { + set_proc_address(&glGetImageHandleARB, "glGetImageHandleNV"); + } + + set_proc_address(&glMakeTextureHandleResidentARB, "glMakeTextureHandleResidentARB"); + if !glMakeTextureHandleResidentARB { + set_proc_address(&glMakeTextureHandleResidentARB, "glMakeTextureHandleResidentNV"); + } + + set_proc_address(&glMakeImageHandleResidentARB, "glMakeImageHandleResidentARB"); + if !glMakeImageHandleResidentARB { + set_proc_address(&glMakeImageHandleResidentARB, "glMakeImageHandleResidentNV"); + } + + set_proc_address(&glMakeTextureHandleNonResidentARB, "glMakeTextureHandleNonResidentARB"); + if !glMakeTextureHandleNonResidentARB { + set_proc_address(&glMakeTextureHandleNonResidentARB, "glMakeTextureHandleNonResidentNV"); + } + + set_proc_address(&glMakeImageHandleNonResidentARB, "glMakeImageHandleNonResidentARB"); + if !glMakeImageHandleNonResidentARB { + set_proc_address(&glMakeImageHandleNonResidentARB, "glMakeImageHandleNonResidentNV"); + } +} + + +// VERSION_4_1 +glReleaseShaderCompiler: proc(); +glShaderBinary: proc(count: i32, shaders: *u32, binaryformat: u32, binary: *void, length: i32); +glGetShaderPrecisionFormat: proc(shadertype: u32, precisiontype: u32, range: *i32, precision: *i32); +glDepthRangef: proc(n: f32, f: f32); +glClearDepthf: proc(d: f32); +glGetProgramBinary: proc(program: u32, bufSize: i32, length: *i32, binaryFormat: *u32, binary: *void); +glProgramBinary: proc(program: u32, binaryFormat: u32, binary: *void, length: i32); +glProgramParameteri: proc(program: u32, pname: u32, value: i32); +glUseProgramStages: proc(pipeline: u32, stages: u32, program: u32); +glActiveShaderProgram: proc(pipeline: u32, program: u32); +glCreateShaderProgramv: proc(type: u32, count: i32, strings: **char): u32; +glBindProgramPipeline: proc(pipeline: u32); +glDeleteProgramPipelines: proc(n: i32, pipelines: *u32); +glGenProgramPipelines: proc(n: i32, pipelines: *u32); +glIsProgramPipeline: proc(pipeline: u32): bool; +glGetProgramPipelineiv: proc(pipeline: u32, pname: u32, params: *i32); +glProgramUniform1i: proc(program: u32, location: i32, v0: i32); +glProgramUniform1iv: proc(program: u32, location: i32, count: i32, value: *i32); +glProgramUniform1f: proc(program: u32, location: i32, v0: f32); +glProgramUniform1fv: proc(program: u32, location: i32, count: i32, value: *f32); +glProgramUniform1d: proc(program: u32, location: i32, v0: f64); +glProgramUniform1dv: proc(program: u32, location: i32, count: i32, value: *f64); +glProgramUniform1ui: proc(program: u32, location: i32, v0: u32); +glProgramUniform1uiv: proc(program: u32, location: i32, count: i32, value: *u32); +glProgramUniform2i: proc(program: u32, location: i32, v0: i32, v1: i32); +glProgramUniform2iv: proc(program: u32, location: i32, count: i32, value: *i32); +glProgramUniform2f: proc(program: u32, location: i32, v0: f32, v1: f32); +glProgramUniform2fv: proc(program: u32, location: i32, count: i32, value: *f32); +glProgramUniform2d: proc(program: u32, location: i32, v0: f64, v1: f64); +glProgramUniform2dv: proc(program: u32, location: i32, count: i32, value: *f64); +glProgramUniform2ui: proc(program: u32, location: i32, v0: u32, v1: u32); +glProgramUniform2uiv: proc(program: u32, location: i32, count: i32, value: *u32); +glProgramUniform3i: proc(program: u32, location: i32, v0: i32, v1: i32, v2: i32); +glProgramUniform3iv: proc(program: u32, location: i32, count: i32, value: *i32); +glProgramUniform3f: proc(program: u32, location: i32, v0: f32, v1: f32, v2: f32); +glProgramUniform3fv: proc(program: u32, location: i32, count: i32, value: *f32); +glProgramUniform3d: proc(program: u32, location: i32, v0: f64, v1: f64, v2: f64); +glProgramUniform3dv: proc(program: u32, location: i32, count: i32, value: *f64); +glProgramUniform3ui: proc(program: u32, location: i32, v0: u32, v1: u32, v2: u32); +glProgramUniform3uiv: proc(program: u32, location: i32, count: i32, value: *u32); +glProgramUniform4i: proc(program: u32, location: i32, v0: i32, v1: i32, v2: i32, v3: i32); +glProgramUniform4iv: proc(program: u32, location: i32, count: i32, value: *i32); +glProgramUniform4f: proc(program: u32, location: i32, v0: f32, v1: f32, v2: f32, v3: f32); +glProgramUniform4fv: proc(program: u32, location: i32, count: i32, value: *f32); +glProgramUniform4d: proc(program: u32, location: i32, v0: f64, v1: f64, v2: f64, v3: f64); +glProgramUniform4dv: proc(program: u32, location: i32, count: i32, value: *f64); +glProgramUniform4ui: proc(program: u32, location: i32, v0: u32, v1: u32, v2: u32, v3: u32); +glProgramUniform4uiv: proc(program: u32, location: i32, count: i32, value: *u32); +glProgramUniformMatrix2fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix3fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix4fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix2dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix3dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix4dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix2x3fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix3x2fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix2x4fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix4x2fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix3x4fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix4x3fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix2x3dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix3x2dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix2x4dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix4x2dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix3x4dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix4x3dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glValidateProgramPipeline: proc(pipeline: u32); +glGetProgramPipelineInfoLog: proc(pipeline: u32, bufSize: i32, length: *i32, infoLog: *u8); +glVertexAttribL1d: proc(index: u32, x: f64); +glVertexAttribL2d: proc(index: u32, x: f64, y: f64); +glVertexAttribL3d: proc(index: u32, x: f64, y: f64, z: f64); +glVertexAttribL4d: proc(index: u32, x: f64, y: f64, z: f64, w: f64); +glVertexAttribL1dv: proc(index: u32, v: *f64); +glVertexAttribL2dv: proc(index: u32, v: *[2]f64); +glVertexAttribL3dv: proc(index: u32, v: *[3]f64); +glVertexAttribL4dv: proc(index: u32, v: *[4]f64); +glVertexAttribLPointer: proc(index: u32, size: i32, type: u32, stride: i32, pointer: uintptr); +glGetVertexAttribLdv: proc(index: u32, pname: u32, params: *f64); +glViewportArrayv: proc(first: u32, count: i32, v: *f32); +glViewportIndexedf: proc(index: u32, x: f32, y: f32, w: f32, h: f32); +glViewportIndexedfv: proc(index: u32, v: *[4]f32); +glScissorArrayv: proc(first: u32, count: i32, v: *i32); +glScissorIndexed: proc(index: u32, left: i32, bottom: i32, width: i32, height: i32); +glScissorIndexedv: proc(index: u32, v: *[4]i32); +glDepthRangeArrayv: proc(first: u32, count: i32, v: *f64); +glDepthRangeIndexed: proc(index: u32, n: f64, f: f64); +glGetFloati_v: proc(target: u32, index: u32, data: *f32); +glGetDoublei_v: proc(target: u32, index: u32, data: *f64); + +load_4_1 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glReleaseShaderCompiler, "glReleaseShaderCompiler"); + set_proc_address(&glShaderBinary, "glShaderBinary"); + set_proc_address(&glGetShaderPrecisionFormat, "glGetShaderPrecisionFormat"); + set_proc_address(&glDepthRangef, "glDepthRangef"); + set_proc_address(&glClearDepthf, "glClearDepthf"); + set_proc_address(&glGetProgramBinary, "glGetProgramBinary"); + set_proc_address(&glProgramBinary, "glProgramBinary"); + set_proc_address(&glProgramParameteri, "glProgramParameteri"); + set_proc_address(&glUseProgramStages, "glUseProgramStages"); + set_proc_address(&glActiveShaderProgram, "glActiveShaderProgram"); + set_proc_address(&glCreateShaderProgramv, "glCreateShaderProgramv"); + set_proc_address(&glBindProgramPipeline, "glBindProgramPipeline"); + set_proc_address(&glDeleteProgramPipelines, "glDeleteProgramPipelines"); + set_proc_address(&glGenProgramPipelines, "glGenProgramPipelines"); + set_proc_address(&glIsProgramPipeline, "glIsProgramPipeline"); + set_proc_address(&glGetProgramPipelineiv, "glGetProgramPipelineiv"); + set_proc_address(&glProgramUniform1i, "glProgramUniform1i"); + set_proc_address(&glProgramUniform1iv, "glProgramUniform1iv"); + set_proc_address(&glProgramUniform1f, "glProgramUniform1f"); + set_proc_address(&glProgramUniform1fv, "glProgramUniform1fv"); + set_proc_address(&glProgramUniform1d, "glProgramUniform1d"); + set_proc_address(&glProgramUniform1dv, "glProgramUniform1dv"); + set_proc_address(&glProgramUniform1ui, "glProgramUniform1ui"); + set_proc_address(&glProgramUniform1uiv, "glProgramUniform1uiv"); + set_proc_address(&glProgramUniform2i, "glProgramUniform2i"); + set_proc_address(&glProgramUniform2iv, "glProgramUniform2iv"); + set_proc_address(&glProgramUniform2f, "glProgramUniform2f"); + set_proc_address(&glProgramUniform2fv, "glProgramUniform2fv"); + set_proc_address(&glProgramUniform2d, "glProgramUniform2d"); + set_proc_address(&glProgramUniform2dv, "glProgramUniform2dv"); + set_proc_address(&glProgramUniform2ui, "glProgramUniform2ui"); + set_proc_address(&glProgramUniform2uiv, "glProgramUniform2uiv"); + set_proc_address(&glProgramUniform3i, "glProgramUniform3i"); + set_proc_address(&glProgramUniform3iv, "glProgramUniform3iv"); + set_proc_address(&glProgramUniform3f, "glProgramUniform3f"); + set_proc_address(&glProgramUniform3fv, "glProgramUniform3fv"); + set_proc_address(&glProgramUniform3d, "glProgramUniform3d"); + set_proc_address(&glProgramUniform3dv, "glProgramUniform3dv"); + set_proc_address(&glProgramUniform3ui, "glProgramUniform3ui"); + set_proc_address(&glProgramUniform3uiv, "glProgramUniform3uiv"); + set_proc_address(&glProgramUniform4i, "glProgramUniform4i"); + set_proc_address(&glProgramUniform4iv, "glProgramUniform4iv"); + set_proc_address(&glProgramUniform4f, "glProgramUniform4f"); + set_proc_address(&glProgramUniform4fv, "glProgramUniform4fv"); + set_proc_address(&glProgramUniform4d, "glProgramUniform4d"); + set_proc_address(&glProgramUniform4dv, "glProgramUniform4dv"); + set_proc_address(&glProgramUniform4ui, "glProgramUniform4ui"); + set_proc_address(&glProgramUniform4uiv, "glProgramUniform4uiv"); + set_proc_address(&glProgramUniformMatrix2fv, "glProgramUniformMatrix2fv"); + set_proc_address(&glProgramUniformMatrix3fv, "glProgramUniformMatrix3fv"); + set_proc_address(&glProgramUniformMatrix4fv, "glProgramUniformMatrix4fv"); + set_proc_address(&glProgramUniformMatrix2dv, "glProgramUniformMatrix2dv"); + set_proc_address(&glProgramUniformMatrix3dv, "glProgramUniformMatrix3dv"); + set_proc_address(&glProgramUniformMatrix4dv, "glProgramUniformMatrix4dv"); + set_proc_address(&glProgramUniformMatrix2x3fv, "glProgramUniformMatrix2x3fv"); + set_proc_address(&glProgramUniformMatrix3x2fv, "glProgramUniformMatrix3x2fv"); + set_proc_address(&glProgramUniformMatrix2x4fv, "glProgramUniformMatrix2x4fv"); + set_proc_address(&glProgramUniformMatrix4x2fv, "glProgramUniformMatrix4x2fv"); + set_proc_address(&glProgramUniformMatrix3x4fv, "glProgramUniformMatrix3x4fv"); + set_proc_address(&glProgramUniformMatrix4x3fv, "glProgramUniformMatrix4x3fv"); + set_proc_address(&glProgramUniformMatrix2x3dv, "glProgramUniformMatrix2x3dv"); + set_proc_address(&glProgramUniformMatrix3x2dv, "glProgramUniformMatrix3x2dv"); + set_proc_address(&glProgramUniformMatrix2x4dv, "glProgramUniformMatrix2x4dv"); + set_proc_address(&glProgramUniformMatrix4x2dv, "glProgramUniformMatrix4x2dv"); + set_proc_address(&glProgramUniformMatrix3x4dv, "glProgramUniformMatrix3x4dv"); + set_proc_address(&glProgramUniformMatrix4x3dv, "glProgramUniformMatrix4x3dv"); + set_proc_address(&glValidateProgramPipeline, "glValidateProgramPipeline"); + set_proc_address(&glGetProgramPipelineInfoLog, "glGetProgramPipelineInfoLog"); + set_proc_address(&glVertexAttribL1d, "glVertexAttribL1d"); + set_proc_address(&glVertexAttribL2d, "glVertexAttribL2d"); + set_proc_address(&glVertexAttribL3d, "glVertexAttribL3d"); + set_proc_address(&glVertexAttribL4d, "glVertexAttribL4d"); + set_proc_address(&glVertexAttribL1dv, "glVertexAttribL1dv"); + set_proc_address(&glVertexAttribL2dv, "glVertexAttribL2dv"); + set_proc_address(&glVertexAttribL3dv, "glVertexAttribL3dv"); + set_proc_address(&glVertexAttribL4dv, "glVertexAttribL4dv"); + set_proc_address(&glVertexAttribLPointer, "glVertexAttribLPointer"); + set_proc_address(&glGetVertexAttribLdv, "glGetVertexAttribLdv"); + set_proc_address(&glViewportArrayv, "glViewportArrayv"); + set_proc_address(&glViewportIndexedf, "glViewportIndexedf"); + set_proc_address(&glViewportIndexedfv, "glViewportIndexedfv"); + set_proc_address(&glScissorArrayv, "glScissorArrayv"); + set_proc_address(&glScissorIndexed, "glScissorIndexed"); + set_proc_address(&glScissorIndexedv, "glScissorIndexedv"); + set_proc_address(&glDepthRangeArrayv, "glDepthRangeArrayv"); + set_proc_address(&glDepthRangeIndexed, "glDepthRangeIndexed"); + set_proc_address(&glGetFloati_v, "glGetFloati_v"); + set_proc_address(&glGetDoublei_v, "glGetDoublei_v"); +} + + +// VERSION_4_2 +glDrawArraysInstancedBaseInstance: proc(mode: u32, first: i32, count: i32, instancecount: i32, baseinstance: u32); +glDrawElementsInstancedBaseInstance: proc(mode: u32, count: i32, type: u32, indices: *void, instancecount: i32, baseinstance: u32); +glDrawElementsInstancedBaseVertexBaseInstance: proc(mode: u32, count: i32, type: u32, indices: *void, instancecount: i32, basevertex: i32, baseinstance: u32); +glGetInternalformativ: proc(target: u32, internalformat: u32, pname: u32, bufSize: i32, params: *i32); +glGetActiveAtomicCounterBufferiv: proc(program: u32, bufferIndex: u32, pname: u32, params: *i32); +glBindImageTexture: proc(unit: u32, texture: u32, level: i32, layered: bool, layer: i32, access: u32, format: u32); +glMemoryBarrier: proc(barriers: u32); +glTexStorage1D: proc(target: u32, levels: i32, internalformat: u32, width: i32); +glTexStorage2D: proc(target: u32, levels: i32, internalformat: u32, width: i32, height: i32); +glTexStorage3D: proc(target: u32, levels: i32, internalformat: u32, width: i32, height: i32, depth: i32); +glDrawTransformFeedbackInstanced: proc(mode: u32, id: u32, instancecount: i32); +glDrawTransformFeedbackStreamInstanced: proc(mode: u32, id: u32, stream: u32, instancecount: i32); + +load_4_2 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glDrawArraysInstancedBaseInstance, "glDrawArraysInstancedBaseInstance"); + set_proc_address(&glDrawElementsInstancedBaseInstance, "glDrawElementsInstancedBaseInstance"); + set_proc_address(&glDrawElementsInstancedBaseVertexBaseInstance, "glDrawElementsInstancedBaseVertexBaseInstance"); + set_proc_address(&glGetInternalformativ, "glGetInternalformativ"); + set_proc_address(&glGetActiveAtomicCounterBufferiv, "glGetActiveAtomicCounterBufferiv"); + set_proc_address(&glBindImageTexture, "glBindImageTexture"); + set_proc_address(&glMemoryBarrier, "glMemoryBarrier"); + set_proc_address(&glTexStorage1D, "glTexStorage1D"); + set_proc_address(&glTexStorage2D, "glTexStorage2D"); + set_proc_address(&glTexStorage3D, "glTexStorage3D"); + set_proc_address(&glDrawTransformFeedbackInstanced, "glDrawTransformFeedbackInstanced"); + set_proc_address(&glDrawTransformFeedbackStreamInstanced, "glDrawTransformFeedbackStreamInstanced"); +} + +// VERSION_4_3 +DispatchIndirectCommand :: struct { + num_groups_x: u32; + num_groups_y: u32; + num_groups_z: u32; +} + +glClearBufferData: proc(target: u32, internalformat: u32, format: u32, type: u32, data: *void); +glClearBufferSubData: proc(target: u32, internalformat: u32, offset: int, size: int, format: u32, type: u32, data: *void); +glDispatchCompute: proc(num_groups_x: u32, num_groups_y: u32, num_groups_z: u32); +glDispatchComputeIndirect: proc(indirect: *DispatchIndirectCommand); +glCopyImageSubData: proc(srcName: u32, srcTarget: u32, srcLevel: i32, srcX: i32, srcY: i32, srcZ: i32, dstName: u32, dstTarget: u32, dstLevel: i32, dstX: i32, dstY: i32, dstZ: i32, srcWidth: i32, srcHeight: i32, srcDepth: i32); +glFramebufferParameteri: proc(target: u32, pname: u32, param: i32); +glGetFramebufferParameteriv: proc(target: u32, pname: u32, params: *i32); +glGetInternalformati64v: proc(target: u32, internalformat: u32, pname: u32, bufSize: i32, params: *i64); +glInvalidateTexSubImage: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32); +glInvalidateTexImage: proc(texture: u32, level: i32); +glInvalidateBufferSubData: proc(buffer: u32, offset: int, length: int); +glInvalidateBufferData: proc(buffer: u32); +glInvalidateFramebuffer: proc(target: u32, numAttachments: i32, attachments: *u32); +glInvalidateSubFramebuffer: proc(target: u32, numAttachments: i32, attachments: *u32, x: i32, y: i32, width: i32, height: i32); +glMultiDrawArraysIndirect: proc(mode: u32, indirect: *DrawArraysIndirectCommand, drawcount: i32, stride: i32); +glMultiDrawElementsIndirect: proc(mode: u32, type: u32, indirect: *DrawElementsIndirectCommand, drawcount: i32, stride: i32); +glGetProgramInterfaceiv: proc(program: u32, programInterface: u32, pname: u32, params: *i32); +glGetProgramResourceIndex: proc(program: u32, programInterface: u32, name: *char): u32; +glGetProgramResourceName: proc(program: u32, programInterface: u32, index: u32, bufSize: i32, length: *i32, name: *u8); +glGetProgramResourceiv: proc(program: u32, programInterface: u32, index: u32, propCount: i32, props: *u32, bufSize: i32, length: *i32, params: *i32); +glGetProgramResourceLocation: proc(program: u32, programInterface: u32, name: *char): i32; +glGetProgramResourceLocationIndex: proc(program: u32, programInterface: u32, name: *char): i32; +glShaderStorageBlockBinding: proc(program: u32, storageBlockIndex: u32, storageBlockBinding: u32); +glTexBufferRange: proc(target: u32, internalformat: u32, buffer: u32, offset: int, size: int); +glTexStorage2DMultisample: proc(target: u32, samples: i32, internalformat: u32, width: i32, height: i32, fixedsamplelocations: bool); +glTexStorage3DMultisample: proc(target: u32, samples: i32, internalformat: u32, width: i32, height: i32, depth: i32, fixedsamplelocations: bool); +glTextureView: proc(texture: u32, target: u32, origtexture: u32, internalformat: u32, minlevel: u32, numlevels: u32, minlayer: u32, numlayers: u32); +glBindVertexBuffer: proc(bindingindex: u32, buffer: u32, offset: int, stride: i32); +glVertexAttribFormat: proc(attribindex: u32, size: i32, type: u32, normalized: bool, relativeoffset: u32); +glVertexAttribIFormat: proc(attribindex: u32, size: i32, type: u32, relativeoffset: u32); +glVertexAttribLFormat: proc(attribindex: u32, size: i32, type: u32, relativeoffset: u32); +glVertexAttribBinding: proc(attribindex: u32, bindingindex: u32); +glVertexBindingDivisor: proc(bindingindex: u32, divisor: u32); +glDebugMessageControl: proc(source: u32, type: u32, severity: u32, count: i32, ids: *u32, enabled: bool); +glDebugMessageInsert: proc(source: u32, type: u32, id: u32, severity: u32, length: i32, message: *char); +glDebugMessageCallback: proc(callback: debug_proc_t, userParam: *void); +glGetDebugMessageLog: proc(count: u32, bufSize: i32, sources: *u32, types: *u32, ids: *u32, severities: *u32, lengths: *i32, messageLog: *u8): u32; +glPushDebugGroup: proc(source: u32, id: u32, length: i32, message: *char); +glPopDebugGroup: proc(); +glObjectLabel: proc(identifier: u32, name: u32, length: i32, label: *char); +glGetObjectLabel: proc(identifier: u32, name: u32, bufSize: i32, length: *i32, label: *u8); +glObjectPtrLabel: proc(ptr: *void, length: i32, label: *char); +glGetObjectPtrLabel: proc(ptr: *void, bufSize: i32, length: *i32, label: *u8); + +load_4_3 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glClearBufferData, "glClearBufferData"); + set_proc_address(&glClearBufferSubData, "glClearBufferSubData"); + set_proc_address(&glDispatchCompute, "glDispatchCompute"); + set_proc_address(&glDispatchComputeIndirect, "glDispatchComputeIndirect"); + set_proc_address(&glCopyImageSubData, "glCopyImageSubData"); + set_proc_address(&glFramebufferParameteri, "glFramebufferParameteri"); + set_proc_address(&glGetFramebufferParameteriv, "glGetFramebufferParameteriv"); + set_proc_address(&glGetInternalformati64v, "glGetInternalformati64v"); + set_proc_address(&glInvalidateTexSubImage, "glInvalidateTexSubImage"); + set_proc_address(&glInvalidateTexImage, "glInvalidateTexImage"); + set_proc_address(&glInvalidateBufferSubData, "glInvalidateBufferSubData"); + set_proc_address(&glInvalidateBufferData, "glInvalidateBufferData"); + set_proc_address(&glInvalidateFramebuffer, "glInvalidateFramebuffer"); + set_proc_address(&glInvalidateSubFramebuffer, "glInvalidateSubFramebuffer"); + set_proc_address(&glMultiDrawArraysIndirect, "glMultiDrawArraysIndirect"); + set_proc_address(&glMultiDrawElementsIndirect, "glMultiDrawElementsIndirect"); + set_proc_address(&glGetProgramInterfaceiv, "glGetProgramInterfaceiv"); + set_proc_address(&glGetProgramResourceIndex, "glGetProgramResourceIndex"); + set_proc_address(&glGetProgramResourceName, "glGetProgramResourceName"); + set_proc_address(&glGetProgramResourceiv, "glGetProgramResourceiv"); + set_proc_address(&glGetProgramResourceLocation, "glGetProgramResourceLocation"); + set_proc_address(&glGetProgramResourceLocationIndex, "glGetProgramResourceLocationIndex"); + set_proc_address(&glShaderStorageBlockBinding, "glShaderStorageBlockBinding"); + set_proc_address(&glTexBufferRange, "glTexBufferRange"); + set_proc_address(&glTexStorage2DMultisample, "glTexStorage2DMultisample"); + set_proc_address(&glTexStorage3DMultisample, "glTexStorage3DMultisample"); + set_proc_address(&glTextureView, "glTextureView"); + set_proc_address(&glBindVertexBuffer, "glBindVertexBuffer"); + set_proc_address(&glVertexAttribFormat, "glVertexAttribFormat"); + set_proc_address(&glVertexAttribIFormat, "glVertexAttribIFormat"); + set_proc_address(&glVertexAttribLFormat, "glVertexAttribLFormat"); + set_proc_address(&glVertexAttribBinding, "glVertexAttribBinding"); + set_proc_address(&glVertexBindingDivisor, "glVertexBindingDivisor"); + set_proc_address(&glDebugMessageControl, "glDebugMessageControl"); + set_proc_address(&glDebugMessageInsert, "glDebugMessageInsert"); + set_proc_address(&glDebugMessageCallback, "glDebugMessageCallback"); + set_proc_address(&glGetDebugMessageLog, "glGetDebugMessageLog"); + set_proc_address(&glPushDebugGroup, "glPushDebugGroup"); + set_proc_address(&glPopDebugGroup, "glPopDebugGroup"); + set_proc_address(&glObjectLabel, "glObjectLabel"); + set_proc_address(&glGetObjectLabel, "glGetObjectLabel"); + set_proc_address(&glObjectPtrLabel, "glObjectPtrLabel"); + set_proc_address(&glGetObjectPtrLabel, "glGetObjectPtrLabel"); +} + +// VERSION_4_4 +glBufferStorage: proc(target: u32, size: int, data: *void, flags: u32); +glClearTexImage: proc(texture: u32, level: i32, format: u32, type: u32, data: *void); +glClearTexSubImage: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, format: u32, type: u32, data: *void); +glBindBuffersBase: proc(target: u32, first: u32, count: i32, buffers: *u32); +glBindBuffersRange: proc(target: u32, first: u32, count: i32, buffers: *u32, offsets: *uintptr, sizes: *int); +glBindTextures: proc(first: u32, count: i32, textures: *u32); +glBindSamplers: proc(first: u32, count: i32, samplers: *u32); +glBindImageTextures: proc(first: u32, count: i32, textures: *u32); +glBindVertexBuffers: proc(first: u32, count: i32, buffers: *u32, offsets: *uintptr, strides: *i32); + +load_4_4 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glBufferStorage, "glBufferStorage"); + set_proc_address(&glClearTexImage, "glClearTexImage"); + set_proc_address(&glClearTexSubImage, "glClearTexSubImage"); + set_proc_address(&glBindBuffersBase, "glBindBuffersBase"); + set_proc_address(&glBindBuffersRange, "glBindBuffersRange"); + set_proc_address(&glBindTextures, "glBindTextures"); + set_proc_address(&glBindSamplers, "glBindSamplers"); + set_proc_address(&glBindImageTextures, "glBindImageTextures"); + set_proc_address(&glBindVertexBuffers, "glBindVertexBuffers"); +} + +// VERSION_4_5 +glClipControl: proc(origin: u32, depth: u32); +glCreateTransformFeedbacks: proc(n: i32, ids: *u32); +glTransformFeedbackBufferBase: proc(xfb: u32, index: u32, buffer: u32); +glTransformFeedbackBufferRange: proc(xfb: u32, index: u32, buffer: u32, offset: int, size: int); +glGetTransformFeedbackiv: proc(xfb: u32, pname: u32, param: *i32); +glGetTransformFeedbacki_v: proc(xfb: u32, pname: u32, index: u32, param: *i32); +glGetTransformFeedbacki64_v: proc(xfb: u32, pname: u32, index: u32, param: *i64); +glCreateBuffers: proc(n: i32, buffers: *u32); +glNamedBufferStorage: proc(buffer: u32, size: int, data: *void, flags: u32); +glNamedBufferData: proc(buffer: u32, size: int, data: *void, usage: u32); +glNamedBufferSubData: proc(buffer: u32, offset: int, size: int, data: *void); +glCopyNamedBufferSubData: proc(readBuffer: u32, writeBuffer: u32, readOffset: int, writeOffset: int, size: int); +glClearNamedBufferData: proc(buffer: u32, internalformat: u32, format: u32, type: u32, data: *void); +glClearNamedBufferSubData: proc(buffer: u32, internalformat: u32, offset: int, size: int, format: u32, type: u32, data: *void); +glMapNamedBuffer: proc(buffer: u32, access: u32): *void; +glMapNamedBufferRange: proc(buffer: u32, offset: int, length: int, access: u32): *void; +glUnmapNamedBuffer: proc(buffer: u32): bool; +glFlushMappedNamedBufferRange: proc(buffer: u32, offset: int, length: int); +glGetNamedBufferParameteriv: proc(buffer: u32, pname: u32, params: *i32); +glGetNamedBufferParameteri64v: proc(buffer: u32, pname: u32, params: *i64); +glGetNamedBufferPointerv: proc(buffer: u32, pname: u32, params: **void); +glGetNamedBufferSubData: proc(buffer: u32, offset: int, size: int, data: *void); +glCreateFramebuffers: proc(n: i32, framebuffers: *u32); +glNamedFramebufferRenderbuffer: proc(framebuffer: u32, attachment: u32, renderbuffertarget: u32, renderbuffer: u32); +glNamedFramebufferParameteri: proc(framebuffer: u32, pname: u32, param: i32); +glNamedFramebufferTexture: proc(framebuffer: u32, attachment: u32, texture: u32, level: i32); +glNamedFramebufferTextureLayer: proc(framebuffer: u32, attachment: u32, texture: u32, level: i32, layer: i32); +glNamedFramebufferDrawBuffer: proc(framebuffer: u32, buf: u32); +glNamedFramebufferDrawBuffers: proc(framebuffer: u32, n: i32, bufs: *u32); +glNamedFramebufferReadBuffer: proc(framebuffer: u32, src: u32); +glInvalidateNamedFramebufferData: proc(framebuffer: u32, numAttachments: i32, attachments: *u32); +glInvalidateNamedFramebufferSubData: proc(framebuffer: u32, numAttachments: i32, attachments: *u32, x: i32, y: i32, width: i32, height: i32); +glClearNamedFramebufferiv: proc(framebuffer: u32, buffer: u32, drawbuffer: i32, value: *i32); +glClearNamedFramebufferuiv: proc(framebuffer: u32, buffer: u32, drawbuffer: i32, value: *u32); +glClearNamedFramebufferfv: proc(framebuffer: u32, buffer: u32, drawbuffer: i32, value: *f32); +glClearNamedFramebufferfi: proc(framebuffer: u32, buffer: u32, drawbuffer: i32, depth: f32, stencil: i32); +glBlitNamedFramebuffer: proc(readFramebuffer: u32, drawFramebuffer: u32, srcX0: i32, srcY0: i32, srcX1: i32, srcY1: i32, dstX0: i32, dstY0: i32, dstX1: i32, dstY1: i32, mask: u32, filter: u32); +glCheckNamedFramebufferStatus: proc(framebuffer: u32, target: u32): u32; +glGetNamedFramebufferParameteriv: proc(framebuffer: u32, pname: u32, param: *i32); +glGetNamedFramebufferAttachmentParameteriv: proc(framebuffer: u32, attachment: u32, pname: u32, params: *i32); +glCreateRenderbuffers: proc(n: i32, renderbuffers: *u32); +glNamedRenderbufferStorage: proc(renderbuffer: u32, internalformat: u32, width: i32, height: i32); +glNamedRenderbufferStorageMultisample: proc(renderbuffer: u32, samples: i32, internalformat: u32, width: i32, height: i32); +glGetNamedRenderbufferParameteriv: proc(renderbuffer: u32, pname: u32, params: *i32); +glCreateTextures: proc(target: u32, n: i32, textures: *u32); +glTextureBuffer: proc(texture: u32, internalformat: u32, buffer: u32); +glTextureBufferRange: proc(texture: u32, internalformat: u32, buffer: u32, offset: int, size: int); +glTextureStorage1D: proc(texture: u32, levels: i32, internalformat: u32, width: i32); +glTextureStorage2D: proc(texture: u32, levels: i32, internalformat: u32, width: i32, height: i32); +glTextureStorage3D: proc(texture: u32, levels: i32, internalformat: u32, width: i32, height: i32, depth: i32); +glTextureStorage2DMultisample: proc(texture: u32, samples: i32, internalformat: u32, width: i32, height: i32, fixedsamplelocations: bool); +glTextureStorage3DMultisample: proc(texture: u32, samples: i32, internalformat: u32, width: i32, height: i32, depth: i32, fixedsamplelocations: bool); +glTextureSubImage1D: proc(texture: u32, level: i32, xoffset: i32, width: i32, format: u32, type: u32, pixels: *void); +glTextureSubImage2D: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, width: i32, height: i32, format: u32, type: u32, pixels: *void); +glTextureSubImage3D: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, format: u32, type: u32, pixels: *void); +glCompressedTextureSubImage1D: proc(texture: u32, level: i32, xoffset: i32, width: i32, format: u32, imageSize: i32, data: *void); +glCompressedTextureSubImage2D: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, width: i32, height: i32, format: u32, imageSize: i32, data: *void); +glCompressedTextureSubImage3D: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, format: u32, imageSize: i32, data: *void); +glCopyTextureSubImage1D: proc(texture: u32, level: i32, xoffset: i32, x: i32, y: i32, width: i32); +glCopyTextureSubImage2D: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, x: i32, y: i32, width: i32, height: i32); +glCopyTextureSubImage3D: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, x: i32, y: i32, width: i32, height: i32); +glTextureParameterf: proc(texture: u32, pname: u32, param: f32); +glTextureParameterfv: proc(texture: u32, pname: u32, param: *f32); +glTextureParameteri: proc(texture: u32, pname: u32, param: i32); +glTextureParameterIiv: proc(texture: u32, pname: u32, params: *i32); +glTextureParameterIuiv: proc(texture: u32, pname: u32, params: *u32); +glTextureParameteriv: proc(texture: u32, pname: u32, param: *i32); +glGenerateTextureMipmap: proc(texture: u32); +glBindTextureUnit: proc(unit: u32, texture: u32); +glGetTextureImage: proc(texture: u32, level: i32, format: u32, type: u32, bufSize: i32, pixels: *void); +glGetCompressedTextureImage: proc(texture: u32, level: i32, bufSize: i32, pixels: *void); +glGetTextureLevelParameterfv: proc(texture: u32, level: i32, pname: u32, params: *f32); +glGetTextureLevelParameteriv: proc(texture: u32, level: i32, pname: u32, params: *i32); +glGetTextureParameterfv: proc(texture: u32, pname: u32, params: *f32); +glGetTextureParameterIiv: proc(texture: u32, pname: u32, params: *i32); +glGetTextureParameterIuiv: proc(texture: u32, pname: u32, params: *u32); +glGetTextureParameteriv: proc(texture: u32, pname: u32, params: *i32); +glCreateVertexArrays: proc(n: i32, arrays: *u32); +glDisableVertexArrayAttrib: proc(vaobj: u32, index: u32); +glEnableVertexArrayAttrib: proc(vaobj: u32, index: u32); +glVertexArrayElementBuffer: proc(vaobj: u32, buffer: u32); +glVertexArrayVertexBuffer: proc(vaobj: u32, bindingindex: u32, buffer: u32, offset: int, stride: i32); +glVertexArrayVertexBuffers: proc(vaobj: u32, first: u32, count: i32, buffers: *u32, offsets: *uintptr, strides: *i32); +glVertexArrayAttribBinding: proc(vaobj: u32, attribindex: u32, bindingindex: u32); +glVertexArrayAttribFormat: proc(vaobj: u32, attribindex: u32, size: i32, type: u32, normalized: bool, relativeoffset: u32); +glVertexArrayAttribIFormat: proc(vaobj: u32, attribindex: u32, size: i32, type: u32, relativeoffset: u32); +glVertexArrayAttribLFormat: proc(vaobj: u32, attribindex: u32, size: i32, type: u32, relativeoffset: u32); +glVertexArrayBindingDivisor: proc(vaobj: u32, bindingindex: u32, divisor: u32); +glGetVertexArrayiv: proc(vaobj: u32, pname: u32, param: *i32); +glGetVertexArrayIndexediv: proc(vaobj: u32, index: u32, pname: u32, param: *i32); +glGetVertexArrayIndexed64iv: proc(vaobj: u32, index: u32, pname: u32, param: *i64); +glCreateSamplers: proc(n: i32, samplers: *u32); +glCreateProgramPipelines: proc(n: i32, pipelines: *u32); +glCreateQueries: proc(target: u32, n: i32, ids: *u32); +glGetQueryBufferObjecti64v: proc(id: u32, buffer: u32, pname: u32, offset: int); +glGetQueryBufferObjectiv: proc(id: u32, buffer: u32, pname: u32, offset: int); +glGetQueryBufferObjectui64v: proc(id: u32, buffer: u32, pname: u32, offset: int); +glGetQueryBufferObjectuiv: proc(id: u32, buffer: u32, pname: u32, offset: int); +glMemoryBarrierByRegion: proc(barriers: u32); +glGetTextureSubImage: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, format: u32, type: u32, bufSize: i32, pixels: *void); +glGetCompressedTextureSubImage: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, bufSize: i32, pixels: *void); +glGetGraphicsResetStatus: proc(): u32; +glGetnCompressedTexImage: proc(target: u32, lod: i32, bufSize: i32, pixels: *void); +glGetnTexImage: proc(target: u32, level: i32, format: u32, type: u32, bufSize: i32, pixels: *void); +glGetnUniformdv: proc(program: u32, location: i32, bufSize: i32, params: *f64); +glGetnUniformfv: proc(program: u32, location: i32, bufSize: i32, params: *f32); +glGetnUniformiv: proc(program: u32, location: i32, bufSize: i32, params: *i32); +glGetnUniformuiv: proc(program: u32, location: i32, bufSize: i32, params: *u32); +glReadnPixels: proc(x: i32, y: i32, width: i32, height: i32, format: u32, type: u32, bufSize: i32, data: *void); +glGetnMapdv: proc(target: u32, query: u32, bufSize: i32, v: *f64); +glGetnMapfv: proc(target: u32, query: u32, bufSize: i32, v: *f32); +glGetnMapiv: proc(target: u32, query: u32, bufSize: i32, v: *i32); +glGetnPixelMapusv: proc(map_: u32, bufSize: i32, values: *u16); +glGetnPixelMapfv: proc(map_: u32, bufSize: i32, values: *f32); +glGetnPixelMapuiv: proc(map_: u32, bufSize: i32, values: *u32); +glGetnPolygonStipple: proc(bufSize: i32, pattern: *u8); +glGetnColorTable: proc(target: u32, format: u32, type: u32, bufSize: i32, table: *void); +glGetnConvolutionFilter: proc(target: u32, format: u32, type: u32, bufSize: i32, image: *void); +glGetnSeparableFilter: proc(target: u32, format: u32, type: u32, rowBufSize: i32, row: *void, columnBufSize: i32, column: *void, span: *void); +glGetnHistogram: proc(target: u32, reset: bool, format: u32, type: u32, bufSize: i32, values: *void); +glGetnMinmax: proc(target: u32, reset: bool, format: u32, type: u32, bufSize: i32, values: *void); +glTextureBarrier: proc(); +glGetUnsignedBytevEXT: proc(pname: u32, data: *u8); +glTexPageCommitmentARB: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, commit: bool); + +load_4_5 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glClipControl, "glClipControl"); + set_proc_address(&glCreateTransformFeedbacks, "glCreateTransformFeedbacks"); + set_proc_address(&glTransformFeedbackBufferBase, "glTransformFeedbackBufferBase"); + set_proc_address(&glTransformFeedbackBufferRange, "glTransformFeedbackBufferRange"); + set_proc_address(&glGetTransformFeedbackiv, "glGetTransformFeedbackiv"); + set_proc_address(&glGetTransformFeedbacki_v, "glGetTransformFeedbacki_v"); + set_proc_address(&glGetTransformFeedbacki64_v, "glGetTransformFeedbacki64_v"); + set_proc_address(&glCreateBuffers, "glCreateBuffers"); + set_proc_address(&glNamedBufferStorage, "glNamedBufferStorage"); + set_proc_address(&glNamedBufferData, "glNamedBufferData"); + set_proc_address(&glNamedBufferSubData, "glNamedBufferSubData"); + set_proc_address(&glCopyNamedBufferSubData, "glCopyNamedBufferSubData"); + set_proc_address(&glClearNamedBufferData, "glClearNamedBufferData"); + set_proc_address(&glClearNamedBufferSubData, "glClearNamedBufferSubData"); + set_proc_address(&glMapNamedBuffer, "glMapNamedBuffer"); + set_proc_address(&glMapNamedBufferRange, "glMapNamedBufferRange"); + set_proc_address(&glUnmapNamedBuffer, "glUnmapNamedBuffer"); + set_proc_address(&glFlushMappedNamedBufferRange, "glFlushMappedNamedBufferRange"); + set_proc_address(&glGetNamedBufferParameteriv, "glGetNamedBufferParameteriv"); + set_proc_address(&glGetNamedBufferParameteri64v, "glGetNamedBufferParameteri64v"); + set_proc_address(&glGetNamedBufferPointerv, "glGetNamedBufferPointerv"); + set_proc_address(&glGetNamedBufferSubData, "glGetNamedBufferSubData"); + set_proc_address(&glCreateFramebuffers, "glCreateFramebuffers"); + set_proc_address(&glNamedFramebufferRenderbuffer, "glNamedFramebufferRenderbuffer"); + set_proc_address(&glNamedFramebufferParameteri, "glNamedFramebufferParameteri"); + set_proc_address(&glNamedFramebufferTexture, "glNamedFramebufferTexture"); + set_proc_address(&glNamedFramebufferTextureLayer, "glNamedFramebufferTextureLayer"); + set_proc_address(&glNamedFramebufferDrawBuffer, "glNamedFramebufferDrawBuffer"); + set_proc_address(&glNamedFramebufferDrawBuffers, "glNamedFramebufferDrawBuffers"); + set_proc_address(&glNamedFramebufferReadBuffer, "glNamedFramebufferReadBuffer"); + set_proc_address(&glInvalidateNamedFramebufferData, "glInvalidateNamedFramebufferData"); + set_proc_address(&glInvalidateNamedFramebufferSubData, "glInvalidateNamedFramebufferSubData"); + set_proc_address(&glClearNamedFramebufferiv, "glClearNamedFramebufferiv"); + set_proc_address(&glClearNamedFramebufferuiv, "glClearNamedFramebufferuiv"); + set_proc_address(&glClearNamedFramebufferfv, "glClearNamedFramebufferfv"); + set_proc_address(&glClearNamedFramebufferfi, "glClearNamedFramebufferfi"); + set_proc_address(&glBlitNamedFramebuffer, "glBlitNamedFramebuffer"); + set_proc_address(&glCheckNamedFramebufferStatus, "glCheckNamedFramebufferStatus"); + set_proc_address(&glGetNamedFramebufferParameteriv, "glGetNamedFramebufferParameteriv"); + set_proc_address(&glGetNamedFramebufferAttachmentParameteriv, "glGetNamedFramebufferAttachmentParameteriv"); + set_proc_address(&glCreateRenderbuffers, "glCreateRenderbuffers"); + set_proc_address(&glNamedRenderbufferStorage, "glNamedRenderbufferStorage"); + set_proc_address(&glNamedRenderbufferStorageMultisample, "glNamedRenderbufferStorageMultisample"); + set_proc_address(&glGetNamedRenderbufferParameteriv, "glGetNamedRenderbufferParameteriv"); + set_proc_address(&glCreateTextures, "glCreateTextures"); + set_proc_address(&glTextureBuffer, "glTextureBuffer"); + set_proc_address(&glTextureBufferRange, "glTextureBufferRange"); + set_proc_address(&glTextureStorage1D, "glTextureStorage1D"); + set_proc_address(&glTextureStorage2D, "glTextureStorage2D"); + set_proc_address(&glTextureStorage3D, "glTextureStorage3D"); + set_proc_address(&glTextureStorage2DMultisample, "glTextureStorage2DMultisample"); + set_proc_address(&glTextureStorage3DMultisample, "glTextureStorage3DMultisample"); + set_proc_address(&glTextureSubImage1D, "glTextureSubImage1D"); + set_proc_address(&glTextureSubImage2D, "glTextureSubImage2D"); + set_proc_address(&glTextureSubImage3D, "glTextureSubImage3D"); + set_proc_address(&glCompressedTextureSubImage1D, "glCompressedTextureSubImage1D"); + set_proc_address(&glCompressedTextureSubImage2D, "glCompressedTextureSubImage2D"); + set_proc_address(&glCompressedTextureSubImage3D, "glCompressedTextureSubImage3D"); + set_proc_address(&glCopyTextureSubImage1D, "glCopyTextureSubImage1D"); + set_proc_address(&glCopyTextureSubImage2D, "glCopyTextureSubImage2D"); + set_proc_address(&glCopyTextureSubImage3D, "glCopyTextureSubImage3D"); + set_proc_address(&glTextureParameterf, "glTextureParameterf"); + set_proc_address(&glTextureParameterfv, "glTextureParameterfv"); + set_proc_address(&glTextureParameteri, "glTextureParameteri"); + set_proc_address(&glTextureParameterIiv, "glTextureParameterIiv"); + set_proc_address(&glTextureParameterIuiv, "glTextureParameterIuiv"); + set_proc_address(&glTextureParameteriv, "glTextureParameteriv"); + set_proc_address(&glGenerateTextureMipmap, "glGenerateTextureMipmap"); + set_proc_address(&glBindTextureUnit, "glBindTextureUnit"); + set_proc_address(&glGetTextureImage, "glGetTextureImage"); + set_proc_address(&glGetCompressedTextureImage, "glGetCompressedTextureImage"); + set_proc_address(&glGetTextureLevelParameterfv, "glGetTextureLevelParameterfv"); + set_proc_address(&glGetTextureLevelParameteriv, "glGetTextureLevelParameteriv"); + set_proc_address(&glGetTextureParameterfv, "glGetTextureParameterfv"); + set_proc_address(&glGetTextureParameterIiv, "glGetTextureParameterIiv"); + set_proc_address(&glGetTextureParameterIuiv, "glGetTextureParameterIuiv"); + set_proc_address(&glGetTextureParameteriv, "glGetTextureParameteriv"); + set_proc_address(&glCreateVertexArrays, "glCreateVertexArrays"); + set_proc_address(&glDisableVertexArrayAttrib, "glDisableVertexArrayAttrib"); + set_proc_address(&glEnableVertexArrayAttrib, "glEnableVertexArrayAttrib"); + set_proc_address(&glVertexArrayElementBuffer, "glVertexArrayElementBuffer"); + set_proc_address(&glVertexArrayVertexBuffer, "glVertexArrayVertexBuffer"); + set_proc_address(&glVertexArrayVertexBuffers, "glVertexArrayVertexBuffers"); + set_proc_address(&glVertexArrayAttribBinding, "glVertexArrayAttribBinding"); + set_proc_address(&glVertexArrayAttribFormat, "glVertexArrayAttribFormat"); + set_proc_address(&glVertexArrayAttribIFormat, "glVertexArrayAttribIFormat"); + set_proc_address(&glVertexArrayAttribLFormat, "glVertexArrayAttribLFormat"); + set_proc_address(&glVertexArrayBindingDivisor, "glVertexArrayBindingDivisor"); + set_proc_address(&glGetVertexArrayiv, "glGetVertexArrayiv"); + set_proc_address(&glGetVertexArrayIndexediv, "glGetVertexArrayIndexediv"); + set_proc_address(&glGetVertexArrayIndexed64iv, "glGetVertexArrayIndexed64iv"); + set_proc_address(&glCreateSamplers, "glCreateSamplers"); + set_proc_address(&glCreateProgramPipelines, "glCreateProgramPipelines"); + set_proc_address(&glCreateQueries, "glCreateQueries"); + set_proc_address(&glGetQueryBufferObjecti64v, "glGetQueryBufferObjecti64v"); + set_proc_address(&glGetQueryBufferObjectiv, "glGetQueryBufferObjectiv"); + set_proc_address(&glGetQueryBufferObjectui64v, "glGetQueryBufferObjectui64v"); + set_proc_address(&glGetQueryBufferObjectuiv, "glGetQueryBufferObjectuiv"); + set_proc_address(&glMemoryBarrierByRegion, "glMemoryBarrierByRegion"); + set_proc_address(&glGetTextureSubImage, "glGetTextureSubImage"); + set_proc_address(&glGetCompressedTextureSubImage, "glGetCompressedTextureSubImage"); + set_proc_address(&glGetGraphicsResetStatus, "glGetGraphicsResetStatus"); + set_proc_address(&glGetnCompressedTexImage, "glGetnCompressedTexImage"); + set_proc_address(&glGetnTexImage, "glGetnTexImage"); + set_proc_address(&glGetnUniformdv, "glGetnUniformdv"); + set_proc_address(&glGetnUniformfv, "glGetnUniformfv"); + set_proc_address(&glGetnUniformiv, "glGetnUniformiv"); + set_proc_address(&glGetnUniformuiv, "glGetnUniformuiv"); + set_proc_address(&glReadnPixels, "glReadnPixels"); + set_proc_address(&glGetnMapdv, "glGetnMapdv"); + set_proc_address(&glGetnMapfv, "glGetnMapfv"); + set_proc_address(&glGetnMapiv, "glGetnMapiv"); + set_proc_address(&glGetnPixelMapfv, "glGetnPixelMapfv"); + set_proc_address(&glGetnPixelMapuiv, "glGetnPixelMapuiv"); + set_proc_address(&glGetnPixelMapusv, "glGetnPixelMapusv"); + set_proc_address(&glGetnPolygonStipple, "glGetnPolygonStipple"); + set_proc_address(&glGetnColorTable, "glGetnColorTable"); + set_proc_address(&glGetnConvolutionFilter, "glGetnConvolutionFilter"); + set_proc_address(&glGetnSeparableFilter, "glGetnSeparableFilter"); + set_proc_address(&glGetnHistogram, "glGetnHistogram"); + set_proc_address(&glGetnMinmax, "glGetnMinmax"); + set_proc_address(&glTextureBarrier, "glTextureBarrier"); + set_proc_address(&glGetUnsignedBytevEXT, "glGetUnsignedBytevEXT"); + set_proc_address(&glTexPageCommitmentARB, "glTexPageCommitmentARB"); +} + +// VERSION_4_6 +glSpecializeShader: proc(shader: u32, pEntryPoint: *char, numSpecializationConstants: u32, pConstantIndex: *u32, pConstantValue: *u32); +glMultiDrawArraysIndirectCount: proc(mode: i32, indirect: *DrawArraysIndirectCommand, drawcount: i32, maxdrawcount: i32, stride: i32); +glMultiDrawElementsIndirectCount: proc(mode: i32, type: i32, indirect: *DrawElementsIndirectCommand, drawcount: i32, maxdrawcount: i32, stride: i32); +glPolygonOffsetClamp: proc(factor: f32, units: f32, clamp: f32); + +load_4_6 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(&glSpecializeShader, "glSpecializeShader"); + set_proc_address(&glMultiDrawArraysIndirectCount, "glMultiDrawArraysIndirectCount"); + set_proc_address(&glMultiDrawElementsIndirectCount, "glMultiDrawElementsIndirectCount"); + set_proc_address(&glPolygonOffsetClamp, "glPolygonOffsetClamp"); +} diff --git a/tests/example_ui_and_hot_reloading/dll/render_opengl.lc b/tests/example_ui_and_hot_reloading/dll/render_opengl.lc new file mode 100644 index 0000000..ec1b5f4 --- /dev/null +++ b/tests/example_ui_and_hot_reloading/dll/render_opengl.lc @@ -0,0 +1,545 @@ +R_CommandBufferSize :: 1024 * 1024; + +R_Atlas :: struct { + bitmap : *u32; + sizei : V2I; + size : V2; + inverse_size : V2; + cursor : V2I; + biggest_height : i32; + white_texture_bounding_box : R2P; + texture_id : u32; + padding : V2I; +} + +R_FontGlyph :: struct { + size : V2; + offset : V2; + x_advance : f32; + left_side_bearing : f32; + atlas_bounding_box : R2P; +} + +R_Font :: struct { + atlas : *R_Atlas; + glyphs : [96]R_FontGlyph; + glyph_count : i32; + + first_char : i32; + last_char : i32; + + // This is for oversampling + // 0.5 = we draw the font as 2 times smaller then it is. + // Should lead to better quality result. + scaling_transform : f32; + + // scaling transform is applied to these + size : f32; + ascent : f32; + descent : f32; + line_gap : f32; + + // scaling factor not applied, not sure if these will be useful + scale : f32; + em_scale : f32; + + white_texture_bounding_box : R2P; +} + +R_Vertex2D :: struct { + pos : V2; + tex : V2; + color: V4; +} + +R_CommandKind :: typedef int; +R_CommandKind_Null :: 0; +R_CommandKind_Triangle :: ^; +R_CommandKind_Triangle2D :: ^; + +R_Command :: struct { + kind: R_CommandKind; + next: *R_Command; + + out : *R_Vertex2D; // user write + data: *R_Vertex2D; + count: i32; + max_count: i32; +} + +R_Shader :: struct { + pipeline: u32; + fragment: u32; + vertex : u32; +} + +R_Render :: struct { + first_command2d: *R_Command; + last_command2d : *R_Command; + total_vertex_count: u64; + + vbo: u32; + vao: u32; + shader2d: R_Shader; + + atlas: R_Atlas; + font_medium: R_Font; + font: *R_Font; +} + +R_Text2DDesc :: struct { + pos: V2; + text: S8_String; + color: V4; + scale: f32; + + do_draw: bool; + rects_arena: *MA_Arena; +} + +R_StringMeasure :: struct { + first_rect: *R_RectNode; + last_rect : *R_RectNode; + rect: R2P; +} + +R_RectNode :: struct { + next: *R_RectNode; + rect: R2P; + utf8_codepoint_byte_size: i32; +} + +R_PackType :: typedef int; +R_PackType_MonoColorFont :: 0; +R_PackType_RGBABitmap :: ^; + +R_CreateAtlas :: proc(arena: *MA_Arena, size: V2I, padding: V2I): R_Atlas { + result: R_Atlas; + result.padding = padding; + result.sizei = size; + result.size = V2_FromV2I(size); + result.inverse_size.x = 1.0 / result.size.x; + result.inverse_size.y = 1.0 / result.size.y; + result.bitmap = MA_PushSize(arena, :usize(:i32(sizeof(:u32)) * size.x * size.y)); + + // Add a whitebox first for rectangle rendering + for y: i32 = 0; y < 16; y += 1 { + for x: i32 = 0; x < 16; x += 1 { + dst := &result.bitmap[x + y * result.sizei.x]; + *dst = 0xffffffff; + } + } + // Skipping some pixels to avoid linear interpolation on edges + result.white_texture_bounding_box = :R2P{ + {2.0 * result.inverse_size.x, 2.0 / result.size.y}, + {14.0 * result.inverse_size.x, 14.0 / result.size.y}, + }; + result.cursor.x += 16 + padding.x; + result.biggest_height += 16 + padding.y; + return result; +} + +R_PackBitmapInvertY :: proc(atlas: *R_Atlas, pack_type: R_PackType, bitmap: *u8, width: i32, height: i32): R2P { + // Packing into a texture atlas + // @Inefficient The algorithm is a simplest thing I had in mind, first we advance + // through the atlas in X packing consecutive glyphs. After we get to the end of the row + // we advance to the next row by the Y size of the biggest packed glyph. If we get to the + // end of atlas and fail to pack everything the app panics. + + if (atlas.cursor.x + width > atlas.sizei.x) { + if (atlas.cursor.y + height < atlas.sizei.y) { + atlas.cursor.x = 0; + atlas.cursor.y += atlas.biggest_height + atlas.padding.y; + } + else { + IO_FatalErrorf("Error while packing a font into atlas. Atlas size for this font scale is a bit too small"); + } + } + + // Write the bitmap with inverted Y + src := bitmap; + // @todo: ambigious syntax, expression parsing doesn't stop at '{', error in wrong place + // for y := atlas.cursor.y + height - 1; y >= atlas.cursor.y; y++ { + for y := atlas.cursor.y + height - 1; y >= atlas.cursor.y; y -= 1 { + for x := atlas.cursor.x; x < atlas.cursor.x + width; x += 1 { + if (pack_type == R_PackType_RGBABitmap) { + atlas.bitmap[x + y * atlas.sizei.x] = *:*u32(src); + src = &src[4]; + continue; + } + if (pack_type == R_PackType_MonoColorFont) { + dst := :*u8(&atlas.bitmap[x + y * atlas.sizei.x]); + dst[0] = 0xFF; + dst[1] = 0xFF; + dst[2] = 0xFF; + dst[3] = *src; + src = &src[1]; + continue; + } + IO_InvalidCodepath(); + } + } + + size := :V2{:f32(width) * atlas.inverse_size.x, :f32(height) * atlas.inverse_size.y}; + cursor := V2_FromV2I(atlas.cursor); + pos := V2_Mul(cursor, atlas.inverse_size); + result := R2P_Size(pos, size); + + atlas.cursor.x += width + atlas.padding.x; + atlas.biggest_height = I32_Max(atlas.biggest_height, height); + + return result; +} + +Font_Create :: proc(atlas: *R_Atlas, size: f32, path: S8_String, oversampling: f32): R_Font { + scratch := MA_GetScratch(); + font_file := OS_ReadFile(scratch.arena, path); + + result: R_Font; + result.scaling_transform = 1.0 / oversampling; + result.size = oversampling * size; + + result.first_char = ' '; + result.last_char = '~'; + stb_font: stbtt_fontinfo; + if (font_file.len) { + success := stbtt_InitFont(&stb_font, :*uchar(font_file.str), 0); + if (success) { + ascent: int; + descent: int; + gap: int; + stbtt_GetFontVMetrics(&stb_font, &ascent, &descent, &gap); + result.scale = stbtt_ScaleForPixelHeight(&stb_font, result.size); + result.em_scale = stbtt_ScaleForMappingEmToPixels(&stb_font, result.size); + result.ascent = :f32(ascent) * result.scale; + result.descent = :f32(descent) * result.scale; + result.line_gap = :f32(gap) * result.scale; + result.white_texture_bounding_box = atlas.white_texture_bounding_box; + + for ascii_symbol := result.first_char; ascii_symbol <= result.last_char; ascii_symbol+=1 { + width: int; + height: int; + xoff: int; + yoff: int; + bitmap := :*u8(stbtt_GetCodepointBitmap(&stb_font, 0, result.scale, :int(ascii_symbol), &width, &height, &xoff, &yoff)); + + x_advance: int; + left_side_bearing: int; + stbtt_GetCodepointHMetrics(&stb_font, :int(ascii_symbol), &x_advance, &left_side_bearing); + + g := &result.glyphs[result.glyph_count]; + result.glyph_count += 1; + + g.atlas_bounding_box = R_PackBitmapInvertY(atlas, R_PackType_MonoColorFont, bitmap, :i32(width), :i32(height)); + g.size = :V2{:f32(width), :f32(height)}; + + // Offset y needs to be inverted cause bitmap has inverted Y + g.offset = :V2{:f32(xoff), -(g.size.y + :f32(yoff))}; + g.x_advance = :f32(x_advance) * result.scale; + g.left_side_bearing = :f32(left_side_bearing) * result.scale; + + // Apply scaling transform + g.offset = V2_MulF(g.offset, result.scaling_transform); + g.x_advance = g.x_advance * result.scaling_transform; + g.left_side_bearing = g.left_side_bearing * result.scaling_transform; + g.size = V2_MulF(g.size, result.scaling_transform); + + stbtt_FreeBitmap(:*uchar(bitmap), nil); + } + + result.ascent *= result.scaling_transform; + result.descent *= result.scaling_transform; + result.size *= result.scaling_transform; + result.line_gap *= result.scaling_transform; + } + } + + MA_EndTemp(scratch); + return result; +} + +Font_GetGlyph :: proc(font: *R_Font, codepoint: i32): *R_FontGlyph { + is_in_range := codepoint >= font.first_char && codepoint <= font.last_char; + if (is_in_range) { + index := codepoint - font.first_char; + return &font.glyphs[index]; + } + else { + index := '?' - font.first_char; + return &font.glyphs[index]; + } +} + +GL_DebugCallback :: proc(source: GLenum @unused, type: GLenum @unused, id: GLuint @unused, severity: GLenum, length: GLsizei @unused, message: *GLchar, user: *void @unused) { + IO_Printf("%s\n", message); + if (severity == GL_DEBUG_SEVERITY_HIGH || severity == GL_DEBUG_SEVERITY_MEDIUM) { + IO_FatalErrorf("%s", message); + } +} + +GL_SetProcAddress :: proc(p: *void, name: *char) { + pp := :**void(p); + *pp = Mu.gl_get_proc_address(name); +} + +GL_LoadProcs :: proc() { + load_up_to(4, 5, :*void(GL_SetProcAddress)); + glDebugMessageCallback(:*void(GL_DebugCallback), nil); + glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); +} + +R_Reload :: proc() { + GL_LoadProcs(); +} + +R_Init :: proc(render: *R_Render) { + R = render; + GL_LoadProcs(); + atlas := R_CreateAtlas(Temp, :V2I{1024, 1024}, :V2I{4, 4}); + R.font_medium = Font_Create(&atlas, 32, S8_Lit("C:/windows/fonts/Calibri.ttf"), 1.0); + { + glCreateTextures(GL_TEXTURE_2D, 1, &atlas.texture_id); + glTextureParameteri(atlas.texture_id, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTextureParameteri(atlas.texture_id, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTextureParameteri(atlas.texture_id, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTextureParameteri(atlas.texture_id, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTextureStorage2D(atlas.texture_id, 1, GL_RGBA8, :i32(atlas.sizei.x), :i32(atlas.sizei.y)); + glTextureSubImage2D(atlas.texture_id, 0, 0, 0, :i32(atlas.sizei.x), :i32(atlas.sizei.y), GL_RGBA, GL_UNSIGNED_BYTE, atlas.bitmap); + } + R.atlas = atlas; + R.font_medium.atlas = &R.atlas; + R.font = &R.font_medium; + + glCreateBuffers(1, &R.vbo); + glNamedBufferStorage(R.vbo, R_CommandBufferSize, nil, GL_DYNAMIC_STORAGE_BIT); + + { + glCreateVertexArrays(1, &R.vao); + + vbuf_index: u32 = 0; + glVertexArrayVertexBuffer(R.vao, vbuf_index, R.vbo, 0, :i32(sizeof(:R_Vertex2D))); + + a_pos: u32 = 0; + pos_offset: u32 = #`offsetof(R_Vertex2D, pos)`; + glVertexArrayAttribFormat(R.vao, a_pos, 2, GL_FLOAT, GL_FALSE, pos_offset); + glVertexArrayAttribBinding(R.vao, a_pos, vbuf_index); + glEnableVertexArrayAttrib(R.vao, a_pos); + + a_tex: u32 = 1; + tex_offset: u32 = #`offsetof(R_Vertex2D, tex)`; + glVertexArrayAttribFormat(R.vao, a_tex, 2, GL_FLOAT, GL_FALSE, tex_offset); + glVertexArrayAttribBinding(R.vao, a_tex, vbuf_index); + glEnableVertexArrayAttrib(R.vao, a_tex); + + a_color: u32 = 2; + color_offset: u32 = #`offsetof(R_Vertex2D, color)`; // @todo + glVertexArrayAttribFormat(R.vao, a_color, 4, GL_FLOAT, GL_FALSE, color_offset); + glVertexArrayAttribBinding(R.vao, a_color, vbuf_index); + glEnableVertexArrayAttrib(R.vao, a_color); + } + + vshader := `#version 450 core + layout(location=0) uniform vec2 U_InvHalfScreenSize; + layout(location=0) in vec2 IN_Pos; + layout(location=1) in vec2 IN_Tex; + layout(location=2) in vec4 IN_Color; + + out gl_PerVertex { vec4 gl_Position; }; // required because of ARB_separate_shader_objects + out vec2 OUT_UV; + out vec4 OUT_Color; + void main() { + vec2 pos = IN_Pos * U_InvHalfScreenSize; + pos -= vec2(1, 1); + gl_Position = vec4(pos, 0, 1); + OUT_UV = IN_Tex; + OUT_Color = IN_Color; + } + `; + + fshader := `#version 450 core + in vec2 IN_UV; + in vec4 IN_Color; + layout (binding=0) uniform sampler2D S_Texture; + layout (location=0) out vec4 OUT_Color; + void main() { + vec4 c = IN_Color; + vec4 texture_color = texture(S_Texture, IN_UV); + OUT_Color = c * texture_color; + } + `; + + R.shader2d = R_CreateShader(vshader, fshader); +} + + +R_CreateShader :: proc(glsl_vshader: *char, glsl_fshader: *char): R_Shader { + result: R_Shader; + result.vertex = glCreateShaderProgramv(GL_VERTEX_SHADER, 1, &glsl_vshader); + result.fragment = glCreateShaderProgramv(GL_FRAGMENT_SHADER, 1, &glsl_fshader); + + linked: i32; + glGetProgramiv(result.vertex, GL_LINK_STATUS, &linked); + if (!linked) { + message: [1024]char; + glGetProgramInfoLog(result.vertex, :i32(sizeof(message)), nil, :*u8(&message[0])); + IO_FatalErrorf("[GL] Failed to create vertex shader! %s", message); + } + + glGetProgramiv(result.fragment, GL_LINK_STATUS, &linked); + if (!linked) { + message: [1024]char; + glGetProgramInfoLog(result.fragment, :i32(sizeof(message)), nil, :*u8(&message[0])); + IO_FatalErrorf("[GL] Failed to create fragment shader! %s", message); + } + + glGenProgramPipelines(1, &result.pipeline); + glUseProgramStages(result.pipeline, GL_VERTEX_SHADER_BIT, result.vertex); + glUseProgramStages(result.pipeline, GL_FRAGMENT_SHADER_BIT, result.fragment); + return result; +} + +R_GetCommand :: proc(kind: R_CommandKind, vcount_to_add: i32): *R_Command { + make_new := R.last_command2d == 0 || + R.last_command2d.kind != kind || + R.last_command2d.count + vcount_to_add > R.last_command2d.max_count; + + if make_new { + sizeof_r_command: usize = #`sizeof(R_Command)`; + c: *R_Command = MA_PushSize(Temp, sizeof_r_command); + c.kind = kind; + c.data = MA_PushSizeNonZeroed(Temp, R_CommandBufferSize); + if (kind == R_CommandKind_Triangle2D) { + c.max_count = R_CommandBufferSize / :i32(sizeof(:R_Vertex2D)); + SLL_QUEUE_ADD(R.first_command2d, R.last_command2d, c); + } + else IO_InvalidCodepath(); + } + + c := R.last_command2d; + c.out = &c.data[c.count]; + c.count += vcount_to_add; + R.total_vertex_count += :u64(vcount_to_add); + return c; +} + +R_Rect2D :: proc(rect: R2P, tex: R2P, color: V4) { + c := R_GetCommand(R_CommandKind_Triangle2D, 6); + c.out[0].pos = :V2{rect.min.x, rect.max.y}; + c.out[0].tex = :V2{tex.min.x, tex.max.y}; + c.out[0].color = color; + c.out[1].pos = :V2{rect.max.x, rect.max.y}; + c.out[1].tex = :V2{tex.max.x, tex.max.y}; + c.out[1].color = color; + c.out[2].pos = :V2{rect.min.x, rect.min.y}; + c.out[2].tex = :V2{tex.min.x, tex.min.y}; + c.out[2].color = color; + c.out[3].pos = :V2{rect.min.x, rect.min.y}; + c.out[3].tex = :V2{tex.min.x, tex.min.y}; + c.out[3].color = color; + c.out[4].pos = :V2{rect.max.x, rect.max.y}; + c.out[4].tex = :V2{tex.max.x, tex.max.y}; + c.out[4].color = color; + c.out[5].pos = :V2{rect.max.x, rect.min.y}; + c.out[5].tex = :V2{tex.max.x, tex.min.y}; + c.out[5].color = color; +} + +R_Text2D :: proc(params: R_Text2DDesc): R_StringMeasure { + result: R_StringMeasure; + + original_pos := params.pos; + max_pos := params.pos; + pos := params.pos; + scale := params.scale; + for iter := UTF8_IterateEx(params.text.str, :int(params.text.len)); iter.item /*;UTF8_Advance(&iter)@todo*/ { + it: u32 = iter.item; + if it == '\n' { + pos.x = original_pos.x; + pos.y -= R.font.size * scale; + if (pos.x > max_pos.x) max_pos.x = pos.x; + if (pos.y < max_pos.y) max_pos.y = pos.y; // @warning: min position y actually + continue; + } + g: *R_FontGlyph = Font_GetGlyph(R.font, :i32(it)); + + sym_pos := pos; + pos.x += g.x_advance * scale; + if (pos.x > max_pos.x) max_pos.x = pos.x; + if (pos.y < max_pos.y) max_pos.y = pos.y; // @warning: min position y actually + + sym_pos.x += g.offset.x * scale; + sym_pos.y += g.offset.y * scale; + + minp: V2 = {sym_pos.x, sym_pos.y}; + rect: R2P = R2P_Size(minp, V2_MulF(g.size, scale)); + if (params.do_draw) { + R_Rect2D(rect, g.atlas_bounding_box, params.color); + } + if (params.rects_arena) { + node: *R_RectNode = MA_PushSize(params.rects_arena, :usize(sizeof(:R_RectNode))); + node.rect = rect; + node.utf8_codepoint_byte_size = :i32(iter.utf8_codepoint_byte_size); + SLL_QUEUE_ADD(result.first_rect, result.last_rect, node); + } + UTF8_Advance(&iter); // @todo + } + + result.rect = { + {original_pos.x, max_pos.y + R.font.descent * scale}, /* @warning: min position y actually */ + {max_pos.x, original_pos.y + R.font.ascent * scale}, + }; + + return result; +} + + +R_GetTextSize :: proc(text: S8_String): f32 { + m := R_Text2D({text = text, scale = 1.0}); + size := R2P_GetSize(m.rect).x; + return size; +} + +R_ColorWhite: V4 = {1,1,1,1}; +R_ColorBlack: V4 = {0,0,0,1}; + +R_DrawText :: proc(text: S8_String, pos: V2, color: V4): R_StringMeasure { + result := R_Text2D({text = text, color = color, pos = pos, do_draw = true, scale = 1.0}); + return result; +} + +R_EndFrame :: proc() { + ws := :V2{:f32(Mu.window.size.x), :f32(Mu.window.size.y)}; + wsi := :V2I{:i32(Mu.window.size.x), :i32(Mu.window.size.y)}; + x: f32 = 1 / (ws.x / 2); + y: f32 = 1 / (ws.y / 2); + + glViewport(0, 0, wsi.x, wsi.y); + glClearColor(0, 0, 0, 0); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + + // Default draw using the font texture + { + glBindProgramPipeline(R.shader2d.pipeline); + glProgramUniform2f(R.shader2d.vertex, 0, x, y); + for it := R.first_command2d; it; it = it.next { + if (it.kind == R_CommandKind_Triangle2D) { + glNamedBufferSubData(R.vbo, 0, :int(it.count) * :int(sizeof(:R_Vertex2D)), it.data); + glBindVertexArray(R.vao); + s_texture: u32 = 0; // texture unit that sampler2D will use in GLSL code + glBindTextureUnit(s_texture, R.font.atlas.texture_id); + glDrawArrays(GL_TRIANGLES, 0, it.count); + continue; + } + IO_InvalidCodepath(); + } + } + + R.first_command2d = nil; + R.last_command2d = nil; + R.total_vertex_count = 0; +} \ No newline at end of file diff --git a/tests/example_ui_and_hot_reloading/dll/stb_truetype.lc b/tests/example_ui_and_hot_reloading/dll/stb_truetype.lc new file mode 100644 index 0000000..d49d1fe --- /dev/null +++ b/tests/example_ui_and_hot_reloading/dll/stb_truetype.lc @@ -0,0 +1,183 @@ +#`#include "vendor/stb_truetype.c"`; + +@foreign stbrp_rect :: struct {f: int;} + +@foreign +stbtt__buf :: struct { + data: *uchar; + cursor: int; + size: int; +} + +@foreign +stbtt_bakedchar :: struct { + x0: ushort; + y0: ushort; + x1: ushort; + y1: ushort; + xoff: float; + yoff: float; + xadvance: float; +} + +@foreign stbtt_BakeFontBitmap :: proc(data: *uchar, offset: int, pixel_height: float, pixels: *uchar, pw: int, ph: int, first_char: int, num_chars: int, chardata: *stbtt_bakedchar): int; +@foreign +stbtt_aligned_quad :: struct { + x0: float; + y0: float; + s0: float; + t0: float; + x1: float; + y1: float; + s1: float; + t1: float; +} + +@foreign stbtt_GetBakedQuad :: proc(chardata: *stbtt_bakedchar, pw: int, ph: int, char_index: int, xpos: *float, ypos: *float, q: *stbtt_aligned_quad, opengl_fillrule: int); +@foreign stbtt_GetScaledFontVMetrics :: proc(fontdata: *uchar, index: int, size: float, ascent: *float, descent: *float, lineGap: *float); +@foreign +stbtt_packedchar :: struct { + x0: ushort; + y0: ushort; + x1: ushort; + y1: ushort; + xoff: float; + yoff: float; + xadvance: float; + xoff2: float; + yoff2: float; +} + +@foreign stbtt_PackBegin :: proc(spc: *stbtt_pack_context, pixels: *uchar, width: int, height: int, stride_in_bytes: int, padding: int, alloc_context: *void): int; +@foreign stbtt_PackEnd :: proc(spc: *stbtt_pack_context); +@foreign stbtt_PackFontRange :: proc(spc: *stbtt_pack_context, fontdata: *uchar, font_index: int, font_size: float, first_unicode_char_in_range: int, num_chars_in_range: int, chardata_for_range: *stbtt_packedchar): int; +@foreign +stbtt_pack_range :: struct { + font_size: float; + first_unicode_codepoint_in_range: int; + array_of_unicode_codepoints: *int; + num_chars: int; + chardata_for_range: *stbtt_packedchar; + h_oversample: uchar; + v_oversample: uchar; +} + +@foreign stbtt_PackFontRanges :: proc(spc: *stbtt_pack_context, fontdata: *uchar, font_index: int, ranges: *stbtt_pack_range, num_ranges: int): int; +@foreign stbtt_PackSetOversampling :: proc(spc: *stbtt_pack_context, h_oversample: uint, v_oversample: uint); +@foreign stbtt_PackSetSkipMissingCodepoints :: proc(spc: *stbtt_pack_context, skip: int); +@foreign stbtt_GetPackedQuad :: proc(chardata: *stbtt_packedchar, pw: int, ph: int, char_index: int, xpos: *float, ypos: *float, q: *stbtt_aligned_quad, align_to_integer: int); +@foreign stbtt_PackFontRangesGatherRects :: proc(spc: *stbtt_pack_context, info: *stbtt_fontinfo, ranges: *stbtt_pack_range, num_ranges: int, rects: *stbrp_rect): int; +@foreign stbtt_PackFontRangesPackRects :: proc(spc: *stbtt_pack_context, rects: *stbrp_rect, num_rects: int); +@foreign stbtt_PackFontRangesRenderIntoRects :: proc(spc: *stbtt_pack_context, info: *stbtt_fontinfo, ranges: *stbtt_pack_range, num_ranges: int, rects: *stbrp_rect): int; +@foreign +stbtt_pack_context :: struct { + user_allocator_context: *void; + pack_info: *void; + width: int; + height: int; + stride_in_bytes: int; + padding: int; + skip_missing: int; + h_oversample: uint; + v_oversample: uint; + pixels: *uchar; + nodes: *void; +} + +@foreign stbtt_GetNumberOfFonts :: proc(data: *uchar): int; +@foreign stbtt_GetFontOffsetForIndex :: proc(data: *uchar, index: int): int; +@foreign +stbtt_fontinfo :: struct { + userdata: *void; + data: *uchar; + fontstart: int; + numGlyphs: int; + loca: int; + head: int; + glyf: int; + hhea: int; + hmtx: int; + kern: int; + gpos: int; + svg: int; + index_map: int; + indexToLocFormat: int; + cff: stbtt__buf; + charstrings: stbtt__buf; + gsubrs: stbtt__buf; + subrs: stbtt__buf; + fontdicts: stbtt__buf; + fdselect: stbtt__buf; +} + +@foreign stbtt_InitFont :: proc(info: *stbtt_fontinfo, data: *uchar, offset: int): int; +@foreign stbtt_FindGlyphIndex :: proc(info: *stbtt_fontinfo, unicode_codepoint: int): int; +@foreign stbtt_ScaleForPixelHeight :: proc(info: *stbtt_fontinfo, pixels: float): float; +@foreign stbtt_ScaleForMappingEmToPixels :: proc(info: *stbtt_fontinfo, pixels: float): float; +@foreign stbtt_GetFontVMetrics :: proc(info: *stbtt_fontinfo, ascent: *int, descent: *int, lineGap: *int); +@foreign stbtt_GetFontVMetricsOS2 :: proc(info: *stbtt_fontinfo, typoAscent: *int, typoDescent: *int, typoLineGap: *int): int; +@foreign stbtt_GetFontBoundingBox :: proc(info: *stbtt_fontinfo, x0: *int, y0: *int, x1: *int, y1: *int); +@foreign stbtt_GetCodepointHMetrics :: proc(info: *stbtt_fontinfo, codepoint: int, advanceWidth: *int, leftSideBearing: *int); +@foreign stbtt_GetCodepointKernAdvance :: proc(info: *stbtt_fontinfo, ch1: int, ch2: int): int; +@foreign stbtt_GetCodepointBox :: proc(info: *stbtt_fontinfo, codepoint: int, x0: *int, y0: *int, x1: *int, y1: *int): int; +@foreign stbtt_GetGlyphHMetrics :: proc(info: *stbtt_fontinfo, glyph_index: int, advanceWidth: *int, leftSideBearing: *int); +@foreign stbtt_GetGlyphKernAdvance :: proc(info: *stbtt_fontinfo, glyph1: int, glyph2: int): int; +@foreign stbtt_GetGlyphBox :: proc(info: *stbtt_fontinfo, glyph_index: int, x0: *int, y0: *int, x1: *int, y1: *int): int; +@foreign +stbtt_kerningentry :: struct { + glyph1: int; + glyph2: int; + advance: int; +} + +@foreign stbtt_GetKerningTableLength :: proc(info: *stbtt_fontinfo): int; +@foreign stbtt_GetKerningTable :: proc(info: *stbtt_fontinfo, table: *stbtt_kerningentry, table_length: int): int; +@foreign +stbtt_vertex :: struct { + x: short; + y: short; + cx: short; + cy: short; + cx1: short; + cy1: short; + type: uchar; + padding: uchar; +} + +@foreign stbtt_IsGlyphEmpty :: proc(info: *stbtt_fontinfo, glyph_index: int): int; +@foreign stbtt_GetCodepointShape :: proc(info: *stbtt_fontinfo, unicode_codepoint: int, vertices: **stbtt_vertex): int; +@foreign stbtt_GetGlyphShape :: proc(info: *stbtt_fontinfo, glyph_index: int, vertices: **stbtt_vertex): int; +@foreign stbtt_FreeShape :: proc(info: *stbtt_fontinfo, vertices: *stbtt_vertex); +@foreign stbtt_FindSVGDoc :: proc(info: *stbtt_fontinfo, gl: int): *uchar; +@foreign stbtt_GetCodepointSVG :: proc(info: *stbtt_fontinfo, unicode_codepoint: int, svg: **char): int; +@foreign stbtt_GetGlyphSVG :: proc(info: *stbtt_fontinfo, gl: int, svg: **char): int; +@foreign stbtt_FreeBitmap :: proc(bitmap: *uchar, userdata: *void); +@foreign stbtt_GetCodepointBitmap :: proc(info: *stbtt_fontinfo, scale_x: float, scale_y: float, codepoint: int, width: *int, height: *int, xoff: *int, yoff: *int): *uchar; +@foreign stbtt_GetCodepointBitmapSubpixel :: proc(info: *stbtt_fontinfo, scale_x: float, scale_y: float, shift_x: float, shift_y: float, codepoint: int, width: *int, height: *int, xoff: *int, yoff: *int): *uchar; +@foreign stbtt_MakeCodepointBitmap :: proc(info: *stbtt_fontinfo, output: *uchar, out_w: int, out_h: int, out_stride: int, scale_x: float, scale_y: float, codepoint: int); +@foreign stbtt_MakeCodepointBitmapSubpixel :: proc(info: *stbtt_fontinfo, output: *uchar, out_w: int, out_h: int, out_stride: int, scale_x: float, scale_y: float, shift_x: float, shift_y: float, codepoint: int); +@foreign stbtt_MakeCodepointBitmapSubpixelPrefilter :: proc(info: *stbtt_fontinfo, output: *uchar, out_w: int, out_h: int, out_stride: int, scale_x: float, scale_y: float, shift_x: float, shift_y: float, oversample_x: int, oversample_y: int, sub_x: *float, sub_y: *float, codepoint: int); +@foreign stbtt_GetCodepointBitmapBox :: proc(font: *stbtt_fontinfo, codepoint: int, scale_x: float, scale_y: float, ix0: *int, iy0: *int, ix1: *int, iy1: *int); +@foreign stbtt_GetCodepointBitmapBoxSubpixel :: proc(font: *stbtt_fontinfo, codepoint: int, scale_x: float, scale_y: float, shift_x: float, shift_y: float, ix0: *int, iy0: *int, ix1: *int, iy1: *int); +@foreign stbtt_GetGlyphBitmap :: proc(info: *stbtt_fontinfo, scale_x: float, scale_y: float, glyph: int, width: *int, height: *int, xoff: *int, yoff: *int): *uchar; +@foreign stbtt_GetGlyphBitmapSubpixel :: proc(info: *stbtt_fontinfo, scale_x: float, scale_y: float, shift_x: float, shift_y: float, glyph: int, width: *int, height: *int, xoff: *int, yoff: *int): *uchar; +@foreign stbtt_MakeGlyphBitmap :: proc(info: *stbtt_fontinfo, output: *uchar, out_w: int, out_h: int, out_stride: int, scale_x: float, scale_y: float, glyph: int); +@foreign stbtt_MakeGlyphBitmapSubpixel :: proc(info: *stbtt_fontinfo, output: *uchar, out_w: int, out_h: int, out_stride: int, scale_x: float, scale_y: float, shift_x: float, shift_y: float, glyph: int); +@foreign stbtt_MakeGlyphBitmapSubpixelPrefilter :: proc(info: *stbtt_fontinfo, output: *uchar, out_w: int, out_h: int, out_stride: int, scale_x: float, scale_y: float, shift_x: float, shift_y: float, oversample_x: int, oversample_y: int, sub_x: *float, sub_y: *float, glyph: int); +@foreign stbtt_GetGlyphBitmapBox :: proc(font: *stbtt_fontinfo, glyph: int, scale_x: float, scale_y: float, ix0: *int, iy0: *int, ix1: *int, iy1: *int); +@foreign stbtt_GetGlyphBitmapBoxSubpixel :: proc(font: *stbtt_fontinfo, glyph: int, scale_x: float, scale_y: float, shift_x: float, shift_y: float, ix0: *int, iy0: *int, ix1: *int, iy1: *int); +@foreign +stbtt__bitmap :: struct { + w: int; + h: int; + stride: int; + pixels: *uchar; +} + +@foreign stbtt_Rasterize :: proc(result: *stbtt__bitmap, flatness_in_pixels: float, vertices: *stbtt_vertex, num_verts: int, scale_x: float, scale_y: float, shift_x: float, shift_y: float, x_off: int, y_off: int, invert: int, userdata: *void); +@foreign stbtt_FreeSDF :: proc(bitmap: *uchar, userdata: *void); +@foreign stbtt_GetGlyphSDF :: proc(info: *stbtt_fontinfo, scale: float, glyph: int, padding: int, onedge_value: uchar, pixel_dist_scale: float, width: *int, height: *int, xoff: *int, yoff: *int): *uchar; +@foreign stbtt_GetCodepointSDF :: proc(info: *stbtt_fontinfo, scale: float, codepoint: int, padding: int, onedge_value: uchar, pixel_dist_scale: float, width: *int, height: *int, xoff: *int, yoff: *int): *uchar; +@foreign stbtt_FindMatchingFont :: proc(fontdata: *uchar, name: *char, flags: int): int; +@foreign stbtt_CompareUTF8toUTF16_bigendian :: proc(s1: *char, len1: int, s2: *char, len2: int): int; +@foreign stbtt_GetFontNameString :: proc(font: *stbtt_fontinfo, length: *int, platformID: int, encodingID: int, languageID: int, nameID: int): *char; \ No newline at end of file diff --git a/tests/example_ui_and_hot_reloading/dll/ui.lc b/tests/example_ui_and_hot_reloading/dll/ui.lc new file mode 100644 index 0000000..1956502 --- /dev/null +++ b/tests/example_ui_and_hot_reloading/dll/ui.lc @@ -0,0 +1,342 @@ +Ui: UI_State; + +UI_TextAlign :: typedef int; +UI_TextAlign_Center :: 0; +UI_TextAlign_CenterLeft :: ^; + + +UI_Layout :: struct { + rect: R2P; +} + +UI_Widget :: struct { + next: *UI_Widget; + id: u64; + last_touched_frame_index: u64; +} + +UI_Cut :: typedef int; +UI_Cut_Left :: 0; +UI_Cut_Right :: ^; +UI_Cut_Top :: ^; +UI_Cut_Bottom :: ^; + +UI_Style :: struct { + cut_size: V2; + text_align: UI_TextAlign; + scroll: V2; + absolute: bool; + absolute_rect: R2P; + button_background_color: V4; + hot_button_background_color: V4; + interacting_with_button_background_color: V4; + active_button_background_color: V4; + text_color: V4; + button_border_color: V4; + checked_checkbox_button_background_color: V4; + draw_text_shadow: bool; +} + +UI_BaseButtonDesc :: struct { + text: S8_String; + draw_text: bool; + draw_border: bool; + draw_background: bool; + use_checked_checkbox_button_background_colors: bool; +} + +UI_Result :: struct { + pressed: bool; + interacting_with: bool; + hot: bool; + drag: V2; +} + +UI_LayoutStack :: struct { + data: [256]UI_Layout; + len : i32; +} + +UI_State :: struct { + cut: UI_Cut; + s: UI_Style; // current style + base_style: UI_Style; + + // @todo: add stack id concept + cached_widgets: LC_Map; // @todo: add removing widgets at end of frame + layouts: UI_LayoutStack; + + font: *R_Font; + + hot: u64; + interacting_with: u64; + id: u64; + inside_begin_end_pair: bool; + + // next cut output + text_width: f32; + text_size: V2; +} + +UI_AddLayout :: proc(s: *UI_LayoutStack, layout: UI_Layout) { + if s.len + 1 > lengthof(s.data) { + IO_FatalErrorf("layout stack overflow reached max item count: %d", lengthof(s.data)); + } + + s.data[s.len] = layout; + s.len += 1; +} + +UI_GetLastLayout :: proc(s: *UI_LayoutStack): *UI_Layout { + if (s.len == 0) IO_FatalErrorf("error, trying to get last layout but there are none"); + + return &s.data[s.len - 1]; +} + +UI_Begin :: proc() { + IO_Assert(Ui.inside_begin_end_pair == false); + Ui.inside_begin_end_pair = true; + + IO_Assert(Ui.layouts.len == 0 || Ui.layouts.len == 1); + Ui.layouts.len = 0; + UI_AddLayout(&Ui.layouts, {R2P_SizeF(0, 0, :f32(Mu.window.size.x), :f32(Mu.window.size.y))}); + + UI_SetStyle(); +} + +UI_SetStyle :: proc() { + Ui.font = R.font; + Ui.base_style = { + cut_size = :V2{-1, Ui.font.size + 4}, + button_background_color = :V4{0, 0, 0, 1.0}, + text_color = :V4{1, 1, 1, 1}, + button_border_color = :V4{1, 1, 1, 1}, + checked_checkbox_button_background_color = :V4{0.5, 0.5, 0.5, 1.0}, + hot_button_background_color = :V4{0.5, 0, 0, 1}, + interacting_with_button_background_color = :V4{1.0, 0, 0, 1}, + active_button_background_color = :V4{1, 0, 0, 1}, + }; + Ui.s = Ui.base_style; +} + +UI_End :: proc() { + IO_Assert(Ui.inside_begin_end_pair); + Ui.inside_begin_end_pair = false; + + if (Mu.window.mouse.left.unpress) { + Ui.interacting_with = NULL; + } + Ui.hot = NULL; +} + +R_DrawBorder :: proc(r: R2P, color: V4) { + r = R2P_Shrink(r, 1); + R_Rect2D(R2P_CutLeft(&r, 1), R.atlas.white_texture_bounding_box, color); + R_Rect2D(R2P_CutRight(&r, 1), R.atlas.white_texture_bounding_box, color); + R_Rect2D(R2P_CutTop(&r, 1), R.atlas.white_texture_bounding_box, color); + R_Rect2D(R2P_CutBottom(&r, 1), R.atlas.white_texture_bounding_box, color); +} + +UI_GetNextRect :: proc(text: S8_String): R2P { + if (Ui.s.absolute) return Ui.s.absolute_rect; + l := UI_GetLastLayout(&Ui.layouts); + cut := Ui.s.cut_size; + font := Ui.font; + + if (text.len) { + Ui.text_width = R_GetTextSize(text); + Ui.text_size = :V2{Ui.text_width, font.ascent}; + } + + if (cut.x < 0) { + cut.x = Ui.text_width + 32; + if (cut.x < 0) { + cut.x = 32; + } + } + + if (cut.y < 0) { + cut.y = font.ascent; + } + + if (Ui.cut == UI_Cut_Top || Ui.cut == UI_Cut_Bottom) { + scroll_y := F32_Clamp(Ui.s.scroll.y, -cut.y, cut.y); + cut.y -= scroll_y; + Ui.s.scroll.y -= scroll_y; + } + + if (Ui.cut == UI_Cut_Left || Ui.cut == UI_Cut_Right) { + scrollx := F32_Clamp(Ui.s.scroll.x, -cut.x, cut.x); + cut.x -= scrollx; + Ui.s.scroll.x -= scrollx; + } + + if (Ui.cut == UI_Cut_Left) { + return R2P_CutLeft(&l.rect, cut.x); + } + if (Ui.cut == UI_Cut_Right) { + return R2P_CutRight(&l.rect, cut.x); + } + if (Ui.cut == UI_Cut_Top) { + return R2P_CutTop(&l.rect, cut.y); + } + if (Ui.cut == UI_Cut_Bottom) { + return R2P_CutBottom(&l.rect, cut.y); + } + IO_InvalidCodepath(); + return :R2P{}; +} + +UI_GetWidget :: proc(text: S8_String): *UI_Widget { + if (Ui.cached_widgets.allocator.p == NULL) { + Ui.cached_widgets.allocator = Perm.allocator; + } + + hash := HashBytes(text.str, :u64(text.len)); + widget: *UI_Widget = LC_MapGetU64(&Ui.cached_widgets, hash); + if (!widget) { + widget = MA_PushSize(Perm, :usize(sizeof(:UI_Widget))); + widget.id = hash; + LC_MapInsertU64(&Ui.cached_widgets, hash, widget); + } + IO_Assert(widget.id == hash); + widget.last_touched_frame_index = :u64(Mu.frame); + return widget; +} + +UI_BaseButton :: proc(desc: UI_BaseButtonDesc): UI_Result { + result: UI_Result; + rect := UI_GetNextRect(desc.text); + + mouse_pos: V2 = {:f32(Mu.window.mouse.pos.x), :f32(Mu.window.mouse.pos.y)}; + delta_mouse_pos: V2 = {:f32(Mu.window.mouse.delta_pos.x), :f32(Mu.window.mouse.delta_pos.y)}; + + if (rect.min.x == rect.max.x || rect.min.y == rect.max.y) { + return result; + } + + widget := UI_GetWidget(desc.text); + if (R2P_CollidesV2(rect, mouse_pos)) { + Ui.hot = widget.id; + } + + if (Ui.hot == widget.id) { + result.hot = true; + if (Mu.window.mouse.left.press) { + Ui.interacting_with = widget.id; + } + } + + if (Ui.interacting_with == widget.id) { + result.interacting_with = true; + result.drag = delta_mouse_pos; + if (Ui.hot == widget.id && Mu.window.mouse.left.unpress) { + result.pressed = true; + } + } + + text_pos := rect.min; + rect_size := R2P_GetSize(rect); + centered_text_pos := V2_Add(text_pos, V2_DivF(V2_Sub(rect_size, Ui.text_size), 2.0)); + if (Ui.s.text_align == UI_TextAlign_Center) { + text_pos = centered_text_pos; + } + if (Ui.s.text_align == UI_TextAlign_CenterLeft) { + text_pos.y = centered_text_pos.y; + text_pos.x += 4; + } + + button_background_color: V4 = Ui.s.button_background_color; + text_color: V4 = Ui.s.text_color; + button_border_color: V4 = Ui.s.button_border_color; + + if (desc.use_checked_checkbox_button_background_colors) { + button_background_color = Ui.s.checked_checkbox_button_background_color; + } + + if (Ui.hot == widget.id) { + button_background_color = Ui.s.hot_button_background_color; + } + if (Ui.interacting_with == widget.id) { + button_background_color = Ui.s.interacting_with_button_background_color; + } + if (result.pressed) { + button_background_color = Ui.s.active_button_background_color; + } + + if (desc.draw_background) { + R_Rect2D(rect, R.atlas.white_texture_bounding_box, button_background_color); + } + if (desc.draw_border) { + R_DrawBorder(rect, button_border_color); + } + if (desc.draw_text) { + if (Ui.s.draw_text_shadow) { + R_Text2D({ + text = desc.text, + color = R_ColorWhite, + pos = :V2{text_pos.x + 2, text_pos.y - 2}, + do_draw = true, + scale = 1.0, + }); + } + + R_DrawText(desc.text, text_pos, text_color); + } + + return result; +} + +UI_Button :: proc(str: *char): bool { + result := UI_BaseButton({ + text = S8_MakeFromChar(str), + draw_text = true, + draw_border = true, + draw_background = true, + }); + return result.pressed; +} + +UI_Checkbox :: proc(val: *bool, str: *char): bool { + result: UI_Result = UI_BaseButton({ + text = S8_MakeFromChar(str), + draw_text = true, + draw_border = true, + draw_background = true, + use_checked_checkbox_button_background_colors = *val, + }); + if (result.pressed) { + *val = !*val; + } + return *val; +} + +UI_Fill :: proc() { + rect := UI_GetNextRect(S8_MakeEmpty()); + R_Rect2D(rect, R.atlas.white_texture_bounding_box, Ui.s.button_background_color); + R_DrawBorder(rect, Ui.s.button_border_color); +} + +UI_PopStyle :: proc() { + Ui.s = Ui.base_style; +} + +UI_PopLayout :: proc() { + if Ui.layouts.len == 0 { + IO_FatalError("tryign to pop a layout but layout stack is empty"); + } + Ui.layouts.len -= 1; +} + +UI_PushLayout :: proc(rect_override: R2P): R2P { + rect: R2P; + if (rect_override.min.x != 0 || rect_override.min.y != 0 || rect_override.max.x != 0 || rect_override.max.y != 0) { + rect = rect_override; + } + else { + rect = UI_GetNextRect(S8_MakeEmpty()); + } + + UI_AddLayout(&Ui.layouts, {rect}); + return rect; +} diff --git a/tests/example_ui_and_hot_reloading/exe/exe_main.lc b/tests/example_ui_and_hot_reloading/exe/exe_main.lc new file mode 100644 index 0000000..3294da9 --- /dev/null +++ b/tests/example_ui_and_hot_reloading/exe/exe_main.lc @@ -0,0 +1,89 @@ +import "shared"; + +Mu: *MU_Context; +TempArena: MA_Arena; +Temp := &TempArena; + +@foreign RandomSeed :: struct { a: u64; } +@foreign GetRandomU64 :: proc(state: *RandomSeed): u64; + +LibraryHotLoad :: struct { + reload_count: int; + user_context: DLL_Context; + library: LIB_Library; + update_proc: LibraryUpdate; + last_write_time: i64; + seed: RandomSeed; + init_happened_on_this_frame: bool; +} + +ReloadUpdate :: proc(lib: *LibraryHotLoad) { + new_write_time := OS_GetFileModTime(S8_MakeFromChar("game.dll")); + if new_write_time == -1 || new_write_time == lib.last_write_time { + return; + } + + if lib.update_proc { + lib.update_proc(Unload, Mu, &lib.user_context); + lib.update_proc = nil; + } + + if (lib.seed.a == 0) lib.seed.a = 13; + random_value := GetRandomU64(&lib.seed); + out_filename_dll := S8_Format(Temp, "temp_%u.dll", random_value); + out_filename_pdb := S8_Format(Temp, "temp_%u.pdb", random_value); + OS_CopyFile(S8_MakeFromChar("game.dll"), out_filename_dll, true); + OS_CopyFile(S8_MakeFromChar("game.pdb"), out_filename_pdb, true); + + library := LIB_LoadLibrary(out_filename_dll.str); + if !library { + IO_Printf("Failed to load library %Q\n", out_filename_dll); + return; + } + + update_proc: LibraryUpdate = LIB_LoadSymbol(library, "APP_Update"); + if !library { + IO_Printf("Failed to load library %Q\n", out_filename_dll); + return; + } + + lib.library = library; + lib.update_proc = update_proc; + lib.last_write_time = new_write_time; + if lib.reload_count == 0 { + lib.update_proc(Init, Mu, &lib.user_context); + lib.init_happened_on_this_frame = true; + } + else { + lib.update_proc(Reload, Mu, &lib.user_context); + } + lib.reload_count += 1; +} + +CallUpdate :: proc(lib: *LibraryHotLoad) { + ReloadUpdate(lib); + if lib.update_proc && !lib.init_happened_on_this_frame { + lib.update_proc(Update, Mu, &lib.user_context); + } + lib.init_happened_on_this_frame = false; +} + +main :: proc(): int { + Mu = MU_Start({ + enable_opengl = true, + window = { + size = {1280, 720} + }, + delta_time = 0.0166666 + }); + + + lib: LibraryHotLoad = {user_context = {temp = Temp}}; + for MU_Update(Mu) { + CallUpdate(&lib); + if (Mu.window.key[MU_KEY_ESCAPE].down) { + MU_Quit(Mu); + } + } + return 0; +} \ No newline at end of file diff --git a/tests/example_ui_and_hot_reloading/shared/core.lc b/tests/example_ui_and_hot_reloading/shared/core.lc new file mode 100644 index 0000000..8ba5ec5 --- /dev/null +++ b/tests/example_ui_and_hot_reloading/shared/core.lc @@ -0,0 +1,557 @@ +#` + +#include "core/core.c" +#include "core/map.c" +`; +@foreign +UTF32_Result :: struct { + out_str: u32; + advance: int; + error: int; +} + +@foreign +UTF8_Result :: struct { + out_str: [4]u8; + len: int; + error: int; +} + +@foreign +UTF16_Result :: struct { + out_str: [2]u16; + len: int; + error: int; +} + +@foreign +UTF8_Iter :: struct { + str: *char; + len: int; + utf8_codepoint_byte_size: int; + i: int; + item: u32; +} + +@foreign UTF_ConvertUTF16ToUTF32 :: proc(c: *u16, max_advance: int): UTF32_Result; +@foreign UTF_ConvertUTF32ToUTF8 :: proc(codepoint: u32): UTF8_Result; +@foreign UTF_ConvertUTF8ToUTF32 :: proc(c: *char, max_advance: int): UTF32_Result; +@foreign UTF_ConvertUTF32ToUTF16 :: proc(codepoint: u32): UTF16_Result; +@foreign UTF_CreateCharFromWidechar :: proc(buffer: *char, buffer_size: i64, in: *wchar_t, inlen: i64): i64; +@foreign UTF_CreateWidecharFromChar :: proc(buffer: *wchar_t, buffer_size: i64, in: *char, inlen: i64): i64; +@foreign UTF8_Advance :: proc(iter: *UTF8_Iter); +@foreign UTF8_IterateEx :: proc(str: *char, len: int): UTF8_Iter; +@foreign UTF8_Iterate :: proc(str: *char): UTF8_Iter; +@foreign UTF_CreateStringFromWidechar :: proc(arena: *MA_Arena, wstr: *wchar_t, wsize: i64): S8_String; + +@foreign +IO_ErrorResult :: typedef int; +IO_ErrorResult_Continue :: 0; +IO_ErrorResult_Break :: ^; +IO_ErrorResult_Exit :: ^; + +@foreign IO_Printf :: proc(msg: *char, ...); +@foreign IO_Print :: proc(msg: *char); +@foreign IO_OutputMessage :: proc(str: *char, len: int); +@foreign IO_OutputError :: proc(str: *char, len: int): IO_ErrorResult; +@foreign IO_Exit :: proc(error_code: int); +@foreign IO_IsDebuggerPresent :: proc(): bool; +@foreign +M_AllocatorOp :: typedef int; +M_AllocatorOp_Allocate :: 0; +M_AllocatorOp_Deallocate :: ^; + +@foreign M_AllocatorProc :: typedef proc(a: *void, b: M_AllocatorOp, c: *void, d: usize): *void; +@foreign +M_Allocator :: struct { + obj: *void; + p: proc(a: *void, b: M_AllocatorOp, c: *void, d: usize): *void; +} + +@foreign M_AllocNonZeroed :: proc(allocator: M_Allocator, size: usize): *void; +@foreign M_Alloc :: proc(allocator: M_Allocator, size: usize): *void; +@foreign M_AllocCopy :: proc(allocator: M_Allocator, p: *void, size: usize): *void; +@foreign M_Dealloc :: proc(allocator: M_Allocator, p: *void); +@foreign MA_AllocatorProc :: proc(allocator: M_Allocator, kind: M_AllocatorOp, p: *void, size: usize): *void; +@foreign M_GetSystemAllocator :: proc(): M_Allocator; +@foreign +MV_Memory :: struct { + commit: usize; + reserve: usize; + data: *u8; +} + +@foreign +MA_Arena :: struct { + allocator: M_Allocator; + memory: MV_Memory; + alignment: int; + saved_alignment: int; + len: usize; + packed_array_element_size: usize; + packed_array_begin: usize; +} + +@foreign +MA_Temp :: struct { + arena: *MA_Arena; + pos: usize; +} + +@foreign MA_MemoryZero :: proc(p: *void, size: usize); +@foreign MA_MemoryCopy :: proc(dst: *void, src: *void, size: usize); +@foreign MA_GetAlignOffset :: proc(size: usize, align: usize): usize; +@foreign MA_AlignUp :: proc(size: usize, align: usize): usize; +@foreign MA_AlignDown :: proc(size: usize, align: usize): usize; +@foreign MA_DeallocateStub :: proc(arena: *MA_Arena, p: *void); +@foreign MA_PopToPos :: proc(arena: *MA_Arena, pos: usize); +@foreign MA_PopSize :: proc(arena: *MA_Arena, size: usize): *void; +@foreign MA_DeallocateArena :: proc(arena: *MA_Arena); +@foreign MA_Reset :: proc(arena: *MA_Arena); +@foreign MA__BeginPackedArray :: proc(arena: *MA_Arena, element_size: usize): *void; +@foreign MA_EndPackedArray :: proc(arena: *MA_Arena): int; +@foreign MA_SetAlignment :: proc(arena: *MA_Arena, alignment: int); +@foreign MA_GetTop :: proc(a: *MA_Arena): *u8; +@foreign MA_PushSizeNonZeroed :: proc(a: *MA_Arena, size: usize): *void; +@foreign MA_PushSize :: proc(arena: *MA_Arena, size: usize): *void; +@foreign MA_Init :: proc(a: *MA_Arena, reserve: usize); +@foreign MA_Create :: proc(): MA_Arena; +@foreign MA_InitFromBuffer :: proc(arena: *MA_Arena, buffer: *void, size: usize); +@foreign MA_MakeFromBuffer :: proc(buffer: *void, size: usize): MA_Arena; +@foreign MA_PushStringCopy :: proc(arena: *MA_Arena, p: *char, size: usize): *char; +@foreign MA_PushCopy :: proc(arena: *MA_Arena, p: *void, size: usize): *void; +@foreign MA_IsPointerInside :: proc(arena: *MA_Arena, p: *void): bool; +@foreign MA_PushArena :: proc(arena: *MA_Arena, size: usize): MA_Arena; +@foreign MA_BeginTemp :: proc(arena: *MA_Arena): MA_Temp; +@foreign MA_EndTemp :: proc(checkpoint: MA_Temp); +@foreign MA_GetScratchEx :: proc(conflicts: **MA_Arena, conflict_count: int): MA_Temp; +@foreign MA_GetScratch :: proc(): MA_Temp; +@foreign MA_GetScratch1 :: proc(conflict: *MA_Arena): MA_Temp; +@foreign MV_Reserve :: proc(size: usize): MV_Memory; +@foreign MV_Commit :: proc(m: *MV_Memory, commit: usize): bool; +@foreign MV_Deallocate :: proc(m: *MV_Memory); +@foreign MV_DecommitPos :: proc(m: *MV_Memory, pos: usize): bool; +@foreign +S8_String :: struct { + str: *char; + len: i64; +} + +@foreign +S8_Node :: struct { + next: *S8_Node; + string: S8_String; +} + +@foreign +S8_List :: struct { + node_count: i64; + char_count: i64; + first: *S8_Node; + last: *S8_Node; +} + +@foreign S8_AreEqual :: proc(a: S8_String, b: S8_String, ignore_case: uint): bool; +@foreign S8_EndsWith :: proc(a: S8_String, end: S8_String, ignore_case: uint): bool; +@foreign S8_StartsWith :: proc(a: S8_String, start: S8_String, ignore_case: uint): bool; +@foreign S8_Make :: proc(str: *char, len: i64): S8_String; +@foreign S8_Copy :: proc(allocator: *MA_Arena, string: S8_String): S8_String; +@foreign S8_NormalizePath :: proc(s: S8_String); +@foreign S8_Chop :: proc(string: S8_String, len: i64): S8_String; +@foreign S8_Skip :: proc(string: S8_String, len: i64): S8_String; +@foreign S8_GetPostfix :: proc(string: S8_String, len: i64): S8_String; +@foreign S8_GetPrefix :: proc(string: S8_String, len: i64): S8_String; +@foreign S8_Slice :: proc(string: S8_String, first_index: i64, one_past_last_index: i64): S8_String; +@foreign S8_Trim :: proc(string: S8_String): S8_String; +@foreign S8_TrimEnd :: proc(string: S8_String): S8_String; +@foreign S8_ToLowerCase :: proc(allocator: *MA_Arena, s: S8_String): S8_String; +@foreign S8_ToUpperCase :: proc(allocator: *MA_Arena, s: S8_String): S8_String; +@foreign S8_Find :: proc(string: S8_String, find: S8_String, flags: uint, index_out: *i64): bool; +@foreign S8_Split :: proc(allocator: *MA_Arena, string: S8_String, find: S8_String, flags: uint): S8_List; +@foreign S8_MergeWithSeparator :: proc(allocator: *MA_Arena, list: S8_List, separator: S8_String): S8_String; +@foreign S8_Merge :: proc(allocator: *MA_Arena, list: S8_List): S8_String; +@foreign S8_ReplaceAll :: proc(allocator: *MA_Arena, string: S8_String, replace: S8_String, with: S8_String, flags: uint): S8_String; +@foreign S8_FindAll :: proc(allocator: *MA_Arena, string: S8_String, find: S8_String, flags: uint): S8_List; +@foreign S8_ChopLastSlash :: proc(s: S8_String): S8_String; +@foreign S8_ChopLastPeriod :: proc(s: S8_String): S8_String; +@foreign S8_SkipToLastSlash :: proc(s: S8_String): S8_String; +@foreign S8_SkipToLastPeriod :: proc(s: S8_String): S8_String; +@foreign S8_Length :: proc(string: *char): i64; +@foreign S8_WideLength :: proc(string: *wchar_t): i64; +@foreign S8_MakeFromChar :: proc(string: *char): S8_String; +@foreign S8_MakeEmpty :: proc(): S8_String; +@foreign S8_MakeEmptyList :: proc(): S8_List; +@foreign S8_FormatV :: proc(allocator: *MA_Arena, str: *char, args1: va_list): S8_String; +@foreign S8_Format :: proc(allocator: *MA_Arena, str: *char, ...): S8_String; +@foreign S8_CreateNode :: proc(allocator: *MA_Arena, string: S8_String): *S8_Node; +@foreign S8_ReplaceNodeString :: proc(list: *S8_List, node: *S8_Node, new_string: S8_String); +@foreign S8_AddExistingNode :: proc(list: *S8_List, node: *S8_Node); +@foreign S8_AddArray :: proc(allocator: *MA_Arena, list: *S8_List, array: **char, count: int); +@foreign S8_AddArrayWithPrefix :: proc(allocator: *MA_Arena, list: *S8_List, prefix: *char, array: **char, count: int); +@foreign S8_MakeList :: proc(allocator: *MA_Arena, a: S8_String): S8_List; +@foreign S8_CopyList :: proc(allocator: *MA_Arena, a: S8_List): S8_List; +@foreign S8_ConcatLists :: proc(allocator: *MA_Arena, a: S8_List, b: S8_List): S8_List; +@foreign S8_AddNode :: proc(allocator: *MA_Arena, list: *S8_List, string: S8_String): *S8_Node; +@foreign S8_AddF :: proc(allocator: *MA_Arena, list: *S8_List, str: *char, ...): S8_String; +@foreign +MU__Float2 :: struct { + x: float; + y: float; +} + +@foreign +MU__Int2 :: struct { + x: int; + y: int; +} + +@foreign MU_glGetProcAddress :: typedef proc(a: *char): *void; +@foreign +MU_Window_Params :: struct { + size: MU__Int2; + pos: MU__Int2; + title: *char; + enable_canvas: bool; + resizable: bool; + borderless: bool; + fps_cursor: bool; +} + +@foreign +MU_Params :: struct { + memory: *void; + cap: usize; + enable_opengl: bool; + opengl_major: int; + opengl_minor: int; + delta_time: double; + window: MU_Window_Params; + sound_callback: proc(a: *MU_Context, b: *u16, c: u32): void; +} + +@foreign +MU_Key_State :: struct { + down: bool; + press: bool; + unpress: bool; + raw_press: bool; +} + +@foreign +MU_Key :: typedef int; + MU_KEY_INVALID :: 0; + MU_KEY_ESCAPE :: ^; + MU_KEY_ENTER :: ^; + MU_KEY_TAB :: ^; + MU_KEY_BACKSPACE :: ^; + MU_KEY_INSERT :: ^; + MU_KEY_DELETE :: ^; + MU_KEY_RIGHT :: ^; + MU_KEY_LEFT :: ^; + MU_KEY_DOWN :: ^; + MU_KEY_UP :: ^; + MU_KEY_PAGE_UP :: ^; + MU_KEY_PAGE_DOWN :: ^; + MU_KEY_HOME :: ^; + MU_KEY_END :: ^; + MU_KEY_F1 :: ^; + MU_KEY_F2 :: ^; + MU_KEY_F3 :: ^; + MU_KEY_F4 :: ^; + MU_KEY_F5 :: ^; + MU_KEY_F6 :: ^; + MU_KEY_F7 :: ^; + MU_KEY_F8 :: ^; + MU_KEY_F9 :: ^; + MU_KEY_F10 :: ^; + MU_KEY_F11 :: ^; + MU_KEY_F12 :: ^; + MU_KEY_SPACE :: 32; + MU_KEY_APOSTROPHE :: 39; + MU_KEY_PLUS :: 43; + MU_KEY_COMMA :: 44; + MU_KEY_MINUS :: 45; + MU_KEY_PERIOD :: 46; + MU_KEY_SLASH :: 47; + MU_KEY_0 :: 48; + MU_KEY_1 :: 49; + MU_KEY_2 :: 50; + MU_KEY_3 :: 51; + MU_KEY_4 :: 52; + MU_KEY_5 :: 53; + MU_KEY_6 :: 54; + MU_KEY_7 :: 55; + MU_KEY_8 :: 56; + MU_KEY_9 :: 57; + MU_KEY_SEMICOLON :: 59; + MU_KEY_EQUAL :: 61; + MU_KEY_A :: 65; + MU_KEY_B :: 66; + MU_KEY_C :: 67; + MU_KEY_D :: 68; + MU_KEY_E :: 69; + MU_KEY_F :: 70; + MU_KEY_G :: 71; + MU_KEY_H :: 72; + MU_KEY_I :: 73; + MU_KEY_J :: 74; + MU_KEY_K :: 75; + MU_KEY_L :: 76; + MU_KEY_M :: 77; + MU_KEY_N :: 78; + MU_KEY_O :: 79; + MU_KEY_P :: 80; + MU_KEY_Q :: 81; + MU_KEY_R :: 82; + MU_KEY_S :: 83; + MU_KEY_T :: 84; + MU_KEY_U :: 85; + MU_KEY_V :: 86; + MU_KEY_W :: 87; + MU_KEY_X :: 88; + MU_KEY_Y :: 89; + MU_KEY_Z :: 90; + MU_KEY_LEFT_BRACKET :: 91; + MU_KEY_BACKSLASH :: 92; + MU_KEY_RIGHT_BRACKET :: 93; + MU_KEY_GRAVE_ACCENT :: 96; + MU_KEY_F13 :: ^; + MU_KEY_F14 :: ^; + MU_KEY_F15 :: ^; + MU_KEY_F16 :: ^; + MU_KEY_F17 :: ^; + MU_KEY_F18 :: ^; + MU_KEY_F19 :: ^; + MU_KEY_F20 :: ^; + MU_KEY_F21 :: ^; + MU_KEY_F22 :: ^; + MU_KEY_F23 :: ^; + MU_KEY_F24 :: ^; + MU_KEY_KP_0 :: ^; + MU_KEY_KP_1 :: ^; + MU_KEY_KP_2 :: ^; + MU_KEY_KP_3 :: ^; + MU_KEY_KP_4 :: ^; + MU_KEY_KP_5 :: ^; + MU_KEY_KP_6 :: ^; + MU_KEY_KP_7 :: ^; + MU_KEY_KP_8 :: ^; + MU_KEY_KP_9 :: ^; + MU_KEY_KP_DECIMAL :: ^; + MU_KEY_KP_DIVIDE :: ^; + MU_KEY_KP_MULTIPLY :: ^; + MU_KEY_KP_SUBTRACT :: ^; + MU_KEY_KP_ADD :: ^; + MU_KEY_KP_ENTER :: ^; + MU_KEY_LEFT_SHIFT :: ^; + MU_KEY_LEFT_CONTROL :: ^; + MU_KEY_LEFT_ALT :: ^; + MU_KEY_LEFT_SUPER :: ^; + MU_KEY_RIGHT_SHIFT :: ^; + MU_KEY_RIGHT_CONTROL :: ^; + MU_KEY_RIGHT_ALT :: ^; + MU_KEY_RIGHT_SUPER :: ^; + MU_KEY_CAPS_LOCK :: ^; + MU_KEY_SCROLL_LOCK :: ^; + MU_KEY_NUM_LOCK :: ^; + MU_KEY_PRINT_SCREEN :: ^; + MU_KEY_PAUSE :: ^; + MU_KEY_SHIFT :: ^; + MU_KEY_CONTROL :: ^; + MU_KEY_COUNT :: ^; + +@foreign +MU_Mouse_State :: struct { + pos: MU__Int2; + posf: MU__Float2; + delta_pos: MU__Int2; + delta_pos_normalized: MU__Float2; + left: MU_Key_State; + middle: MU_Key_State; + right: MU_Key_State; + delta_wheel: float; +} + +@foreign +MU_DroppedFile :: struct { + next: *MU_DroppedFile; + filename: *char; + filename_size: int; +} + +@foreign +MU_Arena :: struct { + memory: *char; + len: usize; + cap: usize; +} + +@foreign +MU_Window :: struct { + size: MU__Int2; + sizef: MU__Float2; + pos: MU__Int2; + posf: MU__Float2; + dpi_scale: float; + is_fullscreen: bool; + is_fps_mode: bool; + is_focused: bool; + change_cursor_on_mouse_hold: bool; + processed_events_this_frame: u64; + should_render: bool; + first_dropped_file: *MU_DroppedFile; + canvas: *u32; + canvas_enabled: bool; + mouse: MU_Mouse_State; + key: [140]MU_Key_State; + user_text32: [32]u32; + user_text32_count: int; + user_text8: [32]char; + user_text8_count: int; + next: *MU_Window; + handle: *void; + platform: *void; +} + +@foreign +MU_Time :: struct { + app_start: double; + frame_start: double; + update: double; + update_total: double; + delta: double; + deltaf: float; + total: double; + totalf: float; +} + +@foreign +MU_Sound :: struct { + initialized: bool; + samples_per_second: uint; + number_of_channels: uint; + bytes_per_sample: uint; + callback: proc(a: *MU_Context, b: *u16, c: u32): void; +} + +@foreign +MU_Context :: struct { + quit: bool; + sound: MU_Sound; + time: MU_Time; + first_frame: bool; + _MU_Update_count: int; + frame: usize; + consecutive_missed_frames: usize; + total_missed_frames: usize; + primary_monitor_size: MU__Int2; + opengl_initialized: bool; + opengl_major: int; + opengl_minor: int; + gl_get_proc_address: proc(a: *char): *void; + params: MU_Params; + window: *MU_Window; + all_windows: *MU_Window; + perm_arena: MU_Arena; + frame_arena: MU_Arena; + platform: *void; +} + +@foreign MU_Quit :: proc(mu: *MU_Context); +@foreign MU_DefaultSoundCallback :: proc(mu: *MU_Context, buffer: *u16, samples_to_fill: u32); +@foreign MU_GetTime :: proc(): double; +@foreign MU_ToggleFPSMode :: proc(window: *MU_Window); +@foreign MU_DisableFPSMode :: proc(window: *MU_Window); +@foreign MU_EnableFPSMode :: proc(window: *MU_Window); +@foreign MU_ToggleFullscreen :: proc(window: *MU_Window); +@foreign MU_Init :: proc(mu: *MU_Context, params: MU_Params, len: usize); +@foreign MU_AddWindow :: proc(mu: *MU_Context, params: MU_Window_Params): *MU_Window; +@foreign MU_InitWindow :: proc(mu: *MU_Context, window: *MU_Window, params: MU_Window_Params); +@foreign MU_Start :: proc(params: MU_Params): *MU_Context; +@foreign MU_Update :: proc(mu: *MU_Context): bool; +@foreign LIB_Library :: typedef *void; +@foreign LIB_LoadLibrary :: proc(str: *char): LIB_Library; +@foreign LIB_LoadSymbol :: proc(lib: LIB_Library, symbol: *char): *void; +@foreign LIB_UnloadLibrary :: proc(lib: LIB_Library): bool; +@foreign +CTX_Context :: struct { + heap: M_Allocator; + temp_alloc: M_Allocator; + perm_alloc: M_Allocator; + temp: *MA_Arena; + perm: *MA_Arena; + temporary_arena: MA_Arena; + pernament_arena: MA_Arena; + user_context: *void; +} + +@foreign CTX_Init :: proc(); +@foreign +OS_Result :: typedef int; + OS_SUCCESS :: 0; + OS_ALREADY_EXISTS :: ^; + OS_PATH_NOT_FOUND :: ^; + OS_FAILURE :: ^; + +@foreign +OS_Date :: struct { + year: u32; + month: u32; + day: u32; + hour: u32; + minute: u32; + second: u32; + milliseconds: u32; +} + +@foreign OS_IsAbsolute :: proc(path: S8_String): bool; +@foreign OS_GetExePath :: proc(arena: *MA_Arena): S8_String; +@foreign OS_GetExeDir :: proc(arena: *MA_Arena): S8_String; +@foreign OS_GetWorkingDir :: proc(arena: *MA_Arena): S8_String; +@foreign OS_SetWorkingDir :: proc(path: S8_String); +@foreign OS_GetAbsolutePath :: proc(arena: *MA_Arena, relative: S8_String): S8_String; +@foreign OS_FileExists :: proc(path: S8_String): bool; +@foreign OS_IsDir :: proc(path: S8_String): bool; +@foreign OS_IsFile :: proc(path: S8_String): bool; +@foreign OS_GetTime :: proc(): double; +@foreign OS_ListDir :: proc(arena: *MA_Arena, path: S8_String, flags: uint): S8_List; +@foreign OS_MakeDir :: proc(path: S8_String): OS_Result; +@foreign OS_CopyFile :: proc(from: S8_String, to: S8_String, overwrite: bool): OS_Result; +@foreign OS_DeleteFile :: proc(path: S8_String): OS_Result; +@foreign OS_DeleteDir :: proc(path: S8_String, flags: uint): OS_Result; +@foreign OS_AppendFile :: proc(path: S8_String, string: S8_String): OS_Result; +@foreign OS_WriteFile :: proc(path: S8_String, string: S8_String): OS_Result; +@foreign OS_ReadFile :: proc(arena: *MA_Arena, path: S8_String): S8_String; +@foreign OS_SystemF :: proc(string: *char, ...): int; +@foreign OS_GetFileModTime :: proc(file: S8_String): i64; +@foreign OS_GetDate :: proc(): OS_Date; +@foreign S8_SplitOnRegex :: proc(arena: *MA_Arena, string: S8_String, regex: S8_String, flags: uint): S8_List; +@foreign OS_ListDirRegex :: proc(arena: *MA_Arena, path: S8_String, flags: uint, regex: *char): S8_List; +@foreign OS_ListDirRegexAsString :: proc(arena: *MA_Arena, path: S8_String, flags: uint, regex: *char): S8_String; +@foreign OS_ExpandIncludesList :: proc(arena: *MA_Arena, out: *S8_List, filepath: S8_String): bool; +@foreign OS_ExpandIncludes :: proc(arena: *MA_Arena, filepath: S8_String): S8_String; +@foreign +LC_MapEntry :: struct { + key: u64; + value: u64; +} + +@foreign +LC_Map :: struct { + allocator: M_Allocator; + entries: *LC_MapEntry; + cap: int; + len: int; +} + +@foreign LC_MapReserve :: proc(map: *LC_Map, size: int); +@foreign LC_GetMapEntryEx :: proc(map: *LC_Map, key: u64): *LC_MapEntry; +@foreign LC_InsertMapEntry :: proc(map: *LC_Map, key: u64, value: u64): *LC_MapEntry; +@foreign LC_GetMapEntry :: proc(map: *LC_Map, key: u64): *LC_MapEntry; +@foreign LC_MapInsert :: proc(map: *LC_Map, keystr: S8_String, value: *void); +@foreign LC_MapGet :: proc(map: *LC_Map, keystr: S8_String): *void; +@foreign LC_MapInsertU64 :: proc(map: *LC_Map, keystr: u64, value: *void); +@foreign LC_MapGetU64 :: proc(map: *LC_Map, keystr: u64): *void; +@foreign LC_MapGetP :: proc(map: *LC_Map, key: *void): *void; +@foreign LC_MapInsertP :: proc(map: *LC_Map, key: *void, value: *void); +@foreign Map_Insert2P :: proc(map: *LC_Map, key: *void, value: *void); diff --git a/tests/example_ui_and_hot_reloading/shared/events.lc b/tests/example_ui_and_hot_reloading/shared/events.lc new file mode 100644 index 0000000..1049ef1 --- /dev/null +++ b/tests/example_ui_and_hot_reloading/shared/events.lc @@ -0,0 +1,13 @@ +LibraryUpdate :: typedef proc(event: LibraryEvent, mu: *MU_Context, context: *DLL_Context); + +LibraryEvent :: typedef int; + Init :: 0; + Reload :: ^; + Unload :: ^; + Update :: ^; + +DLL_Context :: struct { + temp: *MA_Arena; + perm: MA_Arena; + context: *void; +} \ No newline at end of file diff --git a/tests/example_ui_and_hot_reloading/shared/windows_types.lc b/tests/example_ui_and_hot_reloading/shared/windows_types.lc new file mode 100644 index 0000000..bb66122 --- /dev/null +++ b/tests/example_ui_and_hot_reloading/shared/windows_types.lc @@ -0,0 +1,34 @@ +#`#include `; + +@foreign(int8_t) i8 :: typedef char; +@foreign(int16_t) i16 :: typedef short; +@foreign(int32_t) i32 :: typedef int; +@foreign(int64_t) i64 :: typedef llong; + +@foreign(uint8_t) u8 :: typedef uchar; +@foreign(uint16_t) u16 :: typedef ushort; +@foreign(uint32_t) u32 :: typedef uint; +@foreign(uint64_t) u64 :: typedef ullong; + +@foreign(size_t) usize :: typedef u64; +@foreign(intptr_t) isize :: typedef i64; +@foreign(intptr_t) intptr :: typedef i64; +@foreign(uintptr_t) uintptr :: typedef u64; + +@weak @foreign f32 :: typedef float; +@weak @foreign f64 :: typedef double; + +@foreign wchar_t :: typedef u16; +@foreign va_list :: typedef u64; + +NULL :: 0; + +@foreign UINT64_MAX: u64; +@foreign UINT32_MAX: u32; +@foreign UINT16_MAX: u16; +@foreign UINT8_MAX: u8; + +@foreign INT64_MAX: i64; +@foreign INT32_MAX: i32; +@foreign INT16_MAX: i16; +@foreign INT8_MAX: i8; diff --git a/tests/field_access.txt b/tests/field_access.txt new file mode 100644 index 0000000..60adc4c --- /dev/null +++ b/tests/field_access.txt @@ -0,0 +1,37 @@ +import "libc"; + +T :: struct { + a: int; + t2: T2; +} + +T2 :: struct { + b: int; +} + +T3 :: struct { + om: T; +} + +main :: proc(): int { + t: T; + a := t.a; @unused + b := (t).a; @unused + + i0 := :T{10}.a; + i1 := :T{}.t2.b; + i2 := :T{t2={1}}.t2; + + assert(i0 == 10); + assert(i1 == 0); + assert(i2.b == 1); + assert(t.t2.b == 0); + + i3: T3; + i3.om.a = 10; + i3.om.t2.b = 10; + + + + return 0; +} \ No newline at end of file diff --git a/tests/field_pointer_offset.txt b/tests/field_pointer_offset.txt new file mode 100644 index 0000000..962c860 --- /dev/null +++ b/tests/field_pointer_offset.txt @@ -0,0 +1,21 @@ +import "libc"; +Some_Struct :: struct { + i: *int; +} + +main :: proc(): int { + i: [4]int = {1, 2, 3, 4}; + s: Some_Struct = {i = addptr(i, 1)}; + + assert(s.i[0] == 2); + assert(s.i[-1] == 1); + assert(s.i[1] == 3); + + assert(addptr(s.i, 1)[0] == 3); + assert(*addptr(s.i, -1) == 1); + assert(addptr(s.i, -1)[0] == 1); + + + + return 0; +} \ No newline at end of file diff --git a/tests/for.txt b/tests/for.txt new file mode 100644 index 0000000..e181276 --- /dev/null +++ b/tests/for.txt @@ -0,0 +1,17 @@ +main :: proc(): int { + for i := 0; i < 4 { + i += 1; + } + + i := 0; + for i < 4; i += 1 { + // + } + + i = 0; + for i < 4 { + i += 1; + } + + return 0; +} \ No newline at end of file diff --git a/tests/for2.txt b/tests/for2.txt new file mode 100644 index 0000000..25a42a4 --- /dev/null +++ b/tests/for2.txt @@ -0,0 +1,12 @@ + +A :: struct { + a: int; +} + +main :: proc(): int { + result := 2; + for &:A{1} {result -= 1; break;} + for "asd" {result -= 1; break;} + + return result; +} \ No newline at end of file diff --git a/tests/fpointers.txt b/tests/fpointers.txt new file mode 100644 index 0000000..d0318f3 --- /dev/null +++ b/tests/fpointers.txt @@ -0,0 +1,66 @@ + +ValidProc :: proc(): int {return 1;} +ProcPointer: proc(): int = ValidProc; + +ProcT :: typedef proc(): int; @weak +ProcP: ProcT; + +main :: proc(): int { + ProcPointer = ValidProc; + ProcPointer = nil; + + ProcP = ValidProc; + ProcP = nil; + + v: *void; + ProcP = v; + ProcPointer = v; + + ProcP = nil; + + ProcPointer = ValidProc; + value := ProcPointer(); @unused + + ProcP = ValidProc; + ProcP(); + + v = ProcPointer; + ProcP = ProcPointer; + vv := :*void(ProcPointer); + + pv := :ProcT(vv); @unused + + pv2 := :proc(): int(vv); @unused + + a: *int; + b := :ProcT(a); @unused + + c := &ProcP; @unused + + return 0; +} + +FP :: typedef proc(i: int = 10); + +Thing :: struct { + fp: FP; + fp2: proc(i: int); +} + +glob0: FP; +glob1: proc(j: int); + +Another :: proc() { + thing: Thing; + thing.fp(); + thing.fp2(10); + + var0: FP; + var1: proc(j: int); + + var0(); + var1(j = 10); + + glob0(); + glob1(j = 10); +} \ No newline at end of file diff --git a/tests/implicit_compo_array_size.txt b/tests/implicit_compo_array_size.txt new file mode 100644 index 0000000..de22699 --- /dev/null +++ b/tests/implicit_compo_array_size.txt @@ -0,0 +1,16 @@ +import c "libc"; + +a: []int = {1, 2, 3, 4, 5}; +b: [6]int = {1, 2, 3, 4}; + + +main :: proc(): int { + local_a: []int = {1, 2, 3, 4, 5}; + local_b: [6]int = {1, 2, 3, 4}; + + c.assert(lengthof(a) == 5); + c.assert(lengthof(b) == 6); + c.assert(lengthof(local_a) == 5); + c.assert(lengthof(local_b) == 6); + return 0; +} \ No newline at end of file diff --git a/tests/import_libc.txt b/tests/import_libc.txt new file mode 100644 index 0000000..55d336a --- /dev/null +++ b/tests/import_libc.txt @@ -0,0 +1,9 @@ +// #failed: parse +// #error: no package with name +import "qweeeewewe"; + +main :: proc(): int { + a := malloc(32); + free(a); + return 0; +} \ No newline at end of file diff --git a/tests/import_libc/main/main.lc b/tests/import_libc/main/main.lc new file mode 100644 index 0000000..7bbe5bc --- /dev/null +++ b/tests/import_libc/main/main.lc @@ -0,0 +1,12 @@ +import "libc"; + +main :: proc(): int { + a := malloc(32); + free(a); + + s := sin(32.0); @unused + result := ceil(0.7); + result -= 1; + + return :int(result); +} \ No newline at end of file diff --git a/tests/import_libc2.txt b/tests/import_libc2.txt new file mode 100644 index 0000000..2dcb1dc --- /dev/null +++ b/tests/import_libc2.txt @@ -0,0 +1,7 @@ +import "libc"; + +main :: proc(): int { + a: *int = malloc(sizeof(:int)); + defer free(a); + return 0; +} \ No newline at end of file diff --git a/tests/invalid_note_name.txt b/tests/invalid_note_name.txt new file mode 100644 index 0000000..00d1ec5 --- /dev/null +++ b/tests/invalid_note_name.txt @@ -0,0 +1,18 @@ +// #failed: parse +// #error: unregistered note name: 'something' +// #error: unregistered note name: 'other' +// #error: unregistered note name: 'another' +// #error: unregistered note name: 'and_other' +// #error: unregistered note name: 'andd' + +#something; +@other +A :: proc() { +} + +#another; + +@and_other +@andd +B :: proc() { +} diff --git a/tests/labeled_breaks.txt b/tests/labeled_breaks.txt new file mode 100644 index 0000000..7bab7c4 --- /dev/null +++ b/tests/labeled_breaks.txt @@ -0,0 +1,40 @@ +import "libc"; +v: int; +p :: proc() { + for { + defer v += 1; + for { + defer v += 1; + { defer v += 1; return; } + } + } +} + +main :: proc(): int { + i := 0; + out: for { + defer i += 1; + in: for { + defer i += 1; + break out; + } + } + assert(i == 2); + + i = 0; + out1: for { + defer { i += 1; } + in1: for { + defer i += 1; + if (i < 2) continue out1; + if (i > 2) break in1; + } + break; + } + assert(i == 5); + + p(); + assert(v == 3); + + return 0; +} diff --git a/tests/lack_return.txt b/tests/lack_return.txt new file mode 100644 index 0000000..e619d34 --- /dev/null +++ b/tests/lack_return.txt @@ -0,0 +1,92 @@ +// #failed: resolve + +// #error: you can get through this procedure without hitting a return stmt +a :: proc(): int { + val := 10; + + { + if (val == 1) { + return 0; + } else if val == 2 { + val = 5; + } else { + val = 4; + } + } +} + +// #error: you can get through this procedure without hitting a return stmt +b :: proc(): int { + val := 10; + + { + if val == 10 { + if val == 10 { + return 0; + } + } else if val == 5 { + return 20; + } else { + return 0; + } + } +} + +// regression, error in return and we don't want to report the lack of return by accident +// #error: cannot assign void +c :: proc(): int { + for { + return; + } +} + +// #error: cannot assign void +d :: proc(): int { + val := 4; + if val { + return; + } +} + +// #error: you can get through this procedure without hitting a return stmt +e :: proc(): int { + val := false; + for { + if val { + return 10; + } + } + + if val { + } + else { + return 10; + } +} + +f :: proc(): int { + switch 4 { + case 1: return 0; + default: return 0; + } +} + +// #error: you can get through this procedure without hitting a return stmt +g :: proc(): int { + val := 4; + switch val { + case 1: return 0; + case 2: return 0; + case 3: return 0; + } +} + +h :: proc(): int { + val := 4; + switch val { + case 1: return 0; + case 2: return 0; + case 3: return 0; + default: return 0; + } +} \ No newline at end of file diff --git a/tests/large_values.txt b/tests/large_values.txt new file mode 100644 index 0000000..21771b6 --- /dev/null +++ b/tests/large_values.txt @@ -0,0 +1,12 @@ +import "libc"; +VAL :: -9223372036854775800; +AFTER_VAL :: ^; + +main :: proc(): int { + #static_assert(VAL == -9223372036854775800); + const_value: llong = -9223372036854775800; + enum_value: llong = VAL; + assert(const_value == enum_value); + assert(AFTER_VAL == const_value + 1); + return 0; +} \ No newline at end of file diff --git a/tests/literals.txt b/tests/literals.txt new file mode 100644 index 0000000..f70bd62 --- /dev/null +++ b/tests/literals.txt @@ -0,0 +1,94 @@ +import "libc"; + +main :: proc(argc: int @unused, argv: **char @unused): int { + { + i: int; + j0 := &i; @unused + j1 := :ullong(&i); @unused + } + + { + b := 0 && 1; @unused + } + + { + d := 20.0 + 40; + assert(d == 60.0); + e: float = 20; @unused + c: float = 10 + 20; + assert(c == :float(30)); + assert(d == :double(60.0)); + assert(:int(d) == :int(60.0)); + assert(:int(d) == 60); + assert(:uint(-1) > 1000000); + f: float; + assert(f == 0.0); + assert(:double(f) == 0); + } + + { + c := !1; + assert(typeof(c) == typeof(:bool)); + } + + { + a: int = 10; + b: double = 10; + assert(:int(b) == a); + assert(:double(a) == b); + assert(a == 10*true); + assert(a != 0); + } + + { + assert(10.0 == 10); + assert(10.0 != 9.0); + assert(10.0 != 9); + } + + { + assert(:uint(1) == 1); + assert(:uint(-1) != 1); + c: uchar = :uchar(-1); + assert(c == 255); + a: ushort = :ushort(-1); + assert(a == :ushort(-1)); + assert(:uint(a) != :uint(-1)); + assert(:int(a) != :int(-1)); + assert(:uint(:ushort(-1)) != :uint(-1)); + assert(:ullong(:uchar(-1)) != :ullong(-1)); + } + + { + a := :[]uchar{:uchar(-1), :uchar(-2), :uchar(-3)}; + first := 255; + for i: uchar = 0; i < lengthof(a); i += 1 { + assert(:uchar(first) - i == a[i]); + } + + assert(typeof(a[0]) == typeof(:uchar)); + } + + { + b: double = 10; + a := 10.0 == b; + assert(typeof(a) == typeof(:bool)); + } + + { + a: bool = true; + b := false; + assert(typeof(a) == typeof(b)); + } + + { + a :: 1 << 63; + U64MAX :: 0xffffffffffffffff; + assert(U64MAX == :ullong(-1)); + assert(a == :ullong(1) << 63); + } + + + + return 0; +} \ No newline at end of file diff --git a/tests/loops.txt b/tests/loops.txt new file mode 100644 index 0000000..99ceaf2 --- /dev/null +++ b/tests/loops.txt @@ -0,0 +1,46 @@ +import "libc"; + +main :: proc(): int { + i := 0; + + for { + if (i == 2) break; + i += 1; + } + assert(i == 2); + + for i = 0; i < 2; i += 1 { + + } + assert(i == 2); + + for ;i < 4; i += 1 {} + assert(i == 4); + + for i < 5 { + i += 1; + } + assert(i == 5); + + for ;;i += 1 { + if (i == 8) break; + } + assert(i == 8); + + for i = 0; i < 3 { + i += 1; + } + + for i = 4 { + assert(i == 4); + break; + } + assert(i == 4); + + for j := 4 { + assert(j == 4); + break; + } + + return 0; +} \ No newline at end of file diff --git a/tests/lvalues.txt b/tests/lvalues.txt new file mode 100644 index 0000000..853a2d0 --- /dev/null +++ b/tests/lvalues.txt @@ -0,0 +1,19 @@ +import "libc"; + +main :: proc(): int { + i4: llong = 4; + + p := &i4; + assert(*p == i4); + + *p -= 1; + *&i4 -= 1; + assert(*&i4 == 2); + + pp := &p; + **pp += 2; + assert(i4 == 4); + assert(**pp == 4); + + return 0; +} \ No newline at end of file diff --git a/tests/lvalues2.txt b/tests/lvalues2.txt new file mode 100644 index 0000000..14bcf8c --- /dev/null +++ b/tests/lvalues2.txt @@ -0,0 +1,5 @@ +// #failed: resolve +// #error: assigning value to a temporal object (lvalue) +f0 :: proc() { (1+1) = 2; } +// #error: assigning value to a temporal object (lvalue) +f1 :: proc() { 1+1 = 2; } diff --git a/tests/make_sure_to_try_resolving_all_imports_despite_errors/a/a.lc b/tests/make_sure_to_try_resolving_all_imports_despite_errors/a/a.lc new file mode 100644 index 0000000..42166d2 --- /dev/null +++ b/tests/make_sure_to_try_resolving_all_imports_despite_errors/a/a.lc @@ -0,0 +1,6 @@ +a :: proc(): int { + return 0; +} + +a :: proc() { +} \ No newline at end of file diff --git a/tests/make_sure_to_try_resolving_all_imports_despite_errors/b/b.lc b/tests/make_sure_to_try_resolving_all_imports_despite_errors/b/b.lc new file mode 100644 index 0000000..978ae6d --- /dev/null +++ b/tests/make_sure_to_try_resolving_all_imports_despite_errors/b/b.lc @@ -0,0 +1,3 @@ +import "b"; +b :: proc() { +} \ No newline at end of file diff --git a/tests/make_sure_to_try_resolving_all_imports_despite_errors/d_not_working/d.lc b/tests/make_sure_to_try_resolving_all_imports_despite_errors/d_not_working/d.lc new file mode 100644 index 0000000..0298913 --- /dev/null +++ b/tests/make_sure_to_try_resolving_all_imports_despite_errors/d_not_working/d.lc @@ -0,0 +1,2 @@ +d :: proc(): int { +} \ No newline at end of file diff --git a/tests/make_sure_to_try_resolving_all_imports_despite_errors/main/main.lc b/tests/make_sure_to_try_resolving_all_imports_despite_errors/main/main.lc new file mode 100644 index 0000000..48ffaa5 --- /dev/null +++ b/tests/make_sure_to_try_resolving_all_imports_despite_errors/main/main.lc @@ -0,0 +1,13 @@ +import "a"; +import "b"; +import "working"; +import "d_not_working"; + +a :: proc(): int { + return 0; +} + +should_not_report_undeclared_n :: proc(): int { + result := b(); + return result; +} \ No newline at end of file diff --git a/tests/make_sure_to_try_resolving_all_imports_despite_errors/test.txt b/tests/make_sure_to_try_resolving_all_imports_despite_errors/test.txt new file mode 100644 index 0000000..be40835 --- /dev/null +++ b/tests/make_sure_to_try_resolving_all_imports_despite_errors/test.txt @@ -0,0 +1,7 @@ +Idea behind this test is that we want to make sure all imports are looked into regardless of errors. + +// #failed: package +// #error: there are 2 decls +// #error: there are 2 decls +// #error: circular import +// #error: you can get through this procedure without \ No newline at end of file diff --git a/tests/make_sure_to_try_resolving_all_imports_despite_errors/working/c.lc b/tests/make_sure_to_try_resolving_all_imports_despite_errors/working/c.lc new file mode 100644 index 0000000..08d8db5 --- /dev/null +++ b/tests/make_sure_to_try_resolving_all_imports_despite_errors/working/c.lc @@ -0,0 +1,7 @@ +thing :: proc(): int { + return 0; +} + +not_thing :: proc(): int { + return 0; +} \ No newline at end of file diff --git a/tests/multiple_errors_in_same_struct.txt b/tests/multiple_errors_in_same_struct.txt new file mode 100644 index 0000000..7e6d1f2 --- /dev/null +++ b/tests/multiple_errors_in_same_struct.txt @@ -0,0 +1,19 @@ +// #failed: resolve +// #error: undeclared identifier 'asd' +// #error: undeclared identifier 'qwe' +// #error: undeclared identifier 'asd' +// #error: undeclared identifier 'totk' + +A :: struct { + a: asd; + b: qwe; + c: asd; + d: totk; +} + +// #error: duplicate field 'O' + +B :: struct { + O: int; + O: int; +} \ No newline at end of file diff --git a/tests/negate.txt b/tests/negate.txt new file mode 100644 index 0000000..5f7db82 --- /dev/null +++ b/tests/negate.txt @@ -0,0 +1,16 @@ +import "libc"; + +#static_assert(~4 | (1 << 37) == -5); + +main :: proc(): int { + {a: llong = ~1; + b := ~:llong(1); + assert(a == b);} + + {a: ullong = ~1; + b := ~:ullong(1); + assert(a == b);} + + return 0; +} + diff --git a/tests/nested_comments.txt b/tests/nested_comments.txt new file mode 100644 index 0000000..1de9c35 --- /dev/null +++ b/tests/nested_comments.txt @@ -0,0 +1,32 @@ + +/* Nesting 0 + /* Nesting 1 + + + */ + + /* Nesting 1 + /* Nesting 2 + + + */ + */ +*/ + +main :: proc(): int { + /* Nesting 0 + /* Nesting 1 + + + */ + + /* Nesting 1 + /* Nesting 2 + /* Nesting 3 */ + /* Nesting 3 */ + /* Nesting 3 */ + */ + */ + */ + return 0; +} \ No newline at end of file diff --git a/tests/new_get_pointer.txt b/tests/new_get_pointer.txt new file mode 100644 index 0000000..bba5138 --- /dev/null +++ b/tests/new_get_pointer.txt @@ -0,0 +1,9 @@ +main :: proc(): int { + i: int; + + a: [32]int; + b := addptr(a, 4); @unused + + val := i ^ i; @unused + return i; +} \ No newline at end of file diff --git a/tests/nil.txt b/tests/nil.txt new file mode 100644 index 0000000..e182cb0 --- /dev/null +++ b/tests/nil.txt @@ -0,0 +1,7 @@ +main :: proc(): int { + a: *int; + if a == nil { + return 0; + } + return 1; +} \ No newline at end of file diff --git a/tests/opengl_loader.txt b/tests/opengl_loader.txt new file mode 100644 index 0000000..f220a40 --- /dev/null +++ b/tests/opengl_loader.txt @@ -0,0 +1,3028 @@ +import "std_types"; +import "libc"; + +main :: proc(): int { + load_up_to(4, 5, :Set_Proc_Address_Type(set_proc_address_stub)); + return counter - 710; +} + +counter := 0; +set_proc_address_stub :: proc(p: **void, name: *char) { + counter += 1; +} + +// +// converted from: https://github.com/odin-lang/Odin +// + +loaded_up_to: [2]int; +loaded_up_to_major := 0; +loaded_up_to_minor := 0; + +Set_Proc_Address_Type :: typedef proc(p: **void, name: *char); + +load_up_to :: proc(major: int, minor: int, set_proc_address: Set_Proc_Address_Type) { + loaded_up_to = {major, minor}; + loaded_up_to_major = major; + loaded_up_to_minor = minor; + + switch major*10+minor { + case 46: { load_4_6(set_proc_address); } @fallthrough + case 45: { load_4_5(set_proc_address); } @fallthrough + case 44: { load_4_4(set_proc_address); } @fallthrough + case 43: { load_4_3(set_proc_address); } @fallthrough + case 42: { load_4_2(set_proc_address); } @fallthrough + case 41: { load_4_1(set_proc_address); } @fallthrough + case 40: { load_4_0(set_proc_address); } @fallthrough + case 33: { load_3_3(set_proc_address); } @fallthrough + case 32: { load_3_2(set_proc_address); } @fallthrough + case 31: { load_3_1(set_proc_address); } @fallthrough + case 30: { load_3_0(set_proc_address); } @fallthrough + case 21: { load_2_1(set_proc_address); } @fallthrough + case 20: { load_2_0(set_proc_address); } @fallthrough + case 15: { load_1_5(set_proc_address); } @fallthrough + case 14: { load_1_4(set_proc_address); } @fallthrough + case 13: { load_1_3(set_proc_address); } @fallthrough + case 12: { load_1_2(set_proc_address); } @fallthrough + case 11: { load_1_1(set_proc_address); } @fallthrough + case 10: { load_1_0(set_proc_address); } + } +} + +/* +Type conversion overview: + typedef unsigned int GLenum; : u32 + typedef unsigned char GLboolean;: bool + typedef unsigned int GLbitfield;: u32 + typedef signed char GLbyte; : i8 + typedef short GLshort; : i16 + typedef int GLint; : i32 + typedef unsigned char GLubyte; : u8 + typedef unsigned short GLushort;: u16 + typedef unsigned int GLuint; : u32 + typedef int GLsizei; : i32 + typedef float GLfloat; : f32 + typedef double GLdouble; : f64 + typedef char GLchar; : u8 + typedef ptrdiff_t GLintptr; : int + typedef ptrdiff_t GLsizeiptr; : int + typedef int64_t GLint64; : i64 + typedef uint64_t GLuint64; : u64 + + void* : *void +*/ + +sync_t :: typedef *void; +debug_proc_t :: typedef proc(source: u32, type: u32, id: u32, severity: u32, length: i32, message: *char, userParam: *void); @weak + + +GLfloat :: typedef float; +GLdouble :: typedef double; +GLchar :: typedef char; +GLenum :: typedef uint; +GLint :: typedef int; +GLuint :: typedef uint; +GLsizei :: typedef int; +GLboolean :: typedef uchar; +GLbitfield :: typedef uint; +GLvoid :: typedef void; +GLbyte :: typedef i8; +GLubyte :: typedef u8; +GLshort :: typedef i16; +GLushort :: typedef u16; + +GL_DEPTH_BUFFER_BIT :: 0x00000100; +GL_STENCIL_BUFFER_BIT :: 0x00000400; +GL_COLOR_BUFFER_BIT :: 0x00004000; +GL_FALSE :: 0; +GL_TRUE :: 1; +GL_POINTS :: 0x0000; +GL_LINES :: 0x0001; +GL_LINE_LOOP :: 0x0002; +GL_LINE_STRIP :: 0x0003; +GL_TRIANGLES :: 0x0004; +GL_TRIANGLE_STRIP :: 0x0005; +GL_TRIANGLE_FAN :: 0x0006; +GL_NEVER :: 0x0200; +GL_LESS :: 0x0201; +GL_EQUAL :: 0x0202; +GL_LEQUAL :: 0x0203; +GL_GREATER :: 0x0204; +GL_NOTEQUAL :: 0x0205; +GL_GEQUAL :: 0x0206; +GL_ALWAYS :: 0x0207; +GL_ZERO :: 0; +GL_ONE :: 1; +GL_SRC_COLOR :: 0x0300; +GL_ONE_MINUS_SRC_COLOR :: 0x0301; +GL_SRC_ALPHA :: 0x0302; +GL_ONE_MINUS_SRC_ALPHA :: 0x0303; +GL_DST_ALPHA :: 0x0304; +GL_ONE_MINUS_DST_ALPHA :: 0x0305; +GL_DST_COLOR :: 0x0306; +GL_ONE_MINUS_DST_COLOR :: 0x0307; +GL_SRC_ALPHA_SATURATE :: 0x0308; +GL_NONE :: 0; +GL_FRONT_LEFT :: 0x0400; +GL_FRONT_RIGHT :: 0x0401; +GL_BACK_LEFT :: 0x0402; +GL_BACK_RIGHT :: 0x0403; +GL_FRONT :: 0x0404; +GL_BACK :: 0x0405; +GL_LEFT :: 0x0406; +GL_RIGHT :: 0x0407; +GL_FRONT_AND_BACK :: 0x0408; +GL_NO_ERROR :: 0; +GL_INVALID_ENUM :: 0x0500; +GL_INVALID_VALUE :: 0x0501; +GL_INVALID_OPERATION :: 0x0502; +GL_OUT_OF_MEMORY :: 0x0505; +GL_CW :: 0x0900; +GL_CCW :: 0x0901; +GL_POINT_SIZE :: 0x0b11; +GL_POINT_SIZE_RANGE :: 0x0b12; +GL_POINT_SIZE_GRANULARITY :: 0x0b13; +GL_LINE_SMOOTH :: 0x0b20; +GL_LINE_WIDTH :: 0x0b21; +GL_LINE_WIDTH_RANGE :: 0x0b22; +GL_LINE_WIDTH_GRANULARITY :: 0x0b23; +GL_POLYGON_MODE :: 0x0b40; +GL_POLYGON_SMOOTH :: 0x0b41; +GL_CULL_FACE :: 0x0b44; +GL_CULL_FACE_MODE :: 0x0b45; +GL_FRONT_FACE :: 0x0b46; +GL_DEPTH_RANGE :: 0x0b70; +GL_DEPTH_TEST :: 0x0b71; +GL_DEPTH_WRITEMASK :: 0x0b72; +GL_DEPTH_CLEAR_VALUE :: 0x0b73; +GL_DEPTH_FUNC :: 0x0b74; +GL_STENCIL_TEST :: 0x0b90; +GL_STENCIL_CLEAR_VALUE :: 0x0b91; +GL_STENCIL_FUNC :: 0x0b92; +GL_STENCIL_VALUE_MASK :: 0x0b93; +GL_STENCIL_FAIL :: 0x0b94; +GL_STENCIL_PASS_DEPTH_FAIL :: 0x0b95; +GL_STENCIL_PASS_DEPTH_PASS :: 0x0b96; +GL_STENCIL_REF :: 0x0b97; +GL_STENCIL_WRITEMASK :: 0x0b98; +GL_VIEWPORT :: 0x0ba2; +GL_DITHER :: 0x0bd0; +GL_BLEND_DST :: 0x0be0; +GL_BLEND_SRC :: 0x0be1; +GL_BLEND :: 0x0be2; +GL_LOGIC_OP_MODE :: 0x0bf0; +GL_DRAW_BUFFER :: 0x0c01; +GL_READ_BUFFER :: 0x0c02; +GL_SCISSOR_BOX :: 0x0c10; +GL_SCISSOR_TEST :: 0x0c11; +GL_COLOR_CLEAR_VALUE :: 0x0c22; +GL_COLOR_WRITEMASK :: 0x0c23; +GL_DOUBLEBUFFER :: 0x0c32; +GL_STEREO :: 0x0c33; +GL_LINE_SMOOTH_HINT :: 0x0c52; +GL_POLYGON_SMOOTH_HINT :: 0x0c53; +GL_UNPACK_SWAP_BYTES :: 0x0cf0; +GL_UNPACK_LSB_FIRST :: 0x0cf1; +GL_UNPACK_ROW_LENGTH :: 0x0cf2; +GL_UNPACK_SKIP_ROWS :: 0x0cf3; +GL_UNPACK_SKIP_PIXELS :: 0x0cf4; +GL_UNPACK_ALIGNMENT :: 0x0cf5; +GL_PACK_SWAP_BYTES :: 0x0d00; +GL_PACK_LSB_FIRST :: 0x0d01; +GL_PACK_ROW_LENGTH :: 0x0d02; +GL_PACK_SKIP_ROWS :: 0x0d03; +GL_PACK_SKIP_PIXELS :: 0x0d04; +GL_PACK_ALIGNMENT :: 0x0d05; +GL_MAX_TEXTURE_SIZE :: 0x0d33; +GL_MAX_VIEWPORT_DIMS :: 0x0d3a; +GL_SUBPIXEL_BITS :: 0x0d50; +GL_TEXTURE_1D :: 0x0de0; +GL_TEXTURE_2D :: 0x0de1; +GL_TEXTURE_WIDTH :: 0x1000; +GL_TEXTURE_HEIGHT :: 0x1001; +GL_TEXTURE_BORDER_COLOR :: 0x1004; +GL_DONT_CARE :: 0x1100; +GL_FASTEST :: 0x1101; +GL_NICEST :: 0x1102; +GL_BYTE :: 0x1400; +GL_UNSIGNED_BYTE :: 0x1401; +GL_SHORT :: 0x1402; +GL_UNSIGNED_SHORT :: 0x1403; +GL_INT :: 0x1404; +GL_UNSIGNED_INT :: 0x1405; +GL_FLOAT :: 0x1406; +GL_CLEAR :: 0x1500; +GL_AND :: 0x1501; +GL_AND_REVERSE :: 0x1502; +GL_COPY :: 0x1503; +GL_AND_INVERTED :: 0x1504; +GL_NOOP :: 0x1505; +GL_XOR :: 0x1506; +GL_OR :: 0x1507; +GL_NOR :: 0x1508; +GL_EQUIV :: 0x1509; +GL_INVERT :: 0x150a; +GL_OR_REVERSE :: 0x150b; +GL_COPY_INVERTED :: 0x150c; +GL_OR_INVERTED :: 0x150d; +GL_NAND :: 0x150e; +GL_SET :: 0x150f; +GL_TEXTURE :: 0x1702; +GL_COLOR :: 0x1800; +GL_DEPTH :: 0x1801; +GL_STENCIL :: 0x1802; +GL_STENCIL_INDEX :: 0x1901; +GL_DEPTH_COMPONENT :: 0x1902; +GL_RED :: 0x1903; +GL_GREEN :: 0x1904; +GL_BLUE :: 0x1905; +GL_ALPHA :: 0x1906; +GL_RGB :: 0x1907; +GL_RGBA :: 0x1908; +GL_POINT :: 0x1b00; +GL_LINE :: 0x1b01; +GL_FILL :: 0x1b02; +GL_KEEP :: 0x1e00; +GL_REPLACE :: 0x1e01; +GL_INCR :: 0x1e02; +GL_DECR :: 0x1e03; +GL_VENDOR :: 0x1f00; +GL_RENDERER :: 0x1f01; +GL_VERSION :: 0x1f02; +GL_EXTENSIONS :: 0x1f03; +GL_NEAREST :: 0x2600; +GL_LINEAR :: 0x2601; +GL_NEAREST_MIPMAP_NEAREST :: 0x2700; +GL_LINEAR_MIPMAP_NEAREST :: 0x2701; +GL_NEAREST_MIPMAP_LINEAR :: 0x2702; +GL_LINEAR_MIPMAP_LINEAR :: 0x2703; +GL_TEXTURE_MAG_FILTER :: 0x2800; +GL_TEXTURE_MIN_FILTER :: 0x2801; +GL_TEXTURE_WRAP_S :: 0x2802; +GL_TEXTURE_WRAP_T :: 0x2803; +GL_REPEAT :: 0x2901; +GL_COLOR_LOGIC_OP :: 0x0bf2; +GL_POLYGON_OFFSET_UNITS :: 0x2a00; +GL_POLYGON_OFFSET_POINT :: 0x2a01; +GL_POLYGON_OFFSET_LINE :: 0x2a02; +GL_POLYGON_OFFSET_FILL :: 0x8037; +GL_POLYGON_OFFSET_FACTOR :: 0x8038; +GL_TEXTURE_BINDING_1D :: 0x8068; +GL_TEXTURE_BINDING_2D :: 0x8069; +GL_TEXTURE_INTERNAL_FORMAT :: 0x1003; +GL_TEXTURE_RED_SIZE :: 0x805c; +GL_TEXTURE_GREEN_SIZE :: 0x805d; +GL_TEXTURE_BLUE_SIZE :: 0x805e; +GL_TEXTURE_ALPHA_SIZE :: 0x805f; +GL_DOUBLE :: 0x140a; +GL_PROXY_TEXTURE_1D :: 0x8063; +GL_PROXY_TEXTURE_2D :: 0x8064; +GL_R3_G3_B2 :: 0x2a10; +GL_RGB4 :: 0x804f; +GL_RGB5 :: 0x8050; +GL_RGB8 :: 0x8051; +GL_RGB10 :: 0x8052; +GL_RGB12 :: 0x8053; +GL_RGB16 :: 0x8054; +GL_RGBA2 :: 0x8055; +GL_RGBA4 :: 0x8056; +GL_RGB5_A1 :: 0x8057; +GL_RGBA8 :: 0x8058; +GL_RGB10_A2 :: 0x8059; +GL_RGBA12 :: 0x805a; +GL_RGBA16 :: 0x805b; +GL_UNSIGNED_BYTE_3_3_2 :: 0x8032; +GL_UNSIGNED_SHORT_4_4_4_4 :: 0x8033; +GL_UNSIGNED_SHORT_5_5_5_1 :: 0x8034; +GL_UNSIGNED_INT_8_8_8_8 :: 0x8035; +GL_UNSIGNED_INT_10_10_10_2 :: 0x8036; +GL_TEXTURE_BINDING_3D :: 0x806a; +GL_PACK_SKIP_IMAGES :: 0x806b; +GL_PACK_IMAGE_HEIGHT :: 0x806c; +GL_UNPACK_SKIP_IMAGES :: 0x806d; +GL_UNPACK_IMAGE_HEIGHT :: 0x806e; +GL_TEXTURE_3D :: 0x806f; +GL_PROXY_TEXTURE_3D :: 0x8070; +GL_TEXTURE_DEPTH :: 0x8071; +GL_TEXTURE_WRAP_R :: 0x8072; +GL_MAX_3D_TEXTURE_SIZE :: 0x8073; +GL_UNSIGNED_BYTE_2_3_3_REV :: 0x8362; +GL_UNSIGNED_SHORT_5_6_5 :: 0x8363; +GL_UNSIGNED_SHORT_5_6_5_REV :: 0x8364; +GL_UNSIGNED_SHORT_4_4_4_4_REV :: 0x8365; +GL_UNSIGNED_SHORT_1_5_5_5_REV :: 0x8366; +GL_UNSIGNED_INT_8_8_8_8_REV :: 0x8367; +GL_UNSIGNED_INT_2_10_10_10_REV :: 0x8368; +GL_BGR :: 0x80e0; +GL_BGRA :: 0x80e1; +GL_MAX_ELEMENTS_VERTICES :: 0x80e8; +GL_MAX_ELEMENTS_INDICES :: 0x80e9; +GL_CLAMP_TO_EDGE :: 0x812f; +GL_TEXTURE_MIN_LOD :: 0x813a; +GL_TEXTURE_MAX_LOD :: 0x813b; +GL_TEXTURE_BASE_LEVEL :: 0x813c; +GL_TEXTURE_MAX_LEVEL :: 0x813d; +GL_SMOOTH_POINT_SIZE_RANGE :: 0x0b12; +GL_SMOOTH_POINT_SIZE_GRANULARITY :: 0x0b13; +GL_SMOOTH_LINE_WIDTH_RANGE :: 0x0b22; +GL_SMOOTH_LINE_WIDTH_GRANULARITY :: 0x0b23; +GL_ALIASED_LINE_WIDTH_RANGE :: 0x846e; +GL_TEXTURE0 :: 0x84c0; +GL_TEXTURE1 :: 0x84c1; +GL_TEXTURE2 :: 0x84c2; +GL_TEXTURE3 :: 0x84c3; +GL_TEXTURE4 :: 0x84c4; +GL_TEXTURE5 :: 0x84c5; +GL_TEXTURE6 :: 0x84c6; +GL_TEXTURE7 :: 0x84c7; +GL_TEXTURE8 :: 0x84c8; +GL_TEXTURE9 :: 0x84c9; +GL_TEXTURE10 :: 0x84ca; +GL_TEXTURE11 :: 0x84cb; +GL_TEXTURE12 :: 0x84cc; +GL_TEXTURE13 :: 0x84cd; +GL_TEXTURE14 :: 0x84ce; +GL_TEXTURE15 :: 0x84cf; +GL_TEXTURE16 :: 0x84d0; +GL_TEXTURE17 :: 0x84d1; +GL_TEXTURE18 :: 0x84d2; +GL_TEXTURE19 :: 0x84d3; +GL_TEXTURE20 :: 0x84d4; +GL_TEXTURE21 :: 0x84d5; +GL_TEXTURE22 :: 0x84d6; +GL_TEXTURE23 :: 0x84d7; +GL_TEXTURE24 :: 0x84d8; +GL_TEXTURE25 :: 0x84d9; +GL_TEXTURE26 :: 0x84da; +GL_TEXTURE27 :: 0x84db; +GL_TEXTURE28 :: 0x84dc; +GL_TEXTURE29 :: 0x84dd; +GL_TEXTURE30 :: 0x84de; +GL_TEXTURE31 :: 0x84df; +GL_ACTIVE_TEXTURE :: 0x84e0; +GL_MULTISAMPLE :: 0x809d; +GL_SAMPLE_ALPHA_TO_COVERAGE :: 0x809e; +GL_SAMPLE_ALPHA_TO_ONE :: 0x809f; +GL_SAMPLE_COVERAGE :: 0x80a0; +GL_SAMPLE_BUFFERS :: 0x80a8; +GL_SAMPLES :: 0x80a9; +GL_SAMPLE_COVERAGE_VALUE :: 0x80aa; +GL_SAMPLE_COVERAGE_INVERT :: 0x80ab; +GL_TEXTURE_CUBE_MAP :: 0x8513; +GL_TEXTURE_BINDING_CUBE_MAP :: 0x8514; +GL_TEXTURE_CUBE_MAP_POSITIVE_X :: 0x8515; +GL_TEXTURE_CUBE_MAP_NEGATIVE_X :: 0x8516; +GL_TEXTURE_CUBE_MAP_POSITIVE_Y :: 0x8517; +GL_TEXTURE_CUBE_MAP_NEGATIVE_Y :: 0x8518; +GL_TEXTURE_CUBE_MAP_POSITIVE_Z :: 0x8519; +GL_TEXTURE_CUBE_MAP_NEGATIVE_Z :: 0x851a; +GL_PROXY_TEXTURE_CUBE_MAP :: 0x851b; +GL_MAX_CUBE_MAP_TEXTURE_SIZE :: 0x851c; +GL_COMPRESSED_RGB :: 0x84ed; +GL_COMPRESSED_RGBA :: 0x84ee; +GL_TEXTURE_COMPRESSION_HINT :: 0x84ef; +GL_TEXTURE_COMPRESSED_IMAGE_SIZE :: 0x86a0; +GL_TEXTURE_COMPRESSED :: 0x86a1; +GL_NUM_COMPRESSED_TEXTURE_FORMATS :: 0x86a2; +GL_COMPRESSED_TEXTURE_FORMATS :: 0x86a3; +GL_CLAMP_TO_BORDER :: 0x812d; +GL_BLEND_DST_RGB :: 0x80c8; +GL_BLEND_SRC_RGB :: 0x80c9; +GL_BLEND_DST_ALPHA :: 0x80ca; +GL_BLEND_SRC_ALPHA :: 0x80cb; +GL_POINT_FADE_THRESHOLD_SIZE :: 0x8128; +GL_DEPTH_COMPONENT16 :: 0x81a5; +GL_DEPTH_COMPONENT24 :: 0x81a6; +GL_DEPTH_COMPONENT32 :: 0x81a7; +GL_MIRRORED_REPEAT :: 0x8370; +GL_MAX_TEXTURE_LOD_BIAS :: 0x84fd; +GL_TEXTURE_LOD_BIAS :: 0x8501; +GL_INCR_WRAP :: 0x8507; +GL_DECR_WRAP :: 0x8508; +GL_TEXTURE_DEPTH_SIZE :: 0x884a; +GL_TEXTURE_COMPARE_MODE :: 0x884c; +GL_TEXTURE_COMPARE_FUNC :: 0x884d; +GL_BLEND_COLOR :: 0x8005; +GL_BLEND_EQUATION :: 0x8009; +GL_CONSTANT_COLOR :: 0x8001; +GL_ONE_MINUS_CONSTANT_COLOR :: 0x8002; +GL_CONSTANT_ALPHA :: 0x8003; +GL_ONE_MINUS_CONSTANT_ALPHA :: 0x8004; +GL_FUNC_ADD :: 0x8006; +GL_FUNC_REVERSE_SUBTRACT :: 0x800b; +GL_FUNC_SUBTRACT :: 0x800a; +GL_MIN :: 0x8007; +GL_MAX :: 0x8008; +GL_BUFFER_SIZE :: 0x8764; +GL_BUFFER_USAGE :: 0x8765; +GL_QUERY_COUNTER_BITS :: 0x8864; +GL_CURRENT_QUERY :: 0x8865; +GL_QUERY_RESULT :: 0x8866; +GL_QUERY_RESULT_AVAILABLE :: 0x8867; +GL_ARRAY_BUFFER :: 0x8892; +GL_ELEMENT_ARRAY_BUFFER :: 0x8893; +GL_ARRAY_BUFFER_BINDING :: 0x8894; +GL_ELEMENT_ARRAY_BUFFER_BINDING :: 0x8895; +GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING :: 0x889f; +GL_READ_ONLY :: 0x88b8; +GL_WRITE_ONLY :: 0x88b9; +GL_READ_WRITE :: 0x88ba; +GL_BUFFER_ACCESS :: 0x88bb; +GL_BUFFER_MAPPED :: 0x88bc; +GL_BUFFER_MAP_POINTER :: 0x88bd; +GL_STREAM_DRAW :: 0x88e0; +GL_STREAM_READ :: 0x88e1; +GL_STREAM_COPY :: 0x88e2; +GL_STATIC_DRAW :: 0x88e4; +GL_STATIC_READ :: 0x88e5; +GL_STATIC_COPY :: 0x88e6; +GL_DYNAMIC_DRAW :: 0x88e8; +GL_DYNAMIC_READ :: 0x88e9; +GL_DYNAMIC_COPY :: 0x88ea; +GL_SAMPLES_PASSED :: 0x8914; +GL_SRC1_ALPHA :: 0x8589; +GL_BLEND_EQUATION_RGB :: 0x8009; +GL_VERTEX_ATTRIB_ARRAY_ENABLED :: 0x8622; +GL_VERTEX_ATTRIB_ARRAY_SIZE :: 0x8623; +GL_VERTEX_ATTRIB_ARRAY_STRIDE :: 0x8624; +GL_VERTEX_ATTRIB_ARRAY_TYPE :: 0x8625; +GL_CURRENT_VERTEX_ATTRIB :: 0x8626; +GL_VERTEX_PROGRAM_POINT_SIZE :: 0x8642; +GL_VERTEX_ATTRIB_ARRAY_POINTER :: 0x8645; +GL_STENCIL_BACK_FUNC :: 0x8800; +GL_STENCIL_BACK_FAIL :: 0x8801; +GL_STENCIL_BACK_PASS_DEPTH_FAIL :: 0x8802; +GL_STENCIL_BACK_PASS_DEPTH_PASS :: 0x8803; +GL_MAX_DRAW_BUFFERS :: 0x8824; +GL_DRAW_BUFFER0 :: 0x8825; +GL_DRAW_BUFFER1 :: 0x8826; +GL_DRAW_BUFFER2 :: 0x8827; +GL_DRAW_BUFFER3 :: 0x8828; +GL_DRAW_BUFFER4 :: 0x8829; +GL_DRAW_BUFFER5 :: 0x882a; +GL_DRAW_BUFFER6 :: 0x882b; +GL_DRAW_BUFFER7 :: 0x882c; +GL_DRAW_BUFFER8 :: 0x882d; +GL_DRAW_BUFFER9 :: 0x882e; +GL_DRAW_BUFFER10 :: 0x882f; +GL_DRAW_BUFFER11 :: 0x8830; +GL_DRAW_BUFFER12 :: 0x8831; +GL_DRAW_BUFFER13 :: 0x8832; +GL_DRAW_BUFFER14 :: 0x8833; +GL_DRAW_BUFFER15 :: 0x8834; +GL_BLEND_EQUATION_ALPHA :: 0x883d; +GL_MAX_VERTEX_ATTRIBS :: 0x8869; +GL_VERTEX_ATTRIB_ARRAY_NORMALIZED :: 0x886a; +GL_MAX_TEXTURE_IMAGE_UNITS :: 0x8872; +GL_FRAGMENT_SHADER :: 0x8b30; +GL_VERTEX_SHADER :: 0x8b31; +GL_MAX_FRAGMENT_UNIFORM_COMPONENTS :: 0x8b49; +GL_MAX_VERTEX_UNIFORM_COMPONENTS :: 0x8b4a; +GL_MAX_VARYING_FLOATS :: 0x8b4b; +GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS :: 0x8b4c; +GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS :: 0x8b4d; +GL_SHADER_TYPE :: 0x8b4f; +GL_FLOAT_VEC2 :: 0x8b50; +GL_FLOAT_VEC3 :: 0x8b51; +GL_FLOAT_VEC4 :: 0x8b52; +GL_INT_VEC2 :: 0x8b53; +GL_INT_VEC3 :: 0x8b54; +GL_INT_VEC4 :: 0x8b55; +GL_BOOL :: 0x8b56; +GL_BOOL_VEC2 :: 0x8b57; +GL_BOOL_VEC3 :: 0x8b58; +GL_BOOL_VEC4 :: 0x8b59; +GL_FLOAT_MAT2 :: 0x8b5a; +GL_FLOAT_MAT3 :: 0x8b5b; +GL_FLOAT_MAT4 :: 0x8b5c; +GL_SAMPLER_1D :: 0x8b5d; +GL_SAMPLER_2D :: 0x8b5e; +GL_SAMPLER_3D :: 0x8b5f; +GL_SAMPLER_CUBE :: 0x8b60; +GL_SAMPLER_1D_SHADOW :: 0x8b61; +GL_SAMPLER_2D_SHADOW :: 0x8b62; +GL_DELETE_STATUS :: 0x8b80; +GL_COMPILE_STATUS :: 0x8b81; +GL_LINK_STATUS :: 0x8b82; +GL_VALIDATE_STATUS :: 0x8b83; +GL_INFO_LOG_LENGTH :: 0x8b84; +GL_ATTACHED_SHADERS :: 0x8b85; +GL_ACTIVE_UNIFORMS :: 0x8b86; +GL_ACTIVE_UNIFORM_MAX_LENGTH :: 0x8b87; +GL_SHADER_SOURCE_LENGTH :: 0x8b88; +GL_ACTIVE_ATTRIBUTES :: 0x8b89; +GL_ACTIVE_ATTRIBUTE_MAX_LENGTH :: 0x8b8a; +GL_FRAGMENT_SHADER_DERIVATIVE_HINT :: 0x8b8b; +GL_SHADING_LANGUAGE_VERSION :: 0x8b8c; +GL_CURRENT_PROGRAM :: 0x8b8d; +GL_POINT_SPRITE_COORD_ORIGIN :: 0x8ca0; +GL_LOWER_LEFT :: 0x8ca1; +GL_UPPER_LEFT :: 0x8ca2; +GL_STENCIL_BACK_REF :: 0x8ca3; +GL_STENCIL_BACK_VALUE_MASK :: 0x8ca4; +GL_STENCIL_BACK_WRITEMASK :: 0x8ca5; +GL_PIXEL_PACK_BUFFER :: 0x88eb; +GL_PIXEL_UNPACK_BUFFER :: 0x88ec; +GL_PIXEL_PACK_BUFFER_BINDING :: 0x88ed; +GL_PIXEL_UNPACK_BUFFER_BINDING :: 0x88ef; +GL_FLOAT_MAT2x3 :: 0x8b65; +GL_FLOAT_MAT2x4 :: 0x8b66; +GL_FLOAT_MAT3x2 :: 0x8b67; +GL_FLOAT_MAT3x4 :: 0x8b68; +GL_FLOAT_MAT4x2 :: 0x8b69; +GL_FLOAT_MAT4x3 :: 0x8b6a; +GL_SRGB :: 0x8c40; +GL_SRGB8 :: 0x8c41; +GL_SRGB_ALPHA :: 0x8c42; +GL_SRGB8_ALPHA8 :: 0x8c43; +GL_COMPRESSED_SRGB :: 0x8c48; +GL_COMPRESSED_SRGB_ALPHA :: 0x8c49; +GL_COMPARE_REF_TO_TEXTURE :: 0x884e; +GL_CLIP_DISTANCE0 :: 0x3000; +GL_CLIP_DISTANCE1 :: 0x3001; +GL_CLIP_DISTANCE2 :: 0x3002; +GL_CLIP_DISTANCE3 :: 0x3003; +GL_CLIP_DISTANCE4 :: 0x3004; +GL_CLIP_DISTANCE5 :: 0x3005; +GL_CLIP_DISTANCE6 :: 0x3006; +GL_CLIP_DISTANCE7 :: 0x3007; +GL_MAX_CLIP_DISTANCES :: 0x0d32; +GL_MAJOR_VERSION :: 0x821b; +GL_MINOR_VERSION :: 0x821c; +GL_NUM_EXTENSIONS :: 0x821d; +GL_CONTEXT_FLAGS :: 0x821e; +GL_COMPRESSED_RED :: 0x8225; +GL_COMPRESSED_RG :: 0x8226; +GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT :: 0x00000001; +GL_RGBA32F :: 0x8814; +GL_RGB32F :: 0x8815; +GL_RGBA16F :: 0x881a; +GL_RGB16F :: 0x881b; +GL_VERTEX_ATTRIB_ARRAY_INTEGER :: 0x88fd; +GL_MAX_ARRAY_TEXTURE_LAYERS :: 0x88ff; +GL_MIN_PROGRAM_TEXEL_OFFSET :: 0x8904; +GL_MAX_PROGRAM_TEXEL_OFFSET :: 0x8905; +GL_CLAMP_READ_COLOR :: 0x891c; +GL_FIXED_ONLY :: 0x891d; +GL_MAX_VARYING_COMPONENTS :: 0x8b4b; +GL_TEXTURE_1D_ARRAY :: 0x8c18; +GL_PROXY_TEXTURE_1D_ARRAY :: 0x8c19; +GL_TEXTURE_2D_ARRAY :: 0x8c1a; +GL_PROXY_TEXTURE_2D_ARRAY :: 0x8c1b; +GL_TEXTURE_BINDING_1D_ARRAY :: 0x8c1c; +GL_TEXTURE_BINDING_2D_ARRAY :: 0x8c1d; +GL_R11F_G11F_B10F :: 0x8c3a; +GL_UNSIGNED_INT_10F_11F_11F_REV :: 0x8c3b; +GL_RGB9_E5 :: 0x8c3d; +GL_UNSIGNED_INT_5_9_9_9_REV :: 0x8c3e; +GL_TEXTURE_SHARED_SIZE :: 0x8c3f; +GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH :: 0x8c76; +GL_TRANSFORM_FEEDBACK_BUFFER_MODE :: 0x8c7f; +GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS :: 0x8c80; +GL_TRANSFORM_FEEDBACK_VARYINGS :: 0x8c83; +GL_TRANSFORM_FEEDBACK_BUFFER_START :: 0x8c84; +GL_TRANSFORM_FEEDBACK_BUFFER_SIZE :: 0x8c85; +GL_PRIMITIVES_GENERATED :: 0x8c87; +GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN :: 0x8c88; +GL_RASTERIZER_DISCARD :: 0x8c89; +GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS :: 0x8c8a; +GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS :: 0x8c8b; +GL_INTERLEAVED_ATTRIBS :: 0x8c8c; +GL_SEPARATE_ATTRIBS :: 0x8c8d; +GL_TRANSFORM_FEEDBACK_BUFFER :: 0x8c8e; +GL_TRANSFORM_FEEDBACK_BUFFER_BINDING :: 0x8c8f; +GL_RGBA32UI :: 0x8d70; +GL_RGB32UI :: 0x8d71; +GL_RGBA16UI :: 0x8d76; +GL_RGB16UI :: 0x8d77; +GL_RGBA8UI :: 0x8d7c; +GL_RGB8UI :: 0x8d7d; +GL_RGBA32I :: 0x8d82; +GL_RGB32I :: 0x8d83; +GL_RGBA16I :: 0x8d88; +GL_RGB16I :: 0x8d89; +GL_RGBA8I :: 0x8d8e; +GL_RGB8I :: 0x8d8f; +GL_RED_INTEGER :: 0x8d94; +GL_GREEN_INTEGER :: 0x8d95; +GL_BLUE_INTEGER :: 0x8d96; +GL_RGB_INTEGER :: 0x8d98; +GL_RGBA_INTEGER :: 0x8d99; +GL_BGR_INTEGER :: 0x8d9a; +GL_BGRA_INTEGER :: 0x8d9b; +GL_SAMPLER_1D_ARRAY :: 0x8dc0; +GL_SAMPLER_2D_ARRAY :: 0x8dc1; +GL_SAMPLER_1D_ARRAY_SHADOW :: 0x8dc3; +GL_SAMPLER_2D_ARRAY_SHADOW :: 0x8dc4; +GL_SAMPLER_CUBE_SHADOW :: 0x8dc5; +GL_UNSIGNED_INT_VEC2 :: 0x8dc6; +GL_UNSIGNED_INT_VEC3 :: 0x8dc7; +GL_UNSIGNED_INT_VEC4 :: 0x8dc8; +GL_INT_SAMPLER_1D :: 0x8dc9; +GL_INT_SAMPLER_2D :: 0x8dca; +GL_INT_SAMPLER_3D :: 0x8dcb; +GL_INT_SAMPLER_CUBE :: 0x8dcc; +GL_INT_SAMPLER_1D_ARRAY :: 0x8dce; +GL_INT_SAMPLER_2D_ARRAY :: 0x8dcf; +GL_UNSIGNED_INT_SAMPLER_1D :: 0x8dd1; +GL_UNSIGNED_INT_SAMPLER_2D :: 0x8dd2; +GL_UNSIGNED_INT_SAMPLER_3D :: 0x8dd3; +GL_UNSIGNED_INT_SAMPLER_CUBE :: 0x8dd4; +GL_UNSIGNED_INT_SAMPLER_1D_ARRAY :: 0x8dd6; +GL_UNSIGNED_INT_SAMPLER_2D_ARRAY :: 0x8dd7; +GL_QUERY_WAIT :: 0x8e13; +GL_QUERY_NO_WAIT :: 0x8e14; +GL_QUERY_BY_REGION_WAIT :: 0x8e15; +GL_QUERY_BY_REGION_NO_WAIT :: 0x8e16; +GL_BUFFER_ACCESS_FLAGS :: 0x911f; +GL_BUFFER_MAP_LENGTH :: 0x9120; +GL_BUFFER_MAP_OFFSET :: 0x9121; +GL_DEPTH_COMPONENT32F :: 0x8cac; +GL_DEPTH32F_STENCIL8 :: 0x8cad; +GL_FLOAT_32_UNSIGNED_INT_24_8_REV :: 0x8dad; +GL_INVALID_FRAMEBUFFER_OPERATION :: 0x0506; +GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING :: 0x8210; +GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE :: 0x8211; +GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE :: 0x8212; +GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE :: 0x8213; +GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE :: 0x8214; +GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE :: 0x8215; +GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE :: 0x8216; +GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE :: 0x8217; +GL_FRAMEBUFFER_DEFAULT :: 0x8218; +GL_FRAMEBUFFER_UNDEFINED :: 0x8219; +GL_DEPTH_STENCIL_ATTACHMENT :: 0x821a; +GL_MAX_RENDERBUFFER_SIZE :: 0x84e8; +GL_DEPTH_STENCIL :: 0x84f9; +GL_UNSIGNED_INT_24_8 :: 0x84fa; +GL_DEPTH24_STENCIL8 :: 0x88f0; +GL_TEXTURE_STENCIL_SIZE :: 0x88f1; +GL_TEXTURE_RED_TYPE :: 0x8c10; +GL_TEXTURE_GREEN_TYPE :: 0x8c11; +GL_TEXTURE_BLUE_TYPE :: 0x8c12; +GL_TEXTURE_ALPHA_TYPE :: 0x8c13; +GL_TEXTURE_DEPTH_TYPE :: 0x8c16; +GL_UNSIGNED_NORMALIZED :: 0x8c17; +GL_FRAMEBUFFER_BINDING :: 0x8ca6; +GL_DRAW_FRAMEBUFFER_BINDING :: 0x8ca6; +GL_RENDERBUFFER_BINDING :: 0x8ca7; +GL_READ_FRAMEBUFFER :: 0x8ca8; +GL_DRAW_FRAMEBUFFER :: 0x8ca9; +GL_READ_FRAMEBUFFER_BINDING :: 0x8caa; +GL_RENDERBUFFER_SAMPLES :: 0x8cab; +GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE :: 0x8cd0; +GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME :: 0x8cd1; +GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL :: 0x8cd2; +GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE :: 0x8cd3; +GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER :: 0x8cd4; +GL_FRAMEBUFFER_COMPLETE :: 0x8cd5; +GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT :: 0x8cd6; +GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT :: 0x8cd7; +GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER :: 0x8cdb; +GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER :: 0x8cdc; +GL_FRAMEBUFFER_UNSUPPORTED :: 0x8cdd; +GL_MAX_COLOR_ATTACHMENTS :: 0x8cdf; +GL_COLOR_ATTACHMENT0 :: 0x8ce0; +GL_COLOR_ATTACHMENT1 :: 0x8ce1; +GL_COLOR_ATTACHMENT2 :: 0x8ce2; +GL_COLOR_ATTACHMENT3 :: 0x8ce3; +GL_COLOR_ATTACHMENT4 :: 0x8ce4; +GL_COLOR_ATTACHMENT5 :: 0x8ce5; +GL_COLOR_ATTACHMENT6 :: 0x8ce6; +GL_COLOR_ATTACHMENT7 :: 0x8ce7; +GL_COLOR_ATTACHMENT8 :: 0x8ce8; +GL_COLOR_ATTACHMENT9 :: 0x8ce9; +GL_COLOR_ATTACHMENT10 :: 0x8cea; +GL_COLOR_ATTACHMENT11 :: 0x8ceb; +GL_COLOR_ATTACHMENT12 :: 0x8cec; +GL_COLOR_ATTACHMENT13 :: 0x8ced; +GL_COLOR_ATTACHMENT14 :: 0x8cee; +GL_COLOR_ATTACHMENT15 :: 0x8cef; +GL_COLOR_ATTACHMENT16 :: 0x8cf0; +GL_COLOR_ATTACHMENT17 :: 0x8cf1; +GL_COLOR_ATTACHMENT18 :: 0x8cf2; +GL_COLOR_ATTACHMENT19 :: 0x8cf3; +GL_COLOR_ATTACHMENT20 :: 0x8cf4; +GL_COLOR_ATTACHMENT21 :: 0x8cf5; +GL_COLOR_ATTACHMENT22 :: 0x8cf6; +GL_COLOR_ATTACHMENT23 :: 0x8cf7; +GL_COLOR_ATTACHMENT24 :: 0x8cf8; +GL_COLOR_ATTACHMENT25 :: 0x8cf9; +GL_COLOR_ATTACHMENT26 :: 0x8cfa; +GL_COLOR_ATTACHMENT27 :: 0x8cfb; +GL_COLOR_ATTACHMENT28 :: 0x8cfc; +GL_COLOR_ATTACHMENT29 :: 0x8cfd; +GL_COLOR_ATTACHMENT30 :: 0x8cfe; +GL_COLOR_ATTACHMENT31 :: 0x8cff; +GL_DEPTH_ATTACHMENT :: 0x8d00; +GL_STENCIL_ATTACHMENT :: 0x8d20; +GL_FRAMEBUFFER :: 0x8d40; +GL_RENDERBUFFER :: 0x8d41; +GL_RENDERBUFFER_WIDTH :: 0x8d42; +GL_RENDERBUFFER_HEIGHT :: 0x8d43; +GL_RENDERBUFFER_INTERNAL_FORMAT :: 0x8d44; +GL_STENCIL_INDEX1 :: 0x8d46; +GL_STENCIL_INDEX4 :: 0x8d47; +GL_STENCIL_INDEX8 :: 0x8d48; +GL_STENCIL_INDEX16 :: 0x8d49; +GL_RENDERBUFFER_RED_SIZE :: 0x8d50; +GL_RENDERBUFFER_GREEN_SIZE :: 0x8d51; +GL_RENDERBUFFER_BLUE_SIZE :: 0x8d52; +GL_RENDERBUFFER_ALPHA_SIZE :: 0x8d53; +GL_RENDERBUFFER_DEPTH_SIZE :: 0x8d54; +GL_RENDERBUFFER_STENCIL_SIZE :: 0x8d55; +GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE :: 0x8d56; +GL_MAX_SAMPLES :: 0x8d57; +GL_FRAMEBUFFER_SRGB :: 0x8db9; +GL_HALF_FLOAT :: 0x140b; +GL_MAP_READ_BIT :: 0x0001; +GL_MAP_WRITE_BIT :: 0x0002; +GL_MAP_INVALIDATE_RANGE_BIT :: 0x0004; +GL_MAP_INVALIDATE_BUFFER_BIT :: 0x0008; +GL_MAP_FLUSH_EXPLICIT_BIT :: 0x0010; +GL_MAP_UNSYNCHRONIZED_BIT :: 0x0020; +GL_COMPRESSED_RED_RGTC1 :: 0x8dbb; +GL_COMPRESSED_SIGNED_RED_RGTC1 :: 0x8dbc; +GL_COMPRESSED_RG_RGTC2 :: 0x8dbd; +GL_COMPRESSED_SIGNED_RG_RGTC2 :: 0x8dbe; +GL_RG :: 0x8227; +GL_RG_INTEGER :: 0x8228; +GL_R8 :: 0x8229; +GL_R16 :: 0x822a; +GL_RG8 :: 0x822b; +GL_RG16 :: 0x822c; +GL_R16F :: 0x822d; +GL_R32F :: 0x822e; +GL_RG16F :: 0x822f; +GL_RG32F :: 0x8230; +GL_R8I :: 0x8231; +GL_R8UI :: 0x8232; +GL_R16I :: 0x8233; +GL_R16UI :: 0x8234; +GL_R32I :: 0x8235; +GL_R32UI :: 0x8236; +GL_RG8I :: 0x8237; +GL_RG8UI :: 0x8238; +GL_RG16I :: 0x8239; +GL_RG16UI :: 0x823a; +GL_RG32I :: 0x823b; +GL_RG32UI :: 0x823c; +GL_VERTEX_ARRAY_BINDING :: 0x85b5; +GL_SAMPLER_2D_RECT :: 0x8b63; +GL_SAMPLER_2D_RECT_SHADOW :: 0x8b64; +GL_SAMPLER_BUFFER :: 0x8dc2; +GL_INT_SAMPLER_2D_RECT :: 0x8dcd; +GL_INT_SAMPLER_BUFFER :: 0x8dd0; +GL_UNSIGNED_INT_SAMPLER_2D_RECT :: 0x8dd5; +GL_UNSIGNED_INT_SAMPLER_BUFFER :: 0x8dd8; +GL_TEXTURE_BUFFER :: 0x8c2a; +GL_MAX_TEXTURE_BUFFER_SIZE :: 0x8c2b; +GL_TEXTURE_BINDING_BUFFER :: 0x8c2c; +GL_TEXTURE_BUFFER_DATA_STORE_BINDING :: 0x8c2d; +GL_TEXTURE_RECTANGLE :: 0x84f5; +GL_TEXTURE_BINDING_RECTANGLE :: 0x84f6; +GL_PROXY_TEXTURE_RECTANGLE :: 0x84f7; +GL_MAX_RECTANGLE_TEXTURE_SIZE :: 0x84f8; +GL_R8_SNORM :: 0x8f94; +GL_RG8_SNORM :: 0x8f95; +GL_RGB8_SNORM :: 0x8f96; +GL_RGBA8_SNORM :: 0x8f97; +GL_R16_SNORM :: 0x8f98; +GL_RG16_SNORM :: 0x8f99; +GL_RGB16_SNORM :: 0x8f9a; +GL_RGBA16_SNORM :: 0x8f9b; +GL_SIGNED_NORMALIZED :: 0x8f9c; +GL_PRIMITIVE_RESTART :: 0x8f9d; +GL_PRIMITIVE_RESTART_INDEX :: 0x8f9e; +GL_COPY_READ_BUFFER :: 0x8f36; +GL_COPY_WRITE_BUFFER :: 0x8f37; +GL_UNIFORM_BUFFER :: 0x8a11; +GL_UNIFORM_BUFFER_BINDING :: 0x8a28; +GL_UNIFORM_BUFFER_START :: 0x8a29; +GL_UNIFORM_BUFFER_SIZE :: 0x8a2a; +GL_MAX_VERTEX_UNIFORM_BLOCKS :: 0x8a2b; +GL_MAX_GEOMETRY_UNIFORM_BLOCKS :: 0x8a2c; +GL_MAX_FRAGMENT_UNIFORM_BLOCKS :: 0x8a2d; +GL_MAX_COMBINED_UNIFORM_BLOCKS :: 0x8a2e; +GL_MAX_UNIFORM_BUFFER_BINDINGS :: 0x8a2f; +GL_MAX_UNIFORM_BLOCK_SIZE :: 0x8a30; +GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS :: 0x8a31; +GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS :: 0x8a32; +GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS :: 0x8a33; +GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT :: 0x8a34; +GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH :: 0x8a35; +GL_ACTIVE_UNIFORM_BLOCKS :: 0x8a36; +GL_UNIFORM_TYPE :: 0x8a37; +GL_UNIFORM_SIZE :: 0x8a38; +GL_UNIFORM_NAME_LENGTH :: 0x8a39; +GL_UNIFORM_BLOCK_INDEX :: 0x8a3a; +GL_UNIFORM_OFFSET :: 0x8a3b; +GL_UNIFORM_ARRAY_STRIDE :: 0x8a3c; +GL_UNIFORM_MATRIX_STRIDE :: 0x8a3d; +GL_UNIFORM_IS_ROW_MAJOR :: 0x8a3e; +GL_UNIFORM_BLOCK_BINDING :: 0x8a3f; +GL_UNIFORM_BLOCK_DATA_SIZE :: 0x8a40; +GL_UNIFORM_BLOCK_NAME_LENGTH :: 0x8a41; +GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS :: 0x8a42; +GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES :: 0x8a43; +GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER :: 0x8a44; +GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER :: 0x8a45; +GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER :: 0x8a46; +GL_INVALID_INDEX :: 0xffffffff; +GL_CONTEXT_CORE_PROFILE_BIT :: 0x00000001; +GL_CONTEXT_COMPATIBILITY_PROFILE_BIT :: 0x00000002; +GL_LINES_ADJACENCY :: 0x000a; +GL_LINE_STRIP_ADJACENCY :: 0x000b; +GL_TRIANGLES_ADJACENCY :: 0x000c; +GL_TRIANGLE_STRIP_ADJACENCY :: 0x000d; +GL_PROGRAM_POINT_SIZE :: 0x8642; +GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS :: 0x8c29; +GL_FRAMEBUFFER_ATTACHMENT_LAYERED :: 0x8da7; +GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS :: 0x8da8; +GL_GEOMETRY_SHADER :: 0x8dd9; +GL_GEOMETRY_VERTICES_OUT :: 0x8916; +GL_GEOMETRY_INPUT_TYPE :: 0x8917; +GL_GEOMETRY_OUTPUT_TYPE :: 0x8918; +GL_MAX_GEOMETRY_UNIFORM_COMPONENTS :: 0x8ddf; +GL_MAX_GEOMETRY_OUTPUT_VERTICES :: 0x8de0; +GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS :: 0x8de1; +GL_MAX_VERTEX_OUTPUT_COMPONENTS :: 0x9122; +GL_MAX_GEOMETRY_INPUT_COMPONENTS :: 0x9123; +GL_MAX_GEOMETRY_OUTPUT_COMPONENTS :: 0x9124; +GL_MAX_FRAGMENT_INPUT_COMPONENTS :: 0x9125; +GL_CONTEXT_PROFILE_MASK :: 0x9126; +GL_DEPTH_CLAMP :: 0x864f; +GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION :: 0x8e4c; +GL_FIRST_VERTEX_CONVENTION :: 0x8e4d; +GL_LAST_VERTEX_CONVENTION :: 0x8e4e; +GL_PROVOKING_VERTEX :: 0x8e4f; +GL_TEXTURE_CUBE_MAP_SEAMLESS :: 0x884f; +GL_MAX_SERVER_WAIT_TIMEOUT :: 0x9111; +GL_OBJECT_TYPE :: 0x9112; +GL_SYNC_CONDITION :: 0x9113; +GL_SYNC_STATUS :: 0x9114; +GL_SYNC_FLAGS :: 0x9115; +GL_SYNC_FENCE :: 0x9116; +GL_SYNC_GPU_COMMANDS_COMPLETE :: 0x9117; +GL_UNSIGNALED :: 0x9118; +GL_SIGNALED :: 0x9119; +GL_ALREADY_SIGNALED :: 0x911a; +GL_TIMEOUT_EXPIRED :: 0x911b; +GL_CONDITION_SATISFIED :: 0x911c; +GL_WAIT_FAILED :: 0x911d; +GL_TIMEOUT_IGNORED :: 0xffffffffffffffff; +GL_SYNC_FLUSH_COMMANDS_BIT :: 0x00000001; +GL_SAMPLE_POSITION :: 0x8e50; +GL_SAMPLE_MASK :: 0x8e51; +GL_SAMPLE_MASK_VALUE :: 0x8e52; +GL_MAX_SAMPLE_MASK_WORDS :: 0x8e59; +GL_TEXTURE_2D_MULTISAMPLE :: 0x9100; +GL_PROXY_TEXTURE_2D_MULTISAMPLE :: 0x9101; +GL_TEXTURE_2D_MULTISAMPLE_ARRAY :: 0x9102; +GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY :: 0x9103; +GL_TEXTURE_BINDING_2D_MULTISAMPLE :: 0x9104; +GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY :: 0x9105; +GL_TEXTURE_SAMPLES :: 0x9106; +GL_TEXTURE_FIXED_SAMPLE_LOCATIONS :: 0x9107; +GL_SAMPLER_2D_MULTISAMPLE :: 0x9108; +GL_INT_SAMPLER_2D_MULTISAMPLE :: 0x9109; +GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE :: 0x910a; +GL_SAMPLER_2D_MULTISAMPLE_ARRAY :: 0x910b; +GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY :: 0x910c; +GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY :: 0x910d; +GL_MAX_COLOR_TEXTURE_SAMPLES :: 0x910e; +GL_MAX_DEPTH_TEXTURE_SAMPLES :: 0x910f; +GL_MAX_INTEGER_SAMPLES :: 0x9110; +GL_VERTEX_ATTRIB_ARRAY_DIVISOR :: 0x88fe; +GL_SRC1_COLOR :: 0x88f9; +GL_ONE_MINUS_SRC1_COLOR :: 0x88fa; +GL_ONE_MINUS_SRC1_ALPHA :: 0x88fb; +GL_MAX_DUAL_SOURCE_DRAW_BUFFERS :: 0x88fc; +GL_ANY_SAMPLES_PASSED :: 0x8c2f; +GL_SAMPLER_BINDING :: 0x8919; +GL_RGB10_A2UI :: 0x906f; +GL_TEXTURE_SWIZZLE_R :: 0x8e42; +GL_TEXTURE_SWIZZLE_G :: 0x8e43; +GL_TEXTURE_SWIZZLE_B :: 0x8e44; +GL_TEXTURE_SWIZZLE_A :: 0x8e45; +GL_TEXTURE_SWIZZLE_RGBA :: 0x8e46; +GL_TIME_ELAPSED :: 0x88bf; +GL_TIMESTAMP :: 0x8e28; +GL_INT_2_10_10_10_REV :: 0x8d9f; +GL_SAMPLE_SHADING :: 0x8c36; +GL_MIN_SAMPLE_SHADING_VALUE :: 0x8c37; +GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET :: 0x8e5e; +GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET :: 0x8e5f; +GL_TEXTURE_CUBE_MAP_ARRAY :: 0x9009; +GL_TEXTURE_BINDING_CUBE_MAP_ARRAY :: 0x900a; +GL_PROXY_TEXTURE_CUBE_MAP_ARRAY :: 0x900b; +GL_SAMPLER_CUBE_MAP_ARRAY :: 0x900c; +GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW :: 0x900d; +GL_INT_SAMPLER_CUBE_MAP_ARRAY :: 0x900e; +GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY :: 0x900f; +GL_DRAW_INDIRECT_BUFFER :: 0x8f3f; +GL_DRAW_INDIRECT_BUFFER_BINDING :: 0x8f43; +GL_GEOMETRY_SHADER_INVOCATIONS :: 0x887f; +GL_MAX_GEOMETRY_SHADER_INVOCATIONS :: 0x8e5a; +GL_MIN_FRAGMENT_INTERPOLATION_OFFSET :: 0x8e5b; +GL_MAX_FRAGMENT_INTERPOLATION_OFFSET :: 0x8e5c; +GL_FRAGMENT_INTERPOLATION_OFFSET_BITS :: 0x8e5d; +GL_MAX_VERTEX_STREAMS :: 0x8e71; +GL_DOUBLE_VEC2 :: 0x8ffc; +GL_DOUBLE_VEC3 :: 0x8ffd; +GL_DOUBLE_VEC4 :: 0x8ffe; +GL_DOUBLE_MAT2 :: 0x8f46; +GL_DOUBLE_MAT3 :: 0x8f47; +GL_DOUBLE_MAT4 :: 0x8f48; +GL_DOUBLE_MAT2x3 :: 0x8f49; +GL_DOUBLE_MAT2x4 :: 0x8f4a; +GL_DOUBLE_MAT3x2 :: 0x8f4b; +GL_DOUBLE_MAT3x4 :: 0x8f4c; +GL_DOUBLE_MAT4x2 :: 0x8f4d; +GL_DOUBLE_MAT4x3 :: 0x8f4e; +GL_ACTIVE_SUBROUTINES :: 0x8de5; +GL_ACTIVE_SUBROUTINE_UNIFORMS :: 0x8de6; +GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS :: 0x8e47; +GL_ACTIVE_SUBROUTINE_MAX_LENGTH :: 0x8e48; +GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH :: 0x8e49; +GL_MAX_SUBROUTINES :: 0x8de7; +GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS :: 0x8de8; +GL_NUM_COMPATIBLE_SUBROUTINES :: 0x8e4a; +GL_COMPATIBLE_SUBROUTINES :: 0x8e4b; +GL_PATCHES :: 0x000e; +GL_PATCH_VERTICES :: 0x8e72; +GL_PATCH_DEFAULT_INNER_LEVEL :: 0x8e73; +GL_PATCH_DEFAULT_OUTER_LEVEL :: 0x8e74; +GL_TESS_CONTROL_OUTPUT_VERTICES :: 0x8e75; +GL_TESS_GEN_MODE :: 0x8e76; +GL_TESS_GEN_SPACING :: 0x8e77; +GL_TESS_GEN_VERTEX_ORDER :: 0x8e78; +GL_TESS_GEN_POINT_MODE :: 0x8e79; +GL_ISOLINES :: 0x8e7a; +GL_QUADS :: 0x0007; +GL_FRACTIONAL_ODD :: 0x8e7b; +GL_FRACTIONAL_EVEN :: 0x8e7c; +GL_MAX_PATCH_VERTICES :: 0x8e7d; +GL_MAX_TESS_GEN_LEVEL :: 0x8e7e; +GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS :: 0x8e7f; +GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS :: 0x8e80; +GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS :: 0x8e81; +GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS :: 0x8e82; +GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS :: 0x8e83; +GL_MAX_TESS_PATCH_COMPONENTS :: 0x8e84; +GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS :: 0x8e85; +GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS :: 0x8e86; +GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS :: 0x8e89; +GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS :: 0x8e8a; +GL_MAX_TESS_CONTROL_INPUT_COMPONENTS :: 0x886c; +GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS :: 0x886d; +GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS :: 0x8e1e; +GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS :: 0x8e1f; +GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER :: 0x84f0; +GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER :: 0x84f1; +GL_TESS_EVALUATION_SHADER :: 0x8e87; +GL_TESS_CONTROL_SHADER :: 0x8e88; +GL_TRANSFORM_FEEDBACK :: 0x8e22; +GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED :: 0x8e23; +GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE :: 0x8e24; +GL_TRANSFORM_FEEDBACK_BINDING :: 0x8e25; +GL_MAX_TRANSFORM_FEEDBACK_BUFFERS :: 0x8e70; +GL_FIXED :: 0x140c; +GL_IMPLEMENTATION_COLOR_READ_TYPE :: 0x8b9a; +GL_IMPLEMENTATION_COLOR_READ_FORMAT :: 0x8b9b; +GL_LOW_FLOAT :: 0x8df0; +GL_MEDIUM_FLOAT :: 0x8df1; +GL_HIGH_FLOAT :: 0x8df2; +GL_LOW_INT :: 0x8df3; +GL_MEDIUM_INT :: 0x8df4; +GL_HIGH_INT :: 0x8df5; +GL_SHADER_COMPILER :: 0x8dfa; +GL_SHADER_BINARY_FORMATS :: 0x8df8; +GL_NUM_SHADER_BINARY_FORMATS :: 0x8df9; +GL_MAX_VERTEX_UNIFORM_VECTORS :: 0x8dfb; +GL_MAX_VARYING_VECTORS :: 0x8dfc; +GL_MAX_FRAGMENT_UNIFORM_VECTORS :: 0x8dfd; +GL_RGB565 :: 0x8d62; +GL_PROGRAM_BINARY_RETRIEVABLE_HINT :: 0x8257; +GL_PROGRAM_BINARY_LENGTH :: 0x8741; +GL_NUM_PROGRAM_BINARY_FORMATS :: 0x87fe; +GL_PROGRAM_BINARY_FORMATS :: 0x87ff; +GL_VERTEX_SHADER_BIT :: 0x00000001; +GL_FRAGMENT_SHADER_BIT :: 0x00000002; +GL_GEOMETRY_SHADER_BIT :: 0x00000004; +GL_TESS_CONTROL_SHADER_BIT :: 0x00000008; +GL_TESS_EVALUATION_SHADER_BIT :: 0x00000010; +GL_ALL_SHADER_BITS :: 0xffffffff; +GL_PROGRAM_SEPARABLE :: 0x8258; +GL_ACTIVE_PROGRAM :: 0x8259; +GL_PROGRAM_PIPELINE_BINDING :: 0x825a; +GL_MAX_VIEWPORTS :: 0x825b; +GL_VIEWPORT_SUBPIXEL_BITS :: 0x825c; +GL_VIEWPORT_BOUNDS_RANGE :: 0x825d; +GL_LAYER_PROVOKING_VERTEX :: 0x825e; +GL_VIEWPORT_INDEX_PROVOKING_VERTEX :: 0x825f; +GL_UNDEFINED_VERTEX :: 0x8260; +GL_COPY_READ_BUFFER_BINDING :: 0x8f36; +GL_COPY_WRITE_BUFFER_BINDING :: 0x8f37; +GL_TRANSFORM_FEEDBACK_ACTIVE :: 0x8e24; +GL_TRANSFORM_FEEDBACK_PAUSED :: 0x8e23; +GL_UNPACK_COMPRESSED_BLOCK_WIDTH :: 0x9127; +GL_UNPACK_COMPRESSED_BLOCK_HEIGHT :: 0x9128; +GL_UNPACK_COMPRESSED_BLOCK_DEPTH :: 0x9129; +GL_UNPACK_COMPRESSED_BLOCK_SIZE :: 0x912a; +GL_PACK_COMPRESSED_BLOCK_WIDTH :: 0x912b; +GL_PACK_COMPRESSED_BLOCK_HEIGHT :: 0x912c; +GL_PACK_COMPRESSED_BLOCK_DEPTH :: 0x912d; +GL_PACK_COMPRESSED_BLOCK_SIZE :: 0x912e; +GL_NUM_SAMPLE_COUNTS :: 0x9380; +GL_MIN_MAP_BUFFER_ALIGNMENT :: 0x90bc; +GL_ATOMIC_COUNTER_BUFFER :: 0x92c0; +GL_ATOMIC_COUNTER_BUFFER_BINDING :: 0x92c1; +GL_ATOMIC_COUNTER_BUFFER_START :: 0x92c2; +GL_ATOMIC_COUNTER_BUFFER_SIZE :: 0x92c3; +GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE :: 0x92c4; +GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS :: 0x92c5; +GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES :: 0x92c6; +GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER :: 0x92c7; +GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER :: 0x92c8; +GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER :: 0x92c9; +GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER :: 0x92ca; +GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER :: 0x92cb; +GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS :: 0x92cc; +GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS :: 0x92cd; +GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS :: 0x92ce; +GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS :: 0x92cf; +GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS :: 0x92d0; +GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS :: 0x92d1; +GL_MAX_VERTEX_ATOMIC_COUNTERS :: 0x92d2; +GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS :: 0x92d3; +GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS :: 0x92d4; +GL_MAX_GEOMETRY_ATOMIC_COUNTERS :: 0x92d5; +GL_MAX_FRAGMENT_ATOMIC_COUNTERS :: 0x92d6; +GL_MAX_COMBINED_ATOMIC_COUNTERS :: 0x92d7; +GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE :: 0x92d8; +GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS :: 0x92dc; +GL_ACTIVE_ATOMIC_COUNTER_BUFFERS :: 0x92d9; +GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX :: 0x92da; +GL_UNSIGNED_INT_ATOMIC_COUNTER :: 0x92db; +GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT :: 0x00000001; +GL_ELEMENT_ARRAY_BARRIER_BIT :: 0x00000002; +GL_UNIFORM_BARRIER_BIT :: 0x00000004; +GL_TEXTURE_FETCH_BARRIER_BIT :: 0x00000008; +GL_SHADER_IMAGE_ACCESS_BARRIER_BIT :: 0x00000020; +GL_COMMAND_BARRIER_BIT :: 0x00000040; +GL_PIXEL_BUFFER_BARRIER_BIT :: 0x00000080; +GL_TEXTURE_UPDATE_BARRIER_BIT :: 0x00000100; +GL_BUFFER_UPDATE_BARRIER_BIT :: 0x00000200; +GL_FRAMEBUFFER_BARRIER_BIT :: 0x00000400; +GL_TRANSFORM_FEEDBACK_BARRIER_BIT :: 0x00000800; +GL_ATOMIC_COUNTER_BARRIER_BIT :: 0x00001000; +GL_ALL_BARRIER_BITS :: 0xffffffff; +GL_MAX_IMAGE_UNITS :: 0x8f38; +GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS :: 0x8f39; +GL_IMAGE_BINDING_NAME :: 0x8f3a; +GL_IMAGE_BINDING_LEVEL :: 0x8f3b; +GL_IMAGE_BINDING_LAYERED :: 0x8f3c; +GL_IMAGE_BINDING_LAYER :: 0x8f3d; +GL_IMAGE_BINDING_ACCESS :: 0x8f3e; +GL_IMAGE_1D :: 0x904c; +GL_IMAGE_2D :: 0x904d; +GL_IMAGE_3D :: 0x904e; +GL_IMAGE_2D_RECT :: 0x904f; +GL_IMAGE_CUBE :: 0x9050; +GL_IMAGE_BUFFER :: 0x9051; +GL_IMAGE_1D_ARRAY :: 0x9052; +GL_IMAGE_2D_ARRAY :: 0x9053; +GL_IMAGE_CUBE_MAP_ARRAY :: 0x9054; +GL_IMAGE_2D_MULTISAMPLE :: 0x9055; +GL_IMAGE_2D_MULTISAMPLE_ARRAY :: 0x9056; +GL_INT_IMAGE_1D :: 0x9057; +GL_INT_IMAGE_2D :: 0x9058; +GL_INT_IMAGE_3D :: 0x9059; +GL_INT_IMAGE_2D_RECT :: 0x905a; +GL_INT_IMAGE_CUBE :: 0x905b; +GL_INT_IMAGE_BUFFER :: 0x905c; +GL_INT_IMAGE_1D_ARRAY :: 0x905d; +GL_INT_IMAGE_2D_ARRAY :: 0x905e; +GL_INT_IMAGE_CUBE_MAP_ARRAY :: 0x905f; +GL_INT_IMAGE_2D_MULTISAMPLE :: 0x9060; +GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY :: 0x9061; +GL_UNSIGNED_INT_IMAGE_1D :: 0x9062; +GL_UNSIGNED_INT_IMAGE_2D :: 0x9063; +GL_UNSIGNED_INT_IMAGE_3D :: 0x9064; +GL_UNSIGNED_INT_IMAGE_2D_RECT :: 0x9065; +GL_UNSIGNED_INT_IMAGE_CUBE :: 0x9066; +GL_UNSIGNED_INT_IMAGE_BUFFER :: 0x9067; +GL_UNSIGNED_INT_IMAGE_1D_ARRAY :: 0x9068; +GL_UNSIGNED_INT_IMAGE_2D_ARRAY :: 0x9069; +GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY :: 0x906a; +GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE :: 0x906b; +GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY :: 0x906c; +GL_MAX_IMAGE_SAMPLES :: 0x906d; +GL_IMAGE_BINDING_FORMAT :: 0x906e; +GL_IMAGE_FORMAT_COMPATIBILITY_TYPE :: 0x90c7; +GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE :: 0x90c8; +GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS :: 0x90c9; +GL_MAX_VERTEX_IMAGE_UNIFORMS :: 0x90ca; +GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS :: 0x90cb; +GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS :: 0x90cc; +GL_MAX_GEOMETRY_IMAGE_UNIFORMS :: 0x90cd; +GL_MAX_FRAGMENT_IMAGE_UNIFORMS :: 0x90ce; +GL_MAX_COMBINED_IMAGE_UNIFORMS :: 0x90cf; +GL_COMPRESSED_RGBA_BPTC_UNORM :: 0x8e8c; +GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM :: 0x8e8d; +GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT :: 0x8e8e; +GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT :: 0x8e8f; +GL_TEXTURE_IMMUTABLE_FORMAT :: 0x912f; +GL_NUM_SHADING_LANGUAGE_VERSIONS :: 0x82e9; +GL_VERTEX_ATTRIB_ARRAY_LONG :: 0x874e; +GL_COMPRESSED_RGB8_ETC2 :: 0x9274; +GL_COMPRESSED_SRGB8_ETC2 :: 0x9275; +GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 :: 0x9276; +GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 :: 0x9277; +GL_COMPRESSED_RGBA8_ETC2_EAC :: 0x9278; +GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC :: 0x9279; +GL_COMPRESSED_R11_EAC :: 0x9270; +GL_COMPRESSED_SIGNED_R11_EAC :: 0x9271; +GL_COMPRESSED_RG11_EAC :: 0x9272; +GL_COMPRESSED_SIGNED_RG11_EAC :: 0x9273; +GL_PRIMITIVE_RESTART_FIXED_INDEX :: 0x8d69; +GL_ANY_SAMPLES_PASSED_CONSERVATIVE :: 0x8d6a; +GL_MAX_ELEMENT_INDEX :: 0x8d6b; +GL_COMPUTE_SHADER :: 0x91b9; +GL_MAX_COMPUTE_UNIFORM_BLOCKS :: 0x91bb; +GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS :: 0x91bc; +GL_MAX_COMPUTE_IMAGE_UNIFORMS :: 0x91bd; +GL_MAX_COMPUTE_SHARED_MEMORY_SIZE :: 0x8262; +GL_MAX_COMPUTE_UNIFORM_COMPONENTS :: 0x8263; +GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS :: 0x8264; +GL_MAX_COMPUTE_ATOMIC_COUNTERS :: 0x8265; +GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS :: 0x8266; +GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS :: 0x90eb; +GL_MAX_COMPUTE_WORK_GROUP_COUNT :: 0x91be; +GL_MAX_COMPUTE_WORK_GROUP_SIZE :: 0x91bf; +GL_COMPUTE_WORK_GROUP_SIZE :: 0x8267; +GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER :: 0x90ec; +GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER :: 0x90ed; +GL_DISPATCH_INDIRECT_BUFFER :: 0x90ee; +GL_DISPATCH_INDIRECT_BUFFER_BINDING :: 0x90ef; +GL_COMPUTE_SHADER_BIT :: 0x00000020; +GL_DEBUG_OUTPUT_SYNCHRONOUS :: 0x8242; +GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH :: 0x8243; +GL_DEBUG_CALLBACK_FUNCTION :: 0x8244; +GL_DEBUG_CALLBACK_USER_PARAM :: 0x8245; +GL_DEBUG_SOURCE_API :: 0x8246; +GL_DEBUG_SOURCE_WINDOW_SYSTEM :: 0x8247; +GL_DEBUG_SOURCE_SHADER_COMPILER :: 0x8248; +GL_DEBUG_SOURCE_THIRD_PARTY :: 0x8249; +GL_DEBUG_SOURCE_APPLICATION :: 0x824a; +GL_DEBUG_SOURCE_OTHER :: 0x824b; +GL_DEBUG_TYPE_ERROR :: 0x824c; +GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR :: 0x824d; +GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR :: 0x824e; +GL_DEBUG_TYPE_PORTABILITY :: 0x824f; +GL_DEBUG_TYPE_PERFORMANCE :: 0x8250; +GL_DEBUG_TYPE_OTHER :: 0x8251; +GL_MAX_DEBUG_MESSAGE_LENGTH :: 0x9143; +GL_MAX_DEBUG_LOGGED_MESSAGES :: 0x9144; +GL_DEBUG_LOGGED_MESSAGES :: 0x9145; +GL_DEBUG_SEVERITY_HIGH :: 0x9146; +GL_DEBUG_SEVERITY_MEDIUM :: 0x9147; +GL_DEBUG_SEVERITY_LOW :: 0x9148; +GL_DEBUG_TYPE_MARKER :: 0x8268; +GL_DEBUG_TYPE_PUSH_GROUP :: 0x8269; +GL_DEBUG_TYPE_POP_GROUP :: 0x826a; +GL_DEBUG_SEVERITY_NOTIFICATION :: 0x826b; +GL_MAX_DEBUG_GROUP_STACK_DEPTH :: 0x826c; +GL_DEBUG_GROUP_STACK_DEPTH :: 0x826d; +GL_BUFFER :: 0x82e0; +GL_SHADER :: 0x82e1; +GL_PROGRAM :: 0x82e2; +GL_VERTEX_ARRAY :: 0x8074; +GL_QUERY :: 0x82e3; +GL_PROGRAM_PIPELINE :: 0x82e4; +GL_SAMPLER :: 0x82e6; +GL_MAX_LABEL_LENGTH :: 0x82e8; +GL_DEBUG_OUTPUT :: 0x92e0; +GL_CONTEXT_FLAG_DEBUG_BIT :: 0x00000002; +GL_MAX_UNIFORM_LOCATIONS :: 0x826e; +GL_FRAMEBUFFER_DEFAULT_WIDTH :: 0x9310; +GL_FRAMEBUFFER_DEFAULT_HEIGHT :: 0x9311; +GL_FRAMEBUFFER_DEFAULT_LAYERS :: 0x9312; +GL_FRAMEBUFFER_DEFAULT_SAMPLES :: 0x9313; +GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS :: 0x9314; +GL_MAX_FRAMEBUFFER_WIDTH :: 0x9315; +GL_MAX_FRAMEBUFFER_HEIGHT :: 0x9316; +GL_MAX_FRAMEBUFFER_LAYERS :: 0x9317; +GL_MAX_FRAMEBUFFER_SAMPLES :: 0x9318; +GL_INTERNALFORMAT_SUPPORTED :: 0x826f; +GL_INTERNALFORMAT_PREFERRED :: 0x8270; +GL_INTERNALFORMAT_RED_SIZE :: 0x8271; +GL_INTERNALFORMAT_GREEN_SIZE :: 0x8272; +GL_INTERNALFORMAT_BLUE_SIZE :: 0x8273; +GL_INTERNALFORMAT_ALPHA_SIZE :: 0x8274; +GL_INTERNALFORMAT_DEPTH_SIZE :: 0x8275; +GL_INTERNALFORMAT_STENCIL_SIZE :: 0x8276; +GL_INTERNALFORMAT_SHARED_SIZE :: 0x8277; +GL_INTERNALFORMAT_RED_TYPE :: 0x8278; +GL_INTERNALFORMAT_GREEN_TYPE :: 0x8279; +GL_INTERNALFORMAT_BLUE_TYPE :: 0x827a; +GL_INTERNALFORMAT_ALPHA_TYPE :: 0x827b; +GL_INTERNALFORMAT_DEPTH_TYPE :: 0x827c; +GL_INTERNALFORMAT_STENCIL_TYPE :: 0x827d; +GL_MAX_WIDTH :: 0x827e; +GL_MAX_HEIGHT :: 0x827f; +GL_MAX_DEPTH :: 0x8280; +GL_MAX_LAYERS :: 0x8281; +GL_MAX_COMBINED_DIMENSIONS :: 0x8282; +GL_COLOR_COMPONENTS :: 0x8283; +GL_DEPTH_COMPONENTS :: 0x8284; +GL_STENCIL_COMPONENTS :: 0x8285; +GL_COLOR_RENDERABLE :: 0x8286; +GL_DEPTH_RENDERABLE :: 0x8287; +GL_STENCIL_RENDERABLE :: 0x8288; +GL_FRAMEBUFFER_RENDERABLE :: 0x8289; +GL_FRAMEBUFFER_RENDERABLE_LAYERED :: 0x828a; +GL_FRAMEBUFFER_BLEND :: 0x828b; +GL_READ_PIXELS :: 0x828c; +GL_READ_PIXELS_FORMAT :: 0x828d; +GL_READ_PIXELS_TYPE :: 0x828e; +GL_TEXTURE_IMAGE_FORMAT :: 0x828f; +GL_TEXTURE_IMAGE_TYPE :: 0x8290; +GL_GET_TEXTURE_IMAGE_FORMAT :: 0x8291; +GL_GET_TEXTURE_IMAGE_TYPE :: 0x8292; +GL_MIPMAP :: 0x8293; +GL_MANUAL_GENERATE_MIPMAP :: 0x8294; +GL_AUTO_GENERATE_MIPMAP :: 0x8295; +GL_COLOR_ENCODING :: 0x8296; +GL_SRGB_READ :: 0x8297; +GL_SRGB_WRITE :: 0x8298; +GL_FILTER :: 0x829a; +GL_VERTEX_TEXTURE :: 0x829b; +GL_TESS_CONTROL_TEXTURE :: 0x829c; +GL_TESS_EVALUATION_TEXTURE :: 0x829d; +GL_GEOMETRY_TEXTURE :: 0x829e; +GL_FRAGMENT_TEXTURE :: 0x829f; +GL_COMPUTE_TEXTURE :: 0x82a0; +GL_TEXTURE_SHADOW :: 0x82a1; +GL_TEXTURE_GATHER :: 0x82a2; +GL_TEXTURE_GATHER_SHADOW :: 0x82a3; +GL_SHADER_IMAGE_LOAD :: 0x82a4; +GL_SHADER_IMAGE_STORE :: 0x82a5; +GL_SHADER_IMAGE_ATOMIC :: 0x82a6; +GL_IMAGE_TEXEL_SIZE :: 0x82a7; +GL_IMAGE_COMPATIBILITY_CLASS :: 0x82a8; +GL_IMAGE_PIXEL_FORMAT :: 0x82a9; +GL_IMAGE_PIXEL_TYPE :: 0x82aa; +GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST :: 0x82ac; +GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST :: 0x82ad; +GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE :: 0x82ae; +GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE :: 0x82af; +GL_TEXTURE_COMPRESSED_BLOCK_WIDTH :: 0x82b1; +GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT :: 0x82b2; +GL_TEXTURE_COMPRESSED_BLOCK_SIZE :: 0x82b3; +GL_CLEAR_BUFFER :: 0x82b4; +GL_TEXTURE_VIEW :: 0x82b5; +GL_VIEW_COMPATIBILITY_CLASS :: 0x82b6; +GL_FULL_SUPPORT :: 0x82b7; +GL_CAVEAT_SUPPORT :: 0x82b8; +GL_IMAGE_CLASS_4_X_32 :: 0x82b9; +GL_IMAGE_CLASS_2_X_32 :: 0x82ba; +GL_IMAGE_CLASS_1_X_32 :: 0x82bb; +GL_IMAGE_CLASS_4_X_16 :: 0x82bc; +GL_IMAGE_CLASS_2_X_16 :: 0x82bd; +GL_IMAGE_CLASS_1_X_16 :: 0x82be; +GL_IMAGE_CLASS_4_X_8 :: 0x82bf; +GL_IMAGE_CLASS_2_X_8 :: 0x82c0; +GL_IMAGE_CLASS_1_X_8 :: 0x82c1; +GL_IMAGE_CLASS_11_11_10 :: 0x82c2; +GL_IMAGE_CLASS_10_10_10_2 :: 0x82c3; +GL_VIEW_CLASS_128_BITS :: 0x82c4; +GL_VIEW_CLASS_96_BITS :: 0x82c5; +GL_VIEW_CLASS_64_BITS :: 0x82c6; +GL_VIEW_CLASS_48_BITS :: 0x82c7; +GL_VIEW_CLASS_32_BITS :: 0x82c8; +GL_VIEW_CLASS_24_BITS :: 0x82c9; +GL_VIEW_CLASS_16_BITS :: 0x82ca; +GL_VIEW_CLASS_8_BITS :: 0x82cb; +GL_VIEW_CLASS_S3TC_DXT1_RGB :: 0x82cc; +GL_VIEW_CLASS_S3TC_DXT1_RGBA :: 0x82cd; +GL_VIEW_CLASS_S3TC_DXT3_RGBA :: 0x82ce; +GL_VIEW_CLASS_S3TC_DXT5_RGBA :: 0x82cf; +GL_VIEW_CLASS_RGTC1_RED :: 0x82d0; +GL_VIEW_CLASS_RGTC2_RG :: 0x82d1; +GL_VIEW_CLASS_BPTC_UNORM :: 0x82d2; +GL_VIEW_CLASS_BPTC_FLOAT :: 0x82d3; +GL_UNIFORM :: 0x92e1; +GL_UNIFORM_BLOCK :: 0x92e2; +GL_PROGRAM_INPUT :: 0x92e3; +GL_PROGRAM_OUTPUT :: 0x92e4; +GL_BUFFER_VARIABLE :: 0x92e5; +GL_SHADER_STORAGE_BLOCK :: 0x92e6; +GL_VERTEX_SUBROUTINE :: 0x92e8; +GL_TESS_CONTROL_SUBROUTINE :: 0x92e9; +GL_TESS_EVALUATION_SUBROUTINE :: 0x92ea; +GL_GEOMETRY_SUBROUTINE :: 0x92eb; +GL_FRAGMENT_SUBROUTINE :: 0x92ec; +GL_COMPUTE_SUBROUTINE :: 0x92ed; +GL_VERTEX_SUBROUTINE_UNIFORM :: 0x92ee; +GL_TESS_CONTROL_SUBROUTINE_UNIFORM :: 0x92ef; +GL_TESS_EVALUATION_SUBROUTINE_UNIFORM :: 0x92f0; +GL_GEOMETRY_SUBROUTINE_UNIFORM :: 0x92f1; +GL_FRAGMENT_SUBROUTINE_UNIFORM :: 0x92f2; +GL_COMPUTE_SUBROUTINE_UNIFORM :: 0x92f3; +GL_TRANSFORM_FEEDBACK_VARYING :: 0x92f4; +GL_ACTIVE_RESOURCES :: 0x92f5; +GL_MAX_NAME_LENGTH :: 0x92f6; +GL_MAX_NUM_ACTIVE_VARIABLES :: 0x92f7; +GL_MAX_NUM_COMPATIBLE_SUBROUTINES :: 0x92f8; +GL_NAME_LENGTH :: 0x92f9; +GL_TYPE :: 0x92fa; +GL_ARRAY_SIZE :: 0x92fb; +GL_OFFSET :: 0x92fc; +GL_BLOCK_INDEX :: 0x92fd; +GL_ARRAY_STRIDE :: 0x92fe; +GL_MATRIX_STRIDE :: 0x92ff; +GL_IS_ROW_MAJOR :: 0x9300; +GL_ATOMIC_COUNTER_BUFFER_INDEX :: 0x9301; +GL_BUFFER_BINDING :: 0x9302; +GL_BUFFER_DATA_SIZE :: 0x9303; +GL_NUM_ACTIVE_VARIABLES :: 0x9304; +GL_ACTIVE_VARIABLES :: 0x9305; +GL_REFERENCED_BY_VERTEX_SHADER :: 0x9306; +GL_REFERENCED_BY_TESS_CONTROL_SHADER :: 0x9307; +GL_REFERENCED_BY_TESS_EVALUATION_SHADER :: 0x9308; +GL_REFERENCED_BY_GEOMETRY_SHADER :: 0x9309; +GL_REFERENCED_BY_FRAGMENT_SHADER :: 0x930a; +GL_REFERENCED_BY_COMPUTE_SHADER :: 0x930b; +GL_TOP_LEVEL_ARRAY_SIZE :: 0x930c; +GL_TOP_LEVEL_ARRAY_STRIDE :: 0x930d; +GL_LOCATION :: 0x930e; +GL_LOCATION_INDEX :: 0x930f; +GL_IS_PER_PATCH :: 0x92e7; +GL_SHADER_STORAGE_BUFFER :: 0x90d2; +GL_SHADER_STORAGE_BUFFER_BINDING :: 0x90d3; +GL_SHADER_STORAGE_BUFFER_START :: 0x90d4; +GL_SHADER_STORAGE_BUFFER_SIZE :: 0x90d5; +GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS :: 0x90d6; +GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS :: 0x90d7; +GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS :: 0x90d8; +GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS :: 0x90d9; +GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS :: 0x90da; +GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS :: 0x90db; +GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS :: 0x90dc; +GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS :: 0x90dd; +GL_MAX_SHADER_STORAGE_BLOCK_SIZE :: 0x90de; +GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT :: 0x90df; +GL_SHADER_STORAGE_BARRIER_BIT :: 0x00002000; +GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES :: 0x8f39; +GL_DEPTH_STENCIL_TEXTURE_MODE :: 0x90ea; +GL_TEXTURE_BUFFER_OFFSET :: 0x919d; +GL_TEXTURE_BUFFER_SIZE :: 0x919e; +GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT :: 0x919f; +GL_TEXTURE_VIEW_MIN_LEVEL :: 0x82db; +GL_TEXTURE_VIEW_NUM_LEVELS :: 0x82dc; +GL_TEXTURE_VIEW_MIN_LAYER :: 0x82dd; +GL_TEXTURE_VIEW_NUM_LAYERS :: 0x82de; +GL_TEXTURE_IMMUTABLE_LEVELS :: 0x82df; +GL_VERTEX_ATTRIB_BINDING :: 0x82d4; +GL_VERTEX_ATTRIB_RELATIVE_OFFSET :: 0x82d5; +GL_VERTEX_BINDING_DIVISOR :: 0x82d6; +GL_VERTEX_BINDING_OFFSET :: 0x82d7; +GL_VERTEX_BINDING_STRIDE :: 0x82d8; +GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET :: 0x82d9; +GL_MAX_VERTEX_ATTRIB_BINDINGS :: 0x82da; +GL_VERTEX_BINDING_BUFFER :: 0x8f4f; +GL_DISPLAY_LIST :: 0x82e7; +GL_STACK_UNDERFLOW :: 0x0504; +GL_STACK_OVERFLOW :: 0x0503; +GL_MAX_VERTEX_ATTRIB_STRIDE :: 0x82e5; +GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED :: 0x8221; +GL_TEXTURE_BUFFER_BINDING :: 0x8c2a; +GL_MAP_PERSISTENT_BIT :: 0x0040; +GL_MAP_COHERENT_BIT :: 0x0080; +GL_DYNAMIC_STORAGE_BIT :: 0x0100; +GL_CLIENT_STORAGE_BIT :: 0x0200; +GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT :: 0x00004000; +GL_BUFFER_IMMUTABLE_STORAGE :: 0x821f; +GL_BUFFER_STORAGE_FLAGS :: 0x8220; +GL_CLEAR_TEXTURE :: 0x9365; +GL_LOCATION_COMPONENT :: 0x934a; +GL_TRANSFORM_FEEDBACK_BUFFER_INDEX :: 0x934b; +GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE :: 0x934c; +GL_QUERY_BUFFER :: 0x9192; +GL_QUERY_BUFFER_BARRIER_BIT :: 0x00008000; +GL_QUERY_BUFFER_BINDING :: 0x9193; +GL_QUERY_RESULT_NO_WAIT :: 0x9194; +GL_MIRROR_CLAMP_TO_EDGE :: 0x8743; +GL_CONTEXT_LOST :: 0x0507; +GL_NEGATIVE_ONE_TO_ONE :: 0x935e; +GL_ZERO_TO_ONE :: 0x935f; +GL_CLIP_ORIGIN :: 0x935c; +GL_CLIP_DEPTH_MODE :: 0x935d; +GL_QUERY_WAIT_INVERTED :: 0x8e17; +GL_QUERY_NO_WAIT_INVERTED :: 0x8e18; +GL_QUERY_BY_REGION_WAIT_INVERTED :: 0x8e19; +GL_QUERY_BY_REGION_NO_WAIT_INVERTED :: 0x8e1a; +GL_MAX_CULL_DISTANCES :: 0x82f9; +GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES :: 0x82fa; +GL_TEXTURE_TARGET :: 0x1006; +GL_QUERY_TARGET :: 0x82ea; +GL_GUILTY_CONTEXT_RESET :: 0x8253; +GL_INNOCENT_CONTEXT_RESET :: 0x8254; +GL_UNKNOWN_CONTEXT_RESET :: 0x8255; +GL_RESET_NOTIFICATION_STRATEGY :: 0x8256; +GL_LOSE_CONTEXT_ON_RESET :: 0x8252; +GL_NO_RESET_NOTIFICATION :: 0x8261; +GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT :: 0x00000004; +GL_COLOR_TABLE :: 0x80d0; +GL_POST_CONVOLUTION_COLOR_TABLE :: 0x80d1; +GL_POST_COLOR_MATRIX_COLOR_TABLE :: 0x80d2; +GL_PROXY_COLOR_TABLE :: 0x80d3; +GL_PROXY_POST_CONVOLUTION_COLOR_TABLE :: 0x80d4; +GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE :: 0x80d5; +GL_CONVOLUTION_1D :: 0x8010; +GL_CONVOLUTION_2D :: 0x8011; +GL_SEPARABLE_2D :: 0x8012; +GL_HISTOGRAM :: 0x8024; +GL_PROXY_HISTOGRAM :: 0x8025; +GL_MINMAX :: 0x802e; +GL_CONTEXT_RELEASE_BEHAVIOR :: 0x82fb; +GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH :: 0x82fc; + + + +// VERSION_1_0 +glCullFace: proc(mode: u32); +glFrontFace: proc(mode: u32); +glHint: proc(target: u32, mode: u32); +glLineWidth: proc(width: f32); +glPointSize: proc(size: f32); +glPolygonMode: proc(face: u32, mode: u32); +glScissor: proc(x: i32, y: i32, width: i32, height: i32); +glTexParameterf: proc(target: u32, pname: u32, param: f32); +glTexParameterfv: proc(target: u32, pname: u32, params: *f32); +glTexParameteri: proc(target: u32, pname: u32, param: i32); +glTexParameteriv: proc(target: u32, pname: u32, params: *i32); +glTexImage1D: proc(target: u32, level: i32, internalformat: i32, width: i32, border: i32, format: u32, type: u32, pixels: *void); +glTexImage2D: proc(target: u32, level: i32, internalformat: i32, width: i32, height: i32, border: i32, format: u32, type: u32, pixels: *void); +glDrawBuffer: proc(buf: u32); +glClear: proc(mask: u32); +glClearColor: proc(red: f32, green: f32, blue: f32, alpha: f32); +glClearStencil: proc(s: i32); +glClearDepth: proc(depth: f64); +glStencilMask: proc(mask: u32); +glColorMask: proc(red: bool, green: bool, blue: bool, alpha: bool); +glDepthMask: proc(flag: bool); +glDisable: proc(cap: u32); +glEnable: proc(cap: u32); +glFinish: proc(); +glFlush: proc(); +glBlendFunc: proc(sfactor: u32, dfactor: u32); +glLogicOp: proc(opcode: u32); +glStencilFunc: proc(func: u32, ref: i32, mask: u32); +glStencilOp: proc(fail: u32, zfail: u32, zpass: u32); +glDepthFunc: proc(func: u32); +glPixelStoref: proc(pname: u32, param: f32); +glPixelStorei: proc(pname: u32, param: i32); +glReadBuffer: proc(src: u32); +glReadPixels: proc(x: i32, y: i32, width: i32, height: i32, format: u32, type: u32, pixels: *void); +glGetBooleanv: proc(pname: u32, data: *bool); +glGetDoublev: proc(pname: u32, data: *f64); +glGetError: proc(): u32; +glGetFloatv: proc(pname: u32, data: *f32); +glGetIntegerv: proc(pname: u32, data: *i32); +glGetString: proc(name: u32): *char; +glGetTexImage: proc(target: u32, level: i32, format: u32, type: u32, pixels: *void); +glGetTexParameterfv: proc(target: u32, pname: u32, params: *f32); +glGetTexParameteriv: proc(target: u32, pname: u32, params: *i32); +glGetTexLevelParameterfv: proc(target: u32, level: i32, pname: u32, params: *f32); +glGetTexLevelParameteriv: proc(target: u32, level: i32, pname: u32, params: *i32); +glIsEnabled: proc(cap: u32): bool; +glDepthRange: proc(near: f64, far: f64); +glViewport: proc(x: i32, y: i32, width: i32, height: i32); + +load_1_0 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glCullFace), "glCullFace"); + set_proc_address(:**void(&glFrontFace), "glFrontFace"); + set_proc_address(:**void(&glHint), "glHint"); + set_proc_address(:**void(&glLineWidth), "glLineWidth"); + set_proc_address(:**void(&glPointSize), "glPointSize"); + set_proc_address(:**void(&glPolygonMode), "glPolygonMode"); + set_proc_address(:**void(&glScissor), "glScissor"); + set_proc_address(:**void(&glTexParameterf), "glTexParameterf"); + set_proc_address(:**void(&glTexParameterfv), "glTexParameterfv"); + set_proc_address(:**void(&glTexParameteri), "glTexParameteri"); + set_proc_address(:**void(&glTexParameteriv), "glTexParameteriv"); + set_proc_address(:**void(&glTexImage1D), "glTexImage1D"); + set_proc_address(:**void(&glTexImage2D), "glTexImage2D"); + set_proc_address(:**void(&glDrawBuffer), "glDrawBuffer"); + set_proc_address(:**void(&glClear), "glClear"); + set_proc_address(:**void(&glClearColor), "glClearColor"); + set_proc_address(:**void(&glClearStencil), "glClearStencil"); + set_proc_address(:**void(&glClearDepth), "glClearDepth"); + set_proc_address(:**void(&glStencilMask), "glStencilMask"); + set_proc_address(:**void(&glColorMask), "glColorMask"); + set_proc_address(:**void(&glDepthMask), "glDepthMask"); + set_proc_address(:**void(&glDisable), "glDisable"); + set_proc_address(:**void(&glEnable), "glEnable"); + set_proc_address(:**void(&glFinish), "glFinish"); + set_proc_address(:**void(&glFlush), "glFlush"); + set_proc_address(:**void(&glBlendFunc), "glBlendFunc"); + set_proc_address(:**void(&glLogicOp), "glLogicOp"); + set_proc_address(:**void(&glStencilFunc), "glStencilFunc"); + set_proc_address(:**void(&glStencilOp), "glStencilOp"); + set_proc_address(:**void(&glDepthFunc), "glDepthFunc"); + set_proc_address(:**void(&glPixelStoref), "glPixelStoref"); + set_proc_address(:**void(&glPixelStorei), "glPixelStorei"); + set_proc_address(:**void(&glReadBuffer), "glReadBuffer"); + set_proc_address(:**void(&glReadPixels), "glReadPixels"); + set_proc_address(:**void(&glGetBooleanv), "glGetBooleanv"); + set_proc_address(:**void(&glGetDoublev), "glGetDoublev"); + set_proc_address(:**void(&glGetError), "glGetError"); + set_proc_address(:**void(&glGetFloatv), "glGetFloatv"); + set_proc_address(:**void(&glGetIntegerv), "glGetIntegerv"); + set_proc_address(:**void(&glGetString), "glGetString"); + set_proc_address(:**void(&glGetTexImage), "glGetTexImage"); + set_proc_address(:**void(&glGetTexParameterfv), "glGetTexParameterfv"); + set_proc_address(:**void(&glGetTexParameteriv), "glGetTexParameteriv"); + set_proc_address(:**void(&glGetTexLevelParameterfv), "glGetTexLevelParameterfv"); + set_proc_address(:**void(&glGetTexLevelParameteriv), "glGetTexLevelParameteriv"); + set_proc_address(:**void(&glIsEnabled), "glIsEnabled"); + set_proc_address(:**void(&glDepthRange), "glDepthRange"); + set_proc_address(:**void(&glViewport), "glViewport"); +} + + +// VERSION_1_1 +glDrawArrays: proc(mode: u32, first: i32, count: i32); +glDrawElements: proc(mode: u32, count: i32, type: u32, indices: *void); +glPolygonOffset: proc(factor: f32, units: f32); +glCopyTexImage1D: proc(target: u32, level: i32, internalformat: u32, x: i32, y: i32, width: i32, border: i32); +glCopyTexImage2D: proc(target: u32, level: i32, internalformat: u32, x: i32, y: i32, width: i32, height: i32, border: i32); +glCopyTexSubImage1D: proc(target: u32, level: i32, xoffset: i32, x: i32, y: i32, width: i32); +glCopyTexSubImage2D: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, x: i32, y: i32, width: i32, height: i32); +glTexSubImage1D: proc(target: u32, level: i32, xoffset: i32, width: i32, format: u32, type: u32, pixels: *void); +glTexSubImage2D: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, width: i32, height: i32, format: u32, type: u32, pixels: *void); +glBindTexture: proc(target: u32, texture: u32); +glDeleteTextures: proc(n: i32, textures: *u32); +glGenTextures: proc(n: i32, textures: *u32); +glIsTexture: proc(texture: u32): bool; + +load_1_1 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glDrawArrays), "glDrawArrays"); + set_proc_address(:**void(&glDrawElements), "glDrawElements"); + set_proc_address(:**void(&glPolygonOffset), "glPolygonOffset"); + set_proc_address(:**void(&glCopyTexImage1D), "glCopyTexImage1D"); + set_proc_address(:**void(&glCopyTexImage2D), "glCopyTexImage2D"); + set_proc_address(:**void(&glCopyTexSubImage1D), "glCopyTexSubImage1D"); + set_proc_address(:**void(&glCopyTexSubImage2D), "glCopyTexSubImage2D"); + set_proc_address(:**void(&glTexSubImage1D), "glTexSubImage1D"); + set_proc_address(:**void(&glTexSubImage2D), "glTexSubImage2D"); + set_proc_address(:**void(&glBindTexture), "glBindTexture"); + set_proc_address(:**void(&glDeleteTextures), "glDeleteTextures"); + set_proc_address(:**void(&glGenTextures), "glGenTextures"); + set_proc_address(:**void(&glIsTexture), "glIsTexture"); +} + + +// VERSION_1_2 +glDrawRangeElements: proc(mode: u32, start: u32, end: u32, count: i32, type: u32, indices: *void); +glTexImage3D: proc(target: u32, level: i32, internalformat: i32, width: i32, height: i32, depth: i32, border: i32, format: u32, type: u32, data: *void); +glTexSubImage3D: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, format: u32, type: u32, pixels: *void); +glCopyTexSubImage3D: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, x: i32, y: i32, width: i32, height: i32); + +load_1_2 :: proc(set_proc_address: Set_Proc_Address_Type) { + + set_proc_address(:**void(&glDrawRangeElements), "glDrawRangeElements"); + set_proc_address(:**void(&glTexImage3D), "glTexImage3D"); + set_proc_address(:**void(&glTexSubImage3D), "glTexSubImage3D"); + set_proc_address(:**void(&glCopyTexSubImage3D), "glCopyTexSubImage3D"); +} + + +// VERSION_1_3 +glActiveTexture: proc(texture: u32); +glSampleCoverage: proc(value: f32, invert: bool); +glCompressedTexImage3D: proc(target: u32, level: i32, internalformat: u32, width: i32, height: i32, depth: i32, border: i32, imageSize: i32, data: *void); +glCompressedTexImage2D: proc(target: u32, level: i32, internalformat: u32, width: i32, height: i32, border: i32, imageSize: i32, data: *void); +glCompressedTexImage1D: proc(target: u32, level: i32, internalformat: u32, width: i32, border: i32, imageSize: i32, data: *void); +glCompressedTexSubImage3D: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, format: u32, imageSize: i32, data: *void); +glCompressedTexSubImage2D: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, width: i32, height: i32, format: u32, imageSize: i32, data: *void); +glCompressedTexSubImage1D: proc(target: u32, level: i32, xoffset: i32, width: i32, format: u32, imageSize: i32, data: *void); +glGetCompressedTexImage: proc(target: u32, level: i32, img: *void); + +load_1_3 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glActiveTexture), "glActiveTexture"); + set_proc_address(:**void(&glSampleCoverage), "glSampleCoverage"); + set_proc_address(:**void(&glCompressedTexImage3D), "glCompressedTexImage3D"); + set_proc_address(:**void(&glCompressedTexImage2D), "glCompressedTexImage2D"); + set_proc_address(:**void(&glCompressedTexImage1D), "glCompressedTexImage1D"); + set_proc_address(:**void(&glCompressedTexSubImage3D), "glCompressedTexSubImage3D"); + set_proc_address(:**void(&glCompressedTexSubImage2D), "glCompressedTexSubImage2D"); + set_proc_address(:**void(&glCompressedTexSubImage1D), "glCompressedTexSubImage1D"); + set_proc_address(:**void(&glGetCompressedTexImage), "glGetCompressedTexImage"); +} + + +// VERSION_1_4 +glBlendFuncSeparate: proc(sfactorRGB: u32, dfactorRGB: u32, sfactorAlpha: u32, dfactorAlpha: u32); +glMultiDrawArrays: proc(mode: u32, first: *i32, count: *i32, drawcount: i32); +glMultiDrawElements: proc(mode: u32, count: *i32, type: u32, indices: **void, drawcount: i32); +glPointParameterf: proc(pname: u32, param: f32); +glPointParameterfv: proc(pname: u32, params: *f32); +glPointParameteri: proc(pname: u32, param: i32); +glPointParameteriv: proc(pname: u32, params: *i32); +glBlendColor: proc(red: f32, green: f32, blue: f32, alpha: f32); +glBlendEquation: proc(mode: u32); + + +load_1_4 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glBlendFuncSeparate), "glBlendFuncSeparate"); + set_proc_address(:**void(&glMultiDrawArrays), "glMultiDrawArrays"); + set_proc_address(:**void(&glMultiDrawElements), "glMultiDrawElements"); + set_proc_address(:**void(&glPointParameterf), "glPointParameterf"); + set_proc_address(:**void(&glPointParameterfv), "glPointParameterfv"); + set_proc_address(:**void(&glPointParameteri), "glPointParameteri"); + set_proc_address(:**void(&glPointParameteriv), "glPointParameteriv"); + set_proc_address(:**void(&glBlendColor), "glBlendColor"); + set_proc_address(:**void(&glBlendEquation), "glBlendEquation"); +} + + +// VERSION_1_5 +glGenQueries: proc(n: i32, ids: *u32); +glDeleteQueries: proc(n: i32, ids: *u32); +glIsQuery: proc(id: u32): bool; +glBeginQuery: proc(target: u32, id: u32); +glEndQuery: proc(target: u32); +glGetQueryiv: proc(target: u32, pname: u32, params: *i32); +glGetQueryObjectiv: proc(id: u32, pname: u32, params: *i32); +glGetQueryObjectuiv: proc(id: u32, pname: u32, params: *u32); +glBindBuffer: proc(target: u32, buffer: u32); +glDeleteBuffers: proc(n: i32, buffers: *u32); +glGenBuffers: proc(n: i32, buffers: *u32); +glIsBuffer: proc(buffer: u32): bool; +glBufferData: proc(target: u32, size: int, data: *void, usage: u32); +glBufferSubData: proc(target: u32, offset: int, size: int, data: *void); +glGetBufferSubData: proc(target: u32, offset: int, size: int, data: *void); +glMapBuffer: proc(target: u32, access: u32): *void; +glUnmapBuffer: proc(target: u32): bool; +glGetBufferParameteriv: proc(target: u32, pname: u32, params: *i32); +glGetBufferPointerv: proc(target: u32, pname: u32, params: **void); + +load_1_5 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glGenQueries), "glGenQueries"); + set_proc_address(:**void(&glDeleteQueries), "glDeleteQueries"); + set_proc_address(:**void(&glIsQuery), "glIsQuery"); + set_proc_address(:**void(&glBeginQuery), "glBeginQuery"); + set_proc_address(:**void(&glEndQuery), "glEndQuery"); + set_proc_address(:**void(&glGetQueryiv), "glGetQueryiv"); + set_proc_address(:**void(&glGetQueryObjectiv), "glGetQueryObjectiv"); + set_proc_address(:**void(&glGetQueryObjectuiv), "glGetQueryObjectuiv"); + set_proc_address(:**void(&glBindBuffer), "glBindBuffer"); + set_proc_address(:**void(&glDeleteBuffers), "glDeleteBuffers"); + set_proc_address(:**void(&glGenBuffers), "glGenBuffers"); + set_proc_address(:**void(&glIsBuffer), "glIsBuffer"); + set_proc_address(:**void(&glBufferData), "glBufferData"); + set_proc_address(:**void(&glBufferSubData), "glBufferSubData"); + set_proc_address(:**void(&glGetBufferSubData), "glGetBufferSubData"); + set_proc_address(:**void(&glMapBuffer), "glMapBuffer"); + set_proc_address(:**void(&glUnmapBuffer), "glUnmapBuffer"); + set_proc_address(:**void(&glGetBufferParameteriv), "glGetBufferParameteriv"); + set_proc_address(:**void(&glGetBufferPointerv), "glGetBufferPointerv"); +} + + +// VERSION_2_0 +glBlendEquationSeparate: proc(modeRGB: u32, modeAlpha: u32); +glDrawBuffers: proc(n: i32, bufs: *u32); +glStencilOpSeparate: proc(face: u32, sfail: u32, dpfail: u32, dppass: u32); +glStencilFuncSeparate: proc(face: u32, func: u32, ref: i32, mask: u32); +glStencilMaskSeparate: proc(face: u32, mask: u32); +glAttachShader: proc(program: u32, shader: u32); +glBindAttribLocation: proc(program: u32, index: u32, name: *char); +glCompileShader: proc(shader: u32); +glCreateProgram: proc(): u32; +glCreateShader: proc(type: u32): u32; +glDeleteProgram: proc(program: u32); +glDeleteShader: proc(shader: u32); +glDetachShader: proc(program: u32, shader: u32); +glDisableVertexAttribArray: proc(index: u32); +glEnableVertexAttribArray: proc(index: u32); +glGetActiveAttrib: proc(program: u32, index: u32, bufSize: i32, length: *i32, size: *i32, type: *u32, name: *u8); +glGetActiveUniform: proc(program: u32, index: u32, bufSize: i32, length: *i32, size: *i32, type: *u32, name: *u8); +glGetAttachedShaders: proc(program: u32, maxCount: i32, count: *i32, shaders: *u32); +glGetAttribLocation: proc(program: u32, name: *char): i32; +glGetProgramiv: proc(program: u32, pname: u32, params: *i32); +glGetProgramInfoLog: proc(program: u32, bufSize: i32, length: *i32, infoLog: *u8); +glGetShaderiv: proc(shader: u32, pname: u32, params: *i32); +glGetShaderInfoLog: proc(shader: u32, bufSize: i32, length: *i32, infoLog: *u8); +glGetShaderSource: proc(shader: u32, bufSize: i32, length: *i32, source: *u8); +glGetUniformLocation: proc(program: u32, name: *char): i32; +glGetUniformfv: proc(program: u32, location: i32, params: *f32); +glGetUniformiv: proc(program: u32, location: i32, params: *i32); +glGetVertexAttribdv: proc(index: u32, pname: u32, params: *f64); +glGetVertexAttribfv: proc(index: u32, pname: u32, params: *f32); +glGetVertexAttribiv: proc(index: u32, pname: u32, params: *i32); +glGetVertexAttribPointerv: proc(index: u32, pname: u32, pointer: *uintptr); +glIsProgram: proc(program: u32): bool; +glIsShader: proc(shader: u32): bool; +glLinkProgram: proc(program: u32); +glShaderSource: proc(shader: u32, count: i32, string: **char, length: *i32); +glUseProgram: proc(program: u32); +glUniform1f: proc(location: i32, v0: f32); +glUniform2f: proc(location: i32, v0: f32, v1: f32); +glUniform3f: proc(location: i32, v0: f32, v1: f32, v2: f32); +glUniform4f: proc(location: i32, v0: f32, v1: f32, v2: f32, v3: f32); +glUniform1i: proc(location: i32, v0: i32); +glUniform2i: proc(location: i32, v0: i32, v1: i32); +glUniform3i: proc(location: i32, v0: i32, v1: i32, v2: i32); +glUniform4i: proc(location: i32, v0: i32, v1: i32, v2: i32, v3: i32); +glUniform1fv: proc(location: i32, count: i32, value: *f32); +glUniform2fv: proc(location: i32, count: i32, value: *f32); +glUniform3fv: proc(location: i32, count: i32, value: *f32); +glUniform4fv: proc(location: i32, count: i32, value: *f32); +glUniform1iv: proc(location: i32, count: i32, value: *i32); +glUniform2iv: proc(location: i32, count: i32, value: *i32); +glUniform3iv: proc(location: i32, count: i32, value: *i32); +glUniform4iv: proc(location: i32, count: i32, value: *i32); +glUniformMatrix2fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix3fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix4fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glValidateProgram: proc(program: u32); +glVertexAttrib1d: proc(index: u32, x: f64); +glVertexAttrib1dv: proc(index: u32, v: *f64); +glVertexAttrib1f: proc(index: u32, x: f32); +glVertexAttrib1fv: proc(index: u32, v: *f32); +glVertexAttrib1s: proc(index: u32, x: i16); +glVertexAttrib1sv: proc(index: u32, v: *i16); +glVertexAttrib2d: proc(index: u32, x: f64, y: f64); +glVertexAttrib2dv: proc(index: u32, v: *[2]f64); +glVertexAttrib2f: proc(index: u32, x: f32, y: f32); +glVertexAttrib2fv: proc(index: u32, v: *[2]f32); +glVertexAttrib2s: proc(index: u32, x: i16, y: i16); +glVertexAttrib2sv: proc(index: u32, v: *[2]i16); +glVertexAttrib3d: proc(index: u32, x: f64, y: f64, z: f64); +glVertexAttrib3dv: proc(index: u32, v: *[3]f64); +glVertexAttrib3f: proc(index: u32, x: f32, y: f32, z: f32); +glVertexAttrib3fv: proc(index: u32, v: *[3]f32); +glVertexAttrib3s: proc(index: u32, x: i16, y: i16, z: i16); +glVertexAttrib3sv: proc(index: u32, v: *[3]i16); +glVertexAttrib4Nbv: proc(index: u32, v: *[4]i8); +glVertexAttrib4Niv: proc(index: u32, v: *[4]i32); +glVertexAttrib4Nsv: proc(index: u32, v: *[4]i16); +glVertexAttrib4Nub: proc(index: u32, x: u8, y: u8, z: u8, w: u8); +glVertexAttrib4Nubv: proc(index: u32, v: *[4]u8); +glVertexAttrib4Nuiv: proc(index: u32, v: *[4]u32); +glVertexAttrib4Nusv: proc(index: u32, v: *[4]u16); +glVertexAttrib4bv: proc(index: u32, v: *[4]i8); +glVertexAttrib4d: proc(index: u32, x: f64, y: f64, z: f64, w: f64); +glVertexAttrib4dv: proc(index: u32, v: *[4]f64); +glVertexAttrib4f: proc(index: u32, x: f32, y: f32, z: f32, w: f32); +glVertexAttrib4fv: proc(index: u32, v: *[4]f32); +glVertexAttrib4iv: proc(index: u32, v: *[4]i32); +glVertexAttrib4s: proc(index: u32, x: i16, y: i16, z: i16, w: i16); +glVertexAttrib4sv: proc(index: u32, v: *[4]i16); +glVertexAttrib4ubv: proc(index: u32, v: *[4]u8); +glVertexAttrib4uiv: proc(index: u32, v: *[4]u32); +glVertexAttrib4usv: proc(index: u32, v: *[4]u16); +glVertexAttribPointer: proc(index: u32, size: i32, type: u32, normalized: bool, stride: i32, pointer: uintptr); + +load_2_0 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glBlendEquationSeparate), "glBlendEquationSeparate"); + set_proc_address(:**void(&glDrawBuffers), "glDrawBuffers"); + set_proc_address(:**void(&glStencilOpSeparate), "glStencilOpSeparate"); + set_proc_address(:**void(&glStencilFuncSeparate), "glStencilFuncSeparate"); + set_proc_address(:**void(&glStencilMaskSeparate), "glStencilMaskSeparate"); + set_proc_address(:**void(&glAttachShader), "glAttachShader"); + set_proc_address(:**void(&glBindAttribLocation), "glBindAttribLocation"); + set_proc_address(:**void(&glCompileShader), "glCompileShader"); + set_proc_address(:**void(&glCreateProgram), "glCreateProgram"); + set_proc_address(:**void(&glCreateShader), "glCreateShader"); + set_proc_address(:**void(&glDeleteProgram), "glDeleteProgram"); + set_proc_address(:**void(&glDeleteShader), "glDeleteShader"); + set_proc_address(:**void(&glDetachShader), "glDetachShader"); + set_proc_address(:**void(&glDisableVertexAttribArray), "glDisableVertexAttribArray"); + set_proc_address(:**void(&glEnableVertexAttribArray), "glEnableVertexAttribArray"); + set_proc_address(:**void(&glGetActiveAttrib), "glGetActiveAttrib"); + set_proc_address(:**void(&glGetActiveUniform), "glGetActiveUniform"); + set_proc_address(:**void(&glGetAttachedShaders), "glGetAttachedShaders"); + set_proc_address(:**void(&glGetAttribLocation), "glGetAttribLocation"); + set_proc_address(:**void(&glGetProgramiv), "glGetProgramiv"); + set_proc_address(:**void(&glGetProgramInfoLog), "glGetProgramInfoLog"); + set_proc_address(:**void(&glGetShaderiv), "glGetShaderiv"); + set_proc_address(:**void(&glGetShaderInfoLog), "glGetShaderInfoLog"); + set_proc_address(:**void(&glGetShaderSource), "glGetShaderSource"); + set_proc_address(:**void(&glGetUniformLocation), "glGetUniformLocation"); + set_proc_address(:**void(&glGetUniformfv), "glGetUniformfv"); + set_proc_address(:**void(&glGetUniformiv), "glGetUniformiv"); + set_proc_address(:**void(&glGetVertexAttribdv), "glGetVertexAttribdv"); + set_proc_address(:**void(&glGetVertexAttribfv), "glGetVertexAttribfv"); + set_proc_address(:**void(&glGetVertexAttribiv), "glGetVertexAttribiv"); + set_proc_address(:**void(&glGetVertexAttribPointerv), "glGetVertexAttribPointerv"); + set_proc_address(:**void(&glIsProgram), "glIsProgram"); + set_proc_address(:**void(&glIsShader), "glIsShader"); + set_proc_address(:**void(&glLinkProgram), "glLinkProgram"); + set_proc_address(:**void(&glShaderSource), "glShaderSource"); + set_proc_address(:**void(&glUseProgram), "glUseProgram"); + set_proc_address(:**void(&glUniform1f), "glUniform1f"); + set_proc_address(:**void(&glUniform2f), "glUniform2f"); + set_proc_address(:**void(&glUniform3f), "glUniform3f"); + set_proc_address(:**void(&glUniform4f), "glUniform4f"); + set_proc_address(:**void(&glUniform1i), "glUniform1i"); + set_proc_address(:**void(&glUniform2i), "glUniform2i"); + set_proc_address(:**void(&glUniform3i), "glUniform3i"); + set_proc_address(:**void(&glUniform4i), "glUniform4i"); + set_proc_address(:**void(&glUniform1fv), "glUniform1fv"); + set_proc_address(:**void(&glUniform2fv), "glUniform2fv"); + set_proc_address(:**void(&glUniform3fv), "glUniform3fv"); + set_proc_address(:**void(&glUniform4fv), "glUniform4fv"); + set_proc_address(:**void(&glUniform1iv), "glUniform1iv"); + set_proc_address(:**void(&glUniform2iv), "glUniform2iv"); + set_proc_address(:**void(&glUniform3iv), "glUniform3iv"); + set_proc_address(:**void(&glUniform4iv), "glUniform4iv"); + set_proc_address(:**void(&glUniformMatrix2fv), "glUniformMatrix2fv"); + set_proc_address(:**void(&glUniformMatrix3fv), "glUniformMatrix3fv"); + set_proc_address(:**void(&glUniformMatrix4fv), "glUniformMatrix4fv"); + set_proc_address(:**void(&glValidateProgram), "glValidateProgram"); + set_proc_address(:**void(&glVertexAttrib1d), "glVertexAttrib1d"); + set_proc_address(:**void(&glVertexAttrib1dv), "glVertexAttrib1dv"); + set_proc_address(:**void(&glVertexAttrib1f), "glVertexAttrib1f"); + set_proc_address(:**void(&glVertexAttrib1fv), "glVertexAttrib1fv"); + set_proc_address(:**void(&glVertexAttrib1s), "glVertexAttrib1s"); + set_proc_address(:**void(&glVertexAttrib1sv), "glVertexAttrib1sv"); + set_proc_address(:**void(&glVertexAttrib2d), "glVertexAttrib2d"); + set_proc_address(:**void(&glVertexAttrib2dv), "glVertexAttrib2dv"); + set_proc_address(:**void(&glVertexAttrib2f), "glVertexAttrib2f"); + set_proc_address(:**void(&glVertexAttrib2fv), "glVertexAttrib2fv"); + set_proc_address(:**void(&glVertexAttrib2s), "glVertexAttrib2s"); + set_proc_address(:**void(&glVertexAttrib2sv), "glVertexAttrib2sv"); + set_proc_address(:**void(&glVertexAttrib3d), "glVertexAttrib3d"); + set_proc_address(:**void(&glVertexAttrib3dv), "glVertexAttrib3dv"); + set_proc_address(:**void(&glVertexAttrib3f), "glVertexAttrib3f"); + set_proc_address(:**void(&glVertexAttrib3fv), "glVertexAttrib3fv"); + set_proc_address(:**void(&glVertexAttrib3s), "glVertexAttrib3s"); + set_proc_address(:**void(&glVertexAttrib3sv), "glVertexAttrib3sv"); + set_proc_address(:**void(&glVertexAttrib4Nbv), "glVertexAttrib4Nbv"); + set_proc_address(:**void(&glVertexAttrib4Niv), "glVertexAttrib4Niv"); + set_proc_address(:**void(&glVertexAttrib4Nsv), "glVertexAttrib4Nsv"); + set_proc_address(:**void(&glVertexAttrib4Nub), "glVertexAttrib4Nub"); + set_proc_address(:**void(&glVertexAttrib4Nubv), "glVertexAttrib4Nubv"); + set_proc_address(:**void(&glVertexAttrib4Nuiv), "glVertexAttrib4Nuiv"); + set_proc_address(:**void(&glVertexAttrib4Nusv), "glVertexAttrib4Nusv"); + set_proc_address(:**void(&glVertexAttrib4bv), "glVertexAttrib4bv"); + set_proc_address(:**void(&glVertexAttrib4d), "glVertexAttrib4d"); + set_proc_address(:**void(&glVertexAttrib4dv), "glVertexAttrib4dv"); + set_proc_address(:**void(&glVertexAttrib4f), "glVertexAttrib4f"); + set_proc_address(:**void(&glVertexAttrib4fv), "glVertexAttrib4fv"); + set_proc_address(:**void(&glVertexAttrib4iv), "glVertexAttrib4iv"); + set_proc_address(:**void(&glVertexAttrib4s), "glVertexAttrib4s"); + set_proc_address(:**void(&glVertexAttrib4sv), "glVertexAttrib4sv"); + set_proc_address(:**void(&glVertexAttrib4ubv), "glVertexAttrib4ubv"); + set_proc_address(:**void(&glVertexAttrib4uiv), "glVertexAttrib4uiv"); + set_proc_address(:**void(&glVertexAttrib4usv), "glVertexAttrib4usv"); + set_proc_address(:**void(&glVertexAttribPointer), "glVertexAttribPointer"); +} + + +// VERSION_2_1 +glUniformMatrix2x3fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix3x2fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix2x4fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix4x2fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix3x4fv: proc(location: i32, count: i32, transpose: bool, value: *f32); +glUniformMatrix4x3fv: proc(location: i32, count: i32, transpose: bool, value: *f32); + +load_2_1 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glUniformMatrix2x3fv), "glUniformMatrix2x3fv"); + set_proc_address(:**void(&glUniformMatrix3x2fv), "glUniformMatrix3x2fv"); + set_proc_address(:**void(&glUniformMatrix2x4fv), "glUniformMatrix2x4fv"); + set_proc_address(:**void(&glUniformMatrix4x2fv), "glUniformMatrix4x2fv"); + set_proc_address(:**void(&glUniformMatrix3x4fv), "glUniformMatrix3x4fv"); + set_proc_address(:**void(&glUniformMatrix4x3fv), "glUniformMatrix4x3fv"); +} + + +// VERSION_3_0 +glColorMaski: proc(index: u32, r: bool, g: bool, b: bool, a: bool); +glGetBooleani_v: proc(target: u32, index: u32, data: *bool); +glGetIntegeri_v: proc(target: u32, index: u32, data: *i32); +glEnablei: proc(target: u32, index: u32); +glDisablei: proc(target: u32, index: u32); +glIsEnabledi: proc(target: u32, index: u32): bool; +glBeginTransformFeedback: proc(primitiveMode: u32); +glEndTransformFeedback: proc(); +glBindBufferRange: proc(target: u32, index: u32, buffer: u32, offset: int, size: int); +glBindBufferBase: proc(target: u32, index: u32, buffer: u32); +glTransformFeedbackVaryings: proc(program: u32, count: i32, varyings: **char, bufferMode: u32); +glGetTransformFeedbackVarying: proc(program: u32, index: u32, bufSize: i32, length: *i32, size: *i32, type: *u32, name: *u8); +glClampColor: proc(target: u32, clamp: u32); +glBeginConditionalRender: proc(id: u32, mode: u32); +glEndConditionalRender: proc(); +glVertexAttribIPointer: proc(index: u32, size: i32, type: u32, stride: i32, pointer: uintptr); +glGetVertexAttribIiv: proc(index: u32, pname: u32, params: *i32); +glGetVertexAttribIuiv: proc(index: u32, pname: u32, params: *u32); +glVertexAttribI1i: proc(index: u32, x: i32); +glVertexAttribI2i: proc(index: u32, x: i32, y: i32); +glVertexAttribI3i: proc(index: u32, x: i32, y: i32, z: i32); +glVertexAttribI4i: proc(index: u32, x: i32, y: i32, z: i32, w: i32); +glVertexAttribI1ui: proc(index: u32, x: u32); +glVertexAttribI2ui: proc(index: u32, x: u32, y: u32); +glVertexAttribI3ui: proc(index: u32, x: u32, y: u32, z: u32); +glVertexAttribI4ui: proc(index: u32, x: u32, y: u32, z: u32, w: u32); +glVertexAttribI1iv: proc(index: u32, v: *i32); +glVertexAttribI2iv: proc(index: u32, v: *i32); +glVertexAttribI3iv: proc(index: u32, v: *i32); +glVertexAttribI4iv: proc(index: u32, v: *i32); +glVertexAttribI1uiv: proc(index: u32, v: *u32); +glVertexAttribI2uiv: proc(index: u32, v: *u32); +glVertexAttribI3uiv: proc(index: u32, v: *u32); +glVertexAttribI4uiv: proc(index: u32, v: *u32); +glVertexAttribI4bv: proc(index: u32, v: *i8); +glVertexAttribI4sv: proc(index: u32, v: *i16); +glVertexAttribI4ubv: proc(index: u32, v: *u8); +glVertexAttribI4usv: proc(index: u32, v: *u16); +glGetUniformuiv: proc(program: u32, location: i32, params: *u32); +glBindFragDataLocation: proc(program: u32, color: u32, name: *char); +glGetFragDataLocation: proc(program: u32, name: *char): i32; +glUniform1ui: proc(location: i32, v0: u32); +glUniform2ui: proc(location: i32, v0: u32, v1: u32); +glUniform3ui: proc(location: i32, v0: u32, v1: u32, v2: u32); +glUniform4ui: proc(location: i32, v0: u32, v1: u32, v2: u32, v3: u32); +glUniform1uiv: proc(location: i32, count: i32, value: *u32); +glUniform2uiv: proc(location: i32, count: i32, value: *u32); +glUniform3uiv: proc(location: i32, count: i32, value: *u32); +glUniform4uiv: proc(location: i32, count: i32, value: *u32); +glTexParameterIiv: proc(target: u32, pname: u32, params: *i32); +glTexParameterIuiv: proc(target: u32, pname: u32, params: *u32); +glGetTexParameterIiv: proc(target: u32, pname: u32, params: *i32); +glGetTexParameterIuiv: proc(target: u32, pname: u32, params: *u32); +glClearBufferiv: proc(buffer: u32, drawbuffer: i32, value: *i32); +glClearBufferuiv: proc(buffer: u32, drawbuffer: i32, value: *u32); +glClearBufferfv: proc(buffer: u32, drawbuffer: i32, value: *f32); +glClearBufferfi: proc(buffer: u32, drawbuffer: i32, depth: f32, stencil: i32): *void; +glGetStringi: proc(name: u32, index: u32): *char; +glIsRenderbuffer: proc(renderbuffer: u32): bool; +glBindRenderbuffer: proc(target: u32, renderbuffer: u32); +glDeleteRenderbuffers: proc(n: i32, renderbuffers: *u32); +glGenRenderbuffers: proc(n: i32, renderbuffers: *u32); +glRenderbufferStorage: proc(target: u32, internalformat: u32, width: i32, height: i32); +glGetRenderbufferParameteriv: proc(target: u32, pname: u32, params: *i32); +glIsFramebuffer: proc(framebuffer: u32): bool; +glBindFramebuffer: proc(target: u32, framebuffer: u32); +glDeleteFramebuffers: proc(n: i32, framebuffers: *u32); +glGenFramebuffers: proc(n: i32, framebuffers: *u32); +glCheckFramebufferStatus: proc(target: u32): u32; +glFramebufferTexture1D: proc(target: u32, attachment: u32, textarget: u32, texture: u32, level: i32); +glFramebufferTexture2D: proc(target: u32, attachment: u32, textarget: u32, texture: u32, level: i32); +glFramebufferTexture3D: proc(target: u32, attachment: u32, textarget: u32, texture: u32, level: i32, zoffset: i32); +glFramebufferRenderbuffer: proc(target: u32, attachment: u32, renderbuffertarget: u32, renderbuffer: u32); +glGetFramebufferAttachmentParameteriv: proc(target: u32, attachment: u32, pname: u32, params: *i32); +glGenerateMipmap: proc(target: u32); +glBlitFramebuffer: proc(srcX0: i32, srcY0: i32, srcX1: i32, srcY1: i32, dstX0: i32, dstY0: i32, dstX1: i32, dstY1: i32, mask: u32, filter: u32); +glRenderbufferStorageMultisample: proc(target: u32, samples: i32, internalformat: u32, width: i32, height: i32); +glFramebufferTextureLayer: proc(target: u32, attachment: u32, texture: u32, level: i32, layer: i32); +glMapBufferRange: proc(target: u32, offset: int, length: int, access: u32): *void; +glFlushMappedBufferRange: proc(target: u32, offset: int, length: int); +glBindVertexArray: proc(array: u32); +glDeleteVertexArrays: proc(n: i32, arrays: *u32); +glGenVertexArrays: proc(n: i32, arrays: *u32); +glIsVertexArray: proc(array: u32): bool; + +load_3_0 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glColorMaski), "glColorMaski"); + set_proc_address(:**void(&glGetBooleani_v), "glGetBooleani_v"); + set_proc_address(:**void(&glGetIntegeri_v), "glGetIntegeri_v"); + set_proc_address(:**void(&glEnablei), "glEnablei"); + set_proc_address(:**void(&glDisablei), "glDisablei"); + set_proc_address(:**void(&glIsEnabledi), "glIsEnabledi"); + set_proc_address(:**void(&glBeginTransformFeedback), "glBeginTransformFeedback"); + set_proc_address(:**void(&glEndTransformFeedback), "glEndTransformFeedback"); + set_proc_address(:**void(&glBindBufferRange), "glBindBufferRange"); + set_proc_address(:**void(&glBindBufferBase), "glBindBufferBase"); + set_proc_address(:**void(&glTransformFeedbackVaryings), "glTransformFeedbackVaryings"); + set_proc_address(:**void(&glGetTransformFeedbackVarying), "glGetTransformFeedbackVarying"); + set_proc_address(:**void(&glClampColor), "glClampColor"); + set_proc_address(:**void(&glBeginConditionalRender), "glBeginConditionalRender"); + set_proc_address(:**void(&glEndConditionalRender), "glEndConditionalRender"); + set_proc_address(:**void(&glVertexAttribIPointer), "glVertexAttribIPointer"); + set_proc_address(:**void(&glGetVertexAttribIiv), "glGetVertexAttribIiv"); + set_proc_address(:**void(&glGetVertexAttribIuiv), "glGetVertexAttribIuiv"); + set_proc_address(:**void(&glVertexAttribI1i), "glVertexAttribI1i"); + set_proc_address(:**void(&glVertexAttribI2i), "glVertexAttribI2i"); + set_proc_address(:**void(&glVertexAttribI3i), "glVertexAttribI3i"); + set_proc_address(:**void(&glVertexAttribI4i), "glVertexAttribI4i"); + set_proc_address(:**void(&glVertexAttribI1ui), "glVertexAttribI1ui"); + set_proc_address(:**void(&glVertexAttribI2ui), "glVertexAttribI2ui"); + set_proc_address(:**void(&glVertexAttribI3ui), "glVertexAttribI3ui"); + set_proc_address(:**void(&glVertexAttribI4ui), "glVertexAttribI4ui"); + set_proc_address(:**void(&glVertexAttribI1iv), "glVertexAttribI1iv"); + set_proc_address(:**void(&glVertexAttribI2iv), "glVertexAttribI2iv"); + set_proc_address(:**void(&glVertexAttribI3iv), "glVertexAttribI3iv"); + set_proc_address(:**void(&glVertexAttribI4iv), "glVertexAttribI4iv"); + set_proc_address(:**void(&glVertexAttribI1uiv), "glVertexAttribI1uiv"); + set_proc_address(:**void(&glVertexAttribI2uiv), "glVertexAttribI2uiv"); + set_proc_address(:**void(&glVertexAttribI3uiv), "glVertexAttribI3uiv"); + set_proc_address(:**void(&glVertexAttribI4uiv), "glVertexAttribI4uiv"); + set_proc_address(:**void(&glVertexAttribI4bv), "glVertexAttribI4bv"); + set_proc_address(:**void(&glVertexAttribI4sv), "glVertexAttribI4sv"); + set_proc_address(:**void(&glVertexAttribI4ubv), "glVertexAttribI4ubv"); + set_proc_address(:**void(&glVertexAttribI4usv), "glVertexAttribI4usv"); + set_proc_address(:**void(&glGetUniformuiv), "glGetUniformuiv"); + set_proc_address(:**void(&glBindFragDataLocation), "glBindFragDataLocation"); + set_proc_address(:**void(&glGetFragDataLocation), "glGetFragDataLocation"); + set_proc_address(:**void(&glUniform1ui), "glUniform1ui"); + set_proc_address(:**void(&glUniform2ui), "glUniform2ui"); + set_proc_address(:**void(&glUniform3ui), "glUniform3ui"); + set_proc_address(:**void(&glUniform4ui), "glUniform4ui"); + set_proc_address(:**void(&glUniform1uiv), "glUniform1uiv"); + set_proc_address(:**void(&glUniform2uiv), "glUniform2uiv"); + set_proc_address(:**void(&glUniform3uiv), "glUniform3uiv"); + set_proc_address(:**void(&glUniform4uiv), "glUniform4uiv"); + set_proc_address(:**void(&glTexParameterIiv), "glTexParameterIiv"); + set_proc_address(:**void(&glTexParameterIuiv), "glTexParameterIuiv"); + set_proc_address(:**void(&glGetTexParameterIiv), "glGetTexParameterIiv"); + set_proc_address(:**void(&glGetTexParameterIuiv), "glGetTexParameterIuiv"); + set_proc_address(:**void(&glClearBufferiv), "glClearBufferiv"); + set_proc_address(:**void(&glClearBufferuiv), "glClearBufferuiv"); + set_proc_address(:**void(&glClearBufferfv), "glClearBufferfv"); + set_proc_address(:**void(&glClearBufferfi), "glClearBufferfi"); + set_proc_address(:**void(&glGetStringi), "glGetStringi"); + set_proc_address(:**void(&glIsRenderbuffer), "glIsRenderbuffer"); + set_proc_address(:**void(&glBindRenderbuffer), "glBindRenderbuffer"); + set_proc_address(:**void(&glDeleteRenderbuffers), "glDeleteRenderbuffers"); + set_proc_address(:**void(&glGenRenderbuffers), "glGenRenderbuffers"); + set_proc_address(:**void(&glRenderbufferStorage), "glRenderbufferStorage"); + set_proc_address(:**void(&glGetRenderbufferParameteriv), "glGetRenderbufferParameteriv"); + set_proc_address(:**void(&glIsFramebuffer), "glIsFramebuffer"); + set_proc_address(:**void(&glBindFramebuffer), "glBindFramebuffer"); + set_proc_address(:**void(&glDeleteFramebuffers), "glDeleteFramebuffers"); + set_proc_address(:**void(&glGenFramebuffers), "glGenFramebuffers"); + set_proc_address(:**void(&glCheckFramebufferStatus), "glCheckFramebufferStatus"); + set_proc_address(:**void(&glFramebufferTexture1D), "glFramebufferTexture1D"); + set_proc_address(:**void(&glFramebufferTexture2D), "glFramebufferTexture2D"); + set_proc_address(:**void(&glFramebufferTexture3D), "glFramebufferTexture3D"); + set_proc_address(:**void(&glFramebufferRenderbuffer), "glFramebufferRenderbuffer"); + set_proc_address(:**void(&glGetFramebufferAttachmentParameteriv), "glGetFramebufferAttachmentParameteriv"); + set_proc_address(:**void(&glGenerateMipmap), "glGenerateMipmap"); + set_proc_address(:**void(&glBlitFramebuffer), "glBlitFramebuffer"); + set_proc_address(:**void(&glRenderbufferStorageMultisample), "glRenderbufferStorageMultisample"); + set_proc_address(:**void(&glFramebufferTextureLayer), "glFramebufferTextureLayer"); + set_proc_address(:**void(&glMapBufferRange), "glMapBufferRange"); + set_proc_address(:**void(&glFlushMappedBufferRange), "glFlushMappedBufferRange"); + set_proc_address(:**void(&glBindVertexArray), "glBindVertexArray"); + set_proc_address(:**void(&glDeleteVertexArrays), "glDeleteVertexArrays"); + set_proc_address(:**void(&glGenVertexArrays), "glGenVertexArrays"); + set_proc_address(:**void(&glIsVertexArray), "glIsVertexArray"); +} + + +// VERSION_3_1 +glDrawArraysInstanced: proc(mode: u32, first: i32, count: i32, instancecount: i32); +glDrawElementsInstanced: proc(mode: u32, count: i32, type: u32, indices: *void, instancecount: i32); +glTexBuffer: proc(target: u32, internalformat: u32, buffer: u32); +glPrimitiveRestartIndex: proc(index: u32); +glCopyBufferSubData: proc(readTarget: u32, writeTarget: u32, readOffset: int, writeOffset: int, size: int); +glGetUniformIndices: proc(program: u32, uniformCount: i32, uniformNames: **char, uniformIndices: *u32); +glGetActiveUniformsiv: proc(program: u32, uniformCount: i32, uniformIndices: *u32, pname: u32, params: *i32); +glGetActiveUniformName: proc(program: u32, uniformIndex: u32, bufSize: i32, length: *i32, uniformName: *u8); +glGetUniformBlockIndex: proc(program: u32, uniformBlockName: *char): u32; +glGetActiveUniformBlockiv: proc(program: u32, uniformBlockIndex: u32, pname: u32, params: *i32); +glGetActiveUniformBlockName: proc(program: u32, uniformBlockIndex: u32, bufSize: i32, length: *i32, uniformBlockName: *u8); +glUniformBlockBinding: proc(program: u32, uniformBlockIndex: u32, uniformBlockBinding: u32); + +load_3_1 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glDrawArraysInstanced), "glDrawArraysInstanced"); + set_proc_address(:**void(&glDrawElementsInstanced), "glDrawElementsInstanced"); + set_proc_address(:**void(&glTexBuffer), "glTexBuffer"); + set_proc_address(:**void(&glPrimitiveRestartIndex), "glPrimitiveRestartIndex"); + set_proc_address(:**void(&glCopyBufferSubData), "glCopyBufferSubData"); + set_proc_address(:**void(&glGetUniformIndices), "glGetUniformIndices"); + set_proc_address(:**void(&glGetActiveUniformsiv), "glGetActiveUniformsiv"); + set_proc_address(:**void(&glGetActiveUniformName), "glGetActiveUniformName"); + set_proc_address(:**void(&glGetUniformBlockIndex), "glGetUniformBlockIndex"); + set_proc_address(:**void(&glGetActiveUniformBlockiv), "glGetActiveUniformBlockiv"); + set_proc_address(:**void(&glGetActiveUniformBlockName), "glGetActiveUniformBlockName"); + set_proc_address(:**void(&glUniformBlockBinding), "glUniformBlockBinding"); +} + + +// VERSION_3_2 +glDrawElementsBaseVertex: proc(mode: u32, count: i32, type: u32, indices: *void, basevertex: i32); +glDrawRangeElementsBaseVertex: proc(mode: u32, start: u32, end: u32, count: i32, type: u32, indices: *void, basevertex: i32); +glDrawElementsInstancedBaseVertex: proc(mode: u32, count: i32, type: u32, indices: *void, instancecount: i32, basevertex: i32); +glMultiDrawElementsBaseVertex: proc(mode: u32, count: *i32, type: u32, indices: **void, drawcount: i32, basevertex: *i32); +glProvokingVertex: proc(mode: u32); +glFenceSync: proc(condition: u32, flags: u32): sync_t; +glIsSync: proc(sync: sync_t): bool; +glDeleteSync: proc(sync: sync_t); +glClientWaitSync: proc(sync: sync_t, flags: u32, timeout: u64): u32; +glWaitSync: proc(sync: sync_t, flags: u32, timeout: u64); +glGetInteger64v: proc(pname: u32, data: *i64); +glGetSynciv: proc(sync: sync_t, pname: u32, bufSize: i32, length: *i32, values: *i32); +glGetInteger64i_v: proc(target: u32, index: u32, data: *i64); +glGetBufferParameteri64v: proc(target: u32, pname: u32, params: *i64); +glFramebufferTexture: proc(target: u32, attachment: u32, texture: u32, level: i32); +glTexImage2DMultisample: proc(target: u32, samples: i32, internalformat: u32, width: i32, height: i32, fixedsamplelocations: bool); +glTexImage3DMultisample: proc(target: u32, samples: i32, internalformat: u32, width: i32, height: i32, depth: i32, fixedsamplelocations: bool); +glGetMultisamplefv: proc(pname: u32, index: u32, val: *f32); +glSampleMaski: proc(maskNumber: u32, mask: u32); + +load_3_2 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glDrawElementsBaseVertex), "glDrawElementsBaseVertex"); + set_proc_address(:**void(&glDrawRangeElementsBaseVertex), "glDrawRangeElementsBaseVertex"); + set_proc_address(:**void(&glDrawElementsInstancedBaseVertex), "glDrawElementsInstancedBaseVertex"); + set_proc_address(:**void(&glMultiDrawElementsBaseVertex), "glMultiDrawElementsBaseVertex"); + set_proc_address(:**void(&glProvokingVertex), "glProvokingVertex"); + set_proc_address(:**void(&glFenceSync), "glFenceSync"); + set_proc_address(:**void(&glIsSync), "glIsSync"); + set_proc_address(:**void(&glDeleteSync), "glDeleteSync"); + set_proc_address(:**void(&glClientWaitSync), "glClientWaitSync"); + set_proc_address(:**void(&glWaitSync), "glWaitSync"); + set_proc_address(:**void(&glGetInteger64v), "glGetInteger64v"); + set_proc_address(:**void(&glGetSynciv), "glGetSynciv"); + set_proc_address(:**void(&glGetInteger64i_v), "glGetInteger64i_v"); + set_proc_address(:**void(&glGetBufferParameteri64v), "glGetBufferParameteri64v"); + set_proc_address(:**void(&glFramebufferTexture), "glFramebufferTexture"); + set_proc_address(:**void(&glTexImage2DMultisample), "glTexImage2DMultisample"); + set_proc_address(:**void(&glTexImage3DMultisample), "glTexImage3DMultisample"); + set_proc_address(:**void(&glGetMultisamplefv), "glGetMultisamplefv"); + set_proc_address(:**void(&glSampleMaski), "glSampleMaski"); +} + + +// VERSION_3_3 +glBindFragDataLocationIndexed: proc(program: u32, colorNumber: u32, index: u32, name: *char); +glGetFragDataIndex: proc(program: u32, name: *char): i32; +glGenSamplers: proc(count: i32, samplers: *u32); +glDeleteSamplers: proc(count: i32, samplers: *u32); +glIsSampler: proc(sampler: u32): bool; +glBindSampler: proc(unit: u32, sampler: u32); +glSamplerParameteri: proc(sampler: u32, pname: u32, param: i32); +glSamplerParameteriv: proc(sampler: u32, pname: u32, param: *i32); +glSamplerParameterf: proc(sampler: u32, pname: u32, param: f32); +glSamplerParameterfv: proc(sampler: u32, pname: u32, param: *f32); +glSamplerParameterIiv: proc(sampler: u32, pname: u32, param: *i32); +glSamplerParameterIuiv: proc(sampler: u32, pname: u32, param: *u32); +glGetSamplerParameteriv: proc(sampler: u32, pname: u32, params: *i32); +glGetSamplerParameterIiv: proc(sampler: u32, pname: u32, params: *i32); +glGetSamplerParameterfv: proc(sampler: u32, pname: u32, params: *f32); +glGetSamplerParameterIuiv: proc(sampler: u32, pname: u32, params: *u32); +glQueryCounter: proc(id: u32, target: u32); +glGetQueryObjecti64v: proc(id: u32, pname: u32, params: *i64); +glGetQueryObjectui64v: proc(id: u32, pname: u32, params: *u64); +glVertexAttribDivisor: proc(index: u32, divisor: u32); +glVertexAttribP1ui: proc(index: u32, type: u32, normalized: bool, value: u32); +glVertexAttribP1uiv: proc(index: u32, type: u32, normalized: bool, value: *u32); +glVertexAttribP2ui: proc(index: u32, type: u32, normalized: bool, value: u32); +glVertexAttribP2uiv: proc(index: u32, type: u32, normalized: bool, value: *u32); +glVertexAttribP3ui: proc(index: u32, type: u32, normalized: bool, value: u32); +glVertexAttribP3uiv: proc(index: u32, type: u32, normalized: bool, value: *u32); +glVertexAttribP4ui: proc(index: u32, type: u32, normalized: bool, value: u32); +glVertexAttribP4uiv: proc(index: u32, type: u32, normalized: bool, value: *u32); +glVertexP2ui: proc(type: u32, value: u32); +glVertexP2uiv: proc(type: u32, value: *u32); +glVertexP3ui: proc(type: u32, value: u32); +glVertexP3uiv: proc(type: u32, value: *u32); +glVertexP4ui: proc(type: u32, value: u32); +glVertexP4uiv: proc(type: u32, value: *u32); +glTexCoordP1ui: proc(type: u32, coords: u32); +glTexCoordP1uiv: proc(type: u32, coords: *u32); +glTexCoordP2ui: proc(type: u32, coords: u32); +glTexCoordP2uiv: proc(type: u32, coords: *u32); +glTexCoordP3ui: proc(type: u32, coords: u32); +glTexCoordP3uiv: proc(type: u32, coords: *u32); +glTexCoordP4ui: proc(type: u32, coords: u32); +glTexCoordP4uiv: proc(type: u32, coords: *u32); +glMultiTexCoordP1ui: proc(texture: u32, type: u32, coords: u32); +glMultiTexCoordP1uiv: proc(texture: u32, type: u32, coords: *u32); +glMultiTexCoordP2ui: proc(texture: u32, type: u32, coords: u32); +glMultiTexCoordP2uiv: proc(texture: u32, type: u32, coords: *u32); +glMultiTexCoordP3ui: proc(texture: u32, type: u32, coords: u32); +glMultiTexCoordP3uiv: proc(texture: u32, type: u32, coords: *u32); +glMultiTexCoordP4ui: proc(texture: u32, type: u32, coords: u32); +glMultiTexCoordP4uiv: proc(texture: u32, type: u32, coords: *u32); +glNormalP3ui: proc(type: u32, coords: u32); +glNormalP3uiv: proc(type: u32, coords: *u32); +glColorP3ui: proc(type: u32, color: u32); +glColorP3uiv: proc(type: u32, color: *u32); +glColorP4ui: proc(type: u32, color: u32); +glColorP4uiv: proc(type: u32, color: *u32); +glSecondaryColorP3ui: proc(type: u32, color: u32); +glSecondaryColorP3uiv: proc(type: u32, color: *u32); + +load_3_3 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glBindFragDataLocationIndexed), "glBindFragDataLocationIndexed"); + set_proc_address(:**void(&glGetFragDataIndex), "glGetFragDataIndex"); + set_proc_address(:**void(&glGenSamplers), "glGenSamplers"); + set_proc_address(:**void(&glDeleteSamplers), "glDeleteSamplers"); + set_proc_address(:**void(&glIsSampler), "glIsSampler"); + set_proc_address(:**void(&glBindSampler), "glBindSampler"); + set_proc_address(:**void(&glSamplerParameteri), "glSamplerParameteri"); + set_proc_address(:**void(&glSamplerParameteriv), "glSamplerParameteriv"); + set_proc_address(:**void(&glSamplerParameterf), "glSamplerParameterf"); + set_proc_address(:**void(&glSamplerParameterfv), "glSamplerParameterfv"); + set_proc_address(:**void(&glSamplerParameterIiv), "glSamplerParameterIiv"); + set_proc_address(:**void(&glSamplerParameterIuiv), "glSamplerParameterIuiv"); + set_proc_address(:**void(&glGetSamplerParameteriv), "glGetSamplerParameteriv"); + set_proc_address(:**void(&glGetSamplerParameterIiv), "glGetSamplerParameterIiv"); + set_proc_address(:**void(&glGetSamplerParameterfv), "glGetSamplerParameterfv"); + set_proc_address(:**void(&glGetSamplerParameterIuiv), "glGetSamplerParameterIuiv"); + set_proc_address(:**void(&glQueryCounter), "glQueryCounter"); + set_proc_address(:**void(&glGetQueryObjecti64v), "glGetQueryObjecti64v"); + set_proc_address(:**void(&glGetQueryObjectui64v), "glGetQueryObjectui64v"); + set_proc_address(:**void(&glVertexAttribDivisor), "glVertexAttribDivisor"); + set_proc_address(:**void(&glVertexAttribP1ui), "glVertexAttribP1ui"); + set_proc_address(:**void(&glVertexAttribP1uiv), "glVertexAttribP1uiv"); + set_proc_address(:**void(&glVertexAttribP2ui), "glVertexAttribP2ui"); + set_proc_address(:**void(&glVertexAttribP2uiv), "glVertexAttribP2uiv"); + set_proc_address(:**void(&glVertexAttribP3ui), "glVertexAttribP3ui"); + set_proc_address(:**void(&glVertexAttribP3uiv), "glVertexAttribP3uiv"); + set_proc_address(:**void(&glVertexAttribP4ui), "glVertexAttribP4ui"); + set_proc_address(:**void(&glVertexAttribP4uiv), "glVertexAttribP4uiv"); + set_proc_address(:**void(&glVertexP2ui), "glVertexP2ui"); + set_proc_address(:**void(&glVertexP2uiv), "glVertexP2uiv"); + set_proc_address(:**void(&glVertexP3ui), "glVertexP3ui"); + set_proc_address(:**void(&glVertexP3uiv), "glVertexP3uiv"); + set_proc_address(:**void(&glVertexP4ui), "glVertexP4ui"); + set_proc_address(:**void(&glVertexP4uiv), "glVertexP4uiv"); + set_proc_address(:**void(&glTexCoordP1ui), "glTexCoordP1ui"); + set_proc_address(:**void(&glTexCoordP1uiv), "glTexCoordP1uiv"); + set_proc_address(:**void(&glTexCoordP2ui), "glTexCoordP2ui"); + set_proc_address(:**void(&glTexCoordP2uiv), "glTexCoordP2uiv"); + set_proc_address(:**void(&glTexCoordP3ui), "glTexCoordP3ui"); + set_proc_address(:**void(&glTexCoordP3uiv), "glTexCoordP3uiv"); + set_proc_address(:**void(&glTexCoordP4ui), "glTexCoordP4ui"); + set_proc_address(:**void(&glTexCoordP4uiv), "glTexCoordP4uiv"); + set_proc_address(:**void(&glMultiTexCoordP1ui), "glMultiTexCoordP1ui"); + set_proc_address(:**void(&glMultiTexCoordP1uiv), "glMultiTexCoordP1uiv"); + set_proc_address(:**void(&glMultiTexCoordP2ui), "glMultiTexCoordP2ui"); + set_proc_address(:**void(&glMultiTexCoordP2uiv), "glMultiTexCoordP2uiv"); + set_proc_address(:**void(&glMultiTexCoordP3ui), "glMultiTexCoordP3ui"); + set_proc_address(:**void(&glMultiTexCoordP3uiv), "glMultiTexCoordP3uiv"); + set_proc_address(:**void(&glMultiTexCoordP4ui), "glMultiTexCoordP4ui"); + set_proc_address(:**void(&glMultiTexCoordP4uiv), "glMultiTexCoordP4uiv"); + set_proc_address(:**void(&glNormalP3ui), "glNormalP3ui"); + set_proc_address(:**void(&glNormalP3uiv), "glNormalP3uiv"); + set_proc_address(:**void(&glColorP3ui), "glColorP3ui"); + set_proc_address(:**void(&glColorP3uiv), "glColorP3uiv"); + set_proc_address(:**void(&glColorP4ui), "glColorP4ui"); + set_proc_address(:**void(&glColorP4uiv), "glColorP4uiv"); + set_proc_address(:**void(&glSecondaryColorP3ui), "glSecondaryColorP3ui"); + set_proc_address(:**void(&glSecondaryColorP3uiv), "glSecondaryColorP3uiv"); +} + + +// VERSION_4_0 +DrawArraysIndirectCommand :: struct { + count: u32; + instanceCount: u32; + first: u32; + baseInstance: u32; +} + +DrawElementsIndirectCommand :: struct { + count: u32; + instanceCount: u32; + firstIndex: u32; + baseVertex: u32; + baseInstance: u32; +} + +glMinSampleShading: proc(value: f32); +glBlendEquationi: proc(buf: u32, mode: u32); +glBlendEquationSeparatei: proc(buf: u32, modeRGB: u32, modeAlpha: u32); +glBlendFunci: proc(buf: u32, src: u32, dst: u32); +glBlendFuncSeparatei: proc(buf: u32, srcRGB: u32, dstRGB: u32, srcAlpha: u32, dstAlpha: u32); +glDrawArraysIndirect: proc(mode: u32, indirect: *DrawArraysIndirectCommand); +glDrawElementsIndirect: proc(mode: u32, type: u32, indirect: *DrawElementsIndirectCommand); +glUniform1d: proc(location: i32, x: f64); +glUniform2d: proc(location: i32, x: f64, y: f64); +glUniform3d: proc(location: i32, x: f64, y: f64, z: f64); +glUniform4d: proc(location: i32, x: f64, y: f64, z: f64, w: f64); +glUniform1dv: proc(location: i32, count: i32, value: *f64); +glUniform2dv: proc(location: i32, count: i32, value: *f64); +glUniform3dv: proc(location: i32, count: i32, value: *f64); +glUniform4dv: proc(location: i32, count: i32, value: *f64); +glUniformMatrix2dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix3dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix4dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix2x3dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix2x4dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix3x2dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix3x4dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix4x2dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glUniformMatrix4x3dv: proc(location: i32, count: i32, transpose: bool, value: *f64); +glGetUniformdv: proc(program: u32, location: i32, params: *f64); +glGetSubroutineUniformLocation: proc(program: u32, shadertype: u32, name: *char): i32; +glGetSubroutineIndex: proc(program: u32, shadertype: u32, name: *char): u32; +glGetActiveSubroutineUniformiv: proc(program: u32, shadertype: u32, index: u32, pname: u32, values: *i32); +glGetActiveSubroutineUniformName: proc(program: u32, shadertype: u32, index: u32, bufsize: i32, length: *i32, name: *u8); +glGetActiveSubroutineName: proc(program: u32, shadertype: u32, index: u32, bufsize: i32, length: *i32, name: *u8); +glUniformSubroutinesuiv: proc(shadertype: u32, count: i32, indices: *u32); +glGetUniformSubroutineuiv: proc(shadertype: u32, location: i32, params: *u32); +glGetProgramStageiv: proc(program: u32, shadertype: u32, pname: u32, values: *i32); +glPatchParameteri: proc(pname: u32, value: i32); +glPatchParameterfv: proc(pname: u32, values: *f32); +glBindTransformFeedback: proc(target: u32, id: u32); +glDeleteTransformFeedbacks: proc(n: i32, ids: *u32); +glGenTransformFeedbacks: proc(n: i32, ids: *u32); +glIsTransformFeedback: proc(id: u32): bool; +glPauseTransformFeedback: proc(); +glResumeTransformFeedback: proc(); +glDrawTransformFeedback: proc(mode: u32, id: u32); +glDrawTransformFeedbackStream: proc(mode: u32, id: u32, stream: u32); +glBeginQueryIndexed: proc(target: u32, index: u32, id: u32); +glEndQueryIndexed: proc(target: u32, index: u32); +glGetQueryIndexediv: proc(target: u32, index: u32, pname: u32, params: *i32); +glGetTextureHandleARB: proc(texture: u32): u64; +glGetTextureSamplerHandleARB: proc(texture: u32, sampler: u32): u64; +glGetImageHandleARB: proc(texture: u32, level: i32, layered: bool, layer: i32, format: u32): u64; +glMakeTextureHandleResidentARB: proc(handle: u64); +glMakeImageHandleResidentARB: proc(handle: u64, access: u32); +glMakeTextureHandleNonResidentARB:proc(handle: u64); +glMakeImageHandleNonResidentARB: proc(handle: u64); + +load_4_0 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glMinSampleShading), "glMinSampleShading"); + set_proc_address(:**void(&glBlendEquationi), "glBlendEquationi"); + set_proc_address(:**void(&glBlendEquationSeparatei), "glBlendEquationSeparatei"); + set_proc_address(:**void(&glBlendFunci), "glBlendFunci"); + set_proc_address(:**void(&glBlendFuncSeparatei), "glBlendFuncSeparatei"); + set_proc_address(:**void(&glDrawArraysIndirect), "glDrawArraysIndirect"); + set_proc_address(:**void(&glDrawElementsIndirect), "glDrawElementsIndirect"); + set_proc_address(:**void(&glUniform1d), "glUniform1d"); + set_proc_address(:**void(&glUniform2d), "glUniform2d"); + set_proc_address(:**void(&glUniform3d), "glUniform3d"); + set_proc_address(:**void(&glUniform4d), "glUniform4d"); + set_proc_address(:**void(&glUniform1dv), "glUniform1dv"); + set_proc_address(:**void(&glUniform2dv), "glUniform2dv"); + set_proc_address(:**void(&glUniform3dv), "glUniform3dv"); + set_proc_address(:**void(&glUniform4dv), "glUniform4dv"); + set_proc_address(:**void(&glUniformMatrix2dv), "glUniformMatrix2dv"); + set_proc_address(:**void(&glUniformMatrix3dv), "glUniformMatrix3dv"); + set_proc_address(:**void(&glUniformMatrix4dv), "glUniformMatrix4dv"); + set_proc_address(:**void(&glUniformMatrix2x3dv), "glUniformMatrix2x3dv"); + set_proc_address(:**void(&glUniformMatrix2x4dv), "glUniformMatrix2x4dv"); + set_proc_address(:**void(&glUniformMatrix3x2dv), "glUniformMatrix3x2dv"); + set_proc_address(:**void(&glUniformMatrix3x4dv), "glUniformMatrix3x4dv"); + set_proc_address(:**void(&glUniformMatrix4x2dv), "glUniformMatrix4x2dv"); + set_proc_address(:**void(&glUniformMatrix4x3dv), "glUniformMatrix4x3dv"); + set_proc_address(:**void(&glGetUniformdv), "glGetUniformdv"); + set_proc_address(:**void(&glGetSubroutineUniformLocation), "glGetSubroutineUniformLocation"); + set_proc_address(:**void(&glGetSubroutineIndex), "glGetSubroutineIndex"); + set_proc_address(:**void(&glGetActiveSubroutineUniformiv), "glGetActiveSubroutineUniformiv"); + set_proc_address(:**void(&glGetActiveSubroutineUniformName), "glGetActiveSubroutineUniformName"); + set_proc_address(:**void(&glGetActiveSubroutineName), "glGetActiveSubroutineName"); + set_proc_address(:**void(&glUniformSubroutinesuiv), "glUniformSubroutinesuiv"); + set_proc_address(:**void(&glGetUniformSubroutineuiv), "glGetUniformSubroutineuiv"); + set_proc_address(:**void(&glGetProgramStageiv), "glGetProgramStageiv"); + set_proc_address(:**void(&glPatchParameteri), "glPatchParameteri"); + set_proc_address(:**void(&glPatchParameterfv), "glPatchParameterfv"); + set_proc_address(:**void(&glBindTransformFeedback), "glBindTransformFeedback"); + set_proc_address(:**void(&glDeleteTransformFeedbacks), "glDeleteTransformFeedbacks"); + set_proc_address(:**void(&glGenTransformFeedbacks), "glGenTransformFeedbacks"); + set_proc_address(:**void(&glIsTransformFeedback), "glIsTransformFeedback"); + set_proc_address(:**void(&glPauseTransformFeedback), "glPauseTransformFeedback"); + set_proc_address(:**void(&glResumeTransformFeedback), "glResumeTransformFeedback"); + set_proc_address(:**void(&glDrawTransformFeedback), "glDrawTransformFeedback"); + set_proc_address(:**void(&glDrawTransformFeedbackStream), "glDrawTransformFeedbackStream"); + set_proc_address(:**void(&glBeginQueryIndexed), "glBeginQueryIndexed"); + set_proc_address(:**void(&glEndQueryIndexed), "glEndQueryIndexed"); + set_proc_address(:**void(&glGetQueryIndexediv), "glGetQueryIndexediv"); + + // Load ARB (architecture review board, vendor specific) extensions that might be available + set_proc_address(:**void(&glGetTextureHandleARB), "glGetTextureHandleARB"); + if !glGetTextureHandleARB { + set_proc_address(:**void(&glGetTextureHandleARB), "glGetTextureHandleNV"); + } + + set_proc_address(:**void(&glGetTextureSamplerHandleARB), "glGetTextureSamplerHandleARB"); + if !glGetTextureSamplerHandleARB { + set_proc_address(:**void(&glGetTextureSamplerHandleARB), "glGetTextureSamplerHandleNV"); + } + + set_proc_address(:**void(&glGetImageHandleARB), "glGetImageHandleARB"); + if !glGetImageHandleARB { + set_proc_address(:**void(&glGetImageHandleARB), "glGetImageHandleNV"); + } + + set_proc_address(:**void(&glMakeTextureHandleResidentARB), "glMakeTextureHandleResidentARB"); + if !glMakeTextureHandleResidentARB { + set_proc_address(:**void(&glMakeTextureHandleResidentARB), "glMakeTextureHandleResidentNV"); + } + + set_proc_address(:**void(&glMakeImageHandleResidentARB), "glMakeImageHandleResidentARB"); + if !glMakeImageHandleResidentARB { + set_proc_address(:**void(&glMakeImageHandleResidentARB), "glMakeImageHandleResidentNV"); + } + + set_proc_address(:**void(&glMakeTextureHandleNonResidentARB), "glMakeTextureHandleNonResidentARB"); + if !glMakeTextureHandleNonResidentARB { + set_proc_address(:**void(&glMakeTextureHandleNonResidentARB), "glMakeTextureHandleNonResidentNV"); + } + + set_proc_address(:**void(&glMakeImageHandleNonResidentARB), "glMakeImageHandleNonResidentARB"); + if !glMakeImageHandleNonResidentARB { + set_proc_address(:**void(&glMakeImageHandleNonResidentARB), "glMakeImageHandleNonResidentNV"); + } +} + + +// VERSION_4_1 +glReleaseShaderCompiler: proc(); +glShaderBinary: proc(count: i32, shaders: *u32, binaryformat: u32, binary: *void, length: i32); +glGetShaderPrecisionFormat: proc(shadertype: u32, precisiontype: u32, range: *i32, precision: *i32); +glDepthRangef: proc(n: f32, f: f32); +glClearDepthf: proc(d: f32); +glGetProgramBinary: proc(program: u32, bufSize: i32, length: *i32, binaryFormat: *u32, binary: *void); +glProgramBinary: proc(program: u32, binaryFormat: u32, binary: *void, length: i32); +glProgramParameteri: proc(program: u32, pname: u32, value: i32); +glUseProgramStages: proc(pipeline: u32, stages: u32, program: u32); +glActiveShaderProgram: proc(pipeline: u32, program: u32); +glCreateShaderProgramv: proc(type: u32, count: i32, strings: **char): u32; +glBindProgramPipeline: proc(pipeline: u32); +glDeleteProgramPipelines: proc(n: i32, pipelines: *u32); +glGenProgramPipelines: proc(n: i32, pipelines: *u32); +glIsProgramPipeline: proc(pipeline: u32): bool; +glGetProgramPipelineiv: proc(pipeline: u32, pname: u32, params: *i32); +glProgramUniform1i: proc(program: u32, location: i32, v0: i32); +glProgramUniform1iv: proc(program: u32, location: i32, count: i32, value: *i32); +glProgramUniform1f: proc(program: u32, location: i32, v0: f32); +glProgramUniform1fv: proc(program: u32, location: i32, count: i32, value: *f32); +glProgramUniform1d: proc(program: u32, location: i32, v0: f64); +glProgramUniform1dv: proc(program: u32, location: i32, count: i32, value: *f64); +glProgramUniform1ui: proc(program: u32, location: i32, v0: u32); +glProgramUniform1uiv: proc(program: u32, location: i32, count: i32, value: *u32); +glProgramUniform2i: proc(program: u32, location: i32, v0: i32, v1: i32); +glProgramUniform2iv: proc(program: u32, location: i32, count: i32, value: *i32); +glProgramUniform2f: proc(program: u32, location: i32, v0: f32, v1: f32); +glProgramUniform2fv: proc(program: u32, location: i32, count: i32, value: *f32); +glProgramUniform2d: proc(program: u32, location: i32, v0: f64, v1: f64); +glProgramUniform2dv: proc(program: u32, location: i32, count: i32, value: *f64); +glProgramUniform2ui: proc(program: u32, location: i32, v0: u32, v1: u32); +glProgramUniform2uiv: proc(program: u32, location: i32, count: i32, value: *u32); +glProgramUniform3i: proc(program: u32, location: i32, v0: i32, v1: i32, v2: i32); +glProgramUniform3iv: proc(program: u32, location: i32, count: i32, value: *i32); +glProgramUniform3f: proc(program: u32, location: i32, v0: f32, v1: f32, v2: f32); +glProgramUniform3fv: proc(program: u32, location: i32, count: i32, value: *f32); +glProgramUniform3d: proc(program: u32, location: i32, v0: f64, v1: f64, v2: f64); +glProgramUniform3dv: proc(program: u32, location: i32, count: i32, value: *f64); +glProgramUniform3ui: proc(program: u32, location: i32, v0: u32, v1: u32, v2: u32); +glProgramUniform3uiv: proc(program: u32, location: i32, count: i32, value: *u32); +glProgramUniform4i: proc(program: u32, location: i32, v0: i32, v1: i32, v2: i32, v3: i32); +glProgramUniform4iv: proc(program: u32, location: i32, count: i32, value: *i32); +glProgramUniform4f: proc(program: u32, location: i32, v0: f32, v1: f32, v2: f32, v3: f32); +glProgramUniform4fv: proc(program: u32, location: i32, count: i32, value: *f32); +glProgramUniform4d: proc(program: u32, location: i32, v0: f64, v1: f64, v2: f64, v3: f64); +glProgramUniform4dv: proc(program: u32, location: i32, count: i32, value: *f64); +glProgramUniform4ui: proc(program: u32, location: i32, v0: u32, v1: u32, v2: u32, v3: u32); +glProgramUniform4uiv: proc(program: u32, location: i32, count: i32, value: *u32); +glProgramUniformMatrix2fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix3fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix4fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix2dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix3dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix4dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix2x3fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix3x2fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix2x4fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix4x2fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix3x4fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix4x3fv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f32); +glProgramUniformMatrix2x3dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix3x2dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix2x4dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix4x2dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix3x4dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glProgramUniformMatrix4x3dv: proc(program: u32, location: i32, count: i32, transpose: bool, value: *f64); +glValidateProgramPipeline: proc(pipeline: u32); +glGetProgramPipelineInfoLog: proc(pipeline: u32, bufSize: i32, length: *i32, infoLog: *u8); +glVertexAttribL1d: proc(index: u32, x: f64); +glVertexAttribL2d: proc(index: u32, x: f64, y: f64); +glVertexAttribL3d: proc(index: u32, x: f64, y: f64, z: f64); +glVertexAttribL4d: proc(index: u32, x: f64, y: f64, z: f64, w: f64); +glVertexAttribL1dv: proc(index: u32, v: *f64); +glVertexAttribL2dv: proc(index: u32, v: *[2]f64); +glVertexAttribL3dv: proc(index: u32, v: *[3]f64); +glVertexAttribL4dv: proc(index: u32, v: *[4]f64); +glVertexAttribLPointer: proc(index: u32, size: i32, type: u32, stride: i32, pointer: uintptr); +glGetVertexAttribLdv: proc(index: u32, pname: u32, params: *f64); +glViewportArrayv: proc(first: u32, count: i32, v: *f32); +glViewportIndexedf: proc(index: u32, x: f32, y: f32, w: f32, h: f32); +glViewportIndexedfv: proc(index: u32, v: *[4]f32); +glScissorArrayv: proc(first: u32, count: i32, v: *i32); +glScissorIndexed: proc(index: u32, left: i32, bottom: i32, width: i32, height: i32); +glScissorIndexedv: proc(index: u32, v: *[4]i32); +glDepthRangeArrayv: proc(first: u32, count: i32, v: *f64); +glDepthRangeIndexed: proc(index: u32, n: f64, f: f64); +glGetFloati_v: proc(target: u32, index: u32, data: *f32); +glGetDoublei_v: proc(target: u32, index: u32, data: *f64); + +load_4_1 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glReleaseShaderCompiler), "glReleaseShaderCompiler"); + set_proc_address(:**void(&glShaderBinary), "glShaderBinary"); + set_proc_address(:**void(&glGetShaderPrecisionFormat), "glGetShaderPrecisionFormat"); + set_proc_address(:**void(&glDepthRangef), "glDepthRangef"); + set_proc_address(:**void(&glClearDepthf), "glClearDepthf"); + set_proc_address(:**void(&glGetProgramBinary), "glGetProgramBinary"); + set_proc_address(:**void(&glProgramBinary), "glProgramBinary"); + set_proc_address(:**void(&glProgramParameteri), "glProgramParameteri"); + set_proc_address(:**void(&glUseProgramStages), "glUseProgramStages"); + set_proc_address(:**void(&glActiveShaderProgram), "glActiveShaderProgram"); + set_proc_address(:**void(&glCreateShaderProgramv), "glCreateShaderProgramv"); + set_proc_address(:**void(&glBindProgramPipeline), "glBindProgramPipeline"); + set_proc_address(:**void(&glDeleteProgramPipelines), "glDeleteProgramPipelines"); + set_proc_address(:**void(&glGenProgramPipelines), "glGenProgramPipelines"); + set_proc_address(:**void(&glIsProgramPipeline), "glIsProgramPipeline"); + set_proc_address(:**void(&glGetProgramPipelineiv), "glGetProgramPipelineiv"); + set_proc_address(:**void(&glProgramUniform1i), "glProgramUniform1i"); + set_proc_address(:**void(&glProgramUniform1iv), "glProgramUniform1iv"); + set_proc_address(:**void(&glProgramUniform1f), "glProgramUniform1f"); + set_proc_address(:**void(&glProgramUniform1fv), "glProgramUniform1fv"); + set_proc_address(:**void(&glProgramUniform1d), "glProgramUniform1d"); + set_proc_address(:**void(&glProgramUniform1dv), "glProgramUniform1dv"); + set_proc_address(:**void(&glProgramUniform1ui), "glProgramUniform1ui"); + set_proc_address(:**void(&glProgramUniform1uiv), "glProgramUniform1uiv"); + set_proc_address(:**void(&glProgramUniform2i), "glProgramUniform2i"); + set_proc_address(:**void(&glProgramUniform2iv), "glProgramUniform2iv"); + set_proc_address(:**void(&glProgramUniform2f), "glProgramUniform2f"); + set_proc_address(:**void(&glProgramUniform2fv), "glProgramUniform2fv"); + set_proc_address(:**void(&glProgramUniform2d), "glProgramUniform2d"); + set_proc_address(:**void(&glProgramUniform2dv), "glProgramUniform2dv"); + set_proc_address(:**void(&glProgramUniform2ui), "glProgramUniform2ui"); + set_proc_address(:**void(&glProgramUniform2uiv), "glProgramUniform2uiv"); + set_proc_address(:**void(&glProgramUniform3i), "glProgramUniform3i"); + set_proc_address(:**void(&glProgramUniform3iv), "glProgramUniform3iv"); + set_proc_address(:**void(&glProgramUniform3f), "glProgramUniform3f"); + set_proc_address(:**void(&glProgramUniform3fv), "glProgramUniform3fv"); + set_proc_address(:**void(&glProgramUniform3d), "glProgramUniform3d"); + set_proc_address(:**void(&glProgramUniform3dv), "glProgramUniform3dv"); + set_proc_address(:**void(&glProgramUniform3ui), "glProgramUniform3ui"); + set_proc_address(:**void(&glProgramUniform3uiv), "glProgramUniform3uiv"); + set_proc_address(:**void(&glProgramUniform4i), "glProgramUniform4i"); + set_proc_address(:**void(&glProgramUniform4iv), "glProgramUniform4iv"); + set_proc_address(:**void(&glProgramUniform4f), "glProgramUniform4f"); + set_proc_address(:**void(&glProgramUniform4fv), "glProgramUniform4fv"); + set_proc_address(:**void(&glProgramUniform4d), "glProgramUniform4d"); + set_proc_address(:**void(&glProgramUniform4dv), "glProgramUniform4dv"); + set_proc_address(:**void(&glProgramUniform4ui), "glProgramUniform4ui"); + set_proc_address(:**void(&glProgramUniform4uiv), "glProgramUniform4uiv"); + set_proc_address(:**void(&glProgramUniformMatrix2fv), "glProgramUniformMatrix2fv"); + set_proc_address(:**void(&glProgramUniformMatrix3fv), "glProgramUniformMatrix3fv"); + set_proc_address(:**void(&glProgramUniformMatrix4fv), "glProgramUniformMatrix4fv"); + set_proc_address(:**void(&glProgramUniformMatrix2dv), "glProgramUniformMatrix2dv"); + set_proc_address(:**void(&glProgramUniformMatrix3dv), "glProgramUniformMatrix3dv"); + set_proc_address(:**void(&glProgramUniformMatrix4dv), "glProgramUniformMatrix4dv"); + set_proc_address(:**void(&glProgramUniformMatrix2x3fv), "glProgramUniformMatrix2x3fv"); + set_proc_address(:**void(&glProgramUniformMatrix3x2fv), "glProgramUniformMatrix3x2fv"); + set_proc_address(:**void(&glProgramUniformMatrix2x4fv), "glProgramUniformMatrix2x4fv"); + set_proc_address(:**void(&glProgramUniformMatrix4x2fv), "glProgramUniformMatrix4x2fv"); + set_proc_address(:**void(&glProgramUniformMatrix3x4fv), "glProgramUniformMatrix3x4fv"); + set_proc_address(:**void(&glProgramUniformMatrix4x3fv), "glProgramUniformMatrix4x3fv"); + set_proc_address(:**void(&glProgramUniformMatrix2x3dv), "glProgramUniformMatrix2x3dv"); + set_proc_address(:**void(&glProgramUniformMatrix3x2dv), "glProgramUniformMatrix3x2dv"); + set_proc_address(:**void(&glProgramUniformMatrix2x4dv), "glProgramUniformMatrix2x4dv"); + set_proc_address(:**void(&glProgramUniformMatrix4x2dv), "glProgramUniformMatrix4x2dv"); + set_proc_address(:**void(&glProgramUniformMatrix3x4dv), "glProgramUniformMatrix3x4dv"); + set_proc_address(:**void(&glProgramUniformMatrix4x3dv), "glProgramUniformMatrix4x3dv"); + set_proc_address(:**void(&glValidateProgramPipeline), "glValidateProgramPipeline"); + set_proc_address(:**void(&glGetProgramPipelineInfoLog), "glGetProgramPipelineInfoLog"); + set_proc_address(:**void(&glVertexAttribL1d), "glVertexAttribL1d"); + set_proc_address(:**void(&glVertexAttribL2d), "glVertexAttribL2d"); + set_proc_address(:**void(&glVertexAttribL3d), "glVertexAttribL3d"); + set_proc_address(:**void(&glVertexAttribL4d), "glVertexAttribL4d"); + set_proc_address(:**void(&glVertexAttribL1dv), "glVertexAttribL1dv"); + set_proc_address(:**void(&glVertexAttribL2dv), "glVertexAttribL2dv"); + set_proc_address(:**void(&glVertexAttribL3dv), "glVertexAttribL3dv"); + set_proc_address(:**void(&glVertexAttribL4dv), "glVertexAttribL4dv"); + set_proc_address(:**void(&glVertexAttribLPointer), "glVertexAttribLPointer"); + set_proc_address(:**void(&glGetVertexAttribLdv), "glGetVertexAttribLdv"); + set_proc_address(:**void(&glViewportArrayv), "glViewportArrayv"); + set_proc_address(:**void(&glViewportIndexedf), "glViewportIndexedf"); + set_proc_address(:**void(&glViewportIndexedfv), "glViewportIndexedfv"); + set_proc_address(:**void(&glScissorArrayv), "glScissorArrayv"); + set_proc_address(:**void(&glScissorIndexed), "glScissorIndexed"); + set_proc_address(:**void(&glScissorIndexedv), "glScissorIndexedv"); + set_proc_address(:**void(&glDepthRangeArrayv), "glDepthRangeArrayv"); + set_proc_address(:**void(&glDepthRangeIndexed), "glDepthRangeIndexed"); + set_proc_address(:**void(&glGetFloati_v), "glGetFloati_v"); + set_proc_address(:**void(&glGetDoublei_v), "glGetDoublei_v"); +} + + +// VERSION_4_2 +glDrawArraysInstancedBaseInstance: proc(mode: u32, first: i32, count: i32, instancecount: i32, baseinstance: u32); +glDrawElementsInstancedBaseInstance: proc(mode: u32, count: i32, type: u32, indices: *void, instancecount: i32, baseinstance: u32); +glDrawElementsInstancedBaseVertexBaseInstance: proc(mode: u32, count: i32, type: u32, indices: *void, instancecount: i32, basevertex: i32, baseinstance: u32); +glGetInternalformativ: proc(target: u32, internalformat: u32, pname: u32, bufSize: i32, params: *i32); +glGetActiveAtomicCounterBufferiv: proc(program: u32, bufferIndex: u32, pname: u32, params: *i32); +glBindImageTexture: proc(unit: u32, texture: u32, level: i32, layered: bool, layer: i32, access: u32, format: u32); +glMemoryBarrier: proc(barriers: u32); +glTexStorage1D: proc(target: u32, levels: i32, internalformat: u32, width: i32); +glTexStorage2D: proc(target: u32, levels: i32, internalformat: u32, width: i32, height: i32); +glTexStorage3D: proc(target: u32, levels: i32, internalformat: u32, width: i32, height: i32, depth: i32); +glDrawTransformFeedbackInstanced: proc(mode: u32, id: u32, instancecount: i32); +glDrawTransformFeedbackStreamInstanced: proc(mode: u32, id: u32, stream: u32, instancecount: i32); + +load_4_2 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glDrawArraysInstancedBaseInstance), "glDrawArraysInstancedBaseInstance"); + set_proc_address(:**void(&glDrawElementsInstancedBaseInstance), "glDrawElementsInstancedBaseInstance"); + set_proc_address(:**void(&glDrawElementsInstancedBaseVertexBaseInstance), "glDrawElementsInstancedBaseVertexBaseInstance"); + set_proc_address(:**void(&glGetInternalformativ), "glGetInternalformativ"); + set_proc_address(:**void(&glGetActiveAtomicCounterBufferiv), "glGetActiveAtomicCounterBufferiv"); + set_proc_address(:**void(&glBindImageTexture), "glBindImageTexture"); + set_proc_address(:**void(&glMemoryBarrier), "glMemoryBarrier"); + set_proc_address(:**void(&glTexStorage1D), "glTexStorage1D"); + set_proc_address(:**void(&glTexStorage2D), "glTexStorage2D"); + set_proc_address(:**void(&glTexStorage3D), "glTexStorage3D"); + set_proc_address(:**void(&glDrawTransformFeedbackInstanced), "glDrawTransformFeedbackInstanced"); + set_proc_address(:**void(&glDrawTransformFeedbackStreamInstanced), "glDrawTransformFeedbackStreamInstanced"); +} + +// VERSION_4_3 +DispatchIndirectCommand :: struct { + num_groups_x: u32; + num_groups_y: u32; + num_groups_z: u32; +} + +glClearBufferData: proc(target: u32, internalformat: u32, format: u32, type: u32, data: *void); +glClearBufferSubData: proc(target: u32, internalformat: u32, offset: int, size: int, format: u32, type: u32, data: *void); +glDispatchCompute: proc(num_groups_x: u32, num_groups_y: u32, num_groups_z: u32); +glDispatchComputeIndirect: proc(indirect: *DispatchIndirectCommand); +glCopyImageSubData: proc(srcName: u32, srcTarget: u32, srcLevel: i32, srcX: i32, srcY: i32, srcZ: i32, dstName: u32, dstTarget: u32, dstLevel: i32, dstX: i32, dstY: i32, dstZ: i32, srcWidth: i32, srcHeight: i32, srcDepth: i32); +glFramebufferParameteri: proc(target: u32, pname: u32, param: i32); +glGetFramebufferParameteriv: proc(target: u32, pname: u32, params: *i32); +glGetInternalformati64v: proc(target: u32, internalformat: u32, pname: u32, bufSize: i32, params: *i64); +glInvalidateTexSubImage: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32); +glInvalidateTexImage: proc(texture: u32, level: i32); +glInvalidateBufferSubData: proc(buffer: u32, offset: int, length: int); +glInvalidateBufferData: proc(buffer: u32); +glInvalidateFramebuffer: proc(target: u32, numAttachments: i32, attachments: *u32); +glInvalidateSubFramebuffer: proc(target: u32, numAttachments: i32, attachments: *u32, x: i32, y: i32, width: i32, height: i32); +glMultiDrawArraysIndirect: proc(mode: u32, indirect: *DrawArraysIndirectCommand, drawcount: i32, stride: i32); +glMultiDrawElementsIndirect: proc(mode: u32, type: u32, indirect: *DrawElementsIndirectCommand, drawcount: i32, stride: i32); +glGetProgramInterfaceiv: proc(program: u32, programInterface: u32, pname: u32, params: *i32); +glGetProgramResourceIndex: proc(program: u32, programInterface: u32, name: *char): u32; +glGetProgramResourceName: proc(program: u32, programInterface: u32, index: u32, bufSize: i32, length: *i32, name: *u8); +glGetProgramResourceiv: proc(program: u32, programInterface: u32, index: u32, propCount: i32, props: *u32, bufSize: i32, length: *i32, params: *i32); +glGetProgramResourceLocation: proc(program: u32, programInterface: u32, name: *char): i32; +glGetProgramResourceLocationIndex: proc(program: u32, programInterface: u32, name: *char): i32; +glShaderStorageBlockBinding: proc(program: u32, storageBlockIndex: u32, storageBlockBinding: u32); +glTexBufferRange: proc(target: u32, internalformat: u32, buffer: u32, offset: int, size: int); +glTexStorage2DMultisample: proc(target: u32, samples: i32, internalformat: u32, width: i32, height: i32, fixedsamplelocations: bool); +glTexStorage3DMultisample: proc(target: u32, samples: i32, internalformat: u32, width: i32, height: i32, depth: i32, fixedsamplelocations: bool); +glTextureView: proc(texture: u32, target: u32, origtexture: u32, internalformat: u32, minlevel: u32, numlevels: u32, minlayer: u32, numlayers: u32); +glBindVertexBuffer: proc(bindingindex: u32, buffer: u32, offset: int, stride: i32); +glVertexAttribFormat: proc(attribindex: u32, size: i32, type: u32, normalized: bool, relativeoffset: u32); +glVertexAttribIFormat: proc(attribindex: u32, size: i32, type: u32, relativeoffset: u32); +glVertexAttribLFormat: proc(attribindex: u32, size: i32, type: u32, relativeoffset: u32); +glVertexAttribBinding: proc(attribindex: u32, bindingindex: u32); +glVertexBindingDivisor: proc(bindingindex: u32, divisor: u32); +glDebugMessageControl: proc(source: u32, type: u32, severity: u32, count: i32, ids: *u32, enabled: bool); +glDebugMessageInsert: proc(source: u32, type: u32, id: u32, severity: u32, length: i32, message: *char); +glDebugMessageCallback: proc(callback: debug_proc_t, userParam: *void); +glGetDebugMessageLog: proc(count: u32, bufSize: i32, sources: *u32, types: *u32, ids: *u32, severities: *u32, lengths: *i32, messageLog: *u8): u32; +glPushDebugGroup: proc(source: u32, id: u32, length: i32, message: *char); +glPopDebugGroup: proc(); +glObjectLabel: proc(identifier: u32, name: u32, length: i32, label: *char); +glGetObjectLabel: proc(identifier: u32, name: u32, bufSize: i32, length: *i32, label: *u8); +glObjectPtrLabel: proc(ptr: *void, length: i32, label: *char); +glGetObjectPtrLabel: proc(ptr: *void, bufSize: i32, length: *i32, label: *u8); + +load_4_3 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glClearBufferData), "glClearBufferData"); + set_proc_address(:**void(&glClearBufferSubData), "glClearBufferSubData"); + set_proc_address(:**void(&glDispatchCompute), "glDispatchCompute"); + set_proc_address(:**void(&glDispatchComputeIndirect), "glDispatchComputeIndirect"); + set_proc_address(:**void(&glCopyImageSubData), "glCopyImageSubData"); + set_proc_address(:**void(&glFramebufferParameteri), "glFramebufferParameteri"); + set_proc_address(:**void(&glGetFramebufferParameteriv), "glGetFramebufferParameteriv"); + set_proc_address(:**void(&glGetInternalformati64v), "glGetInternalformati64v"); + set_proc_address(:**void(&glInvalidateTexSubImage), "glInvalidateTexSubImage"); + set_proc_address(:**void(&glInvalidateTexImage), "glInvalidateTexImage"); + set_proc_address(:**void(&glInvalidateBufferSubData), "glInvalidateBufferSubData"); + set_proc_address(:**void(&glInvalidateBufferData), "glInvalidateBufferData"); + set_proc_address(:**void(&glInvalidateFramebuffer), "glInvalidateFramebuffer"); + set_proc_address(:**void(&glInvalidateSubFramebuffer), "glInvalidateSubFramebuffer"); + set_proc_address(:**void(&glMultiDrawArraysIndirect), "glMultiDrawArraysIndirect"); + set_proc_address(:**void(&glMultiDrawElementsIndirect), "glMultiDrawElementsIndirect"); + set_proc_address(:**void(&glGetProgramInterfaceiv), "glGetProgramInterfaceiv"); + set_proc_address(:**void(&glGetProgramResourceIndex), "glGetProgramResourceIndex"); + set_proc_address(:**void(&glGetProgramResourceName), "glGetProgramResourceName"); + set_proc_address(:**void(&glGetProgramResourceiv), "glGetProgramResourceiv"); + set_proc_address(:**void(&glGetProgramResourceLocation), "glGetProgramResourceLocation"); + set_proc_address(:**void(&glGetProgramResourceLocationIndex), "glGetProgramResourceLocationIndex"); + set_proc_address(:**void(&glShaderStorageBlockBinding), "glShaderStorageBlockBinding"); + set_proc_address(:**void(&glTexBufferRange), "glTexBufferRange"); + set_proc_address(:**void(&glTexStorage2DMultisample), "glTexStorage2DMultisample"); + set_proc_address(:**void(&glTexStorage3DMultisample), "glTexStorage3DMultisample"); + set_proc_address(:**void(&glTextureView), "glTextureView"); + set_proc_address(:**void(&glBindVertexBuffer), "glBindVertexBuffer"); + set_proc_address(:**void(&glVertexAttribFormat), "glVertexAttribFormat"); + set_proc_address(:**void(&glVertexAttribIFormat), "glVertexAttribIFormat"); + set_proc_address(:**void(&glVertexAttribLFormat), "glVertexAttribLFormat"); + set_proc_address(:**void(&glVertexAttribBinding), "glVertexAttribBinding"); + set_proc_address(:**void(&glVertexBindingDivisor), "glVertexBindingDivisor"); + set_proc_address(:**void(&glDebugMessageControl), "glDebugMessageControl"); + set_proc_address(:**void(&glDebugMessageInsert), "glDebugMessageInsert"); + set_proc_address(:**void(&glDebugMessageCallback), "glDebugMessageCallback"); + set_proc_address(:**void(&glGetDebugMessageLog), "glGetDebugMessageLog"); + set_proc_address(:**void(&glPushDebugGroup), "glPushDebugGroup"); + set_proc_address(:**void(&glPopDebugGroup), "glPopDebugGroup"); + set_proc_address(:**void(&glObjectLabel), "glObjectLabel"); + set_proc_address(:**void(&glGetObjectLabel), "glGetObjectLabel"); + set_proc_address(:**void(&glObjectPtrLabel), "glObjectPtrLabel"); + set_proc_address(:**void(&glGetObjectPtrLabel), "glGetObjectPtrLabel"); +} + +// VERSION_4_4 +glBufferStorage: proc(target: u32, size: int, data: *void, flags: u32); +glClearTexImage: proc(texture: u32, level: i32, format: u32, type: u32, data: *void); +glClearTexSubImage: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, format: u32, type: u32, data: *void); +glBindBuffersBase: proc(target: u32, first: u32, count: i32, buffers: *u32); +glBindBuffersRange: proc(target: u32, first: u32, count: i32, buffers: *u32, offsets: *uintptr, sizes: *int); +glBindTextures: proc(first: u32, count: i32, textures: *u32); +glBindSamplers: proc(first: u32, count: i32, samplers: *u32); +glBindImageTextures: proc(first: u32, count: i32, textures: *u32); +glBindVertexBuffers: proc(first: u32, count: i32, buffers: *u32, offsets: *uintptr, strides: *i32); + +load_4_4 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glBufferStorage), "glBufferStorage"); + set_proc_address(:**void(&glClearTexImage), "glClearTexImage"); + set_proc_address(:**void(&glClearTexSubImage), "glClearTexSubImage"); + set_proc_address(:**void(&glBindBuffersBase), "glBindBuffersBase"); + set_proc_address(:**void(&glBindBuffersRange), "glBindBuffersRange"); + set_proc_address(:**void(&glBindTextures), "glBindTextures"); + set_proc_address(:**void(&glBindSamplers), "glBindSamplers"); + set_proc_address(:**void(&glBindImageTextures), "glBindImageTextures"); + set_proc_address(:**void(&glBindVertexBuffers), "glBindVertexBuffers"); +} + +// VERSION_4_5 +glClipControl: proc(origin: u32, depth: u32); +glCreateTransformFeedbacks: proc(n: i32, ids: *u32); +glTransformFeedbackBufferBase: proc(xfb: u32, index: u32, buffer: u32); +glTransformFeedbackBufferRange: proc(xfb: u32, index: u32, buffer: u32, offset: int, size: int); +glGetTransformFeedbackiv: proc(xfb: u32, pname: u32, param: *i32); +glGetTransformFeedbacki_v: proc(xfb: u32, pname: u32, index: u32, param: *i32); +glGetTransformFeedbacki64_v: proc(xfb: u32, pname: u32, index: u32, param: *i64); +glCreateBuffers: proc(n: i32, buffers: *u32); +glNamedBufferStorage: proc(buffer: u32, size: int, data: *void, flags: u32); +glNamedBufferData: proc(buffer: u32, size: int, data: *void, usage: u32); +glNamedBufferSubData: proc(buffer: u32, offset: int, size: int, data: *void); +glCopyNamedBufferSubData: proc(readBuffer: u32, writeBuffer: u32, readOffset: int, writeOffset: int, size: int); +glClearNamedBufferData: proc(buffer: u32, internalformat: u32, format: u32, type: u32, data: *void); +glClearNamedBufferSubData: proc(buffer: u32, internalformat: u32, offset: int, size: int, format: u32, type: u32, data: *void); +glMapNamedBuffer: proc(buffer: u32, access: u32): *void; +glMapNamedBufferRange: proc(buffer: u32, offset: int, length: int, access: u32): *void; +glUnmapNamedBuffer: proc(buffer: u32): bool; +glFlushMappedNamedBufferRange: proc(buffer: u32, offset: int, length: int); +glGetNamedBufferParameteriv: proc(buffer: u32, pname: u32, params: *i32); +glGetNamedBufferParameteri64v: proc(buffer: u32, pname: u32, params: *i64); +glGetNamedBufferPointerv: proc(buffer: u32, pname: u32, params: **void); +glGetNamedBufferSubData: proc(buffer: u32, offset: int, size: int, data: *void); +glCreateFramebuffers: proc(n: i32, framebuffers: *u32); +glNamedFramebufferRenderbuffer: proc(framebuffer: u32, attachment: u32, renderbuffertarget: u32, renderbuffer: u32); +glNamedFramebufferParameteri: proc(framebuffer: u32, pname: u32, param: i32); +glNamedFramebufferTexture: proc(framebuffer: u32, attachment: u32, texture: u32, level: i32); +glNamedFramebufferTextureLayer: proc(framebuffer: u32, attachment: u32, texture: u32, level: i32, layer: i32); +glNamedFramebufferDrawBuffer: proc(framebuffer: u32, buf: u32); +glNamedFramebufferDrawBuffers: proc(framebuffer: u32, n: i32, bufs: *u32); +glNamedFramebufferReadBuffer: proc(framebuffer: u32, src: u32); +glInvalidateNamedFramebufferData: proc(framebuffer: u32, numAttachments: i32, attachments: *u32); +glInvalidateNamedFramebufferSubData: proc(framebuffer: u32, numAttachments: i32, attachments: *u32, x: i32, y: i32, width: i32, height: i32); +glClearNamedFramebufferiv: proc(framebuffer: u32, buffer: u32, drawbuffer: i32, value: *i32); +glClearNamedFramebufferuiv: proc(framebuffer: u32, buffer: u32, drawbuffer: i32, value: *u32); +glClearNamedFramebufferfv: proc(framebuffer: u32, buffer: u32, drawbuffer: i32, value: *f32); +glClearNamedFramebufferfi: proc(framebuffer: u32, buffer: u32, drawbuffer: i32, depth: f32, stencil: i32); +glBlitNamedFramebuffer: proc(readFramebuffer: u32, drawFramebuffer: u32, srcX0: i32, srcY0: i32, srcX1: i32, srcY1: i32, dstX0: i32, dstY0: i32, dstX1: i32, dstY1: i32, mask: u32, filter: u32); +glCheckNamedFramebufferStatus: proc(framebuffer: u32, target: u32): u32; +glGetNamedFramebufferParameteriv: proc(framebuffer: u32, pname: u32, param: *i32); +glGetNamedFramebufferAttachmentParameteriv: proc(framebuffer: u32, attachment: u32, pname: u32, params: *i32); +glCreateRenderbuffers: proc(n: i32, renderbuffers: *u32); +glNamedRenderbufferStorage: proc(renderbuffer: u32, internalformat: u32, width: i32, height: i32); +glNamedRenderbufferStorageMultisample: proc(renderbuffer: u32, samples: i32, internalformat: u32, width: i32, height: i32); +glGetNamedRenderbufferParameteriv: proc(renderbuffer: u32, pname: u32, params: *i32); +glCreateTextures: proc(target: u32, n: i32, textures: *u32); +glTextureBuffer: proc(texture: u32, internalformat: u32, buffer: u32); +glTextureBufferRange: proc(texture: u32, internalformat: u32, buffer: u32, offset: int, size: int); +glTextureStorage1D: proc(texture: u32, levels: i32, internalformat: u32, width: i32); +glTextureStorage2D: proc(texture: u32, levels: i32, internalformat: u32, width: i32, height: i32); +glTextureStorage3D: proc(texture: u32, levels: i32, internalformat: u32, width: i32, height: i32, depth: i32); +glTextureStorage2DMultisample: proc(texture: u32, samples: i32, internalformat: u32, width: i32, height: i32, fixedsamplelocations: bool); +glTextureStorage3DMultisample: proc(texture: u32, samples: i32, internalformat: u32, width: i32, height: i32, depth: i32, fixedsamplelocations: bool); +glTextureSubImage1D: proc(texture: u32, level: i32, xoffset: i32, width: i32, format: u32, type: u32, pixels: *void); +glTextureSubImage2D: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, width: i32, height: i32, format: u32, type: u32, pixels: *void); +glTextureSubImage3D: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, format: u32, type: u32, pixels: *void); +glCompressedTextureSubImage1D: proc(texture: u32, level: i32, xoffset: i32, width: i32, format: u32, imageSize: i32, data: *void); +glCompressedTextureSubImage2D: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, width: i32, height: i32, format: u32, imageSize: i32, data: *void); +glCompressedTextureSubImage3D: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, format: u32, imageSize: i32, data: *void); +glCopyTextureSubImage1D: proc(texture: u32, level: i32, xoffset: i32, x: i32, y: i32, width: i32); +glCopyTextureSubImage2D: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, x: i32, y: i32, width: i32, height: i32); +glCopyTextureSubImage3D: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, x: i32, y: i32, width: i32, height: i32); +glTextureParameterf: proc(texture: u32, pname: u32, param: f32); +glTextureParameterfv: proc(texture: u32, pname: u32, param: *f32); +glTextureParameteri: proc(texture: u32, pname: u32, param: i32); +glTextureParameterIiv: proc(texture: u32, pname: u32, params: *i32); +glTextureParameterIuiv: proc(texture: u32, pname: u32, params: *u32); +glTextureParameteriv: proc(texture: u32, pname: u32, param: *i32); +glGenerateTextureMipmap: proc(texture: u32); +glBindTextureUnit: proc(unit: u32, texture: u32); +glGetTextureImage: proc(texture: u32, level: i32, format: u32, type: u32, bufSize: i32, pixels: *void); +glGetCompressedTextureImage: proc(texture: u32, level: i32, bufSize: i32, pixels: *void); +glGetTextureLevelParameterfv: proc(texture: u32, level: i32, pname: u32, params: *f32); +glGetTextureLevelParameteriv: proc(texture: u32, level: i32, pname: u32, params: *i32); +glGetTextureParameterfv: proc(texture: u32, pname: u32, params: *f32); +glGetTextureParameterIiv: proc(texture: u32, pname: u32, params: *i32); +glGetTextureParameterIuiv: proc(texture: u32, pname: u32, params: *u32); +glGetTextureParameteriv: proc(texture: u32, pname: u32, params: *i32); +glCreateVertexArrays: proc(n: i32, arrays: *u32); +glDisableVertexArrayAttrib: proc(vaobj: u32, index: u32); +glEnableVertexArrayAttrib: proc(vaobj: u32, index: u32); +glVertexArrayElementBuffer: proc(vaobj: u32, buffer: u32); +glVertexArrayVertexBuffer: proc(vaobj: u32, bindingindex: u32, buffer: u32, offset: int, stride: i32); +glVertexArrayVertexBuffers: proc(vaobj: u32, first: u32, count: i32, buffers: *u32, offsets: *uintptr, strides: *i32); +glVertexArrayAttribBinding: proc(vaobj: u32, attribindex: u32, bindingindex: u32); +glVertexArrayAttribFormat: proc(vaobj: u32, attribindex: u32, size: i32, type: u32, normalized: bool, relativeoffset: u32); +glVertexArrayAttribIFormat: proc(vaobj: u32, attribindex: u32, size: i32, type: u32, relativeoffset: u32); +glVertexArrayAttribLFormat: proc(vaobj: u32, attribindex: u32, size: i32, type: u32, relativeoffset: u32); +glVertexArrayBindingDivisor: proc(vaobj: u32, bindingindex: u32, divisor: u32); +glGetVertexArrayiv: proc(vaobj: u32, pname: u32, param: *i32); +glGetVertexArrayIndexediv: proc(vaobj: u32, index: u32, pname: u32, param: *i32); +glGetVertexArrayIndexed64iv: proc(vaobj: u32, index: u32, pname: u32, param: *i64); +glCreateSamplers: proc(n: i32, samplers: *u32); +glCreateProgramPipelines: proc(n: i32, pipelines: *u32); +glCreateQueries: proc(target: u32, n: i32, ids: *u32); +glGetQueryBufferObjecti64v: proc(id: u32, buffer: u32, pname: u32, offset: int); +glGetQueryBufferObjectiv: proc(id: u32, buffer: u32, pname: u32, offset: int); +glGetQueryBufferObjectui64v: proc(id: u32, buffer: u32, pname: u32, offset: int); +glGetQueryBufferObjectuiv: proc(id: u32, buffer: u32, pname: u32, offset: int); +glMemoryBarrierByRegion: proc(barriers: u32); +glGetTextureSubImage: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, format: u32, type: u32, bufSize: i32, pixels: *void); +glGetCompressedTextureSubImage: proc(texture: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, bufSize: i32, pixels: *void); +glGetGraphicsResetStatus: proc(): u32; +glGetnCompressedTexImage: proc(target: u32, lod: i32, bufSize: i32, pixels: *void); +glGetnTexImage: proc(target: u32, level: i32, format: u32, type: u32, bufSize: i32, pixels: *void); +glGetnUniformdv: proc(program: u32, location: i32, bufSize: i32, params: *f64); +glGetnUniformfv: proc(program: u32, location: i32, bufSize: i32, params: *f32); +glGetnUniformiv: proc(program: u32, location: i32, bufSize: i32, params: *i32); +glGetnUniformuiv: proc(program: u32, location: i32, bufSize: i32, params: *u32); +glReadnPixels: proc(x: i32, y: i32, width: i32, height: i32, format: u32, type: u32, bufSize: i32, data: *void); +glGetnMapdv: proc(target: u32, query: u32, bufSize: i32, v: *f64); +glGetnMapfv: proc(target: u32, query: u32, bufSize: i32, v: *f32); +glGetnMapiv: proc(target: u32, query: u32, bufSize: i32, v: *i32); +glGetnPixelMapusv: proc(map_: u32, bufSize: i32, values: *u16); +glGetnPixelMapfv: proc(map_: u32, bufSize: i32, values: *f32); +glGetnPixelMapuiv: proc(map_: u32, bufSize: i32, values: *u32); +glGetnPolygonStipple: proc(bufSize: i32, pattern: *u8); +glGetnColorTable: proc(target: u32, format: u32, type: u32, bufSize: i32, table: *void); +glGetnConvolutionFilter: proc(target: u32, format: u32, type: u32, bufSize: i32, image: *void); +glGetnSeparableFilter: proc(target: u32, format: u32, type: u32, rowBufSize: i32, row: *void, columnBufSize: i32, column: *void, span: *void); +glGetnHistogram: proc(target: u32, reset: bool, format: u32, type: u32, bufSize: i32, values: *void); +glGetnMinmax: proc(target: u32, reset: bool, format: u32, type: u32, bufSize: i32, values: *void); +glTextureBarrier: proc(); +glGetUnsignedBytevEXT: proc(pname: u32, data: *u8); +glTexPageCommitmentARB: proc(target: u32, level: i32, xoffset: i32, yoffset: i32, zoffset: i32, width: i32, height: i32, depth: i32, commit: bool); + +load_4_5 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glClipControl), "glClipControl"); + set_proc_address(:**void(&glCreateTransformFeedbacks), "glCreateTransformFeedbacks"); + set_proc_address(:**void(&glTransformFeedbackBufferBase), "glTransformFeedbackBufferBase"); + set_proc_address(:**void(&glTransformFeedbackBufferRange), "glTransformFeedbackBufferRange"); + set_proc_address(:**void(&glGetTransformFeedbackiv), "glGetTransformFeedbackiv"); + set_proc_address(:**void(&glGetTransformFeedbacki_v), "glGetTransformFeedbacki_v"); + set_proc_address(:**void(&glGetTransformFeedbacki64_v), "glGetTransformFeedbacki64_v"); + set_proc_address(:**void(&glCreateBuffers), "glCreateBuffers"); + set_proc_address(:**void(&glNamedBufferStorage), "glNamedBufferStorage"); + set_proc_address(:**void(&glNamedBufferData), "glNamedBufferData"); + set_proc_address(:**void(&glNamedBufferSubData), "glNamedBufferSubData"); + set_proc_address(:**void(&glCopyNamedBufferSubData), "glCopyNamedBufferSubData"); + set_proc_address(:**void(&glClearNamedBufferData), "glClearNamedBufferData"); + set_proc_address(:**void(&glClearNamedBufferSubData), "glClearNamedBufferSubData"); + set_proc_address(:**void(&glMapNamedBuffer), "glMapNamedBuffer"); + set_proc_address(:**void(&glMapNamedBufferRange), "glMapNamedBufferRange"); + set_proc_address(:**void(&glUnmapNamedBuffer), "glUnmapNamedBuffer"); + set_proc_address(:**void(&glFlushMappedNamedBufferRange), "glFlushMappedNamedBufferRange"); + set_proc_address(:**void(&glGetNamedBufferParameteriv), "glGetNamedBufferParameteriv"); + set_proc_address(:**void(&glGetNamedBufferParameteri64v), "glGetNamedBufferParameteri64v"); + set_proc_address(:**void(&glGetNamedBufferPointerv), "glGetNamedBufferPointerv"); + set_proc_address(:**void(&glGetNamedBufferSubData), "glGetNamedBufferSubData"); + set_proc_address(:**void(&glCreateFramebuffers), "glCreateFramebuffers"); + set_proc_address(:**void(&glNamedFramebufferRenderbuffer), "glNamedFramebufferRenderbuffer"); + set_proc_address(:**void(&glNamedFramebufferParameteri), "glNamedFramebufferParameteri"); + set_proc_address(:**void(&glNamedFramebufferTexture), "glNamedFramebufferTexture"); + set_proc_address(:**void(&glNamedFramebufferTextureLayer), "glNamedFramebufferTextureLayer"); + set_proc_address(:**void(&glNamedFramebufferDrawBuffer), "glNamedFramebufferDrawBuffer"); + set_proc_address(:**void(&glNamedFramebufferDrawBuffers), "glNamedFramebufferDrawBuffers"); + set_proc_address(:**void(&glNamedFramebufferReadBuffer), "glNamedFramebufferReadBuffer"); + set_proc_address(:**void(&glInvalidateNamedFramebufferData), "glInvalidateNamedFramebufferData"); + set_proc_address(:**void(&glInvalidateNamedFramebufferSubData), "glInvalidateNamedFramebufferSubData"); + set_proc_address(:**void(&glClearNamedFramebufferiv), "glClearNamedFramebufferiv"); + set_proc_address(:**void(&glClearNamedFramebufferuiv), "glClearNamedFramebufferuiv"); + set_proc_address(:**void(&glClearNamedFramebufferfv), "glClearNamedFramebufferfv"); + set_proc_address(:**void(&glClearNamedFramebufferfi), "glClearNamedFramebufferfi"); + set_proc_address(:**void(&glBlitNamedFramebuffer), "glBlitNamedFramebuffer"); + set_proc_address(:**void(&glCheckNamedFramebufferStatus), "glCheckNamedFramebufferStatus"); + set_proc_address(:**void(&glGetNamedFramebufferParameteriv), "glGetNamedFramebufferParameteriv"); + set_proc_address(:**void(&glGetNamedFramebufferAttachmentParameteriv), "glGetNamedFramebufferAttachmentParameteriv"); + set_proc_address(:**void(&glCreateRenderbuffers), "glCreateRenderbuffers"); + set_proc_address(:**void(&glNamedRenderbufferStorage), "glNamedRenderbufferStorage"); + set_proc_address(:**void(&glNamedRenderbufferStorageMultisample), "glNamedRenderbufferStorageMultisample"); + set_proc_address(:**void(&glGetNamedRenderbufferParameteriv), "glGetNamedRenderbufferParameteriv"); + set_proc_address(:**void(&glCreateTextures), "glCreateTextures"); + set_proc_address(:**void(&glTextureBuffer), "glTextureBuffer"); + set_proc_address(:**void(&glTextureBufferRange), "glTextureBufferRange"); + set_proc_address(:**void(&glTextureStorage1D), "glTextureStorage1D"); + set_proc_address(:**void(&glTextureStorage2D), "glTextureStorage2D"); + set_proc_address(:**void(&glTextureStorage3D), "glTextureStorage3D"); + set_proc_address(:**void(&glTextureStorage2DMultisample), "glTextureStorage2DMultisample"); + set_proc_address(:**void(&glTextureStorage3DMultisample), "glTextureStorage3DMultisample"); + set_proc_address(:**void(&glTextureSubImage1D), "glTextureSubImage1D"); + set_proc_address(:**void(&glTextureSubImage2D), "glTextureSubImage2D"); + set_proc_address(:**void(&glTextureSubImage3D), "glTextureSubImage3D"); + set_proc_address(:**void(&glCompressedTextureSubImage1D), "glCompressedTextureSubImage1D"); + set_proc_address(:**void(&glCompressedTextureSubImage2D), "glCompressedTextureSubImage2D"); + set_proc_address(:**void(&glCompressedTextureSubImage3D), "glCompressedTextureSubImage3D"); + set_proc_address(:**void(&glCopyTextureSubImage1D), "glCopyTextureSubImage1D"); + set_proc_address(:**void(&glCopyTextureSubImage2D), "glCopyTextureSubImage2D"); + set_proc_address(:**void(&glCopyTextureSubImage3D), "glCopyTextureSubImage3D"); + set_proc_address(:**void(&glTextureParameterf), "glTextureParameterf"); + set_proc_address(:**void(&glTextureParameterfv), "glTextureParameterfv"); + set_proc_address(:**void(&glTextureParameteri), "glTextureParameteri"); + set_proc_address(:**void(&glTextureParameterIiv), "glTextureParameterIiv"); + set_proc_address(:**void(&glTextureParameterIuiv), "glTextureParameterIuiv"); + set_proc_address(:**void(&glTextureParameteriv), "glTextureParameteriv"); + set_proc_address(:**void(&glGenerateTextureMipmap), "glGenerateTextureMipmap"); + set_proc_address(:**void(&glBindTextureUnit), "glBindTextureUnit"); + set_proc_address(:**void(&glGetTextureImage), "glGetTextureImage"); + set_proc_address(:**void(&glGetCompressedTextureImage), "glGetCompressedTextureImage"); + set_proc_address(:**void(&glGetTextureLevelParameterfv), "glGetTextureLevelParameterfv"); + set_proc_address(:**void(&glGetTextureLevelParameteriv), "glGetTextureLevelParameteriv"); + set_proc_address(:**void(&glGetTextureParameterfv), "glGetTextureParameterfv"); + set_proc_address(:**void(&glGetTextureParameterIiv), "glGetTextureParameterIiv"); + set_proc_address(:**void(&glGetTextureParameterIuiv), "glGetTextureParameterIuiv"); + set_proc_address(:**void(&glGetTextureParameteriv), "glGetTextureParameteriv"); + set_proc_address(:**void(&glCreateVertexArrays), "glCreateVertexArrays"); + set_proc_address(:**void(&glDisableVertexArrayAttrib), "glDisableVertexArrayAttrib"); + set_proc_address(:**void(&glEnableVertexArrayAttrib), "glEnableVertexArrayAttrib"); + set_proc_address(:**void(&glVertexArrayElementBuffer), "glVertexArrayElementBuffer"); + set_proc_address(:**void(&glVertexArrayVertexBuffer), "glVertexArrayVertexBuffer"); + set_proc_address(:**void(&glVertexArrayVertexBuffers), "glVertexArrayVertexBuffers"); + set_proc_address(:**void(&glVertexArrayAttribBinding), "glVertexArrayAttribBinding"); + set_proc_address(:**void(&glVertexArrayAttribFormat), "glVertexArrayAttribFormat"); + set_proc_address(:**void(&glVertexArrayAttribIFormat), "glVertexArrayAttribIFormat"); + set_proc_address(:**void(&glVertexArrayAttribLFormat), "glVertexArrayAttribLFormat"); + set_proc_address(:**void(&glVertexArrayBindingDivisor), "glVertexArrayBindingDivisor"); + set_proc_address(:**void(&glGetVertexArrayiv), "glGetVertexArrayiv"); + set_proc_address(:**void(&glGetVertexArrayIndexediv), "glGetVertexArrayIndexediv"); + set_proc_address(:**void(&glGetVertexArrayIndexed64iv), "glGetVertexArrayIndexed64iv"); + set_proc_address(:**void(&glCreateSamplers), "glCreateSamplers"); + set_proc_address(:**void(&glCreateProgramPipelines), "glCreateProgramPipelines"); + set_proc_address(:**void(&glCreateQueries), "glCreateQueries"); + set_proc_address(:**void(&glGetQueryBufferObjecti64v), "glGetQueryBufferObjecti64v"); + set_proc_address(:**void(&glGetQueryBufferObjectiv), "glGetQueryBufferObjectiv"); + set_proc_address(:**void(&glGetQueryBufferObjectui64v), "glGetQueryBufferObjectui64v"); + set_proc_address(:**void(&glGetQueryBufferObjectuiv), "glGetQueryBufferObjectuiv"); + set_proc_address(:**void(&glMemoryBarrierByRegion), "glMemoryBarrierByRegion"); + set_proc_address(:**void(&glGetTextureSubImage), "glGetTextureSubImage"); + set_proc_address(:**void(&glGetCompressedTextureSubImage), "glGetCompressedTextureSubImage"); + set_proc_address(:**void(&glGetGraphicsResetStatus), "glGetGraphicsResetStatus"); + set_proc_address(:**void(&glGetnCompressedTexImage), "glGetnCompressedTexImage"); + set_proc_address(:**void(&glGetnTexImage), "glGetnTexImage"); + set_proc_address(:**void(&glGetnUniformdv), "glGetnUniformdv"); + set_proc_address(:**void(&glGetnUniformfv), "glGetnUniformfv"); + set_proc_address(:**void(&glGetnUniformiv), "glGetnUniformiv"); + set_proc_address(:**void(&glGetnUniformuiv), "glGetnUniformuiv"); + set_proc_address(:**void(&glReadnPixels), "glReadnPixels"); + set_proc_address(:**void(&glGetnMapdv), "glGetnMapdv"); + set_proc_address(:**void(&glGetnMapfv), "glGetnMapfv"); + set_proc_address(:**void(&glGetnMapiv), "glGetnMapiv"); + set_proc_address(:**void(&glGetnPixelMapfv), "glGetnPixelMapfv"); + set_proc_address(:**void(&glGetnPixelMapuiv), "glGetnPixelMapuiv"); + set_proc_address(:**void(&glGetnPixelMapusv), "glGetnPixelMapusv"); + set_proc_address(:**void(&glGetnPolygonStipple), "glGetnPolygonStipple"); + set_proc_address(:**void(&glGetnColorTable), "glGetnColorTable"); + set_proc_address(:**void(&glGetnConvolutionFilter), "glGetnConvolutionFilter"); + set_proc_address(:**void(&glGetnSeparableFilter), "glGetnSeparableFilter"); + set_proc_address(:**void(&glGetnHistogram), "glGetnHistogram"); + set_proc_address(:**void(&glGetnMinmax), "glGetnMinmax"); + set_proc_address(:**void(&glTextureBarrier), "glTextureBarrier"); + set_proc_address(:**void(&glGetUnsignedBytevEXT), "glGetUnsignedBytevEXT"); + set_proc_address(:**void(&glTexPageCommitmentARB), "glTexPageCommitmentARB"); +} + +// VERSION_4_6 +glSpecializeShader: proc(shader: u32, pEntryPoint: *char, numSpecializationConstants: u32, pConstantIndex: *u32, pConstantValue: *u32); +glMultiDrawArraysIndirectCount: proc(mode: i32, indirect: *DrawArraysIndirectCommand, drawcount: i32, maxdrawcount: i32, stride: i32); +glMultiDrawElementsIndirectCount: proc(mode: i32, type: i32, indirect: *DrawElementsIndirectCommand, drawcount: i32, maxdrawcount: i32, stride: i32); +glPolygonOffsetClamp: proc(factor: f32, units: f32, clamp: f32); + +load_4_6 :: proc(set_proc_address: Set_Proc_Address_Type) { + set_proc_address(:**void(&glSpecializeShader), "glSpecializeShader"); + set_proc_address(:**void(&glMultiDrawArraysIndirectCount), "glMultiDrawArraysIndirectCount"); + set_proc_address(:**void(&glMultiDrawElementsIndirectCount), "glMultiDrawElementsIndirectCount"); + set_proc_address(:**void(&glPolygonOffsetClamp), "glPolygonOffsetClamp"); +} diff --git a/tests/ops_on_basic_types_and_casts.txt b/tests/ops_on_basic_types_and_casts.txt new file mode 100644 index 0000000..98e236a --- /dev/null +++ b/tests/ops_on_basic_types_and_casts.txt @@ -0,0 +1,129 @@ +// #failed: resolve +// #error: invalid binary operation for type 'float' +// #error: invalid binary operation for type 'float' +// #error: invalid binary operation for type 'float' +// #error: invalid binary operation for type 'float' +// #error: invalid binary operation for type 'float' +// #error: invalid binary operation for type 'double' +// #error: invalid binary operation for type 'double' +// #error: invalid binary operation for type 'double' +// #error: invalid binary operation for type 'double' +// #error: invalid binary operation for type 'double' + +char1184605005 := :char(451)+:char(200); +char1543628619 := :char(451)-:char(200); +char2426623557 := :char(451)*:char(200); +char1926046121 := :char(451)/:char(200); +char3015104713 := :char(451)%:char(200); +char4094601016 := :char(451)>>:char(200); +char3594810486 := :char(451)<<:char(200); +char4661534 := :char(451)|:char(200); +char4128516316 := :char(451)&:char(200); +uchar418625421 := :uchar(451)+:uchar(200); +uchar1301943202 := :uchar(451)-:uchar(200); +uchar133926661 := :uchar(451)*:uchar(200); +uchar306256219 := :uchar(451)/:uchar(200); +uchar2048152242 := :uchar(451)%:uchar(200); +uchar2693568151 := :uchar(451)>>:uchar(200); +uchar1859046010 := :uchar(451)<<:uchar(200); +uchar271747438 := :uchar(451)|:uchar(200); +uchar2456123388 := :uchar(451)&:uchar(200); +short1892008467 := :short(451)+:short(200); +short397978967 := :short(451)-:short(200); +short3347868109 := :short(451)*:short(200); +short1385996894 := :short(451)/:short(200); +short295729027 := :short(451)%:short(200); +short4097226668 := :short(451)>>:short(200); +short3909136835 := :short(451)<<:short(200); +short3691421792 := :short(451)|:short(200); +short1750775072 := :short(451)&:short(200); +ushort2551662666 := :ushort(451)+:ushort(200); +ushort424162394 := :ushort(451)-:ushort(200); +ushort446231218 := :ushort(451)*:ushort(200); +ushort694759383 := :ushort(451)/:ushort(200); +ushort289787800 := :ushort(451)%:ushort(200); +ushort2817106439 := :ushort(451)>>:ushort(200); +ushort2340950147 := :ushort(451)<<:ushort(200); +ushort1213153378 := :ushort(451)|:ushort(200); +ushort2747762274 := :ushort(451)&:ushort(200); +bool2725368302 := :bool(451)+:bool(200); +bool4108749261 := :bool(451)-:bool(200); +bool3030947742 := :bool(451)*:bool(200); +bool2306203953 := :bool(451)/:bool(200); +bool3072857278 := :bool(451)%:bool(200); +bool3371870999 := :bool(451)>>:bool(200); +bool2007071617 := :bool(451)<<:bool(200); +bool3624728886 := :bool(451)|:bool(200); +bool2301390148 := :bool(451)&:bool(200); +int3652314270 := :int(451)+:int(200); +int88498391 := :int(451)-:int(200); +int828520918 := :int(451)*:int(200); +int3506325541 := :int(451)/:int(200); +int3107620494 := :int(451)%:int(200); +int3023998979 := :int(451)>>:int(200); +int1597279715 := :int(451)<<:int(200); +int4049992760 := :int(451)|:int(200); +int4026481088 := :int(451)&:int(200); +uint3551573939 := :uint(451)+:uint(200); +uint2297715228 := :uint(451)-:uint(200); +uint2027992488 := :uint(451)*:uint(200); +uint4212072131 := :uint(451)/:uint(200); +uint2351180318 := :uint(451)%:uint(200); +uint820061642 := :uint(451)>>:uint(200); +uint3195196673 := :uint(451)<<:uint(200); +uint2563592427 := :uint(451)|:uint(200); +uint2241958026 := :uint(451)&:uint(200); +long914993451 := :long(451)+:long(200); +long3082782857 := :long(451)-:long(200); +long1033106904 := :long(451)*:long(200); +long3821577267 := :long(451)/:long(200); +long2849045448 := :long(451)%:long(200); +long3183126591 := :long(451)>>:long(200); +long3862049455 := :long(451)<<:long(200); +long3375570186 := :long(451)|:long(200); +long2762439088 := :long(451)&:long(200); +ulong1669356355 := :ulong(451)+:ulong(200); +ulong2958289717 := :ulong(451)-:ulong(200); +ulong837362083 := :ulong(451)*:ulong(200); +ulong3417766688 := :ulong(451)/:ulong(200); +ulong3734930923 := :ulong(451)%:ulong(200); +ulong3430916640 := :ulong(451)>>:ulong(200); +ulong3263419748 := :ulong(451)<<:ulong(200); +ulong4106423246 := :ulong(451)|:ulong(200); +ulong2418261593 := :ulong(451)&:ulong(200); +llong2532134757 := :llong(451)+:llong(200); +llong4027182267 := :llong(451)-:llong(200); +llong2738991522 := :llong(451)*:llong(200); +llong584915521 := :llong(451)/:llong(200); +llong539575637 := :llong(451)%:llong(200); +llong1269621407 := :llong(451)>>:llong(200); +llong3781491866 := :llong(451)<<:llong(200); +llong4056699875 := :llong(451)|:llong(200); +llong3763295108 := :llong(451)&:llong(200); +ullong3899501603 := :ullong(451)+:ullong(200); +ullong4163116987 := :ullong(451)-:ullong(200); +ullong900520260 := :ullong(451)*:ullong(200); +ullong2083869174 := :ullong(451)/:ullong(200); +ullong1864796312 := :ullong(451)%:ullong(200); +ullong2757485449 := :ullong(451)>>:ullong(200); +ullong461805070 := :ullong(451)<<:ullong(200); +ullong1569839266 := :ullong(451)|:ullong(200); +ullong1735299987 := :ullong(451)&:ullong(200); +float1386138228 := :float(451)+:float(200); +float2298997472 := :float(451)-:float(200); +float1658412341 := :float(451)*:float(200); +float410190543 := :float(451)/:float(200); +float1517791460 := :float(451)%:float(200); +float3613392565 := :float(451)>>:float(200); +float214453256 := :float(451)<<:float(200); +float1348722320 := :float(451)|:float(200); +float1203551533 := :float(451)&:float(200); +double2979475223 := :double(451)+:double(200); +double667886729 := :double(451)-:double(200); +double3956848768 := :double(451)*:double(200); +double550709745 := :double(451)/:double(200); +double1846357701 := :double(451)%:double(200); +double1374823896 := :double(451)>>:double(200); +double1816508307 := :double(451)<<:double(200); +double3749361724 := :double(451)|:double(200); +double2314584652 := :double(451)&:double(200); diff --git a/tests/packed_struct.txt b/tests/packed_struct.txt new file mode 100644 index 0000000..2ea5cc1 --- /dev/null +++ b/tests/packed_struct.txt @@ -0,0 +1,52 @@ +import "libc"; + +A :: struct { + a: short; + b: char; + c: int; + d: char; + e: llong; + f: uchar; +} @packed + +B :: struct { + a: A; + b: A; +} + +C :: struct { + a: llong; + b: A; + c: A; +} + +D :: struct { + a: A; + b: int; + c: char; +} @packed + +#static_assert(sizeof(:A) == 17); +#static_assert(alignof(:A) == 1); + +#static_assert(sizeof(:B) == 34); +#static_assert(alignof(:B) == 1); + +#static_assert(sizeof(:C) == 48); +#static_assert(alignof(:C) == 8); + +#static_assert(sizeof(:D) == 22); +#static_assert(alignof(:D) == 1); + +main :: proc(): int { + assert(sizeof(:A) == 17); + assert(alignof(:A) == 1); + + assert(sizeof(:B) == 34); + assert(alignof(:B) == 1); + + assert(sizeof(:C) == 48); + assert(alignof(:C) == 8); + + return 0; +} \ No newline at end of file diff --git a/tests/parse_decl_errors.txt b/tests/parse_decl_errors.txt new file mode 100644 index 0000000..61097b7 --- /dev/null +++ b/tests/parse_decl_errors.txt @@ -0,0 +1,22 @@ + + +ASDF; + + +Something :: proc() { +} + + +^Memes; + +Some_Struct :: struct { + i: int; +} + + +Another_One + +// #failed: parse +// #error: got unexpected token +// #error: got unexpected token +// #error: got unexpected token \ No newline at end of file diff --git a/tests/parse_decl_note.txt b/tests/parse_decl_note.txt new file mode 100644 index 0000000..73bd9a8 --- /dev/null +++ b/tests/parse_decl_note.txt @@ -0,0 +1,8 @@ +// #failed: resolve +// #expected_error_count: 4 +m :: proc(); @api +m :: proc(); @api +m :: proc(); @api + @api + +@api \ No newline at end of file diff --git a/tests/pointers.txt b/tests/pointers.txt new file mode 100644 index 0000000..c5ab773 --- /dev/null +++ b/tests/pointers.txt @@ -0,0 +1,33 @@ +import "libc"; + +main :: proc(): int { + { + arr: [100]int = {1, 2 ,3 ,4}; + p0 := addptr(arr, 1); + assert(*p0 == 2); + + p1 := addptr(p0, 1); + assert(p1[0] == 3); + } + + { + i: *int = :*int(1); + if i { + i = nil; + assert(i == 0); + } + } + + { + token_count :: 20; + tokens: [token_count]int; + x: *int = addptr(tokens, 0); + t: *int = addptr(tokens, 4); + r1 := x && (t >= &tokens[0] && t < &tokens[token_count]); + r2 := x && (t >= addptr(tokens, 0) && t < addptr(tokens, token_count)); + assert(r1 == true); + assert(r2 == true); + } + + return 0; +} \ No newline at end of file diff --git a/tests/raw_strings.txt b/tests/raw_strings.txt new file mode 100644 index 0000000..fc52937 --- /dev/null +++ b/tests/raw_strings.txt @@ -0,0 +1,46 @@ +import "libc"; + +A :: `THING +THING`; + +B: String = `THING +THING`; + +main :: proc(): int { + a :: ` + Something + Other thing + Another thing + `; + + b := ` + Something + Other thing + Another thing + `; @unused + + + c: String = ` + Something + Other thing + Another thing + `; + + d := a; @unused + e := A; @unused + + has_new_lines: bool; + for i := 0; i < c.len; i += 1 { + if c.str[i] == '\n' { + has_new_lines = true; + } + assert(c.str[i] != 0); + } + assert(has_new_lines); + + lena := lengthof(A); @unused + assert(lengthof(A) == 11 || lengthof(A) == 12); // either CRLF or LF + assert(B.len == 11 || B.len == 12); + + return 0; +} \ No newline at end of file diff --git a/tests/regression_const_assign_decls.txt b/tests/regression_const_assign_decls.txt new file mode 100644 index 0000000..28bd0b7 --- /dev/null +++ b/tests/regression_const_assign_decls.txt @@ -0,0 +1,10 @@ +// #failed: resolve +PROC :: proc() {} +CONST :: 40; +STRUCT :: struct { a: int; } + +// #error: declaration is type, unexpected inside expression +A :: STRUCT; +// #error: expected an untyped constant +C :: PROC; +D :: CONST; \ No newline at end of file diff --git a/tests/regression_crash_on_decl_like_builtin.txt b/tests/regression_crash_on_decl_like_builtin.txt new file mode 100644 index 0000000..2c55078 --- /dev/null +++ b/tests/regression_crash_on_decl_like_builtin.txt @@ -0,0 +1,17 @@ +// #failed: resolve +// #expected_error_count: 6 +OS_WINDOWS :: 10; + + +String :: struct { + a: int; +} + +int :: struct { + i: long; +} + +// This should be OK +UntypedFloat :: struct { + a: float; +} \ No newline at end of file diff --git a/tests/regression_error_address_of_address.txt b/tests/regression_error_address_of_address.txt new file mode 100644 index 0000000..fa6509e --- /dev/null +++ b/tests/regression_error_address_of_address.txt @@ -0,0 +1,7 @@ +// #failed: resolve +// #error: trying to access address of a temporal object +main :: proc(): int { + a := 0; + app := &(&(a)); + return 0; +} \ No newline at end of file diff --git a/tests/regression_error_field_followed_by_invalid.txt b/tests/regression_error_field_followed_by_invalid.txt new file mode 100644 index 0000000..076ba9d --- /dev/null +++ b/tests/regression_error_field_followed_by_invalid.txt @@ -0,0 +1,25 @@ +// #failed: parse + +S :: struct { i: int; } +A :: struct { i: int; } + +main :: proc(): int { + s: S; + +// #error: expected identifier got instead integer literal + a := s.32; + +// #error: expected identifier got instead string literal + b := s."asd"; + +// #error: expected identifier got instead open paren + d := s.("asd"); + + + val := 32; +// #error: expected identifier got instead open paren + e := s.(24 + val); +// #error: expected identifier got instead open paren + f := s.(24 + 24); +} + diff --git a/tests/regression_error_handling_field_access.txt b/tests/regression_error_handling_field_access.txt new file mode 100644 index 0000000..82b09db --- /dev/null +++ b/tests/regression_error_handling_field_access.txt @@ -0,0 +1,20 @@ +// #failed: resolve + +Some_Struct :: struct { + item: int; + another_item: int; +} + +main :: proc() { + + { + some_struct: Some_Struct; +// #error: undeclared identifier 'i' + i := some_struct.i; + } + + @unused im: int; // int should be declared + @unused thing: Some_Struct; +// #error: undeclared identifier 'undeclared' + another_undeclared: undeclared; +} \ No newline at end of file diff --git a/tests/regression_error_handling_field_access2.txt b/tests/regression_error_handling_field_access2.txt new file mode 100644 index 0000000..a7817d3 --- /dev/null +++ b/tests/regression_error_handling_field_access2.txt @@ -0,0 +1,26 @@ +// #failed: resolve + +Some_Struct :: struct { + item: int; + another_item: int; +} + +main :: proc() { + ss: Some_Struct; + if ss.item { + { +// #error: undeclared identifier 'i' + a := ss.i; +// #error: undeclared identifier 'b' + ss.item = b - a; + } + } + + @unused thing: Some_Struct; +// #error: undeclared identifier 'undeclared' + undeclared; + + another_thing: Some_Struct; +// #error: very likely a bug, expression statement + another_thing; +} diff --git a/tests/regression_incomplete_type.txt b/tests/regression_incomplete_type.txt new file mode 100644 index 0000000..6fdf02d --- /dev/null +++ b/tests/regression_incomplete_type.txt @@ -0,0 +1,18 @@ +// #dont_run +#static_assert(sizeof(:A) == 8); +A :: struct { + a: int; + b: int; +} + +#static_assert(offsetof(:B, a) == 0); +B :: struct { + a: int; + b: int; +} + +#static_assert(alignof(:C) != 0); +C :: struct { + a: int; + b: int; +} diff --git a/tests/regression_note_after_if.txt b/tests/regression_note_after_if.txt new file mode 100644 index 0000000..22105d7 --- /dev/null +++ b/tests/regression_note_after_if.txt @@ -0,0 +1,12 @@ +main :: proc(): int { + a := true; + if a { + a = false; + } + thing := 10; @unused + + // I had an error once because note got eaten by else clause parse + // I have reversed that but if I decided that else if / else could be + // tagged then this test is meant to catch that + return 0; +} \ No newline at end of file diff --git a/tests/regression_return_null_pointer.txt b/tests/regression_return_null_pointer.txt new file mode 100644 index 0000000..c27db46 --- /dev/null +++ b/tests/regression_return_null_pointer.txt @@ -0,0 +1,10 @@ +A :: struct { i: int; } + +thing :: proc(): *A { + return nil; +} + +main :: proc(): int { + result := :int(:ullong(thing())); + return result; +} \ No newline at end of file diff --git a/tests/regression_same_named_agg_fields.txt b/tests/regression_same_named_agg_fields.txt new file mode 100644 index 0000000..9adb13a --- /dev/null +++ b/tests/regression_same_named_agg_fields.txt @@ -0,0 +1,6 @@ +// #failed: resolve +// #error: duplicate field 'a' in aggregate type 'A' +A :: struct { + a: int; + a: int; +} \ No newline at end of file diff --git a/tests/regression_same_named_proc_arguments.txt b/tests/regression_same_named_proc_arguments.txt new file mode 100644 index 0000000..a073828 --- /dev/null +++ b/tests/regression_same_named_proc_arguments.txt @@ -0,0 +1,4 @@ +// #failed: resolve +// #error: duplicate proc argument 'a' +A :: proc(a: int, a: int) { +} \ No newline at end of file diff --git a/tests/regression_sizeof_mismatch_with_c.txt b/tests/regression_sizeof_mismatch_with_c.txt new file mode 100644 index 0000000..8e1fdba --- /dev/null +++ b/tests/regression_sizeof_mismatch_with_c.txt @@ -0,0 +1,19 @@ +import "libc"; + +TEST_R_CommandKind :: typedef int; + +TEST_R_Command :: struct { + kind: TEST_R_CommandKind; + next: *TEST_R_Command; + + out : *int; + data: *int; + count: int; + max_count: int; +} @dont_mangle + +main :: proc(): int { + sizeof_in_c: ullong = #`sizeof(TEST_R_Command)`; + assert(sizeof_in_c == sizeof(:TEST_R_Command)); + return 0; +} \ No newline at end of file diff --git a/tests/regression_subtract_from_pointer.txt b/tests/regression_subtract_from_pointer.txt new file mode 100644 index 0000000..98d1181 --- /dev/null +++ b/tests/regression_subtract_from_pointer.txt @@ -0,0 +1,10 @@ +// #failed: resolve +// #error: cannot perform binary operation, types don't qualify for it, left: 'int' right: '*int' +// #error: invalid binary operation for type +main :: proc(): int { + a := 0; + b := &a; + c := a - b; + d := b - a; + return 0; +} \ No newline at end of file diff --git a/tests/regression_typedefs_not_compiling.txt b/tests/regression_typedefs_not_compiling.txt new file mode 100644 index 0000000..4b89fc9 --- /dev/null +++ b/tests/regression_typedefs_not_compiling.txt @@ -0,0 +1,8 @@ +A :: typedef int; +B :: typedef int; @weak +main :: proc(): int { + a: A; @unused + b: B; + + return b; +} \ No newline at end of file diff --git a/tests/regression_unidentified_in_function_please_dont_assert.txt b/tests/regression_unidentified_in_function_please_dont_assert.txt new file mode 100644 index 0000000..053bb64 --- /dev/null +++ b/tests/regression_unidentified_in_function_please_dont_assert.txt @@ -0,0 +1,14 @@ +// #failed: resolve + +// #error: undeclared identifier 'unidentified' +thing :: proc(): unidentified { +} + +// #error: undeclared identifier 'unidentified2' +thing2 :: proc(a: unidentified2) { +} + +main :: proc(): int { + thing(); + return 0; +} \ No newline at end of file diff --git a/tests/resolve_for_error.txt b/tests/resolve_for_error.txt new file mode 100644 index 0000000..3aef31d --- /dev/null +++ b/tests/resolve_for_error.txt @@ -0,0 +1,13 @@ +// #failed: resolve +// #error: undeclared identifier 'i' +// #error: undeclared identifier 'a' + +// purpose of this test is to make sure we don't leak for init statement + +main :: proc() { + for it: i { + } + + for it: a { + } +} \ No newline at end of file diff --git a/tests/simulated_enum.txt b/tests/simulated_enum.txt new file mode 100644 index 0000000..f605a04 --- /dev/null +++ b/tests/simulated_enum.txt @@ -0,0 +1,14 @@ +// #dont_run +THING_A :: 0; +THING_B :: ^; +THING_C :: ^; +THING_D :: ^; +THING_E :: 6; +THING_F :: ^; + +#static_assert(THING_A == 0); +#static_assert(THING_B == 1); +#static_assert(THING_C == 2); +#static_assert(THING_D == 3); +#static_assert(THING_E == 6); +#static_assert(THING_F == 7); diff --git a/tests/simulated_enum2.txt b/tests/simulated_enum2.txt new file mode 100644 index 0000000..3fbed7e --- /dev/null +++ b/tests/simulated_enum2.txt @@ -0,0 +1,4 @@ +// #failed: parse +// #error: invalid usage +A :: ^; +B :: 1; \ No newline at end of file diff --git a/tests/simulated_enum3.txt b/tests/simulated_enum3.txt new file mode 100644 index 0000000..bdf45f6 --- /dev/null +++ b/tests/simulated_enum3.txt @@ -0,0 +1,14 @@ +// #dont_run +A :: 0b1; +B :: <<; +C :: <<; + + +D :: 0b10000; +E :: <<; + +#static_assert(A == 0b1); +#static_assert(B == 0b10); +#static_assert(C == 0b100); +#static_assert(D == 0b10000); +#static_assert(E == 0b100000); \ No newline at end of file diff --git a/tests/sizes1.txt b/tests/sizes1.txt new file mode 100644 index 0000000..13e6050 --- /dev/null +++ b/tests/sizes1.txt @@ -0,0 +1,113 @@ +import "libc"; + +S1 :: struct { + i1: char; + i2: int; + i3: char; + i4: ullong; + i5: char; +} @dont_mangle + +S2 :: struct { + c: char; +} @dont_mangle + +S3 :: struct { + c: uint; +} @dont_mangle + +S4 :: struct { + c: uint; + s1: S1; + s2: S2; +} @dont_mangle + +S5 :: struct { + ul: ullong; + ui: uint; + i: int; + c: char; + s: short; + s2: S2; + v: *void; + c2: char; + s4: S4; +} @dont_mangle + + +main :: proc(): int { + {c_align: int = #`LC_Alignof(S1)`; + assert(c_align == alignof(:S1));} + + {c_align: int = #`LC_Alignof(S2)`; + assert(c_align == alignof(:S2));} + + {c_align: int = #`LC_Alignof(S3)`; + assert(c_align == alignof(:S3));} + + {c_align: int = #`LC_Alignof(S4)`; + assert(c_align == alignof(:S4));} + + {c_sizeof: int = #`sizeof(S1)`; + assert(c_sizeof == sizeof(:S1));} + + {c_sizeof: int = #`sizeof(S2)`; + assert(c_sizeof == sizeof(:S2));} + + {c_sizeof: int = #`sizeof(S3)`; + assert(c_sizeof == sizeof(:S3));} + + {c_sizeof: int = #`sizeof(S4)`; + assert(c_sizeof == sizeof(:S4));} + + {c_sizeof: int = #`sizeof(S5)`; + assert(c_sizeof == sizeof(:S5));} + + {c_alignof: int = #`LC_Alignof(S5)`; + assert(c_alignof == alignof(:S5));} + + {c_offsetof: int = #`offsetof(S4, s1)`; + assert(c_offsetof == offsetof(:S4, s1));} + + {c_offsetof: int = #`offsetof(S4, s2)`; + assert(c_offsetof == offsetof(:S4, s2));} + + {c_offsetof: int = #`offsetof(S1, i1)`; + assert(c_offsetof == offsetof(:S1, i1));} + + {c_offsetof: int = #`offsetof(S1, i2)`; + assert(c_offsetof == offsetof(:S1, i2));} + + {c_offsetof: int = #`offsetof(S1, i3)`; + assert(c_offsetof == offsetof(:S1, i3));} + + {c_offsetof: int = #`offsetof(S1, i4)`; + assert(c_offsetof == offsetof(:S1, i4));} + + {c_offsetof: int = #`offsetof(S1, i5)`; + assert(c_offsetof == offsetof(:S1, i5));} + + {c_offsetof: int = #`offsetof(S3, c)`; + assert(c_offsetof == offsetof(:S3, c));} + + {c_offsetof: int = #`offsetof(S5, ul)`; + assert(c_offsetof == offsetof(:S5, ul));} + {c_offsetof: int = #`offsetof(S5, ui)`; + assert(c_offsetof == offsetof(:S5, ui));} + {c_offsetof: int = #`offsetof(S5, i)`; + assert(c_offsetof == offsetof(:S5, i));} + {c_offsetof: int = #`offsetof(S5, c)`; + assert(c_offsetof == offsetof(:S5, c));} + {c_offsetof: int = #`offsetof(S5, s)`; + assert(c_offsetof == offsetof(:S5, s));} + {c_offsetof: int = #`offsetof(S5, s2)`; + assert(c_offsetof == offsetof(:S5, s2));} + {c_offsetof: int = #`offsetof(S5, v)`; + assert(c_offsetof == offsetof(:S5, v));} + {c_offsetof: int = #`offsetof(S5, c2)`; + assert(c_offsetof == offsetof(:S5, c2));} + {c_offsetof: int = #`offsetof(S5, s4)`; + assert(c_offsetof == offsetof(:S5, s4));} + + return 0; +} \ No newline at end of file diff --git a/tests/sizes2.txt b/tests/sizes2.txt new file mode 100644 index 0000000..495f49b --- /dev/null +++ b/tests/sizes2.txt @@ -0,0 +1,313 @@ +import "raylib"; +import "libc"; + +main :: proc(): int { + { + size := sizeof(:Vector2); + csize: int = #`sizeof(lc_raylib_Vector2)`; + assert(size == csize); + + align := alignof(:Vector2); + calign: int = #`LC_Alignof(lc_raylib_Vector2)`; + assert(align == calign); + } + { + size := sizeof(:Vector3); + csize: int = #`sizeof(lc_raylib_Vector3)`; + assert(size == csize); + + align := alignof(:Vector3); + calign: int = #`LC_Alignof(lc_raylib_Vector3)`; + assert(align == calign); + } + { + size := sizeof(:Vector4); + csize: int = #`sizeof(lc_raylib_Vector4)`; + assert(size == csize); + + align := alignof(:Vector4); + calign: int = #`LC_Alignof(lc_raylib_Vector4)`; + assert(align == calign); + } + { + size := sizeof(:Matrix); + csize: int = #`sizeof(lc_raylib_Matrix)`; + assert(size == csize); + + align := alignof(:Matrix); + calign: int = #`LC_Alignof(lc_raylib_Matrix)`; + assert(align == calign); + } + { + size := sizeof(:Color); + csize: int = #`sizeof(lc_raylib_Color)`; + assert(size == csize); + + align := alignof(:Color); + calign: int = #`LC_Alignof(lc_raylib_Color)`; + assert(align == calign); + } + { + size := sizeof(:Rectangle); + csize: int = #`sizeof(lc_raylib_Rectangle)`; + assert(size == csize); + + align := alignof(:Rectangle); + calign: int = #`LC_Alignof(lc_raylib_Rectangle)`; + assert(align == calign); + } + { + size := sizeof(:Image); + csize: int = #`sizeof(lc_raylib_Image)`; + assert(size == csize); + + align := alignof(:Image); + calign: int = #`LC_Alignof(lc_raylib_Image)`; + assert(align == calign); + } + { + size := sizeof(:Texture); + csize: int = #`sizeof(lc_raylib_Texture)`; + assert(size == csize); + + align := alignof(:Texture); + calign: int = #`LC_Alignof(lc_raylib_Texture)`; + assert(align == calign); + } + { + size := sizeof(:RenderTexture); + csize: int = #`sizeof(lc_raylib_RenderTexture)`; + assert(size == csize); + + align := alignof(:RenderTexture); + calign: int = #`LC_Alignof(lc_raylib_RenderTexture)`; + assert(align == calign); + } + { + size := sizeof(:NPatchInfo); + csize: int = #`sizeof(lc_raylib_NPatchInfo)`; + assert(size == csize); + + align := alignof(:NPatchInfo); + calign: int = #`LC_Alignof(lc_raylib_NPatchInfo)`; + assert(align == calign); + } + { + size := sizeof(:GlyphInfo); + csize: int = #`sizeof(lc_raylib_GlyphInfo)`; + assert(size == csize); + + align := alignof(:GlyphInfo); + calign: int = #`LC_Alignof(lc_raylib_GlyphInfo)`; + assert(align == calign); + } + { + size := sizeof(:Font); + csize: int = #`sizeof(lc_raylib_Font)`; + assert(size == csize); + + align := alignof(:Font); + calign: int = #`LC_Alignof(lc_raylib_Font)`; + assert(align == calign); + } + { + size := sizeof(:Camera3D); + csize: int = #`sizeof(lc_raylib_Camera3D)`; + assert(size == csize); + + align := alignof(:Camera3D); + calign: int = #`LC_Alignof(lc_raylib_Camera3D)`; + assert(align == calign); + } + { + size := sizeof(:Camera2D); + csize: int = #`sizeof(lc_raylib_Camera2D)`; + assert(size == csize); + + align := alignof(:Camera2D); + calign: int = #`LC_Alignof(lc_raylib_Camera2D)`; + assert(align == calign); + } + { + size := sizeof(:Mesh); + csize: int = #`sizeof(lc_raylib_Mesh)`; + assert(size == csize); + + align := alignof(:Mesh); + calign: int = #`LC_Alignof(lc_raylib_Mesh)`; + assert(align == calign); + } + { + size := sizeof(:Shader); + csize: int = #`sizeof(lc_raylib_Shader)`; + assert(size == csize); + + align := alignof(:Shader); + calign: int = #`LC_Alignof(lc_raylib_Shader)`; + assert(align == calign); + } + { + size := sizeof(:MaterialMap); + csize: int = #`sizeof(lc_raylib_MaterialMap)`; + assert(size == csize); + + align := alignof(:MaterialMap); + calign: int = #`LC_Alignof(lc_raylib_MaterialMap)`; + assert(align == calign); + } + { + size := sizeof(:Material); + csize: int = #`sizeof(lc_raylib_Material)`; + assert(size == csize); + + align := alignof(:Material); + calign: int = #`LC_Alignof(lc_raylib_Material)`; + assert(align == calign); + } + { + size := sizeof(:Transform); + csize: int = #`sizeof(lc_raylib_Transform)`; + assert(size == csize); + + align := alignof(:Transform); + calign: int = #`LC_Alignof(lc_raylib_Transform)`; + assert(align == calign); + } + { + size := sizeof(:BoneInfo); + csize: int = #`sizeof(lc_raylib_BoneInfo)`; + assert(size == csize); + + align := alignof(:BoneInfo); + calign: int = #`LC_Alignof(lc_raylib_BoneInfo)`; + assert(align == calign); + } + { + size := sizeof(:Model); + csize: int = #`sizeof(lc_raylib_Model)`; + assert(size == csize); + + align := alignof(:Model); + calign: int = #`LC_Alignof(lc_raylib_Model)`; + assert(align == calign); + } + { + size := sizeof(:ModelAnimation); + csize: int = #`sizeof(lc_raylib_ModelAnimation)`; + assert(size == csize); + + align := alignof(:ModelAnimation); + calign: int = #`LC_Alignof(lc_raylib_ModelAnimation)`; + assert(align == calign); + } + { + size := sizeof(:Ray); + csize: int = #`sizeof(lc_raylib_Ray)`; + assert(size == csize); + + align := alignof(:Ray); + calign: int = #`LC_Alignof(lc_raylib_Ray)`; + assert(align == calign); + } + { + size := sizeof(:RayCollision); + csize: int = #`sizeof(lc_raylib_RayCollision)`; + assert(size == csize); + + align := alignof(:RayCollision); + calign: int = #`LC_Alignof(lc_raylib_RayCollision)`; + assert(align == calign); + } + { + size := sizeof(:BoundingBox); + csize: int = #`sizeof(lc_raylib_BoundingBox)`; + assert(size == csize); + + align := alignof(:BoundingBox); + calign: int = #`LC_Alignof(lc_raylib_BoundingBox)`; + assert(align == calign); + } + { + size := sizeof(:Wave); + csize: int = #`sizeof(lc_raylib_Wave)`; + assert(size == csize); + + align := alignof(:Wave); + calign: int = #`LC_Alignof(lc_raylib_Wave)`; + assert(align == calign); + } + { + size := sizeof(:AudioStream); + csize: int = #`sizeof(lc_raylib_AudioStream)`; + assert(size == csize); + + align := alignof(:AudioStream); + calign: int = #`LC_Alignof(lc_raylib_AudioStream)`; + assert(align == calign); + } + { + size := sizeof(:Sound); + csize: int = #`sizeof(lc_raylib_Sound)`; + assert(size == csize); + + align := alignof(:Sound); + calign: int = #`LC_Alignof(lc_raylib_Sound)`; + assert(align == calign); + } + { + size := sizeof(:Music); + csize: int = #`sizeof(lc_raylib_Music)`; + assert(size == csize); + + align := alignof(:Music); + calign: int = #`LC_Alignof(lc_raylib_Music)`; + assert(align == calign); + } + { + size := sizeof(:VrDeviceInfo); + csize: int = #`sizeof(lc_raylib_VrDeviceInfo)`; + assert(size == csize); + + align := alignof(:VrDeviceInfo); + calign: int = #`LC_Alignof(lc_raylib_VrDeviceInfo)`; + assert(align == calign); + } + { + size := sizeof(:VrStereoConfig); + csize: int = #`sizeof(lc_raylib_VrStereoConfig)`; + assert(size == csize); + + align := alignof(:VrStereoConfig); + calign: int = #`LC_Alignof(lc_raylib_VrStereoConfig)`; + assert(align == calign); + } + { + size := sizeof(:FilePathList); + csize: int = #`sizeof(lc_raylib_FilePathList)`; + assert(size == csize); + + align := alignof(:FilePathList); + calign: int = #`LC_Alignof(lc_raylib_FilePathList)`; + assert(align == calign); + } + { + size := sizeof(:AutomationEvent); + csize: int = #`sizeof(lc_raylib_AutomationEvent)`; + assert(size == csize); + + align := alignof(:AutomationEvent); + calign: int = #`LC_Alignof(lc_raylib_AutomationEvent)`; + assert(align == calign); + } + { + size := sizeof(:AutomationEventList); + csize: int = #`sizeof(lc_raylib_AutomationEventList)`; + assert(size == csize); + + align := alignof(:AutomationEventList); + calign: int = #`LC_Alignof(lc_raylib_AutomationEventList)`; + assert(align == calign); + } + + return 0; +} \ No newline at end of file diff --git a/tests/stmt_parse_error1.txt b/tests/stmt_parse_error1.txt new file mode 100644 index 0000000..8eb5b1e --- /dev/null +++ b/tests/stmt_parse_error1.txt @@ -0,0 +1,10 @@ +// #failed: parser +// #error: expected close brace + +main :: proc() { + for a := 0; { + A(); + } + A(); + +} \ No newline at end of file diff --git a/tests/stmt_parse_error2.txt b/tests/stmt_parse_error2.txt new file mode 100644 index 0000000..de9552e --- /dev/null +++ b/tests/stmt_parse_error2.txt @@ -0,0 +1,27 @@ +// #failed: parse + +// #error: failed to parse typespec, invalid token assignment '=' +// #error: failed to parse typespec, invalid token assignment '=' +// #error: failed to parse typespec, invalid token assignment '=' +main :: proc(): int { + a(); + :=; + :=; + { + } + := + + awsd + asd +} + +// #error: expected close paren ')' got instead close brace '}' +A :: proc() { + for A( { + } +} + +// #error: statement lacks a semicolon +B :: proc() { + asd +} \ No newline at end of file diff --git a/tests/stmt_parse_error3.txt b/tests/stmt_parse_error3.txt new file mode 100644 index 0000000..75bc458 --- /dev/null +++ b/tests/stmt_parse_error3.txt @@ -0,0 +1,15 @@ +// #failed: parse +// #error: unclosed open brace '{' +main :: proc(): int { +{; +} + +// #error: statement lacks a semicolon +A :: proc() { + asd +} + +// #error: statement lacks a semicolon +B :: proc() { + asd +} \ No newline at end of file diff --git a/tests/stmt_parse_error4.txt b/tests/stmt_parse_error4.txt new file mode 100644 index 0000000..01c940c --- /dev/null +++ b/tests/stmt_parse_error4.txt @@ -0,0 +1,35 @@ +// #failed: parse +// #error: statement lacks a semicolon at the end +// #error: statement lacks a semicolon at the end + +A :: proc() { + for { + for { + screen_rect := Rectangle{min_screen.x, min_screen.y, r.width, r.height}; + } + } + EndMode2d(); +} + +main :: proc(): int { + for !WindowShouldClose() { + for y_it := 0; y_it < map.y; y_it += 1 { + for x_it := 0; x_it < map.x; x_it += 1 { + screen_rect := Rectangle{min_screen.x, min_screen.y, r.width, r.height}; + if tile.value == 1 { + DrawRectangleRec(r, RED); + } else { + DrawRectangleRec(r, GREEN); + } + + if CheckCollisionPointRec(mouse_p, screen_rect) { + DrawRectangleRec(r, BLUE); + } + } + } + EndMode2D(); + } + + CloseWindow(); + return 0; +} diff --git a/tests/stmt_parse_error5.txt b/tests/stmt_parse_error5.txt new file mode 100644 index 0000000..7fbe11a --- /dev/null +++ b/tests/stmt_parse_error5.txt @@ -0,0 +1,11 @@ +// #failed: parse +// #error: got invalid token: semicolon +// #error: got unexpected token: open brace +A :: proc() { + a := ; @unused + asd := 10; + + } + { + +} \ No newline at end of file diff --git a/tests/string_errors.txt b/tests/string_errors.txt new file mode 100644 index 0000000..23ad260 --- /dev/null +++ b/tests/string_errors.txt @@ -0,0 +1,19 @@ +// #failed: resolve + +main :: proc(): int { + indexing_const := "something"[0]; + + string: String = "something other"; + indexing_string := string[0]; + indexing_string2 := string + indexing_const; + + str: *char = :String("Something"); + other_str: String = :*char("Something"); + + return 0; +} + +// #error: trying to index non indexable type 'String' +// #error: cannot perform binary operation, types don't qualify for it, left: 'String' right: 'char' +// #error: cannot assign, types are incompatible, variable type: '*char' expression type: 'String' +// #error: cannot assign, types are incompatible, variable type: 'String' expression type: '*char' \ No newline at end of file diff --git a/tests/strings.txt b/tests/strings.txt new file mode 100644 index 0000000..5535048 --- /dev/null +++ b/tests/strings.txt @@ -0,0 +1,46 @@ +import "libc"; + +main :: proc(): int { + + empty_string: String = ""; + assert(empty_string.len == 0); + empty_string = ``; + assert(empty_string.len == 0); + + empty_char: *char = ""; + assert(*empty_char == 0); + + A: String = "testing"; + assert(A.str[0] == 't'); + + assert(7 == "\a"[0]); + assert(8 == "\b"[0]); + assert(9 == "\t"[0]); + assert(10 == "\n"[0]); + assert(11 == "\v"[0]); + assert(12 == "\f"[0]); + assert(13 == "\r"[0]); + assert(0x1b == "\e"[0]); + + assert(7 == '\a'); + assert(8 == '\b'); + assert(9 == '\t'); + assert(10 == '\n'); + assert(11 == '\v'); + assert(12 == '\f'); + assert(13 == '\r'); + assert(0x1b == '\e'); + + assert(0 == "\0"[0]); + assert(1 == lengthof("0")); + + assert(97 == "abc"[0]); + assert(98 == "abc"[1]); + assert(99 == "abc"[2]); + assert(0 == "abc"[3]); + assert(3 == lengthof("abc")); + assert(1 == lengthof("\r")); + assert(7 == lengthof("\r\nThing")); + + return 0; +} \ No newline at end of file diff --git a/tests/switch.txt b/tests/switch.txt new file mode 100644 index 0000000..fbd114d --- /dev/null +++ b/tests/switch.txt @@ -0,0 +1,18 @@ +main :: proc(): int { + result := 1; + a := 1; + + switch a { + case 0, 1: { + result = 0; + } + case 2, 3, 4: { + result = 4; + } + default: { + result = 2; + } + } + + return result; +} \ No newline at end of file diff --git a/tests/switch2.txt b/tests/switch2.txt new file mode 100644 index 0000000..bb3dae3 --- /dev/null +++ b/tests/switch2.txt @@ -0,0 +1,15 @@ +// #failed: resolve +// #error: expected an untyped constant +main :: proc(): int { + + value := 1; + switch value { + case 0, 2: { + return 1; + } + case 1, value: { + return 2; + } + } + return 0; +} \ No newline at end of file diff --git a/tests/switch3.txt b/tests/switch3.txt new file mode 100644 index 0000000..e032ba9 --- /dev/null +++ b/tests/switch3.txt @@ -0,0 +1,15 @@ +// #failed: resolve +// #error: duplicate fields +main :: proc(): int { + + value := 1; + switch value { + case 0, 1: { + return 1; + } + case 1, 2: { + return 2; + } + } + return 0; +} \ No newline at end of file diff --git a/tests/switch4.txt b/tests/switch4.txt new file mode 100644 index 0000000..a25f59e --- /dev/null +++ b/tests/switch4.txt @@ -0,0 +1,15 @@ +// #failed: resolve +// #error: value '9999999999 +main :: proc(): int { + + value := 1; + switch value { + case 0, 999999999999999999999999999: { + return 1; + } + case 1, 2: { + return 2; + } + } + return 0; +} \ No newline at end of file diff --git a/tests/switch5.txt b/tests/switch5.txt new file mode 100644 index 0000000..e9d5bf9 --- /dev/null +++ b/tests/switch5.txt @@ -0,0 +1,11 @@ +main :: proc(): int { + value := 4; + switch value { + case 4: { value -= 1; } @fallthrough + case 3: { value -= 1; } @fallthrough + case 2: { value -= 1; } @fallthrough + case 1: { value -= 1; } @fallthrough + default: a := 10; @unused + } + return value; +} \ No newline at end of file diff --git a/tests/switch_non_int.txt b/tests/switch_non_int.txt new file mode 100644 index 0000000..f93f883 --- /dev/null +++ b/tests/switch_non_int.txt @@ -0,0 +1,12 @@ +// #failed: resolve +// #error: invalid type in switch condition '*int', it should be an integer + +main :: proc(): int { + i: *int = nil; + switch i { + case 0: {} + default: {} + } + + return 0; +} \ No newline at end of file diff --git a/tests/test_bound_check.txt b/tests/test_bound_check.txt new file mode 100644 index 0000000..3f73491 --- /dev/null +++ b/tests/test_bound_check.txt @@ -0,0 +1,23 @@ +// #failed: resolve +INT_MAX :: 2147483647; +INT_MORE_THEN_MAX :: INT_MAX + 1; + +main :: proc(): int { +// #error: value '2147483648', doesn't fit into type 'int' + a: int = INT_MORE_THEN_MAX; @unused +// #error: value '2147483648', doesn't fit into type 'int' + a = INT_MORE_THEN_MAX; @unused + + +// #error: value '-1', doesn't fit into type 'uchar' + c: uchar = -1; @unused + + d := INT_MAX; @unused + +// #error: value '2147483648', doesn't fit into type 'int' + e := INT_MAX + 1; @unused + + f: bool = 10; @unused + + return 0; +} \ No newline at end of file diff --git a/tests/test_build_if_import/a/a.lc b/tests/test_build_if_import/a/a.lc new file mode 100644 index 0000000..7a4f662 --- /dev/null +++ b/tests/test_build_if_import/a/a.lc @@ -0,0 +1,5 @@ +#build_if(1); + +A :: proc(): int { + return 0; +} \ No newline at end of file diff --git a/tests/test_build_if_import/a/b.lc b/tests/test_build_if_import/a/b.lc new file mode 100644 index 0000000..7042197 --- /dev/null +++ b/tests/test_build_if_import/a/b.lc @@ -0,0 +1,5 @@ +#build_if(0); + +A :: proc(): int { + return 1; +} \ No newline at end of file diff --git a/tests/test_build_if_import/b/a.lc b/tests/test_build_if_import/b/a.lc new file mode 100644 index 0000000..fa95788 --- /dev/null +++ b/tests/test_build_if_import/b/a.lc @@ -0,0 +1,5 @@ +#build_if(0); + +B :: proc(): int { + return 1; +} \ No newline at end of file diff --git a/tests/test_build_if_import/b/b.lc b/tests/test_build_if_import/b/b.lc new file mode 100644 index 0000000..6738551 --- /dev/null +++ b/tests/test_build_if_import/b/b.lc @@ -0,0 +1,5 @@ +#build_if(1); + +B :: proc(): int { + return 0; +} \ No newline at end of file diff --git a/tests/test_build_if_import/main/main.lc b/tests/test_build_if_import/main/main.lc new file mode 100644 index 0000000..69ebe51 --- /dev/null +++ b/tests/test_build_if_import/main/main.lc @@ -0,0 +1,8 @@ +import "a"; +import "b"; + +main :: proc(): int { + a := A(); + b := B(); + return a + b; +} \ No newline at end of file diff --git a/tests/test_cast_string_lvalue.txt b/tests/test_cast_string_lvalue.txt new file mode 100644 index 0000000..42aecb8 --- /dev/null +++ b/tests/test_cast_string_lvalue.txt @@ -0,0 +1,8 @@ +A := "Something"; + +main :: proc(): int { + B := &:*char(A)[1]; @unused + C := *:*char(A); @unused + D := :*char(A)[0]; @unused + return 0; +} \ No newline at end of file diff --git a/tests/test_circular_imports/circular_b/circular_b.lc b/tests/test_circular_imports/circular_b/circular_b.lc new file mode 100644 index 0000000..7f2a0d7 --- /dev/null +++ b/tests/test_circular_imports/circular_b/circular_b.lc @@ -0,0 +1,4 @@ +import "main"; + +other_thing :: proc() { +} \ No newline at end of file diff --git a/tests/test_circular_imports/main/circular_a.lc b/tests/test_circular_imports/main/circular_a.lc new file mode 100644 index 0000000..7b9d807 --- /dev/null +++ b/tests/test_circular_imports/main/circular_a.lc @@ -0,0 +1,4 @@ +import "circular_b"; + +thing :: proc() { +} \ No newline at end of file diff --git a/tests/test_circular_imports/test.txt b/tests/test_circular_imports/test.txt new file mode 100644 index 0000000..3512b10 --- /dev/null +++ b/tests/test_circular_imports/test.txt @@ -0,0 +1,2 @@ +// #failed: package +// #error: circular import \ No newline at end of file diff --git a/tests/test_circular_imports_namespaced/circular_b/circular_b.lc b/tests/test_circular_imports_namespaced/circular_b/circular_b.lc new file mode 100644 index 0000000..4368ee3 --- /dev/null +++ b/tests/test_circular_imports_namespaced/circular_b/circular_b.lc @@ -0,0 +1,4 @@ +import a "main"; + +other_thing :: proc() { +} \ No newline at end of file diff --git a/tests/test_circular_imports_namespaced/main/circular_a.lc b/tests/test_circular_imports_namespaced/main/circular_a.lc new file mode 100644 index 0000000..1678ed2 --- /dev/null +++ b/tests/test_circular_imports_namespaced/main/circular_a.lc @@ -0,0 +1,4 @@ +import b "circular_b"; + +thing :: proc() { +} \ No newline at end of file diff --git a/tests/test_circular_imports_namespaced/test.txt b/tests/test_circular_imports_namespaced/test.txt new file mode 100644 index 0000000..3512b10 --- /dev/null +++ b/tests/test_circular_imports_namespaced/test.txt @@ -0,0 +1,2 @@ +// #failed: package +// #error: circular import \ No newline at end of file diff --git a/tests/test_cross_package_types/main/main.lc b/tests/test_cross_package_types/main/main.lc new file mode 100644 index 0000000..7ec521b --- /dev/null +++ b/tests/test_cross_package_types/main/main.lc @@ -0,0 +1,17 @@ +import T "type"; + +main :: proc(): int { + a := :T.A{1, 2}; @unused + b: T.A = {0}; @unused + e := T.AVAL.b; @unused + g := T.AVAL.c.a; @unused + h := T.AVAL.c.d.a; @unused + i := (T.AVAL.c).d.a; @unused + j := (T.AVAL).c.d.a; @unused + k := T.AVAL.c.d.a; @unused + l := T.AVALP.c.d.a; @unused + m := T.AVALP[0].c.d.a; @unused + n := offsetof(:T.A, b); @unused + + return T.AVAL.a; +} \ No newline at end of file diff --git a/tests/test_cross_package_types/main_error/main.lc b/tests/test_cross_package_types/main_error/main.lc new file mode 100644 index 0000000..7fc255e --- /dev/null +++ b/tests/test_cross_package_types/main_error/main.lc @@ -0,0 +1,7 @@ +T :: import "type"; + +main :: proc(): int { + a := T.EnumVar.VAL; + T; + T[0]; +} \ No newline at end of file diff --git a/tests/test_cross_package_types/type/type.lc b/tests/test_cross_package_types/type/type.lc new file mode 100644 index 0000000..4a2af4c --- /dev/null +++ b/tests/test_cross_package_types/type/type.lc @@ -0,0 +1,18 @@ + +D :: struct { + a: int; +} + +C :: struct { + a: int; + d: D; +} + +A :: struct { + a: int; + b: int; + c: C; +} + +AVAL: A; +AVALP: *A = &AVAL; diff --git a/tests/test_error_in_other_package/main/main.lc b/tests/test_error_in_other_package/main/main.lc new file mode 100644 index 0000000..3ecc396 --- /dev/null +++ b/tests/test_error_in_other_package/main/main.lc @@ -0,0 +1,14 @@ +import "other"; + +Meme :: proc(): asd2 { + return 0; +} + +make_sure_it_doesnt_report_about_lacking_return :: proc(): int { + asd := Meme(); + return asd; +} + +main :: proc(): int { + c: asd_local; +} \ No newline at end of file diff --git a/tests/test_error_in_other_package/other/other.lc b/tests/test_error_in_other_package/other/other.lc new file mode 100644 index 0000000..96faf7f --- /dev/null +++ b/tests/test_error_in_other_package/other/other.lc @@ -0,0 +1,3 @@ +Thing :: proc(): asd1 { + return 0; +} \ No newline at end of file diff --git a/tests/test_error_in_other_package/test.txt b/tests/test_error_in_other_package/test.txt new file mode 100644 index 0000000..2b9055a --- /dev/null +++ b/tests/test_error_in_other_package/test.txt @@ -0,0 +1,4 @@ +// #failed: package +// #error: undeclared identifier 'asd1' +// #error: undeclared identifier 'asd2' +// #error: undeclared identifier 'asd_local' \ No newline at end of file diff --git a/tests/test_global_const.txt b/tests/test_global_const.txt new file mode 100644 index 0000000..a09d290 --- /dev/null +++ b/tests/test_global_const.txt @@ -0,0 +1,10 @@ +arr: [100]int; +pointer_indexing1 := addptr(arr, 0); + +iconst :: 1; +pointer_indexing2 := addptr(arr, iconst); + + +main :: proc(): int { + return *pointer_indexing1 + *pointer_indexing2; +} \ No newline at end of file diff --git a/tests/test_global_const2.txt b/tests/test_global_const2.txt new file mode 100644 index 0000000..290a3e1 --- /dev/null +++ b/tests/test_global_const2.txt @@ -0,0 +1,11 @@ +// just mimicking C, weird memes + +// #failed: resolve +// #error: non constant global declaration +arr: [100]int; +ivar := 0; +pointer_indexing := &arr[ivar]; + +main :: proc(): int { + return *pointer_indexing; +} \ No newline at end of file diff --git a/tests/test_import_duplicate_symbol/b/b.lc b/tests/test_import_duplicate_symbol/b/b.lc new file mode 100644 index 0000000..529a3b1 --- /dev/null +++ b/tests/test_import_duplicate_symbol/b/b.lc @@ -0,0 +1,4 @@ +/*@api*/ +B :: struct { + a: int; +} \ No newline at end of file diff --git a/tests/test_import_duplicate_symbol/main/a.lc b/tests/test_import_duplicate_symbol/main/a.lc new file mode 100644 index 0000000..464504a --- /dev/null +++ b/tests/test_import_duplicate_symbol/main/a.lc @@ -0,0 +1,4 @@ +import "b"; + +B :: proc() { +} \ No newline at end of file diff --git a/tests/test_import_duplicate_symbol/test.txt b/tests/test_import_duplicate_symbol/test.txt new file mode 100644 index 0000000..304435a --- /dev/null +++ b/tests/test_import_duplicate_symbol/test.txt @@ -0,0 +1,5 @@ +// #failed: package +// #error: there are 2 decls with the same name 'B' + +// I don't know why matching 'B' on empty decl line works here but's that's good +// #error: B \ No newline at end of file diff --git a/tests/test_import_std/main/main.lc b/tests/test_import_std/main/main.lc new file mode 100644 index 0000000..67322e5 --- /dev/null +++ b/tests/test_import_std/main/main.lc @@ -0,0 +1,14 @@ +import "std_types"; +import "libc"; + +#` +#include +#include +#include +`; + +main :: proc(): int { + TestSizes(); + a: u64 = 0; + return :int(a); +} \ No newline at end of file diff --git a/tests/test_import_std/main/test_sizes.lc b/tests/test_import_std/main/test_sizes.lc new file mode 100644 index 0000000..ffd4a32 --- /dev/null +++ b/tests/test_import_std/main/test_sizes.lc @@ -0,0 +1,61 @@ +TestSizes :: proc() { + uint64_max: u64 = #`UINT64_MAX`; + assert(UINT64_MAX == uint64_max); + uint32_max: u32 = #`UINT32_MAX`; + assert(UINT32_MAX == uint32_max); + uint16_max: u16 = #`UINT16_MAX`; + assert(UINT16_MAX == uint16_max); + uint8_max: u8 = #`UINT8_MAX`; + assert(UINT8_MAX == uint8_max); + int64_max: i64 = #`INT64_MAX`; + assert(INT64_MAX == int64_max); + int64_min: i64 = #`INT64_MIN`; + assert(INT64_MIN == int64_min); + int32_max: i32 = #`INT32_MAX`; + assert(INT32_MAX == int32_max); + int32_min: i32 = #`INT32_MIN`; + assert(INT32_MIN == int32_min); + int16_max: i16 = #`INT16_MAX`; + assert(INT16_MAX == int16_max); + int16_min: i16 = #`INT16_MIN`; + assert(INT16_MIN == int16_min); + int8_max: i8 = #`INT8_MAX`; + assert(INT8_MAX == int8_max); + int8_min: i8 = #`INT8_MIN`; + assert(INT8_MIN == int8_min); + char_max: char = #`CHAR_MAX`; + assert(CHAR_MAX == char_max); + char_min: char = #`CHAR_MIN`; + assert(CHAR_MIN == char_min); + uchar_max: uchar = #`UCHAR_MAX`; + assert(UCHAR_MAX == uchar_max); + int_max: int = #`INT_MAX`; + assert(INT_MAX == int_max); + int_min: int = #`INT_MIN`; + assert(INT_MIN == int_min); + uint_max: uint = #`UINT_MAX`; + assert(UINT_MAX == uint_max); + llong_max: llong = #`LLONG_MAX`; + assert(LLONG_MAX == llong_max); + llong_min: llong = #`LLONG_MIN`; + assert(LLONG_MIN == llong_min); + ullong_max: ullong = #`ULLONG_MAX`; + assert(ULLONG_MAX == ullong_max); + + long_max: long = #`LONG_MAX`; + assert(LONG_MAX == long_max); + long_min: long = #`LONG_MIN`; + assert(LONG_MIN == long_min); + ulong_max: ulong = #`ULONG_MAX`; + assert(ULONG_MAX == ulong_max); + ulong_min: ulong = #`0`; + assert(ULONG_MIN == ulong_min); + + intptr_max: intptr = #`INTPTR_MAX`; + assert(INTPTR_MAX == intptr_max); + intptr_min: intptr = #`INTPTR_MIN`; + assert(INTPTR_MIN == intptr_min); + uintptr_max: uintptr = #`UINTPTR_MAX`; + assert(UINTPTR_MAX == uintptr_max); + +} \ No newline at end of file diff --git a/tests/test_import_symbol_leak/a/a.lc b/tests/test_import_symbol_leak/a/a.lc new file mode 100644 index 0000000..2c38f4f --- /dev/null +++ b/tests/test_import_symbol_leak/a/a.lc @@ -0,0 +1,3 @@ +/*@api*/ +A :: proc() { +} \ No newline at end of file diff --git a/tests/test_import_symbol_leak/b/b.lc b/tests/test_import_symbol_leak/b/b.lc new file mode 100644 index 0000000..988d30d --- /dev/null +++ b/tests/test_import_symbol_leak/b/b.lc @@ -0,0 +1,6 @@ +import "a"; + +/*@api*/ +B :: proc() { + A(); +} \ No newline at end of file diff --git a/tests/test_import_symbol_leak/main/c.lc b/tests/test_import_symbol_leak/main/c.lc new file mode 100644 index 0000000..f7ea983 --- /dev/null +++ b/tests/test_import_symbol_leak/main/c.lc @@ -0,0 +1,6 @@ +import "b"; + +C :: proc() { + B(); + A(); +} \ No newline at end of file diff --git a/tests/test_import_symbol_leak/test.txt b/tests/test_import_symbol_leak/test.txt new file mode 100644 index 0000000..bf7c842 --- /dev/null +++ b/tests/test_import_symbol_leak/test.txt @@ -0,0 +1,2 @@ +// #failed: package +// #error: undeclared identifier 'A' \ No newline at end of file diff --git a/tests/test_multiple_imports_of_same_package/b/duplicate_b.lc b/tests/test_multiple_imports_of_same_package/b/duplicate_b.lc new file mode 100644 index 0000000..daa7ffb --- /dev/null +++ b/tests/test_multiple_imports_of_same_package/b/duplicate_b.lc @@ -0,0 +1,2 @@ +other_thing :: proc() { +} \ No newline at end of file diff --git a/tests/test_multiple_imports_of_same_package/main/duplicate_a.lc b/tests/test_multiple_imports_of_same_package/main/duplicate_a.lc new file mode 100644 index 0000000..6fb9d53 --- /dev/null +++ b/tests/test_multiple_imports_of_same_package/main/duplicate_a.lc @@ -0,0 +1,4 @@ +import b "b"; +import "b"; +thing :: proc() { +} \ No newline at end of file diff --git a/tests/test_multiple_imports_of_same_package/test.txt b/tests/test_multiple_imports_of_same_package/test.txt new file mode 100644 index 0000000..870c053 --- /dev/null +++ b/tests/test_multiple_imports_of_same_package/test.txt @@ -0,0 +1,5 @@ +// #failed: package +// #error: duplicate import + +I don't know what I'm matching but this works +// #error: a \ No newline at end of file diff --git a/tests/test_namespaced_duplicate_decl/a2/a2.lc b/tests/test_namespaced_duplicate_decl/a2/a2.lc new file mode 100644 index 0000000..07610df --- /dev/null +++ b/tests/test_namespaced_duplicate_decl/a2/a2.lc @@ -0,0 +1,3 @@ +a :: proc(): int { + return 0; +} \ No newline at end of file diff --git a/tests/test_namespaced_duplicate_decl/main/main.lc b/tests/test_namespaced_duplicate_decl/main/main.lc new file mode 100644 index 0000000..0b64c89 --- /dev/null +++ b/tests/test_namespaced_duplicate_decl/main/main.lc @@ -0,0 +1,6 @@ +import a2 "a2"; +a :: proc(): int { return 0; } + +main :: proc(): int { + return a2.a() + a(); +} \ No newline at end of file diff --git a/tests/test_namespaced_import/a/a.lc b/tests/test_namespaced_import/a/a.lc new file mode 100644 index 0000000..b7cb6ce --- /dev/null +++ b/tests/test_namespaced_import/a/a.lc @@ -0,0 +1,4 @@ +/*@api*/ +A :: proc(): int { + return 0; +} \ No newline at end of file diff --git a/tests/test_namespaced_import/b/b.lc b/tests/test_namespaced_import/b/b.lc new file mode 100644 index 0000000..afb289c --- /dev/null +++ b/tests/test_namespaced_import/b/b.lc @@ -0,0 +1,12 @@ +import "a"; + +/*@api*/ +B :: proc(): int { + return A(); +} + +B_NO_API :: proc() { +} + +/*@api*/ +BCONST :: 32; \ No newline at end of file diff --git a/tests/test_namespaced_import/main/c.lc b/tests/test_namespaced_import/main/c.lc new file mode 100644 index 0000000..687a4d0 --- /dev/null +++ b/tests/test_namespaced_import/main/c.lc @@ -0,0 +1,10 @@ +import b "b"; + +main :: proc(): int { + result := b.B(); + // b.B_NO_API(); + b.A(); + b; + co := b.BCONST; @unused + return result; +} \ No newline at end of file diff --git a/tests/test_namespaced_import/test.txt b/tests/test_namespaced_import/test.txt new file mode 100644 index 0000000..165239e --- /dev/null +++ b/tests/test_namespaced_import/test.txt @@ -0,0 +1,3 @@ +// #failed: package +// #error: undeclared identifier 'A' +// #error: declaration is import \ No newline at end of file diff --git a/tests/test_same_foreign_names.txt b/tests/test_same_foreign_names.txt new file mode 100644 index 0000000..dd71178 --- /dev/null +++ b/tests/test_same_foreign_names.txt @@ -0,0 +1,11 @@ +// #failed: resolve +// #expected_error_count: 4 + +lc_testing_thing :: proc() {} @foreign + +thing :: proc() { +} + +lc_testing_meme :: proc() {} @dont_mangle + +meme :: proc() {} \ No newline at end of file diff --git a/tests/test_two_mains/b/main.lc b/tests/test_two_mains/b/main.lc new file mode 100644 index 0000000..05a7466 --- /dev/null +++ b/tests/test_two_mains/b/main.lc @@ -0,0 +1,3 @@ +main :: proc(): int { + return 0; +} \ No newline at end of file diff --git a/tests/test_two_mains/main/main.lc b/tests/test_two_mains/main/main.lc new file mode 100644 index 0000000..28ddd2f --- /dev/null +++ b/tests/test_two_mains/main/main.lc @@ -0,0 +1,5 @@ +import b "b"; + +main :: proc(): int { + return b.main(); +} \ No newline at end of file diff --git a/tests/test_typechecking_all_errors_reported.txt b/tests/test_typechecking_all_errors_reported.txt new file mode 100644 index 0000000..2c10cb5 --- /dev/null +++ b/tests/test_typechecking_all_errors_reported.txt @@ -0,0 +1,37 @@ +// #failed: resolve + +// #error: duplicate field 'a' in aggregate type 'A' +A :: struct { + a: int; + a: int; +} + +// #error: duplicate field 'a' in aggregate type 'B' +B :: struct { + a: int; + a: int; +} + +C :: struct { + c: A; +} + +// #error: duplicate field 'a' in aggregate type 'D' +D :: struct { + a: int; + a: int; +} + +E :: struct { + a: int; +} + +PROC :: proc() { + a: A; + b: B; + c: C = {1}; + d: D; + e: E; +// #error: undeclared identifier 'b' + f := e.b; +} \ No newline at end of file diff --git a/tests/typedef_struct.txt b/tests/typedef_struct.txt new file mode 100644 index 0000000..ac36fb8 --- /dev/null +++ b/tests/typedef_struct.txt @@ -0,0 +1,24 @@ +STRUCT :: struct { a: int; b: int; } +AnotherStruct :: typedef STRUCT; +AnotherAnotherStruct :: typedef AnotherStruct; + +U :: union { a: int; b: float; } +TU :: typedef U; +TTU :: typedef TU; + +TP :: typedef *U; +TTP :: typedef TP; + +main :: proc(): int { + a: AnotherStruct; + a.b = 0; + b: AnotherAnotherStruct = { a = 0, b = 1 }; + tu: TU = { a = 10 }; + ttu: TTU = { b = 10 }; @unused + tp: TP = :TP(&tu); + tpf := tp.a; @unused + ttp: TTP = :TTP(&tu); + ttpf := ttp.a; @unused + + return a.b + b.a; +} \ No newline at end of file diff --git a/tests/uninitialized.txt b/tests/uninitialized.txt new file mode 100644 index 0000000..31f0dbb --- /dev/null +++ b/tests/uninitialized.txt @@ -0,0 +1,13 @@ +import "libc"; + +S :: struct {i: int; j: int;} +U :: union {i: int; j: float;} + +main :: proc(): int { + thing: int; @unused @not_init + string: String; @unused @not_init + other: *char; @unused @not_init + s: S; @unused @not_init + u: U; @unused @not_init + return 0; +} \ No newline at end of file diff --git a/tests/unreferenced_local_variable.txt b/tests/unreferenced_local_variable.txt new file mode 100644 index 0000000..8ff31a1 --- /dev/null +++ b/tests/unreferenced_local_variable.txt @@ -0,0 +1,7 @@ +// #failed: resolve +// #error: unused local variable 'a' + +main :: proc(): int { + a: int; + return 0; +} \ No newline at end of file diff --git a/tests/untyped_overflow_div.txt b/tests/untyped_overflow_div.txt new file mode 100644 index 0000000..dd67eec --- /dev/null +++ b/tests/untyped_overflow_div.txt @@ -0,0 +1,11 @@ +b :: -2147483648 / -1; +#static_assert(b == 2147483648); + +c :: -9223372036854775808 / -1; +#static_assert(c == 9223372036854775808); + +main :: proc(): int { + a: ullong = c; + result: int = :int(a - 9223372036854775808); + return result; +} \ No newline at end of file diff --git a/tests/untyped_strings.txt b/tests/untyped_strings.txt new file mode 100644 index 0000000..4bc1d24 --- /dev/null +++ b/tests/untyped_strings.txt @@ -0,0 +1,24 @@ +import "libc"; + +main :: proc(): int { + untyped_string_const :: "something"; + default_string := untyped_string_const; + assert(typeof(default_string) == typeof(:*char)); + + with_type: *char = untyped_string_const; @unused + void_type: *void = untyped_string_const; @unused + + indexing_const := untyped_string_const[0]; + assert(indexing_const == 's'); + assert(typeof(indexing_const) == typeof(:char)); + + lengthof_const_string := lengthof(untyped_string_const); + assert(lengthof_const_string == 9); + assert(lengthof_const_string == lengthof("something")); + + pointer_index := addptr("something", 0); + assert(typeof(pointer_index) == typeof(:*char)); + assert(pointer_index[0] == 's'); + + return 0; +} \ No newline at end of file diff --git a/tests/untyped_strings_errors.txt b/tests/untyped_strings_errors.txt new file mode 100644 index 0000000..fefd153 --- /dev/null +++ b/tests/untyped_strings_errors.txt @@ -0,0 +1,22 @@ +// #failed: resolve + +main :: proc(): int { + +// #error: invalid operand add '+' for binary expr of type untyped string + binary_op :: "a" + "b"; +// #error: invalid operand exclamation '!' for unary expr of type untyped string + unary_op0 :: !"a"; +// #error: invalid operand subtract '-' for unary expr of type untyped string + unary_op1 :: -"a"; +// #error: invalid operand add '+' for unary expr of type untyped string + unary_op2 :: +"a"; + +// #error: cannot get sizeof a value that is untyped: 'UntypedString' + sizeof("asd"); +// #error: cannot get alignof a value that is untyped: 'UntypedString' + alignof("asd"); +// #error: cannot get typeof a value that is untyped: 'UntypedString' + typeof("asd"); + + return 0; +} \ No newline at end of file diff --git a/tests/void_ptr_index.txt b/tests/void_ptr_index.txt new file mode 100644 index 0000000..cb3ee16 --- /dev/null +++ b/tests/void_ptr_index.txt @@ -0,0 +1,8 @@ +// #failed: resolve +// #error: void is non indexable + +main :: proc(): int { + a: *void = nil; + r := a[10]; + return 1; +} \ No newline at end of file diff --git a/tests/weird_import_parse.txt b/tests/weird_import_parse.txt new file mode 100644 index 0000000..55e792b --- /dev/null +++ b/tests/weird_import_parse.txt @@ -0,0 +1,12 @@ +// #failed: parse +// #error: expected string after an import +// #error: expected open paren +// #error: unclosed open brace + +import a :: "thing"; + +b :: proc) { +} + + +c :: proc() { \ No newline at end of file diff --git a/tools/bindgen.py b/tools/bindgen.py new file mode 100644 index 0000000..6cb18c4 --- /dev/null +++ b/tools/bindgen.py @@ -0,0 +1,285 @@ +import subprocess +import json +import code + +def filter_types(str): + return str.replace('_Bool', 'bool') + +def parse_struct(decl): + if decl.get("inner") == None: + return None + + outp = {} + outp['kind'] = 'struct' + outp['struct_kind'] = decl["tagUsed"] + outp['name'] = decl['name'] + outp['fields'] = [] + for item_decl in decl['inner']: + if item_decl['kind'] == 'FullComment': continue + if item_decl['kind'] != 'FieldDecl': + print(f"// ERROR: Structs must only contain simple fields ({decl['name']})") + print("/*", item_decl, "*/") + return None + item = {} + if 'name' in item_decl: + item['name'] = item_decl['name'] + item['type'] = filter_types(item_decl['type']['qualType']) + outp['fields'].append(item) + return outp + +def parse_enum(decl): + if decl.get("inner") == None: + return None + outp = {} + if 'name' in decl: + outp['kind'] = 'enum' + outp['name'] = decl['name'] + needs_value = False + else: + outp['kind'] = 'consts' + needs_value = True + outp['items'] = [] + + for item_decl in decl['inner']: + if item_decl['kind'] == 'EnumConstantDecl': + item = {} + item['name'] = item_decl['name'] + if 'inner' in item_decl: + const_expr = item_decl['inner'][0] + if const_expr['kind'] != 'ConstantExpr': + print(f"// ERROR: Enum values must be a ConstantExpr ({item_decl['name']}), is '{const_expr['kind']}'") + return None + if const_expr['valueCategory'] != 'rvalue' and const_expr['valueCategory'] != 'prvalue': + print(f"// ERROR: Enum value ConstantExpr must be 'rvalue' or 'prvalue' ({item_decl['name']}), is '{const_expr['valueCategory']}'") + return None + if not ((len(const_expr['inner']) == 1) and (const_expr['inner'][0]['kind'] == 'IntegerLiteral')): + print(f"// ERROR: Enum value ConstantExpr must have exactly one IntegerLiteral ({item_decl['name']})") + return None + item['value'] = const_expr['inner'][0]['value'] + if needs_value and 'value' not in item: + print(f"// ERROR: anonymous enum items require an explicit value") + return None + outp['items'].append(item) + return outp + +def parse_func(decl): + outp = {} + outp['kind'] = 'func' + outp['name'] = decl['name'] + outp['type'] = filter_types(decl['type']['qualType']) + + outp['variadic'] = False + if decl.get("variadic"): + outp['variadic'] = True + outp['params'] = [] + if 'inner' in decl: + for param in decl['inner']: + if param['kind'] != 'ParmVarDecl': + if param['kind'] == 'BuiltinAttr': continue + if param['kind'] == 'NoThrowAttr': continue + if param['kind'] == 'FullComment': continue + if param['kind'] == 'PureAttr': continue + if param['kind'] == 'DLLImportAttr': continue + if param['kind'] == 'CompoundStmt': continue # function with body + if param['kind'] == 'AlwaysInlineAttr': continue + if param['kind'] == 'FormatAttr': + outp['variadic'] = True + continue + print(f"// warning: ignoring func {decl['name']} (unsupported parameter type) {param['kind']}") + return None + if param.get('name') == None: return None + outp_param = {} + outp_param['name'] = param['name'] + outp_param['type'] = filter_types(param['type']['qualType']) + outp['params'].append(outp_param) + return outp + +def parse_typedef(decl): + if decl['type']['qualType'].startswith("struct") or\ + decl['type']['qualType'].startswith("union") or\ + decl['type']['qualType'].startswith("enum"): + return None + outp = {}; + outp['kind'] = 'typedef' + outp['name'] = decl['name'] + outp['type'] = filter_types(decl['type']['qualType']) + return outp + +def parse_decl(decl): + kind = decl['kind'] + if kind == 'RecordDecl': + return parse_struct(decl) + elif kind == 'EnumDecl': + return parse_enum(decl) + elif kind == 'FunctionDecl': + return parse_func(decl) + elif kind == "TypedefDecl": + return parse_typedef(decl) + else: + return None + +def bindgen_enum(decl): + r += decl["name"] + " :: typedef int;\n" + for item in decl["items"]: + r += item["name"] + if item.get("value"): + r += " :: " + item["value"] + r += ";\n" + return r + +types = { + "unsigned int": "uint", + "unsigned long": "ulong", + "unsigned long long": "ullong", + "long long": "llong", + "unsigned int": "uint", + "unsigned": "uint", + "unsigned short": "ushort", + "unsigned char": "uchar", + "uint64_t": "u64", + "uint32_t": "u32", + "uint16_t": "u16", + "uint8_t": "u8", + "int64_t": "i64", + "int32_t": "i32", + "int16_t": "i16", + "int8_t": "i8", + "size_t": "usize", +} + +def bindgen_type(type): + type = type.replace("const ", "") + type = type.strip() + if types.get(type): return types[type] + if type[-1] == '*': return "*" + bindgen_type(type[:-1]) + if type[-1] == ' ': return bindgen_type(type[:-1]) + if type[-1] == ']': + i = -1 + while type[i] != '[': i += 1 + array = type[i:] + return array + bindgen_type(type[:i]) + + func_ptr_idx = type.find('(*)') + if func_ptr_idx != -1: + args = type[func_ptr_idx+4:-1] + args = args.split(",") + new_args = [] + + name = 'a' + for it in args: + new_args.append(name + ": " + bindgen_type(it)) + name = chr(ord(name[0]) + 1) + new_args = ', '.join(new_args) + + ret = type[:func_ptr_idx] + return "proc(" + new_args + "): " + bindgen_type(ret) + + func_idx = type.find('(') + if func_idx != -1: + args = type[func_idx+1:-1] + args = args.split(",") + new_args = [] + + name = 'a' + for it in args: + new_args.append(name + ": " + bindgen_type(it)) + name = chr(ord(name[0]) + 1) + new_args = ', '.join(new_args) + + ret = type[:func_idx] + return "proc(" + new_args + "): " + bindgen_type(ret) + + return type + +def bindgen_struct(decl): + r = "" + r += decl["name"] + " :: " + decl["struct_kind"] + " {\n" + for field in decl["fields"]: + r += " " + field["name"] + ": " + bindgen_type(field["type"]) + ";\n" + r += "}\n" + return r + +def bindgen_func(decl): + r = "" + vargs = decl['variadic'] + r += decl["name"] + " :: proc(" + i = 0 + for param in decl["params"]: + r += param["name"] + ": " + bindgen_type(param["type"]) + if i != len(decl["params"]) - 1 or vargs: + r += ", " + i += 1 + if vargs: r += ".." + r += ")" + decl_type = decl["type"] + return_type = decl_type[:decl_type.index('(')].strip() + return_type = bindgen_type(return_type) + if return_type != "void": + r += ": " + return_type + r += ";" + return r + +def bindgen_typedef(decl): + return decl["name"] + " :: typedef " + bindgen_type(decl["type"]) + ";" + + +def get_clang_ast(file): + cmd = ['clang', '-IC:/Work/', '-Xclang', '-ast-dump=json'] + cmd.append(file) + out = subprocess.run(cmd, stdout=subprocess.PIPE) + + if out.returncode == 0: + tu = json.loads(out.stdout) + return tu + return None + +def has_prefix(decl, prefixes): + if prefixes == None or len(prefixes) == 0: return True + + for it in prefixes: + if decl["name"].startswith(it): + return True + return False + +def bindgen_to_stdout(file, prefixes): + tu = get_clang_ast(file) + if tu == None: return + + decls = [] + for decl in tu["inner"]: + has_name = decl.get("name") + if has_name == None: continue + + hp = has_prefix(decl, prefixes) + if hp: + out_decl = parse_decl(decl) + if out_decl: + decls.append(out_decl) + + for decl in decls: + try: + if decl["kind"] == "func": out = bindgen_func(decl) + elif decl["kind"] == "struct": out = bindgen_struct(decl) + elif decl["kind"] == "enum": out = bindgen_enum(decl) + elif decl["kind"] == "typedef": out = bindgen_typedef(decl) + else: sys.exit("invalid decl kind", decl) + except IndexError: + print(f"// ERROR: generating {decl['name']} {decl['type']}") + continue + + print(out) + + +if __name__ == "__main__": + import argparse + import sys + + parser = argparse.ArgumentParser(description='generate bindings for a c file using clang') + parser.add_argument('filename') + parser.add_argument('--prefixes', nargs='+', help = 'generate declarations with these prefixes') + args = parser.parse_args() + + if args.filename.endswith(".c") or args.filename.endswith(".cpp"): + print("warning: for some reason clang doesn't like c and c++ files, the file to generate bindings for need to be a header") + + bindgen_to_stdout(args.filename, args.prefixes) \ No newline at end of file diff --git a/tools/lcompile.c b/tools/lcompile.c new file mode 100644 index 0000000..ae42c22 --- /dev/null +++ b/tools/lcompile.c @@ -0,0 +1,50 @@ +#include "../src/core/core.c" + +#define LC_USE_CUSTOM_ARENA +#define LC_Arena MA_Arena +#define LC__PushSizeNonZeroed MA__PushSizeNonZeroed +#define LC__PushSize MA__PushSize +#define LC_InitArena MA_Init +#define LC_DeallocateArena MA_DeallocateArena +#define LC_BootstrapArena MA_Bootstrap +#define LC_TempArena MA_Temp +#define LC_BeginTemp MA_BeginTemp +#define LC_EndTemp MA_EndTemp + +#define LC_String S8_String +#define LIB_COMPILER_IMPLEMENTATION +#include "../lib_compiler.h" + +int main(int argc, char **argv) { + bool colored = LC_EnableTerminalColors(); + MA_Arena arena = {0}; + S8_List dirs = {0}; + + CmdParser p = MakeCmdParser(&arena, argc, argv, "I'm a tool that compiles lc packages - for example: ./lc.exe "); + p.require_one_standalone_arg = true; + AddList(&p, &dirs, "dirs", "additional directories where I can find packages!"); + if (!ParseCmd(&arena, &p)) + return 0; + + IO_Assert(p.args.node_count == 1); + S8_String package = p.args.first->string; + S8_String path_to_package = S8_ChopLastSlash(package); + path_to_package = S8_Copy(&arena, path_to_package); + + package = S8_SkipToLastSlash(package); + package = S8_Copy(&arena, package); + + LC_Lang *lang = LC_LangAlloc(); + lang->use_colored_terminal_output = colored; + LC_LangBegin(lang); + LC_RegisterPackageDir("pkgs"); + LC_RegisterPackageDir(path_to_package.str); + S8_For(it, dirs) { LC_RegisterPackageDir(it->string.str); } + + LC_Intern name = LC_InternStrLen(package.str, (int)package.len); + LC_ASTRefList packages = LC_ResolvePackageByName(name); + if (lang->errors) return 1; + + S8_String code = LC_GenerateUnityBuild(packages); + OS_WriteFile(S8_Lit("output.c"), code); +} \ No newline at end of file diff --git a/tools/nasm.exe b/tools/nasm.exe new file mode 100644 index 0000000..a2e6129 Binary files /dev/null and b/tools/nasm.exe differ diff --git a/tools/ndisasm.exe b/tools/ndisasm.exe new file mode 100644 index 0000000..c4a5b95 Binary files /dev/null and b/tools/ndisasm.exe differ