test(gencpp): add full gencpp/base samples and comprehensive test suite
- Copied 58 files from C:\projects\gencpp\base\ to tests/assets/gencpp_samples - Added test_gencpp_full_suite.py that validates: - Skeleton generation for all .hpp files - Code outline generation - get_definition for key symbols - AST masking with aggregation - All 25 tests pass
This commit is contained in:
@@ -0,0 +1,61 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# include "builder.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Builder
|
||||||
|
|
||||||
|
Builder builder_open( char const* path )
|
||||||
|
{
|
||||||
|
Builder result;
|
||||||
|
|
||||||
|
FileError error = file_open_mode( & result.File, EFileMode_WRITE, path );
|
||||||
|
if ( error != EFileError_NONE )
|
||||||
|
{
|
||||||
|
log_failure( "gen::File::open - Could not open file: %s", path);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
Context* ctx = get_context();
|
||||||
|
GEN_ASSERT_NOT_NULL(ctx);
|
||||||
|
result.Buffer = strbuilder_make_reserve( ctx->Allocator_Temp, ctx->InitSize_BuilderBuffer );
|
||||||
|
|
||||||
|
// log_fmt("$Builder - Opened file: %s\n", result.File.filename );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void builder_pad_lines( Builder* builder, s32 num )
|
||||||
|
{
|
||||||
|
strbuilder_append_str( & builder->Buffer, txt("\n") );
|
||||||
|
}
|
||||||
|
|
||||||
|
void builder_print( Builder* builder, Code code )
|
||||||
|
{
|
||||||
|
StrBuilder str = code_to_strbuilder(code);
|
||||||
|
// const ssize len = str.length();
|
||||||
|
// log_fmt( "%s - print: %.*s\n", File.filename, len > 80 ? 80 : len, str.Data );
|
||||||
|
strbuilder_append_string( & builder->Buffer, str );
|
||||||
|
}
|
||||||
|
|
||||||
|
void builder_print_fmt_va( Builder* builder, char const* fmt, va_list va )
|
||||||
|
{
|
||||||
|
ssize res;
|
||||||
|
char buf[ GEN_PRINTF_MAXLEN ] = { 0 };
|
||||||
|
|
||||||
|
res = c_str_fmt_va( buf, count_of( buf ) - 1, fmt, va ) - 1;
|
||||||
|
|
||||||
|
strbuilder_append_c_str_len( (StrBuilder*) & (builder->Buffer), (char const*)buf, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
void builder_write(Builder* builder)
|
||||||
|
{
|
||||||
|
b32 result = file_write( & builder->File, builder->Buffer, strbuilder_length(builder->Buffer) );
|
||||||
|
|
||||||
|
if ( result == false )
|
||||||
|
log_failure("gen::File::write - Failed to write to file: %s\n", file_name( & builder->File ) );
|
||||||
|
|
||||||
|
log_fmt( "Generated: %s\n", builder->File.filename );
|
||||||
|
file_close( & builder->File );
|
||||||
|
strbuilder_free(& builder->Buffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma endregion Builder
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "helpers/push_ignores.inline.hpp"
|
||||||
|
# include "components/header_start.hpp"
|
||||||
|
# include "components/types.hpp"
|
||||||
|
# include "components/gen/ecodetypes.hpp"
|
||||||
|
# include "components/gen/eoperator.hpp"
|
||||||
|
# include "components/gen/especifier.hpp"
|
||||||
|
# include "components/ast.hpp"
|
||||||
|
# include "components/code_types.hpp"
|
||||||
|
# include "components/ast_types.hpp"
|
||||||
|
# include "components/interface.hpp"
|
||||||
|
# include "components/inlines.hpp"
|
||||||
|
# include "components/gen/ast_inlines.hpp"
|
||||||
|
# include "components/header_end.hpp"
|
||||||
|
using namespace gen;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Builder
|
||||||
|
|
||||||
|
struct Builder;
|
||||||
|
typedef struct Builder Builder;
|
||||||
|
|
||||||
|
GEN_API Builder builder_open ( char const* path );
|
||||||
|
GEN_API void builder_pad_lines ( Builder* builder, s32 num );
|
||||||
|
GEN_API void builder_print ( Builder* builder, Code code );
|
||||||
|
GEN_API void builder_print_fmt_va( Builder* builder, char const* fmt, va_list va );
|
||||||
|
GEN_API void builder_write ( Builder* builder );
|
||||||
|
|
||||||
|
forceinline void builder_print_fmt ( Builder* builder, char const* fmt, ... ) {
|
||||||
|
va_list va;
|
||||||
|
va_start( va, fmt );
|
||||||
|
builder_print_fmt_va( builder, fmt, va );
|
||||||
|
va_end( va );
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Builder
|
||||||
|
{
|
||||||
|
FileInfo File;
|
||||||
|
StrBuilder Buffer;
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP && ! GEN_C_LIKE_CPP
|
||||||
|
forceinline static Builder open( char const* path ) { return builder_open(path); }
|
||||||
|
|
||||||
|
forceinline void pad_lines( s32 num ) { return builder_pad_lines(this, num); }
|
||||||
|
|
||||||
|
forceinline void print( Code code ) { return builder_print(this, code); }
|
||||||
|
forceinline void print_fmt( char const* fmt, ... ) {
|
||||||
|
va_list va;
|
||||||
|
va_start( va, fmt );
|
||||||
|
builder_print_fmt_va( this, fmt, va );
|
||||||
|
va_end( va );
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline void write() { return builder_write(this); }
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP && ! GEN_C_LIKE_CPP
|
||||||
|
forceinline void builder_pad_lines( Builder& builder, s32 num ) { return builder_pad_lines(& builder, num); }
|
||||||
|
forceinline void builder_print ( Builder& builder, Code code ) { return builder_print(& builder, code); }
|
||||||
|
forceinline void builder_write ( Builder& builder ) { return builder_write(& builder ); }
|
||||||
|
forceinline void builder_print_fmt( Builder& builder, char const* fmt, ...) {
|
||||||
|
va_list va;
|
||||||
|
va_start( va, fmt );
|
||||||
|
builder_print_fmt_va( & builder, fmt, va );
|
||||||
|
va_end( va );
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Builder
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "helpers/push_ignores.inline.hpp"
|
||||||
|
# include "components/header_start.hpp"
|
||||||
|
# include "components/types.hpp"
|
||||||
|
# include "components/gen/ecode.hpp"
|
||||||
|
# include "components/gen/eoperator.hpp"
|
||||||
|
# include "components/gen/especifier.hpp"
|
||||||
|
# include "components/ast.hpp"
|
||||||
|
# include "components/code_types.hpp"
|
||||||
|
# include "components/ast_types.hpp"
|
||||||
|
# include "components/interface.hpp"
|
||||||
|
# include "components/inlines.hpp"
|
||||||
|
# include "components/gen/ast_inlines.hpp"
|
||||||
|
# include "components/header_end.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
Explicitly generates a resolved definition of a cpp template definition.
|
||||||
|
|
||||||
|
TODO(Ed): Needs implementing for the C-library variant.
|
||||||
|
TODO(Ed): We need a non <token> syntax subst implemtnation for Strings for this to work. It must subst keywords directly based on template parameter names.
|
||||||
|
|
||||||
|
This is only meant to be used on relatively trivial templates, where the type or numeric is mostly a 'duck' type.
|
||||||
|
It cannot parse complex template parameters.
|
||||||
|
|
||||||
|
The varadic args should correspond 1:1 with the type of objects the generator expects from the template's parameters.alignas.
|
||||||
|
*/
|
||||||
|
|
||||||
|
CodeOperator gen_operator_template( CodeTemplate template, ... );
|
||||||
|
CodeFn gen_func_template( CodeTemplate template, ... );
|
||||||
|
Code gen_class_struct_template( CodeTemplate template, ... );
|
||||||
|
|
||||||
|
Code gen_template( CodeTemplate template, ... );
|
||||||
|
Code gen_template( Str template, Str instantiation );
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# include "scanner.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Scanner
|
||||||
|
|
||||||
|
Code scan_file( char const* path )
|
||||||
|
{
|
||||||
|
FileInfo file;
|
||||||
|
|
||||||
|
FileError error = file_open_mode( & file, EFileMode_READ, path );
|
||||||
|
if ( error != EFileError_NONE )
|
||||||
|
{
|
||||||
|
GEN_FATAL( "scan_file: Could not open: %s", path );
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize fsize = file_size( & file );
|
||||||
|
if ( fsize <= 0 )
|
||||||
|
{
|
||||||
|
GEN_FATAL("scan_file: %s is empty", path );
|
||||||
|
}
|
||||||
|
|
||||||
|
StrBuilder str = strbuilder_make_reserve( get_context()->Allocator_Temp, fsize );
|
||||||
|
file_read( & file, str, fsize );
|
||||||
|
strbuilder_get_header(str)->Length = fsize;
|
||||||
|
|
||||||
|
// Skip INTELLISENSE_DIRECTIVES preprocessor blocks
|
||||||
|
// Its designed so that the directive should be the first thing in the file.
|
||||||
|
// Anything that comes before it will also be omitted.
|
||||||
|
{
|
||||||
|
#define current (*scanner)
|
||||||
|
#define matched 0
|
||||||
|
#define move_fwd() do { ++ scanner; -- left; } while (0)
|
||||||
|
const Str directive_start = txt( "ifdef" );
|
||||||
|
const Str directive_end = txt( "endif" );
|
||||||
|
const Str def_intellisense = txt("INTELLISENSE_DIRECTIVES" );
|
||||||
|
|
||||||
|
bool found_directive = false;
|
||||||
|
char const* scanner = (char const*)str;
|
||||||
|
s32 left = fsize;
|
||||||
|
while ( left )
|
||||||
|
{
|
||||||
|
// Processing directive.
|
||||||
|
if ( current == '#' )
|
||||||
|
{
|
||||||
|
move_fwd();
|
||||||
|
while ( left && char_is_space( current ) )
|
||||||
|
move_fwd();
|
||||||
|
|
||||||
|
if ( ! found_directive )
|
||||||
|
{
|
||||||
|
if ( left && c_str_compare_len( scanner, directive_start.Ptr, directive_start.Len ) == matched )
|
||||||
|
{
|
||||||
|
scanner += directive_start.Len;
|
||||||
|
left -= directive_start.Len;
|
||||||
|
|
||||||
|
while ( left && char_is_space( current ) )
|
||||||
|
move_fwd();
|
||||||
|
|
||||||
|
if ( left && c_str_compare_len( scanner, def_intellisense.Ptr, def_intellisense.Len ) == matched )
|
||||||
|
{
|
||||||
|
scanner += def_intellisense.Len;
|
||||||
|
left -= def_intellisense.Len;
|
||||||
|
|
||||||
|
found_directive = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip to end of line
|
||||||
|
while ( left && current != '\r' && current != '\n' )
|
||||||
|
move_fwd();
|
||||||
|
move_fwd();
|
||||||
|
|
||||||
|
if ( left && current == '\n' )
|
||||||
|
move_fwd();
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( left && c_str_compare_len( scanner, directive_end.Ptr, directive_end.Len ) == matched )
|
||||||
|
{
|
||||||
|
scanner += directive_end.Len;
|
||||||
|
left -= directive_end.Len;
|
||||||
|
|
||||||
|
// Skip to end of line
|
||||||
|
while ( left && current != '\r' && current != '\n' )
|
||||||
|
move_fwd();
|
||||||
|
move_fwd();
|
||||||
|
|
||||||
|
if ( left && current == '\n' )
|
||||||
|
move_fwd();
|
||||||
|
|
||||||
|
// sptr skip_size = fsize - left;
|
||||||
|
if ( (scanner + 2) >= ( (char const*) str + fsize ) )
|
||||||
|
{
|
||||||
|
mem_move( str, scanner, left );
|
||||||
|
strbuilder_get_header(str)->Length = left;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
mem_move( str, scanner, left );
|
||||||
|
strbuilder_get_header(str)->Length = left;
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
move_fwd();
|
||||||
|
}
|
||||||
|
#undef move_fwd
|
||||||
|
#undef matched
|
||||||
|
#undef current
|
||||||
|
}
|
||||||
|
|
||||||
|
file_close( & file );
|
||||||
|
return untyped_str( strbuilder_to_str(str) );
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeBody parse_file( const char* path ) {
|
||||||
|
FileContents file = file_read_contents( get_context()->Allocator_Temp, true, path );
|
||||||
|
Str content = { (char const*)file.data, file.size };
|
||||||
|
CodeBody code = parse_global_body( content );
|
||||||
|
log_fmt("\nParsed: %s\n", path);
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
|
||||||
|
CSV_Column parse_csv_one_column(AllocatorInfo allocator, char const* path) {
|
||||||
|
FileContents content = file_read_contents( allocator, file_zero_terminate, path );
|
||||||
|
Arena csv_arena = arena_init_from_memory(content.data, content.size);
|
||||||
|
|
||||||
|
CSV_Column result;
|
||||||
|
csv_parse( & result.ADT, rcast(char*, content.data), allocator, false );
|
||||||
|
result.Content = result.ADT.nodes[0].nodes;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
CSV_Columns2 parse_csv_two_columns(AllocatorInfo allocator, char const* path) {
|
||||||
|
FileContents content = file_read_contents( allocator, file_zero_terminate, path );
|
||||||
|
Arena csv_arena = arena_init_from_memory(content.data, content.size);
|
||||||
|
|
||||||
|
CSV_Columns2 result;
|
||||||
|
csv_parse( & result.ADT, rcast(char*, content.data), allocator, false );
|
||||||
|
result.Col_1 = result.ADT.nodes[0].nodes;
|
||||||
|
result.Col_2 = result.ADT.nodes[1].nodes;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma endregion Scanner
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "helpers/push_ignores.inline.hpp"
|
||||||
|
# include "components/header_start.hpp"
|
||||||
|
# include "components/types.hpp"
|
||||||
|
# include "components/gen/ecodetypes.hpp"
|
||||||
|
# include "components/gen/eoperator.hpp"
|
||||||
|
# include "components/gen/especifier.hpp"
|
||||||
|
# include "components/ast.hpp"
|
||||||
|
# include "components/code_types.hpp"
|
||||||
|
# include "components/ast_types.hpp"
|
||||||
|
# include "components/interface.hpp"
|
||||||
|
# include "components/inlines.hpp"
|
||||||
|
# include "components/gen/ast_inlines.hpp"
|
||||||
|
# include "components/header_end.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Scanner
|
||||||
|
|
||||||
|
// This is a simple file reader that reads the entire file into memory.
|
||||||
|
// It has an extra option to skip the first few lines for undesired includes.
|
||||||
|
// This is done so that includes can be kept in dependency and component files so that intellisense works.
|
||||||
|
GEN_API Code scan_file( char const* path );
|
||||||
|
|
||||||
|
GEN_API CodeBody parse_file( const char* path );
|
||||||
|
|
||||||
|
// The follow is basic support for light csv parsing (use it as an example)
|
||||||
|
// Make something robust if its more serious.
|
||||||
|
|
||||||
|
typedef struct CSV_Column CSV_Column;
|
||||||
|
struct CSV_Column {
|
||||||
|
CSV_Object ADT;
|
||||||
|
Array(ADT_Node) Content;
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef struct CSV_Columns2 CSV_Columns2;
|
||||||
|
struct CSV_Columns2 {
|
||||||
|
CSV_Object ADT;
|
||||||
|
Array(ADT_Node) Col_1;
|
||||||
|
Array(ADT_Node) Col_2;
|
||||||
|
};
|
||||||
|
|
||||||
|
GEN_API CSV_Column parse_csv_one_column (AllocatorInfo allocator, char const* path);
|
||||||
|
GEN_API CSV_Columns2 parse_csv_two_columns(AllocatorInfo allocator, char const* path);
|
||||||
|
|
||||||
|
#pragma endregion Scanner
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
|
||||||
|
#define GEN_ENFORCE_STRONG_CODE_TYPES
|
||||||
|
#define GEN_C_LIKE_CPP 1
|
||||||
|
#include "gen.cpp"
|
||||||
|
#include "helpers/push_ignores.inline.hpp"
|
||||||
|
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
GEN_NS_BEGIN
|
||||||
|
#include "helpers/base_codegen.hpp"
|
||||||
|
#include "helpers/misc.hpp"
|
||||||
|
GEN_NS_END
|
||||||
|
|
||||||
|
using namespace gen;
|
||||||
|
|
||||||
|
constexpr char const* path_format_style = "../scripts/.clang-format";
|
||||||
|
constexpr char const* scratch_file = "build/scratch.hpp";
|
||||||
|
|
||||||
|
Code format( Code code ) {
|
||||||
|
return code_refactor_and_format(code, scratch_file, nullptr, path_format_style );
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr char const* generation_notice =
|
||||||
|
"// This file was generated automatially by gencpp's bootstrap.cpp "
|
||||||
|
"(See: https://github.com/Ed94/gencpp)\n\n";
|
||||||
|
|
||||||
|
int gen_main()
|
||||||
|
{
|
||||||
|
gen::Context ctx {};
|
||||||
|
gen::init( & ctx);
|
||||||
|
|
||||||
|
CodeBody gen_component_header = def_global_body( args(
|
||||||
|
def_preprocess_cond( PreprocessCond_IfDef, txt("INTELLISENSE_DIRECTIVES") ),
|
||||||
|
pragma_once,
|
||||||
|
def_include(txt("components/types.hpp")),
|
||||||
|
preprocess_endif,
|
||||||
|
fmt_newline,
|
||||||
|
untyped_str( to_str_from_c_str(generation_notice) )
|
||||||
|
));
|
||||||
|
|
||||||
|
CodeBody ecode = gen_ecode ( "enums/ECodeTypes.csv" );
|
||||||
|
CodeBody eoperator = gen_eoperator ( "enums/EOperator.csv" );
|
||||||
|
CodeBody especifier = gen_especifier( "enums/ESpecifier.csv" );
|
||||||
|
CodeBody etoktype = gen_etoktype ( "enums/ETokType.csv", "enums/AttributeTokens.csv" );
|
||||||
|
CodeBody ast_inlines = gen_ast_inlines();
|
||||||
|
|
||||||
|
Builder header_ecode = builder_open( "components/gen/ecodetypes.hpp" );
|
||||||
|
builder_print( & header_ecode, gen_component_header );
|
||||||
|
builder_print( & header_ecode, format(ecode) );
|
||||||
|
builder_write( & header_ecode);
|
||||||
|
|
||||||
|
Builder header_eoperator = builder_open( "components/gen/eoperator.hpp" );
|
||||||
|
builder_print( & header_eoperator, gen_component_header );
|
||||||
|
builder_print( & header_eoperator, format(eoperator) );
|
||||||
|
builder_write( & header_eoperator );
|
||||||
|
|
||||||
|
Builder header_especifier = builder_open( "components/gen/especifier.hpp" );
|
||||||
|
builder_print( & header_especifier, gen_component_header );
|
||||||
|
builder_print( & header_especifier, format(especifier) );
|
||||||
|
builder_write( & header_especifier);
|
||||||
|
|
||||||
|
Builder header_etoktype = builder_open( "components/gen/etoktype.hpp" );
|
||||||
|
builder_print( & header_etoktype, gen_component_header );
|
||||||
|
builder_print( & header_etoktype, format(etoktype) );
|
||||||
|
builder_write( & header_etoktype);
|
||||||
|
|
||||||
|
Builder header_ast_inlines = builder_open( "components/gen/ast_inlines.hpp" );
|
||||||
|
builder_print( & header_ast_inlines, gen_component_header );
|
||||||
|
builder_print( & header_ast_inlines, format(ast_inlines) );
|
||||||
|
builder_write( & header_ast_inlines);
|
||||||
|
|
||||||
|
gen::deinit(& ctx);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,457 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
#pragma once
|
||||||
|
#include "parser_types.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
______ ______ ________ __ __ ______ __
|
||||||
|
/ \ / \| \ | \ | \ / \ | \
|
||||||
|
| ▓▓▓▓▓▓\ ▓▓▓▓▓▓\\▓▓▓▓▓▓▓▓ | ▓▓\ | ▓▓ | ▓▓▓▓▓▓\ ______ ____| ▓▓ ______
|
||||||
|
| ▓▓__| ▓▓ ▓▓___\▓▓ | ▓▓ | ▓▓▓\| ▓▓ | ▓▓ \▓▓/ \ / ▓▓/ \
|
||||||
|
| ▓▓ ▓▓\▓▓ \ | ▓▓ | ▓▓▓▓\ ▓▓ | ▓▓ | ▓▓▓▓▓▓\ ▓▓▓▓▓▓▓ ▓▓▓▓▓▓\
|
||||||
|
| ▓▓▓▓▓▓▓▓_\▓▓▓▓▓▓\ | ▓▓ | ▓▓\▓▓ ▓▓ | ▓▓ __| ▓▓ | ▓▓ ▓▓ | ▓▓ ▓▓ ▓▓
|
||||||
|
| ▓▓ | ▓▓ \__| ▓▓ | ▓▓ | ▓▓ \▓▓▓▓ | ▓▓__/ \ ▓▓__/ ▓▓ ▓▓__| ▓▓ ▓▓▓▓▓▓▓▓
|
||||||
|
| ▓▓ | ▓▓\▓▓ ▓▓ | ▓▓ | ▓▓ \▓▓▓ \▓▓ ▓▓\▓▓ ▓▓\▓▓ ▓▓\▓▓ \
|
||||||
|
\▓▓ \▓▓ \▓▓▓▓▓▓ \▓▓ \▓▓ \▓▓ \▓▓▓▓▓▓ \▓▓▓▓▓▓ \▓▓▓▓▓▓▓ \▓▓▓▓▓▓▓
|
||||||
|
*/
|
||||||
|
|
||||||
|
struct AST;
|
||||||
|
struct AST_Body;
|
||||||
|
struct AST_Attributes;
|
||||||
|
struct AST_Comment;
|
||||||
|
struct AST_Constructor;
|
||||||
|
// struct AST_BaseClass;
|
||||||
|
struct AST_Class;
|
||||||
|
struct AST_Define;
|
||||||
|
struct AST_DefineParams;
|
||||||
|
struct AST_Destructor;
|
||||||
|
struct AST_Enum;
|
||||||
|
struct AST_Exec;
|
||||||
|
struct AST_Extern;
|
||||||
|
struct AST_Include;
|
||||||
|
struct AST_Friend;
|
||||||
|
struct AST_Fn;
|
||||||
|
struct AST_Module;
|
||||||
|
struct AST_NS;
|
||||||
|
struct AST_Operator;
|
||||||
|
struct AST_OpCast;
|
||||||
|
struct AST_Params;
|
||||||
|
struct AST_Pragma;
|
||||||
|
struct AST_PreprocessCond;
|
||||||
|
struct AST_Specifiers;
|
||||||
|
|
||||||
|
#ifdef GEN_EXECUTION_EXPRESSION_SUPPORT
|
||||||
|
struct AST_Expr;
|
||||||
|
struct AST_Expr_Assign;
|
||||||
|
struct AST_Expr_Alignof;
|
||||||
|
struct AST_Expr_Binary;
|
||||||
|
struct AST_Expr_CStyleCast;
|
||||||
|
struct AST_Expr_FunctionalCast;
|
||||||
|
struct AST_Expr_CppCast;
|
||||||
|
struct AST_Expr_ProcCall;
|
||||||
|
struct AST_Expr_Decltype;
|
||||||
|
struct AST_Expr_Comma; // TODO(Ed) : This is a binary op not sure if it needs its own AST...
|
||||||
|
struct AST_Expr_AMS; // Access Member Symbol
|
||||||
|
struct AST_Expr_Sizeof;
|
||||||
|
struct AST_Expr_Subscript;
|
||||||
|
struct AST_Expr_Ternary;
|
||||||
|
struct AST_Expr_UnaryPrefix;
|
||||||
|
struct AST_Expr_UnaryPostfix;
|
||||||
|
struct AST_Expr_Element;
|
||||||
|
|
||||||
|
struct AST_Stmt;
|
||||||
|
struct AST_Stmt_Break;
|
||||||
|
struct AST_Stmt_Case;
|
||||||
|
struct AST_Stmt_Continue;
|
||||||
|
struct AST_Stmt_Decl;
|
||||||
|
struct AST_Stmt_Do;
|
||||||
|
struct AST_Stmt_Expr; // TODO(Ed) : Is this distinction needed? (Should it be a flag instead?)
|
||||||
|
struct AST_Stmt_Else;
|
||||||
|
struct AST_Stmt_If;
|
||||||
|
struct AST_Stmt_For;
|
||||||
|
struct AST_Stmt_Goto;
|
||||||
|
struct AST_Stmt_Label;
|
||||||
|
struct AST_Stmt_Switch;
|
||||||
|
struct AST_Stmt_While;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
struct AST_Struct;
|
||||||
|
struct AST_Template;
|
||||||
|
struct AST_Typename;
|
||||||
|
struct AST_Typedef;
|
||||||
|
struct AST_Union;
|
||||||
|
struct AST_Using;
|
||||||
|
struct AST_Var;
|
||||||
|
|
||||||
|
#if GEN_COMPILER_C
|
||||||
|
typedef AST* Code;
|
||||||
|
#else
|
||||||
|
struct Code;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_C
|
||||||
|
typedef AST_Body* CodeBody;
|
||||||
|
typedef AST_Attributes* CodeAttributes;
|
||||||
|
typedef AST_Comment* CodeComment;
|
||||||
|
typedef AST_Class* CodeClass;
|
||||||
|
typedef AST_Constructor* CodeConstructor;
|
||||||
|
typedef AST_Define* CodeDefine;
|
||||||
|
typedef AST_DefineParams* CodeDefineParams;
|
||||||
|
typedef AST_Destructor* CodeDestructor;
|
||||||
|
typedef AST_Enum* CodeEnum;
|
||||||
|
typedef AST_Exec* CodeExec;
|
||||||
|
typedef AST_Extern* CodeExtern;
|
||||||
|
typedef AST_Include* CodeInclude;
|
||||||
|
typedef AST_Friend* CodeFriend;
|
||||||
|
typedef AST_Fn* CodeFn;
|
||||||
|
typedef AST_Module* CodeModule;
|
||||||
|
typedef AST_NS* CodeNS;
|
||||||
|
typedef AST_Operator* CodeOperator;
|
||||||
|
typedef AST_OpCast* CodeOpCast;
|
||||||
|
typedef AST_Params* CodeParams;
|
||||||
|
typedef AST_PreprocessCond* CodePreprocessCond;
|
||||||
|
typedef AST_Pragma* CodePragma;
|
||||||
|
typedef AST_Specifiers* CodeSpecifiers;
|
||||||
|
#else
|
||||||
|
struct CodeBody;
|
||||||
|
struct CodeAttributes;
|
||||||
|
struct CodeComment;
|
||||||
|
struct CodeClass;
|
||||||
|
struct CodeConstructor;
|
||||||
|
struct CodeDefine;
|
||||||
|
struct CodeDefineParams;
|
||||||
|
struct CodeDestructor;
|
||||||
|
struct CodeEnum;
|
||||||
|
struct CodeExec;
|
||||||
|
struct CodeExtern;
|
||||||
|
struct CodeInclude;
|
||||||
|
struct CodeFriend;
|
||||||
|
struct CodeFn;
|
||||||
|
struct CodeModule;
|
||||||
|
struct CodeNS;
|
||||||
|
struct CodeOperator;
|
||||||
|
struct CodeOpCast;
|
||||||
|
struct CodeParams;
|
||||||
|
struct CodePreprocessCond;
|
||||||
|
struct CodePragma;
|
||||||
|
struct CodeSpecifiers;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GEN_EXECUTION_EXPRESSION_SUPPORT
|
||||||
|
|
||||||
|
#if GEN_COMPILER_C
|
||||||
|
typedef AST_Expr* CodeExpr;
|
||||||
|
typedef AST_Expr_Assign* CodeExpr_Assign;
|
||||||
|
typedef AST_Expr_Alignof* CodeExpr_Alignof;
|
||||||
|
typedef AST_Expr_Binary* CodeExpr_Binary;
|
||||||
|
typedef AST_Expr_CStyleCast* CodeExpr_CStyleCast;
|
||||||
|
typedef AST_Expr_FunctionalCast* CodeExpr_FunctionalCast;
|
||||||
|
typedef AST_Expr_CppCast* CodeExpr_CppCast;
|
||||||
|
typedef AST_Expr_Element* CodeExpr_Element;
|
||||||
|
typedef AST_Expr_ProcCall* CodeExpr_ProcCall;
|
||||||
|
typedef AST_Expr_Decltype* CodeExpr_Decltype;
|
||||||
|
typedef AST_Expr_Comma* CodeExpr_Comma;
|
||||||
|
typedef AST_Expr_AMS* CodeExpr_AMS; // Access Member Symbol
|
||||||
|
typedef AST_Expr_Sizeof* CodeExpr_Sizeof;
|
||||||
|
typedef AST_Expr_Subscript* CodeExpr_Subscript;
|
||||||
|
typedef AST_Expr_Ternary* CodeExpr_Ternary;
|
||||||
|
typedef AST_Expr_UnaryPrefix* CodeExpr_UnaryPrefix;
|
||||||
|
typedef AST_Expr_UnaryPostfix* CodeExpr_UnaryPostfix;
|
||||||
|
#else
|
||||||
|
struct CodeExpr;
|
||||||
|
struct CodeExpr_Assign;
|
||||||
|
struct CodeExpr_Alignof;
|
||||||
|
struct CodeExpr_Binary;
|
||||||
|
struct CodeExpr_CStyleCast;
|
||||||
|
struct CodeExpr_FunctionalCast;
|
||||||
|
struct CodeExpr_CppCast;
|
||||||
|
struct CodeExpr_Element;
|
||||||
|
struct CodeExpr_ProcCall;
|
||||||
|
struct CodeExpr_Decltype;
|
||||||
|
struct CodeExpr_Comma;
|
||||||
|
struct CodeExpr_AMS; // Access Member Symbol
|
||||||
|
struct CodeExpr_Sizeof;
|
||||||
|
struct CodeExpr_Subscript;
|
||||||
|
struct CodeExpr_Ternary;
|
||||||
|
struct CodeExpr_UnaryPrefix;
|
||||||
|
struct CodeExpr_UnaryPostfix;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_C
|
||||||
|
typedef AST_Stmt* CodeStmt;
|
||||||
|
typedef AST_Stmt_Break* CodeStmt_Break;
|
||||||
|
typedef AST_Stmt_Case* CodeStmt_Case;
|
||||||
|
typedef AST_Stmt_Continue* CodeStmt_Continue;
|
||||||
|
typedef AST_Stmt_Decl* CodeStmt_Decl;
|
||||||
|
typedef AST_Stmt_Do* CodeStmt_Do;
|
||||||
|
typedef AST_Stmt_Expr* CodeStmt_Expr;
|
||||||
|
typedef AST_Stmt_Else* CodeStmt_Else;
|
||||||
|
typedef AST_Stmt_If* CodeStmt_If;
|
||||||
|
typedef AST_Stmt_For* CodeStmt_For;
|
||||||
|
typedef AST_Stmt_Goto* CodeStmt_Goto;
|
||||||
|
typedef AST_Stmt_Label* CodeStmt_Label;
|
||||||
|
typedef AST_Stmt_Lambda* CodeStmt_Lambda;
|
||||||
|
typedef AST_Stmt_Switch* CodeStmt_Switch;
|
||||||
|
typedef AST_Stmt_While* CodeStmt_While;
|
||||||
|
#else
|
||||||
|
struct CodeStmt;
|
||||||
|
struct CodeStmt_Break;
|
||||||
|
struct CodeStmt_Case;
|
||||||
|
struct CodeStmt_Continue;
|
||||||
|
struct CodeStmt_Decl;
|
||||||
|
struct CodeStmt_Do;
|
||||||
|
struct CodeStmt_Expr;
|
||||||
|
struct CodeStmt_Else;
|
||||||
|
struct CodeStmt_If;
|
||||||
|
struct CodeStmt_For;
|
||||||
|
struct CodeStmt_Goto;
|
||||||
|
struct CodeStmt_Label;
|
||||||
|
struct CodeStmt_Lambda;
|
||||||
|
struct CodeStmt_Switch;
|
||||||
|
struct CodeStmt_While;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// GEN_EXECUTION_EXPRESSION_SUPPORT
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_C
|
||||||
|
typedef AST_Struct* CodeStruct;
|
||||||
|
typedef AST_Template* CodeTemplate;
|
||||||
|
typedef AST_Typename* CodeTypename;
|
||||||
|
typedef AST_Typedef* CodeTypedef;
|
||||||
|
typedef AST_Union* CodeUnion;
|
||||||
|
typedef AST_Using* CodeUsing;
|
||||||
|
typedef AST_Var* CodeVar;
|
||||||
|
#else
|
||||||
|
struct CodeStruct;
|
||||||
|
struct CodeTemplate;
|
||||||
|
struct CodeTypename;
|
||||||
|
struct CodeTypedef;
|
||||||
|
struct CodeUnion;
|
||||||
|
struct CodeUsing;
|
||||||
|
struct CodeVar;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
template< class Type> forceinline Type tmpl_cast( Code self ) { return * rcast( Type*, & self ); }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Code C-Interface
|
||||||
|
|
||||||
|
void code_append (Code code, Code other );
|
||||||
|
GEN_API Str code_debug_str (Code code);
|
||||||
|
GEN_API Code code_duplicate (Code code);
|
||||||
|
Code* code_entry (Code code, u32 idx );
|
||||||
|
bool code_has_entries (Code code);
|
||||||
|
bool code_is_body (Code code);
|
||||||
|
GEN_API bool code_is_equal (Code code, Code other);
|
||||||
|
bool code_is_valid (Code code);
|
||||||
|
void code_set_global (Code code);
|
||||||
|
GEN_API StrBuilder code_to_strbuilder (Code self );
|
||||||
|
GEN_API void code_to_strbuilder_ref(Code self, StrBuilder* result );
|
||||||
|
Str code_type_str (Code self );
|
||||||
|
GEN_API bool code_validate_body (Code self );
|
||||||
|
|
||||||
|
#pragma endregion Code C-Interface
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
/*
|
||||||
|
AST* wrapper
|
||||||
|
- Not constantly have to append the '*' as this is written often..
|
||||||
|
- Allows for implicit conversion to any of the ASTs (raw or filtered).
|
||||||
|
*/
|
||||||
|
struct Code
|
||||||
|
{
|
||||||
|
AST* ast;
|
||||||
|
|
||||||
|
# define Using_Code( Typename ) \
|
||||||
|
forceinline Str debug_str() { return code_debug_str(* this); } \
|
||||||
|
forceinline Code duplicate() { return code_duplicate(* this); } \
|
||||||
|
forceinline bool is_equal( Code other ) { return code_is_equal(* this, other); } \
|
||||||
|
forceinline bool is_body() { return code_is_body(* this); } \
|
||||||
|
forceinline bool is_valid() { return code_is_valid(* this); } \
|
||||||
|
forceinline void set_global() { return code_set_global(* this); }
|
||||||
|
|
||||||
|
# define Using_CodeOps( Typename ) \
|
||||||
|
forceinline Typename& operator = ( Code other ); \
|
||||||
|
forceinline bool operator ==( Code other ) { return (AST*)ast == other.ast; } \
|
||||||
|
forceinline bool operator !=( Code other ) { return (AST*)ast != other.ast; } \
|
||||||
|
forceinline bool operator ==(std::nullptr_t) const { return ast == nullptr; } \
|
||||||
|
forceinline bool operator !=(std::nullptr_t) const { return ast != nullptr; } \
|
||||||
|
operator bool();
|
||||||
|
|
||||||
|
#if ! GEN_C_LIKE_CPP
|
||||||
|
Using_Code( Code );
|
||||||
|
forceinline void append(Code other) { return code_append(* this, other); }
|
||||||
|
forceinline Code* entry(u32 idx) { return code_entry(* this, idx); }
|
||||||
|
forceinline bool has_entries() { return code_has_entries(* this); }
|
||||||
|
forceinline StrBuilder to_strbuilder() { return code_to_strbuilder(* this); }
|
||||||
|
forceinline void to_strbuilder(StrBuilder& result) { return code_to_strbuilder_ref(* this, & result); }
|
||||||
|
forceinline Str type_str() { return code_type_str(* this); }
|
||||||
|
forceinline bool validate_body() { return code_validate_body(*this); }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
Using_CodeOps( Code );
|
||||||
|
forceinline Code operator *() { return * this; } // Required to support for-range iteration.
|
||||||
|
forceinline AST* operator ->() { return ast; }
|
||||||
|
|
||||||
|
Code& operator ++();
|
||||||
|
|
||||||
|
#ifdef GEN_ENFORCE_STRONG_CODE_TYPES
|
||||||
|
# define operator explicit operator
|
||||||
|
#endif
|
||||||
|
operator CodeBody() const;
|
||||||
|
operator CodeAttributes() const;
|
||||||
|
// operator CodeBaseClass() const;
|
||||||
|
operator CodeComment() const;
|
||||||
|
operator CodeClass() const;
|
||||||
|
operator CodeConstructor() const;
|
||||||
|
operator CodeDefine() const;
|
||||||
|
operator CodeDefineParams() const;
|
||||||
|
operator CodeDestructor() const;
|
||||||
|
operator CodeExec() const;
|
||||||
|
operator CodeEnum() const;
|
||||||
|
operator CodeExtern() const;
|
||||||
|
operator CodeInclude() const;
|
||||||
|
operator CodeFriend() const;
|
||||||
|
operator CodeFn() const;
|
||||||
|
operator CodeModule() const;
|
||||||
|
operator CodeNS() const;
|
||||||
|
operator CodeOperator() const;
|
||||||
|
operator CodeOpCast() const;
|
||||||
|
operator CodeParams() const;
|
||||||
|
operator CodePragma() const;
|
||||||
|
operator CodePreprocessCond() const;
|
||||||
|
operator CodeSpecifiers() const;
|
||||||
|
operator CodeStruct() const;
|
||||||
|
operator CodeTemplate() const;
|
||||||
|
operator CodeTypename() const;
|
||||||
|
operator CodeTypedef() const;
|
||||||
|
operator CodeUnion() const;
|
||||||
|
operator CodeUsing() const;
|
||||||
|
operator CodeVar() const;
|
||||||
|
#undef operator
|
||||||
|
};
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Statics
|
||||||
|
// Used to identify ASTs that should always be duplicated. (Global constant ASTs)
|
||||||
|
GEN_API extern Code Code_Global;
|
||||||
|
|
||||||
|
// Used to identify invalid generated code.
|
||||||
|
GEN_API extern Code Code_Invalid;
|
||||||
|
#pragma endregion Statics
|
||||||
|
|
||||||
|
struct Code_POD
|
||||||
|
{
|
||||||
|
AST* ast;
|
||||||
|
};
|
||||||
|
static_assert( sizeof(Code) == sizeof(Code_POD), "ERROR: Code is not POD" );
|
||||||
|
|
||||||
|
// Desired width of the AST data structure.
|
||||||
|
constexpr int const AST_POD_Size = 128;
|
||||||
|
|
||||||
|
constexpr static
|
||||||
|
int AST_ArrSpecs_Cap =
|
||||||
|
(
|
||||||
|
AST_POD_Size
|
||||||
|
- sizeof(Code)
|
||||||
|
- sizeof(StrCached)
|
||||||
|
- sizeof(Code) * 2
|
||||||
|
- sizeof(Token*)
|
||||||
|
- sizeof(Code)
|
||||||
|
- sizeof(CodeType)
|
||||||
|
- sizeof(ModuleFlag)
|
||||||
|
- sizeof(u32)
|
||||||
|
)
|
||||||
|
/ sizeof(Specifier) - 1;
|
||||||
|
|
||||||
|
/*
|
||||||
|
Simple AST POD with functionality to seralize into C++ syntax.
|
||||||
|
TODO(Ed): Eventually haven't a transparent AST like this will longer be viable once statements & expressions are in (most likely....)
|
||||||
|
*/
|
||||||
|
struct AST
|
||||||
|
{
|
||||||
|
union {
|
||||||
|
struct
|
||||||
|
{
|
||||||
|
Code InlineCmt; // Class, Constructor, Destructor, Enum, Friend, Functon, Operator, OpCast, Struct, Typedef, Using, Variable
|
||||||
|
Code Attributes; // Class, Enum, Function, Struct, Typedef, Union, Using, Variable // TODO(Ed): Parameters can have attributes
|
||||||
|
Code Specs; // Class, Destructor, Function, Operator, Struct, Typename, Variable
|
||||||
|
union {
|
||||||
|
Code InitializerList; // Constructor
|
||||||
|
Code ParentType; // Class, Struct, ParentType->Next has a possible list of interfaces.
|
||||||
|
Code ReturnType; // Function, Operator, Typename
|
||||||
|
Code UnderlyingType; // Enum, Typedef
|
||||||
|
Code ValueType; // Parameter, Variable
|
||||||
|
};
|
||||||
|
union {
|
||||||
|
Code Macro; // Parameter
|
||||||
|
Code BitfieldSize; // Variable (Class/Struct Data Member)
|
||||||
|
Code Params; // Constructor, Define, Function, Operator, Template, Typename
|
||||||
|
Code UnderlyingTypeMacro; // Enum
|
||||||
|
};
|
||||||
|
union {
|
||||||
|
Code ArrExpr; // Typename
|
||||||
|
Code Body; // Class, Constructor, Define, Destructor, Enum, Friend, Function, Namespace, Struct, Union
|
||||||
|
Code Declaration; // Friend, Template
|
||||||
|
Code Value; // Parameter, Variable
|
||||||
|
};
|
||||||
|
union {
|
||||||
|
Code NextVar; // Variable
|
||||||
|
Code SuffixSpecs; // Typename, Function (Thanks Unreal)
|
||||||
|
Code PostNameMacro; // Only used with parameters for specifically UE_REQUIRES (Thanks Unreal)
|
||||||
|
};
|
||||||
|
};
|
||||||
|
StrCached Content; // Attributes, Comment, Execution, Include
|
||||||
|
TokenSlice ContentToks; // TODO(Ed): Use a token slice for content
|
||||||
|
struct {
|
||||||
|
Specifier ArrSpecs[AST_ArrSpecs_Cap]; // Specifiers
|
||||||
|
Code NextSpecs; // Specifiers; If ArrSpecs is full, then NextSpecs is used.
|
||||||
|
};
|
||||||
|
};
|
||||||
|
StrCached Name;
|
||||||
|
union {
|
||||||
|
Code Prev;
|
||||||
|
Code Front;
|
||||||
|
Code Last;
|
||||||
|
};
|
||||||
|
union {
|
||||||
|
Code Next;
|
||||||
|
Code Back;
|
||||||
|
};
|
||||||
|
Token* Token; // Reference to starting token, only available if it was derived from parsing. // TODO(Ed): Change this to a token slice.
|
||||||
|
Code Parent;
|
||||||
|
CodeType Type;
|
||||||
|
// CodeFlag CodeFlags;
|
||||||
|
ModuleFlag ModuleFlags;
|
||||||
|
union {
|
||||||
|
b32 IsFunction; // Used by typedef to not serialize the name field.
|
||||||
|
struct {
|
||||||
|
b16 IsParamPack; // Used by typename to know if type should be considered a parameter pack.
|
||||||
|
ETypenameTag TypeTag; // Used by typename to keep track of explicitly declared tags for the identifier (enum, struct, union)
|
||||||
|
};
|
||||||
|
Operator Op;
|
||||||
|
AccessSpec ParentAccess;
|
||||||
|
s32 NumEntries;
|
||||||
|
s32 VarParenthesizedInit; // Used by variables to know that initialization is using a constructor expression instead of an assignment expression.
|
||||||
|
};
|
||||||
|
};
|
||||||
|
static_assert( sizeof(AST) == AST_POD_Size, "ERROR: AST is not size of AST_POD_Size" );
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
// Uses an implicitly overloaded cast from the AST to the desired code type.
|
||||||
|
// Necessary if the user wants GEN_ENFORCE_STRONG_CODE_TYPES
|
||||||
|
struct InvalidCode_ImplictCaster;
|
||||||
|
#define InvalidCode (InvalidCode_ImplictCaster{})
|
||||||
|
#else
|
||||||
|
#define InvalidCode (void*){ (void*)Code_Invalid }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
struct NullCode_ImplicitCaster;
|
||||||
|
// Used when the its desired when omission is allowed in a definition.
|
||||||
|
#define NullCode (NullCode_ImplicitCaster{})
|
||||||
|
#else
|
||||||
|
#define NullCode nullptr
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
// These macros are used in the swtich cases within ast.cpp, inteface.upfront.cpp, parser.cpp
|
||||||
|
|
||||||
|
# define GEN_AST_BODY_CLASS_UNALLOWED_TYPES_CASES \
|
||||||
|
case CT_PlatformAttributes: \
|
||||||
|
case CT_Class_Body: \
|
||||||
|
case CT_Enum_Body: \
|
||||||
|
case CT_Extern_Linkage: \
|
||||||
|
case CT_Function_Body: \
|
||||||
|
case CT_Function_Fwd: \
|
||||||
|
case CT_Global_Body: \
|
||||||
|
case CT_Namespace: \
|
||||||
|
case CT_Namespace_Body: \
|
||||||
|
case CT_Operator: \
|
||||||
|
case CT_Operator_Fwd: \
|
||||||
|
case CT_Parameters: \
|
||||||
|
case CT_Specifiers: \
|
||||||
|
case CT_Struct_Body: \
|
||||||
|
case CT_Typename
|
||||||
|
# define GEN_AST_BODY_STRUCT_UNALLOWED_TYPES_CASES GEN_AST_BODY_CLASS_UNALLOWED_TYPES_CASES
|
||||||
|
|
||||||
|
# define GEN_AST_BODY_FUNCTION_UNALLOWED_TYPES_CASES \
|
||||||
|
case CT_Access_Public: \
|
||||||
|
case CT_Access_Protected: \
|
||||||
|
case CT_Access_Private: \
|
||||||
|
case CT_PlatformAttributes: \
|
||||||
|
case CT_Class_Body: \
|
||||||
|
case CT_Enum_Body: \
|
||||||
|
case CT_Extern_Linkage: \
|
||||||
|
case CT_Friend: \
|
||||||
|
case CT_Function_Body: \
|
||||||
|
case CT_Function_Fwd: \
|
||||||
|
case CT_Global_Body: \
|
||||||
|
case CT_Namespace: \
|
||||||
|
case CT_Namespace_Body: \
|
||||||
|
case CT_Operator: \
|
||||||
|
case CT_Operator_Fwd: \
|
||||||
|
case CT_Operator_Member: \
|
||||||
|
case CT_Operator_Member_Fwd: \
|
||||||
|
case CT_Parameters: \
|
||||||
|
case CT_Specifiers: \
|
||||||
|
case CT_Struct_Body: \
|
||||||
|
case CT_Typename
|
||||||
|
|
||||||
|
# define GEN_AST_BODY_GLOBAL_UNALLOWED_TYPES_CASES \
|
||||||
|
case CT_Access_Public: \
|
||||||
|
case CT_Access_Protected: \
|
||||||
|
case CT_Access_Private: \
|
||||||
|
case CT_PlatformAttributes: \
|
||||||
|
case CT_Class_Body: \
|
||||||
|
case CT_Enum_Body: \
|
||||||
|
case CT_Execution: \
|
||||||
|
case CT_Friend: \
|
||||||
|
case CT_Function_Body: \
|
||||||
|
case CT_Namespace_Body: \
|
||||||
|
case CT_Operator_Member: \
|
||||||
|
case CT_Operator_Member_Fwd: \
|
||||||
|
case CT_Parameters: \
|
||||||
|
case CT_Specifiers: \
|
||||||
|
case CT_Struct_Body: \
|
||||||
|
case CT_Typename
|
||||||
|
# define GEN_AST_BODY_EXPORT_UNALLOWED_TYPES_CASES GEN_AST_BODY_GLOBAL_UNALLOWED_TYPES_CASES
|
||||||
|
# define GEN_AST_BODY_EXTERN_LINKAGE_UNALLOWED_TYPES_CASES GEN_AST_BODY_GLOBAL_UNALLOWED_TYPES_CASES
|
||||||
|
|
||||||
|
# define GEN_AST_BODY_NAMESPACE_UNALLOWED_TYPES_CASES \
|
||||||
|
case CT_Access_Public: \
|
||||||
|
case CT_Access_Protected: \
|
||||||
|
case CT_Access_Private: \
|
||||||
|
case CT_PlatformAttributes: \
|
||||||
|
case CT_Class_Body: \
|
||||||
|
case CT_Enum_Body: \
|
||||||
|
case CT_Execution: \
|
||||||
|
case CT_Friend: \
|
||||||
|
case CT_Function_Body: \
|
||||||
|
case CT_Namespace_Body: \
|
||||||
|
case CT_Operator_Member: \
|
||||||
|
case CT_Operator_Member_Fwd: \
|
||||||
|
case CT_Parameters: \
|
||||||
|
case CT_Specifiers: \
|
||||||
|
case CT_Struct_Body: \
|
||||||
|
case CT_Typename
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,85 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "interface.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Constants
|
||||||
|
// Predefined typename codes. Are set to readonly and are setup during gen::init()
|
||||||
|
|
||||||
|
GEN_API extern Macro enum_underlying_macro;
|
||||||
|
|
||||||
|
GEN_API extern Code access_public;
|
||||||
|
GEN_API extern Code access_protected;
|
||||||
|
GEN_API extern Code access_private;
|
||||||
|
|
||||||
|
GEN_API extern CodeAttributes attrib_api_export;
|
||||||
|
GEN_API extern CodeAttributes attrib_api_import;
|
||||||
|
|
||||||
|
GEN_API extern Code module_global_fragment;
|
||||||
|
GEN_API extern Code module_private_fragment;
|
||||||
|
|
||||||
|
GEN_API extern Code fmt_newline;
|
||||||
|
|
||||||
|
GEN_API extern CodePragma pragma_once;
|
||||||
|
|
||||||
|
GEN_API extern CodeParams param_varadic;
|
||||||
|
|
||||||
|
GEN_API extern CodePreprocessCond preprocess_else;
|
||||||
|
GEN_API extern CodePreprocessCond preprocess_endif;
|
||||||
|
|
||||||
|
GEN_API extern CodeSpecifiers spec_const;
|
||||||
|
GEN_API extern CodeSpecifiers spec_consteval;
|
||||||
|
GEN_API extern CodeSpecifiers spec_constexpr;
|
||||||
|
GEN_API extern CodeSpecifiers spec_constinit;
|
||||||
|
GEN_API extern CodeSpecifiers spec_extern_linkage;
|
||||||
|
GEN_API extern CodeSpecifiers spec_final;
|
||||||
|
GEN_API extern CodeSpecifiers spec_forceinline;
|
||||||
|
GEN_API extern CodeSpecifiers spec_global;
|
||||||
|
GEN_API extern CodeSpecifiers spec_inline;
|
||||||
|
GEN_API extern CodeSpecifiers spec_internal_linkage;
|
||||||
|
GEN_API extern CodeSpecifiers spec_local_persist;
|
||||||
|
GEN_API extern CodeSpecifiers spec_mutable;
|
||||||
|
GEN_API extern CodeSpecifiers spec_neverinline;
|
||||||
|
GEN_API extern CodeSpecifiers spec_noexcept;
|
||||||
|
GEN_API extern CodeSpecifiers spec_override;
|
||||||
|
GEN_API extern CodeSpecifiers spec_ptr;
|
||||||
|
GEN_API extern CodeSpecifiers spec_pure;
|
||||||
|
GEN_API extern CodeSpecifiers spec_ref;
|
||||||
|
GEN_API extern CodeSpecifiers spec_register;
|
||||||
|
GEN_API extern CodeSpecifiers spec_rvalue;
|
||||||
|
GEN_API extern CodeSpecifiers spec_static_member;
|
||||||
|
GEN_API extern CodeSpecifiers spec_thread_local;
|
||||||
|
GEN_API extern CodeSpecifiers spec_virtual;
|
||||||
|
GEN_API extern CodeSpecifiers spec_volatile;
|
||||||
|
|
||||||
|
GEN_API extern CodeTypename t_empty; // Used with varaidc parameters. (Exposing just in case its useful for another circumstance)
|
||||||
|
GEN_API extern CodeTypename t_auto;
|
||||||
|
GEN_API extern CodeTypename t_void;
|
||||||
|
GEN_API extern CodeTypename t_int;
|
||||||
|
GEN_API extern CodeTypename t_bool;
|
||||||
|
GEN_API extern CodeTypename t_char;
|
||||||
|
GEN_API extern CodeTypename t_wchar_t;
|
||||||
|
GEN_API extern CodeTypename t_class;
|
||||||
|
GEN_API extern CodeTypename t_typename;
|
||||||
|
|
||||||
|
#ifdef GEN_DEFINE_LIBRARY_CODE_CONSTANTS
|
||||||
|
GEN_API extern CodeTypename t_b32;
|
||||||
|
|
||||||
|
GEN_API extern CodeTypename t_s8;
|
||||||
|
GEN_API extern CodeTypename t_s16;
|
||||||
|
GEN_API extern CodeTypename t_s32;
|
||||||
|
GEN_API extern CodeTypename t_s64;
|
||||||
|
|
||||||
|
GEN_API extern CodeTypename t_u8;
|
||||||
|
GEN_API extern CodeTypename t_u16;
|
||||||
|
GEN_API extern CodeTypename t_u32;
|
||||||
|
GEN_API extern CodeTypename t_u64;
|
||||||
|
|
||||||
|
GEN_API extern CodeTypename t_ssize;
|
||||||
|
GEN_API extern CodeTypename t_usize;
|
||||||
|
|
||||||
|
GEN_API extern CodeTypename t_f32;
|
||||||
|
GEN_API extern CodeTypename t_f64;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Constants
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
/*
|
||||||
|
gencpp: An attempt at "simple" staged metaprogramming for c/c++.
|
||||||
|
|
||||||
|
See Readme.md for more information from the project repository.
|
||||||
|
|
||||||
|
Public Address:
|
||||||
|
https://github.com/Ed94/gencpp --------------------------------------------------------------.
|
||||||
|
| _____ _____ _ _ |
|
||||||
|
| / ____) / ____} | | | |
|
||||||
|
| | / ___ ___ _ __ ___ _ __ _ __ | {___ | |__ _ _, __ _, ___ __| | |
|
||||||
|
| | |{_ |/ _ \ '_ \ / __} '_ l| '_ l `\___ \| __/ _` |/ _` |/ _ \/ _` | |
|
||||||
|
| | l__j | ___/ | | | {__; |+l } |+l | ____) | l| (_| | {_| | ___/ (_| | |
|
||||||
|
| \_____|\___}_l |_|\___} ,__/| ,__/ (_____/ \__\__/_|\__, |\___}\__,_l |
|
||||||
|
| | | | | __} | |
|
||||||
|
| l_l l_l {___/ |
|
||||||
|
! ----------------------------------------------------------------------- VERSION: v0.25-Alpha |
|
||||||
|
! ============================================================================================ |
|
||||||
|
! WARNING: THIS IS AN ALPHA VERSION OF THE LIBRARY, USE AT YOUR OWN DISCRETION |
|
||||||
|
! NEVER DO CODE GENERATION WITHOUT AT LEAST HAVING CONTENT IN A CODEBASE UNDER VERSION CONTROL |
|
||||||
|
! ============================================================================================ /
|
||||||
|
*/
|
||||||
|
#if ! defined(GEN_DONT_ENFORCE_GEN_TIME_GUARD) && ! defined(GEN_TIME)
|
||||||
|
# error Gen.hpp : GEN_TIME not defined
|
||||||
|
#endif
|
||||||
|
|
||||||
|
//! If its desired to roll your own dependencies, define GEN_ROLL_OWN_DEPENDENCIES before including this file.
|
||||||
|
// Dependencies are derived from the c-zpl library: https://github.com/zpl-c/zpl
|
||||||
|
#ifndef GEN_ROLL_OWN_DEPENDENCIES
|
||||||
|
# include "gen.dep.hpp"
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,753 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
#pragma once
|
||||||
|
#include "constants.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Serialization
|
||||||
|
inline
|
||||||
|
StrBuilder attributes_to_strbuilder(CodeAttributes attributes) {
|
||||||
|
GEN_ASSERT(attributes);
|
||||||
|
char* raw = ccast(char*, str_duplicate( attributes->Content, get_context()->Allocator_Temp ).Ptr);
|
||||||
|
StrBuilder result = { raw };
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void attributes_to_strbuilder_ref(CodeAttributes attributes, StrBuilder* result) {
|
||||||
|
GEN_ASSERT(attributes);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
strbuilder_append_str(result, attributes->Content);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder comment_to_strbuilder(CodeComment comment) {
|
||||||
|
GEN_ASSERT(comment);
|
||||||
|
char* raw = ccast(char*, str_duplicate( comment->Content, get_context()->Allocator_Temp ).Ptr);
|
||||||
|
StrBuilder result = { raw };
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void body_to_strbuilder_ref( CodeBody body, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(body != nullptr);
|
||||||
|
GEN_ASSERT(result != nullptr);
|
||||||
|
Code curr = body->Front;
|
||||||
|
s32 left = body->NumEntries;
|
||||||
|
while ( left -- )
|
||||||
|
{
|
||||||
|
code_to_strbuilder_ref(curr, result);
|
||||||
|
// strbuilder_append_fmt( result, "%SB", code_to_strbuilder(curr) );
|
||||||
|
curr = curr->Next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void comment_to_strbuilder_ref(CodeComment comment, StrBuilder* result) {
|
||||||
|
GEN_ASSERT(comment);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
strbuilder_append_str(result, comment->Content);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder define_to_strbuilder(CodeDefine define)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(define);
|
||||||
|
StrBuilder result = strbuilder_make_reserve( _ctx->Allocator_Temp, 512 );
|
||||||
|
define_to_strbuilder_ref(define, & result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder define_params_to_strbuilder(CodeDefineParams params)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(params);
|
||||||
|
StrBuilder result = strbuilder_make_reserve( _ctx->Allocator_Temp, 128 );
|
||||||
|
define_params_to_strbuilder_ref( params, & result );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder exec_to_strbuilder(CodeExec exec)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(exec);
|
||||||
|
char* raw = ccast(char*, str_duplicate( exec->Content, _ctx->Allocator_Temp ).Ptr);
|
||||||
|
StrBuilder result = { raw };
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void exec_to_strbuilder_ref(CodeExec exec, StrBuilder* result) {
|
||||||
|
GEN_ASSERT(exec);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
strbuilder_append_str(result, exec->Content);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void extern_to_strbuilder(CodeExtern self, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
if ( self->Body )
|
||||||
|
strbuilder_append_fmt( result, "extern \"%S\"\n{\n%SB\n}\n", self->Name, body_to_strbuilder(self->Body) );
|
||||||
|
else
|
||||||
|
strbuilder_append_fmt( result, "extern \"%S\"\n{}\n", self->Name );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder friend_to_strbuilder(CodeFriend self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
StrBuilder result = strbuilder_make_reserve( _ctx->Allocator_Temp, 256 );
|
||||||
|
friend_to_strbuilder_ref( self, & result );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void friend_to_strbuilder_ref(CodeFriend self, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
strbuilder_append_fmt( result, "friend %SB", code_to_strbuilder(self->Declaration) );
|
||||||
|
|
||||||
|
if ( self->Declaration->Type != CT_Function && self->Declaration->Type != CT_Operator && (* result)[ strbuilder_length(* result) - 1 ] != ';' )
|
||||||
|
{
|
||||||
|
strbuilder_append_str( result, txt(";") );
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( self->InlineCmt )
|
||||||
|
strbuilder_append_fmt( result, " %S", self->InlineCmt->Content );
|
||||||
|
else
|
||||||
|
strbuilder_append_str( result, txt("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder include_to_strbuilder(CodeInclude include)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(include);
|
||||||
|
return strbuilder_fmt_buf( _ctx->Allocator_Temp, "#include %S\n", include->Content );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void include_to_strbuilder_ref( CodeInclude include, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(include);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
strbuilder_append_fmt( result, "#include %S\n", include->Content );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder module_to_strbuilder(CodeModule self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
StrBuilder result = strbuilder_make_reserve( _ctx->Allocator_Temp, 64 );
|
||||||
|
module_to_strbuilder_ref( self, & result );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder namespace_to_strbuilder(CodeNS self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
StrBuilder result = strbuilder_make_reserve( _ctx->Allocator_Temp, 512 );
|
||||||
|
namespace_to_strbuilder_ref( self, & result );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void namespace_to_strbuilder_ref(CodeNS self, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
if ( bitfield_is_set( u32, self->ModuleFlags, ModuleFlag_Export ))
|
||||||
|
strbuilder_append_str( result, txt("export ") );
|
||||||
|
|
||||||
|
strbuilder_append_fmt( result, "namespace %S\n{\n%SB\n}\n", self->Name, body_to_strbuilder(self->Body) );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder params_to_strbuilder(CodeParams self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
StrBuilder result = strbuilder_make_reserve( _ctx->Allocator_Temp, 128 );
|
||||||
|
params_to_strbuilder_ref( self, & result );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder pragma_to_strbuilder(CodePragma self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
StrBuilder result = strbuilder_make_reserve( _ctx->Allocator_Temp, 256 );
|
||||||
|
pragma_to_strbuilder_ref( self, & result );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void pragma_to_strbuilder_ref(CodePragma self, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
strbuilder_append_fmt( result, "#pragma %S\n", self->Content );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void preprocess_to_strbuilder_if(CodePreprocessCond cond, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(cond);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
strbuilder_append_fmt( result, "#if %S", cond->Content );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void preprocess_to_strbuilder_ifdef(CodePreprocessCond cond, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(cond);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
strbuilder_append_fmt( result, "#ifdef %S\n", cond->Content );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void preprocess_to_strbuilder_ifndef(CodePreprocessCond cond, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(cond);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
strbuilder_append_fmt( result, "#ifndef %S", cond->Content );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void preprocess_to_strbuilder_elif(CodePreprocessCond cond, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(cond);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
strbuilder_append_fmt( result, "#elif %S\n", cond->Content );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void preprocess_to_strbuilder_else(CodePreprocessCond cond, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(cond);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
strbuilder_append_str( result, txt("#else\n") );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void preprocess_to_strbuilder_endif(CodePreprocessCond cond, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(cond);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
strbuilder_append_str( result, txt("#endif\n") );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder specifiers_to_strbuilder(CodeSpecifiers self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
StrBuilder result = strbuilder_make_reserve( _ctx->Allocator_Temp, 64 );
|
||||||
|
specifiers_to_strbuilder_ref( self, & result );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder template_to_strbuilder(CodeTemplate self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
StrBuilder result = strbuilder_make_reserve( _ctx->Allocator_Temp, 1024 );
|
||||||
|
template_to_strbuilder_ref( self, & result );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder typedef_to_strbuilder(CodeTypedef self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
StrBuilder result = strbuilder_make_reserve( _ctx->Allocator_Temp, 128 );
|
||||||
|
typedef_to_strbuilder_ref( self, & result );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder typename_to_strbuilder(CodeTypename self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
StrBuilder result = strbuilder_make_str( _ctx->Allocator_Temp, txt("") );
|
||||||
|
typename_to_strbuilder_ref( self, & result );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder using_to_strbuilder(CodeUsing self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
StrBuilder result = strbuilder_make_reserve( _ctx->Allocator_Temp, 128 );
|
||||||
|
switch ( self->Type )
|
||||||
|
{
|
||||||
|
case CT_Using:
|
||||||
|
using_to_strbuilder_ref( self, & result );
|
||||||
|
break;
|
||||||
|
case CT_Using_Namespace:
|
||||||
|
using_to_strbuilder_ns( self, & result );
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void using_to_strbuilder_ns(CodeUsing self, StrBuilder* result )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
GEN_ASSERT(result);
|
||||||
|
if ( self->InlineCmt )
|
||||||
|
strbuilder_append_fmt( result, "using namespace $S; %S", self->Name, self->InlineCmt->Content );
|
||||||
|
else
|
||||||
|
strbuilder_append_fmt( result, "using namespace %S;\n", self->Name );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder var_to_strbuilder(CodeVar self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
StrBuilder result = strbuilder_make_reserve( get_context()->Allocator_Temp, 256 );
|
||||||
|
var_to_strbuilder_ref( self, & result );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
#pragma endregion Serialization
|
||||||
|
|
||||||
|
#pragma region Code
|
||||||
|
inline
|
||||||
|
void code_append( Code self, Code other )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
GEN_ASSERT(other);
|
||||||
|
GEN_ASSERT_MSG(self != other, "Attempted to recursively append Code AST to itself.");
|
||||||
|
|
||||||
|
if ( other->Parent != nullptr )
|
||||||
|
other = code_duplicate(other);
|
||||||
|
|
||||||
|
other->Parent = self;
|
||||||
|
|
||||||
|
if ( self->Front == nullptr )
|
||||||
|
{
|
||||||
|
self->Front = other;
|
||||||
|
self->Back = other;
|
||||||
|
|
||||||
|
self->NumEntries++;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Code
|
||||||
|
Current = self->Back;
|
||||||
|
Current->Next = other;
|
||||||
|
other->Prev = Current;
|
||||||
|
self->Back = other;
|
||||||
|
self->NumEntries++;
|
||||||
|
}
|
||||||
|
inline
|
||||||
|
bool code_is_body(Code self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
switch (self->Type)
|
||||||
|
{
|
||||||
|
case CT_Enum_Body:
|
||||||
|
case CT_Class_Body:
|
||||||
|
case CT_Union_Body:
|
||||||
|
case CT_Export_Body:
|
||||||
|
case CT_Global_Body:
|
||||||
|
case CT_Struct_Body:
|
||||||
|
case CT_Function_Body:
|
||||||
|
case CT_Namespace_Body:
|
||||||
|
case CT_Extern_Linkage_Body:
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
inline
|
||||||
|
Code* code_entry( Code self, u32 idx )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self != nullptr);
|
||||||
|
Code* current = & self->Front;
|
||||||
|
while ( idx >= 0 && current != nullptr )
|
||||||
|
{
|
||||||
|
if ( idx == 0 )
|
||||||
|
return rcast( Code*, current);
|
||||||
|
|
||||||
|
current = & ( * current )->Next;
|
||||||
|
idx--;
|
||||||
|
}
|
||||||
|
|
||||||
|
return rcast( Code*, current);
|
||||||
|
}
|
||||||
|
forceinline
|
||||||
|
bool code_is_valid(Code self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
return self != nullptr && self->Type != CT_Invalid;
|
||||||
|
}
|
||||||
|
forceinline
|
||||||
|
bool code_has_entries(Code self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
return self->NumEntries > 0;
|
||||||
|
}
|
||||||
|
forceinline
|
||||||
|
void code_set_global(Code self)
|
||||||
|
{
|
||||||
|
if ( self == nullptr )
|
||||||
|
{
|
||||||
|
log_failure("Code::set_global: Cannot set code as global, AST is null!");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self->Parent = Code_Global;
|
||||||
|
}
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
forceinline
|
||||||
|
Code& Code::operator ++()
|
||||||
|
{
|
||||||
|
if ( ast )
|
||||||
|
ast = ast->Next.ast;
|
||||||
|
|
||||||
|
return * this;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
forceinline
|
||||||
|
Str code_type_str(Code self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self != nullptr);
|
||||||
|
return codetype_to_str( self->Type );
|
||||||
|
}
|
||||||
|
#pragma endregion Code
|
||||||
|
|
||||||
|
#pragma region CodeBody
|
||||||
|
inline
|
||||||
|
void body_append( CodeBody self, Code other )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
GEN_ASSERT(other);
|
||||||
|
|
||||||
|
if (code_is_body(other)) {
|
||||||
|
body_append_body( self, cast(CodeBody, other) );
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
code_append( cast(Code, self), other );
|
||||||
|
}
|
||||||
|
inline
|
||||||
|
void body_append_body( CodeBody self, CodeBody body )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
GEN_ASSERT(body);
|
||||||
|
GEN_ASSERT_MSG(self != body, "Attempted to append body to itself.");
|
||||||
|
|
||||||
|
for ( Code entry = begin_CodeBody(body); entry != end_CodeBody(body); entry = next_CodeBody(body, entry) ) {
|
||||||
|
body_append( self, entry );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
inline
|
||||||
|
Code begin_CodeBody( CodeBody body) {
|
||||||
|
GEN_ASSERT(body);
|
||||||
|
if ( body != nullptr )
|
||||||
|
return body->Front;
|
||||||
|
|
||||||
|
return NullCode;
|
||||||
|
}
|
||||||
|
forceinline
|
||||||
|
Code end_CodeBody(CodeBody body ){
|
||||||
|
GEN_ASSERT(body);
|
||||||
|
return body->Back->Next;
|
||||||
|
}
|
||||||
|
inline
|
||||||
|
Code next_CodeBody(CodeBody body, Code entry) {
|
||||||
|
GEN_ASSERT(body);
|
||||||
|
GEN_ASSERT(entry);
|
||||||
|
return entry->Next;
|
||||||
|
}
|
||||||
|
#pragma endregion CodeBody
|
||||||
|
|
||||||
|
#pragma region CodeClass
|
||||||
|
inline
|
||||||
|
void class_add_interface( CodeClass self, CodeTypename type )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
GEN_ASSERT(type);
|
||||||
|
CodeTypename possible_slot = self->ParentType;
|
||||||
|
if ( possible_slot != nullptr )
|
||||||
|
{
|
||||||
|
// Were adding an interface to parent type, so we need to make sure the parent type is public.
|
||||||
|
self->ParentAccess = AccessSpec_Public;
|
||||||
|
// If your planning on adding a proper parent,
|
||||||
|
// then you'll need to move this over to ParentType->next and update ParentAccess accordingly.
|
||||||
|
}
|
||||||
|
|
||||||
|
while ( possible_slot->Next != nullptr )
|
||||||
|
{
|
||||||
|
possible_slot = cast(CodeTypename, possible_slot->Next);
|
||||||
|
}
|
||||||
|
|
||||||
|
possible_slot->Next = cast(Code, type);
|
||||||
|
}
|
||||||
|
#pragma endregion CodeClass
|
||||||
|
|
||||||
|
#pragma region CodeParams
|
||||||
|
inline
|
||||||
|
void params_append( CodeParams appendee, CodeParams other )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(appendee);
|
||||||
|
GEN_ASSERT(other);
|
||||||
|
GEN_ASSERT_MSG(appendee != other, "Attempted to append parameter to itself.");
|
||||||
|
Code self = cast(Code, appendee);
|
||||||
|
Code entry = cast(Code, other);
|
||||||
|
|
||||||
|
if ( entry->Parent != nullptr )
|
||||||
|
entry = code_duplicate( entry );
|
||||||
|
|
||||||
|
entry->Parent = self;
|
||||||
|
|
||||||
|
if ( self->Last == nullptr )
|
||||||
|
{
|
||||||
|
self->Last = entry;
|
||||||
|
self->Next = entry;
|
||||||
|
self->NumEntries++;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self->Last->Next = entry;
|
||||||
|
self->Last = entry;
|
||||||
|
self->NumEntries++;
|
||||||
|
}
|
||||||
|
inline
|
||||||
|
CodeParams params_get(CodeParams self, s32 idx )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
CodeParams param = self;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
if ( ++ param != nullptr )
|
||||||
|
return NullCode;
|
||||||
|
|
||||||
|
param = cast(CodeParams, cast(Code, param)->Next);
|
||||||
|
}
|
||||||
|
while ( --idx );
|
||||||
|
|
||||||
|
return param;
|
||||||
|
}
|
||||||
|
forceinline
|
||||||
|
bool params_has_entries(CodeParams self)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self);
|
||||||
|
return self->NumEntries > 0;
|
||||||
|
}
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
forceinline
|
||||||
|
CodeParams& CodeParams::operator ++()
|
||||||
|
{
|
||||||
|
* this = ast->Next;
|
||||||
|
return * this;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
forceinline
|
||||||
|
CodeParams begin_CodeParams(CodeParams params)
|
||||||
|
{
|
||||||
|
if ( params != nullptr )
|
||||||
|
return params;
|
||||||
|
|
||||||
|
return NullCode;
|
||||||
|
}
|
||||||
|
forceinline
|
||||||
|
CodeParams end_CodeParams(CodeParams params)
|
||||||
|
{
|
||||||
|
// return { (AST_Params*) rcast( AST*, ast)->Last };
|
||||||
|
return NullCode;
|
||||||
|
}
|
||||||
|
forceinline
|
||||||
|
CodeParams next_CodeParams(CodeParams params, CodeParams param_iter)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(param_iter);
|
||||||
|
return param_iter->Next;
|
||||||
|
}
|
||||||
|
#pragma endregion CodeParams
|
||||||
|
|
||||||
|
#pragma region CodeDefineParams
|
||||||
|
forceinline void define_params_append (CodeDefineParams appendee, CodeDefineParams other ) { params_append( cast(CodeParams, appendee), cast(CodeParams, other) ); }
|
||||||
|
forceinline CodeDefineParams define_params_get (CodeDefineParams self, s32 idx ) { return (CodeDefineParams) (Code) params_get( cast(CodeParams, self), idx); }
|
||||||
|
forceinline bool define_params_has_entries(CodeDefineParams self) { return params_has_entries( cast(CodeParams, self)); }
|
||||||
|
|
||||||
|
forceinline CodeDefineParams begin_CodeDefineParams(CodeDefineParams params) { return (CodeDefineParams) (Code) begin_CodeParams( cast(CodeParams, (Code)params)); }
|
||||||
|
forceinline CodeDefineParams end_CodeDefineParams (CodeDefineParams params) { return (CodeDefineParams) (Code) end_CodeParams ( cast(CodeParams, (Code)params)); }
|
||||||
|
forceinline CodeDefineParams next_CodeDefineParams (CodeDefineParams params, CodeDefineParams entry_iter) { return (CodeDefineParams) (Code) next_CodeParams ( cast(CodeParams, (Code)params), cast(CodeParams, (Code)entry_iter)); }
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
forceinline
|
||||||
|
CodeDefineParams& CodeDefineParams::operator ++()
|
||||||
|
{
|
||||||
|
* this = ast->Next;
|
||||||
|
return * this;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#pragma endregion CodeDefineParams
|
||||||
|
|
||||||
|
#pragma region CodeSpecifiers
|
||||||
|
inline
|
||||||
|
bool specifiers_append(CodeSpecifiers self, Specifier spec )
|
||||||
|
{
|
||||||
|
if ( self == nullptr )
|
||||||
|
{
|
||||||
|
log_failure("CodeSpecifiers: Attempted to append to a null specifiers AST!");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if ( self->NumEntries == AST_ArrSpecs_Cap )
|
||||||
|
{
|
||||||
|
log_failure("CodeSpecifiers: Attempted to append over %d specifiers to a specifiers AST!", AST_ArrSpecs_Cap );
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
self->ArrSpecs[ self->NumEntries ] = spec;
|
||||||
|
self->NumEntries++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
inline
|
||||||
|
bool specifiers_has(CodeSpecifiers self, Specifier spec)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self != nullptr);
|
||||||
|
for ( s32 idx = 0; idx < self->NumEntries; idx++ ) {
|
||||||
|
if ( self->ArrSpecs[ idx ] == spec )
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
inline
|
||||||
|
s32 specifiers_index_of(CodeSpecifiers self, Specifier spec)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(self != nullptr);
|
||||||
|
for ( s32 idx = 0; idx < self->NumEntries; idx++ ) {
|
||||||
|
if ( self->ArrSpecs[ idx ] == spec )
|
||||||
|
return idx;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
inline
|
||||||
|
s32 specifiers_remove( CodeSpecifiers self, Specifier to_remove )
|
||||||
|
{
|
||||||
|
if ( self == nullptr )
|
||||||
|
{
|
||||||
|
log_failure("CodeSpecifiers: Attempted to append to a null specifiers AST!");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
if ( self->NumEntries == AST_ArrSpecs_Cap )
|
||||||
|
{
|
||||||
|
log_failure("CodeSpecifiers: Attempted to append over %d specifiers to a specifiers AST!", AST_ArrSpecs_Cap );
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
s32 result = -1;
|
||||||
|
|
||||||
|
s32 curr = 0;
|
||||||
|
s32 next = 0;
|
||||||
|
for(; next < self->NumEntries; ++ curr, ++ next)
|
||||||
|
{
|
||||||
|
Specifier spec = self->ArrSpecs[next];
|
||||||
|
if (spec == to_remove)
|
||||||
|
{
|
||||||
|
result = next;
|
||||||
|
|
||||||
|
next ++;
|
||||||
|
if (next >= self->NumEntries)
|
||||||
|
break;
|
||||||
|
|
||||||
|
spec = self->ArrSpecs[next];
|
||||||
|
}
|
||||||
|
|
||||||
|
self->ArrSpecs[ curr ] = spec;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result > -1) {
|
||||||
|
self->NumEntries --;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
forceinline
|
||||||
|
Specifier* begin_CodeSpecifiers(CodeSpecifiers self)
|
||||||
|
{
|
||||||
|
if ( self != nullptr )
|
||||||
|
return & self->ArrSpecs[0];
|
||||||
|
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
forceinline
|
||||||
|
Specifier* end_CodeSpecifiers(CodeSpecifiers self)
|
||||||
|
{
|
||||||
|
return self->ArrSpecs + self->NumEntries;
|
||||||
|
}
|
||||||
|
forceinline
|
||||||
|
Specifier* next_CodeSpecifiers(CodeSpecifiers self, Specifier* spec_iter)
|
||||||
|
{
|
||||||
|
return spec_iter + 1;
|
||||||
|
}
|
||||||
|
#pragma endregion CodeSpecifiers
|
||||||
|
|
||||||
|
#pragma region CodeStruct
|
||||||
|
inline
|
||||||
|
void struct_add_interface(CodeStruct self, CodeTypename type )
|
||||||
|
{
|
||||||
|
CodeTypename possible_slot = self->ParentType;
|
||||||
|
if ( possible_slot != nullptr )
|
||||||
|
{
|
||||||
|
// Were adding an interface to parent type, so we need to make sure the parent type is public.
|
||||||
|
self->ParentAccess = AccessSpec_Public;
|
||||||
|
// If your planning on adding a proper parent,
|
||||||
|
// then you'll need to move this over to ParentType->next and update ParentAccess accordingly.
|
||||||
|
}
|
||||||
|
|
||||||
|
while ( possible_slot->Next != nullptr )
|
||||||
|
{
|
||||||
|
possible_slot = cast(CodeTypename, possible_slot->Next);
|
||||||
|
}
|
||||||
|
|
||||||
|
possible_slot->Next = cast(Code, type);
|
||||||
|
}
|
||||||
|
#pragma endregion Code
|
||||||
|
|
||||||
|
#pragma region Interface
|
||||||
|
inline
|
||||||
|
CodeBody def_body( CodeType type )
|
||||||
|
{
|
||||||
|
switch ( type )
|
||||||
|
{
|
||||||
|
case CT_Class_Body:
|
||||||
|
case CT_Enum_Body:
|
||||||
|
case CT_Export_Body:
|
||||||
|
case CT_Extern_Linkage:
|
||||||
|
case CT_Function_Body:
|
||||||
|
case CT_Global_Body:
|
||||||
|
case CT_Namespace_Body:
|
||||||
|
case CT_Struct_Body:
|
||||||
|
case CT_Union_Body:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
log_failure( "def_body: Invalid type %s", codetype_to_str(type).Ptr );
|
||||||
|
return (CodeBody)Code_Invalid;
|
||||||
|
}
|
||||||
|
|
||||||
|
Code
|
||||||
|
result = make_code();
|
||||||
|
result->Type = type;
|
||||||
|
return (CodeBody)result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
Str token_fmt_impl( ssize num, ... )
|
||||||
|
{
|
||||||
|
local_persist thread_local
|
||||||
|
char buf[GEN_PRINTF_MAXLEN] = { 0 };
|
||||||
|
mem_set( buf, 0, GEN_PRINTF_MAXLEN );
|
||||||
|
|
||||||
|
va_list va;
|
||||||
|
va_start(va, num );
|
||||||
|
ssize result = token_fmt_va(buf, GEN_PRINTF_MAXLEN, num, va);
|
||||||
|
va_end(va);
|
||||||
|
|
||||||
|
Str str = { buf, result };
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
#pragma endregion Interface
|
||||||
@@ -0,0 +1,542 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
#pragma once
|
||||||
|
#include "code_serialization.cpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
internal void parser_init(Context* ctx);
|
||||||
|
internal void parser_deinit(Context* ctx);
|
||||||
|
|
||||||
|
internal
|
||||||
|
void* fallback_allocator_proc( void* allocator_data, AllocType type, ssize size, ssize alignment, void* old_memory, ssize old_size, u64 flags )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(_ctx);
|
||||||
|
GEN_ASSERT(_ctx->Fallback_AllocatorBuckets);
|
||||||
|
Arena* last = array_back(_ctx->Fallback_AllocatorBuckets);
|
||||||
|
|
||||||
|
switch ( type )
|
||||||
|
{
|
||||||
|
case EAllocation_ALLOC:
|
||||||
|
{
|
||||||
|
if ( ( last->TotalUsed + size ) > last->TotalSize )
|
||||||
|
{
|
||||||
|
Arena bucket = arena_init_from_allocator( heap(), _ctx->InitSize_Fallback_Allocator_Bucket_Size );
|
||||||
|
|
||||||
|
if ( bucket.PhysicalStart == nullptr )
|
||||||
|
GEN_FATAL( "Failed to create bucket for Fallback_AllocatorBuckets");
|
||||||
|
|
||||||
|
if ( ! array_append( _ctx->Fallback_AllocatorBuckets, bucket ) )
|
||||||
|
GEN_FATAL( "Failed to append bucket to Fallback_AllocatorBuckets");
|
||||||
|
|
||||||
|
last = array_back(_ctx->Fallback_AllocatorBuckets);
|
||||||
|
}
|
||||||
|
|
||||||
|
return alloc_align( arena_allocator_info(last), size, alignment );
|
||||||
|
}
|
||||||
|
case EAllocation_FREE:
|
||||||
|
{
|
||||||
|
// Doesn't recycle.
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case EAllocation_FREE_ALL:
|
||||||
|
{
|
||||||
|
// Memory::cleanup instead.
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case EAllocation_RESIZE:
|
||||||
|
{
|
||||||
|
if ( last->TotalUsed + size > last->TotalSize )
|
||||||
|
{
|
||||||
|
Arena bucket = arena_init_from_allocator( heap(), _ctx->InitSize_Fallback_Allocator_Bucket_Size );
|
||||||
|
|
||||||
|
if ( bucket.PhysicalStart == nullptr )
|
||||||
|
GEN_FATAL( "Failed to create bucket for Fallback_AllocatorBuckets");
|
||||||
|
|
||||||
|
if ( ! array_append( _ctx->Fallback_AllocatorBuckets, bucket ) )
|
||||||
|
GEN_FATAL( "Failed to append bucket to Fallback_AllocatorBuckets");
|
||||||
|
|
||||||
|
last = array_back( _ctx->Fallback_AllocatorBuckets);
|
||||||
|
}
|
||||||
|
|
||||||
|
void* result = alloc_align( last->Backing, size, alignment );
|
||||||
|
|
||||||
|
if ( result != nullptr && old_memory != nullptr )
|
||||||
|
{
|
||||||
|
mem_copy( result, old_memory, old_size );
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
void fallback_logger(LogEntry entry)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(entry.msg.Len > 0);
|
||||||
|
GEN_ASSERT(entry.msg.Ptr);
|
||||||
|
log_fmt("%S: %S", loglevel_to_str(entry.level), entry.msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
void define_constants()
|
||||||
|
{
|
||||||
|
// We only initalize these if there is no base context.
|
||||||
|
if ( context_counter > 0 )
|
||||||
|
return;
|
||||||
|
|
||||||
|
Code_Global = make_code();
|
||||||
|
Code_Global->Name = cache_str( txt("Global Code") );
|
||||||
|
Code_Global->Content = Code_Global->Name;
|
||||||
|
|
||||||
|
Code_Invalid = make_code();
|
||||||
|
code_set_global(Code_Invalid);
|
||||||
|
|
||||||
|
t_empty = (CodeTypename) make_code();
|
||||||
|
t_empty->Type = CT_Typename;
|
||||||
|
t_empty->Name = cache_str( txt("") );
|
||||||
|
code_set_global(cast(Code, t_empty));
|
||||||
|
|
||||||
|
access_private = make_code();
|
||||||
|
access_private->Type = CT_Access_Private;
|
||||||
|
access_private->Name = cache_str( txt("private:\n") );
|
||||||
|
code_set_global(cast(Code, access_private));
|
||||||
|
|
||||||
|
access_protected = make_code();
|
||||||
|
access_protected->Type = CT_Access_Protected;
|
||||||
|
access_protected->Name = cache_str( txt("protected:\n") );
|
||||||
|
code_set_global(access_protected);
|
||||||
|
|
||||||
|
access_public = make_code();
|
||||||
|
access_public->Type = CT_Access_Public;
|
||||||
|
access_public->Name = cache_str( txt("public:\n") );
|
||||||
|
code_set_global(access_public);
|
||||||
|
|
||||||
|
Str api_export_str = code(GEN_API_Export_Code);
|
||||||
|
attrib_api_export = def_attributes( api_export_str );
|
||||||
|
code_set_global(cast(Code, attrib_api_export));
|
||||||
|
|
||||||
|
Str api_import_str = code(GEN_API_Import_Code);
|
||||||
|
attrib_api_import = def_attributes( api_import_str );
|
||||||
|
code_set_global(cast(Code, attrib_api_import));
|
||||||
|
|
||||||
|
module_global_fragment = make_code();
|
||||||
|
module_global_fragment->Type = CT_Untyped;
|
||||||
|
module_global_fragment->Name = cache_str( txt("module;") );
|
||||||
|
module_global_fragment->Content = module_global_fragment->Name;
|
||||||
|
code_set_global(cast(Code, module_global_fragment));
|
||||||
|
|
||||||
|
module_private_fragment = make_code();
|
||||||
|
module_private_fragment->Type = CT_Untyped;
|
||||||
|
module_private_fragment->Name = cache_str( txt("module : private;") );
|
||||||
|
module_private_fragment->Content = module_private_fragment->Name;
|
||||||
|
code_set_global(cast(Code, module_private_fragment));
|
||||||
|
|
||||||
|
fmt_newline = make_code();
|
||||||
|
fmt_newline->Type = CT_NewLine;
|
||||||
|
code_set_global((Code)fmt_newline);
|
||||||
|
|
||||||
|
pragma_once = (CodePragma) make_code();
|
||||||
|
pragma_once->Type = CT_Preprocess_Pragma;
|
||||||
|
pragma_once->Name = cache_str( txt("once") );
|
||||||
|
pragma_once->Content = pragma_once->Name;
|
||||||
|
code_set_global((Code)pragma_once);
|
||||||
|
|
||||||
|
param_varadic = (CodeParams) make_code();
|
||||||
|
param_varadic->Type = CT_Parameters;
|
||||||
|
param_varadic->Name = cache_str( txt("...") );
|
||||||
|
param_varadic->ValueType = t_empty;
|
||||||
|
code_set_global((Code)param_varadic);
|
||||||
|
|
||||||
|
preprocess_else = (CodePreprocessCond) make_code();
|
||||||
|
preprocess_else->Type = CT_Preprocess_Else;
|
||||||
|
code_set_global((Code)preprocess_else);
|
||||||
|
|
||||||
|
preprocess_endif = (CodePreprocessCond) make_code();
|
||||||
|
preprocess_endif->Type = CT_Preprocess_EndIf;
|
||||||
|
code_set_global((Code)preprocess_endif);
|
||||||
|
|
||||||
|
Str auto_str = txt("auto"); t_auto = def_type( auto_str ); code_set_global( t_auto );
|
||||||
|
Str void_str = txt("void"); t_void = def_type( void_str ); code_set_global( t_void );
|
||||||
|
Str int_str = txt("int"); t_int = def_type( int_str ); code_set_global( t_int );
|
||||||
|
Str bool_str = txt("bool"); t_bool = def_type( bool_str ); code_set_global( t_bool );
|
||||||
|
Str char_str = txt("char"); t_char = def_type( char_str ); code_set_global( t_char );
|
||||||
|
Str wchar_str = txt("wchar_t"); t_wchar_t = def_type( wchar_str ); code_set_global( t_wchar_t );
|
||||||
|
Str class_str = txt("class"); t_class = def_type( class_str ); code_set_global( t_class );
|
||||||
|
Str typename_str = txt("typename"); t_typename = def_type( typename_str ); code_set_global( t_typename );
|
||||||
|
|
||||||
|
#ifdef GEN_DEFINE_LIBRARY_CODE_CONSTANTS
|
||||||
|
t_b32 = def_type( name(b32) ); code_set_global( t_b32 );
|
||||||
|
|
||||||
|
Str s8_str = txt("s8"); t_s8 = def_type( s8_str ); code_set_global( t_s8 );
|
||||||
|
Str s16_str = txt("s16"); t_s16 = def_type( s16_str ); code_set_global( t_s16 );
|
||||||
|
Str s32_str = txt("s32"); t_s32 = def_type( s32_str ); code_set_global( t_s32 );
|
||||||
|
Str s64_str = txt("s64"); t_s64 = def_type( s64_str ); code_set_global( t_s64 );
|
||||||
|
|
||||||
|
Str u8_str = txt("u8"); t_u8 = def_type( u8_str ); code_set_global( t_u8 );
|
||||||
|
Str u16_str = txt("u16"); t_u16 = def_type( u16_str ); code_set_global( t_u16 );
|
||||||
|
Str u32_str = txt("u32"); t_u32 = def_type( u32_str ); code_set_global( t_u32 );
|
||||||
|
Str u64_str = txt("u64"); t_u64 = def_type( u64_str ); code_set_global( t_u64 );
|
||||||
|
|
||||||
|
Str ssize_str = txt("ssize"); t_ssize = def_type( ssize_str ); code_set_global( t_ssize );
|
||||||
|
Str usize_str = txt("usize"); t_usize = def_type( usize_str ); code_set_global( t_usize );
|
||||||
|
|
||||||
|
Str f32_str = txt("f32"); t_f32 = def_type( f32_str ); code_set_global( t_f32 );
|
||||||
|
Str f64_str = txt("f64"); t_f64 = def_type( f64_str ); code_set_global( t_f64 );
|
||||||
|
#endif
|
||||||
|
|
||||||
|
spec_const = def_specifier( Spec_Const); code_set_global( cast(Code, spec_const ));
|
||||||
|
spec_consteval = def_specifier( Spec_Consteval); code_set_global( cast(Code, spec_consteval ));
|
||||||
|
spec_constexpr = def_specifier( Spec_Constexpr); code_set_global( cast(Code, spec_constexpr ));
|
||||||
|
spec_constinit = def_specifier( Spec_Constinit); code_set_global( cast(Code, spec_constinit ));
|
||||||
|
spec_extern_linkage = def_specifier( Spec_External_Linkage); code_set_global( cast(Code, spec_extern_linkage ));
|
||||||
|
spec_final = def_specifier( Spec_Final); code_set_global( cast(Code, spec_final ));
|
||||||
|
spec_forceinline = def_specifier( Spec_ForceInline); code_set_global( cast(Code, spec_forceinline ));
|
||||||
|
spec_global = def_specifier( Spec_Global); code_set_global( cast(Code, spec_global ));
|
||||||
|
spec_inline = def_specifier( Spec_Inline); code_set_global( cast(Code, spec_inline ));
|
||||||
|
spec_internal_linkage = def_specifier( Spec_Internal_Linkage); code_set_global( cast(Code, spec_internal_linkage ));
|
||||||
|
spec_local_persist = def_specifier( Spec_Local_Persist); code_set_global( cast(Code, spec_local_persist ));
|
||||||
|
spec_mutable = def_specifier( Spec_Mutable); code_set_global( cast(Code, spec_mutable ));
|
||||||
|
spec_neverinline = def_specifier( Spec_NeverInline); code_set_global( cast(Code, spec_neverinline ));
|
||||||
|
spec_noexcept = def_specifier( Spec_NoExceptions); code_set_global( cast(Code, spec_noexcept ));
|
||||||
|
spec_override = def_specifier( Spec_Override); code_set_global( cast(Code, spec_override ));
|
||||||
|
spec_ptr = def_specifier( Spec_Ptr); code_set_global( cast(Code, spec_ptr ));
|
||||||
|
spec_pure = def_specifier( Spec_Pure); code_set_global( cast(Code, spec_pure ));
|
||||||
|
spec_ref = def_specifier( Spec_Ref); code_set_global( cast(Code, spec_ref ));
|
||||||
|
spec_register = def_specifier( Spec_Register); code_set_global( cast(Code, spec_register ));
|
||||||
|
spec_rvalue = def_specifier( Spec_RValue); code_set_global( cast(Code, spec_rvalue ));
|
||||||
|
spec_static_member = def_specifier( Spec_Static); code_set_global( cast(Code, spec_static_member ));
|
||||||
|
spec_thread_local = def_specifier( Spec_Thread_Local); code_set_global( cast(Code, spec_thread_local ));
|
||||||
|
spec_virtual = def_specifier( Spec_Virtual); code_set_global( cast(Code, spec_virtual ));
|
||||||
|
spec_volatile = def_specifier( Spec_Volatile); code_set_global( cast(Code, spec_volatile ));
|
||||||
|
|
||||||
|
spec_local_persist = def_specifiers( 1, Spec_Local_Persist );
|
||||||
|
code_set_global(cast(Code, spec_local_persist));
|
||||||
|
|
||||||
|
if (enum_underlying_macro.Name.Len == 0) {
|
||||||
|
enum_underlying_macro.Name = txt("enum_underlying");
|
||||||
|
enum_underlying_macro.Type = MT_Expression;
|
||||||
|
enum_underlying_macro.Flags = MF_Functional;
|
||||||
|
}
|
||||||
|
register_macro(enum_underlying_macro);
|
||||||
|
}
|
||||||
|
|
||||||
|
void init(Context* ctx)
|
||||||
|
{
|
||||||
|
do_once() {
|
||||||
|
context_counter = 0;
|
||||||
|
}
|
||||||
|
AllocatorInfo fallback_allocator = { & fallback_allocator_proc, nullptr };
|
||||||
|
|
||||||
|
b32 using_fallback_allocator = false;
|
||||||
|
if (ctx->Allocator_DyanmicContainers.Proc == nullptr) {
|
||||||
|
ctx->Allocator_DyanmicContainers = fallback_allocator;
|
||||||
|
using_fallback_allocator = true;
|
||||||
|
}
|
||||||
|
if (ctx->Allocator_Pool.Proc == nullptr ) {
|
||||||
|
ctx->Allocator_Pool = fallback_allocator;
|
||||||
|
using_fallback_allocator = true;
|
||||||
|
}
|
||||||
|
if (ctx->Allocator_StrCache.Proc == nullptr) {
|
||||||
|
ctx->Allocator_StrCache = fallback_allocator;
|
||||||
|
using_fallback_allocator = true;
|
||||||
|
}
|
||||||
|
if (ctx->Allocator_Temp.Proc == nullptr) {
|
||||||
|
ctx->Allocator_Temp = fallback_allocator;
|
||||||
|
using_fallback_allocator = true;
|
||||||
|
}
|
||||||
|
// Setup fallback allocator
|
||||||
|
if (using_fallback_allocator)
|
||||||
|
{
|
||||||
|
ctx->Fallback_AllocatorBuckets = array_init_reserve(Arena, heap(), 128 );
|
||||||
|
if ( ctx->Fallback_AllocatorBuckets == nullptr )
|
||||||
|
GEN_FATAL( "Failed to reserve memory for Fallback_AllocatorBuckets");
|
||||||
|
|
||||||
|
Arena bucket = arena_init_from_allocator( heap(), ctx->InitSize_Fallback_Allocator_Bucket_Size );
|
||||||
|
if ( bucket.PhysicalStart == nullptr )
|
||||||
|
GEN_FATAL( "Failed to create first bucket for Fallback_AllocatorBuckets");
|
||||||
|
|
||||||
|
array_append( ctx->Fallback_AllocatorBuckets, bucket );
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx->Max_CommentLineLength == 0) {
|
||||||
|
ctx->Max_CommentLineLength = 1024;
|
||||||
|
}
|
||||||
|
if (ctx->Max_StrCacheLength == 0) {
|
||||||
|
ctx->Max_StrCacheLength = kilobytes(512);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx->InitSize_BuilderBuffer == 0) {
|
||||||
|
ctx->InitSize_BuilderBuffer = megabytes(2);
|
||||||
|
}
|
||||||
|
if (ctx->InitSize_CodePoolsArray == 0) {
|
||||||
|
ctx->InitSize_CodePoolsArray = 16;
|
||||||
|
}
|
||||||
|
if (ctx->InitSize_StringArenasArray == 0) {
|
||||||
|
ctx->InitSize_StringArenasArray = 16;
|
||||||
|
}
|
||||||
|
if (ctx->CodePool_NumBlocks == 0) {
|
||||||
|
ctx->CodePool_NumBlocks = kilobytes(16);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx->InitSize_LexerTokens == 0 ) {
|
||||||
|
ctx->InitSize_LexerTokens = kilobytes(64);
|
||||||
|
}
|
||||||
|
if (ctx->SizePer_StringArena == 0) {
|
||||||
|
ctx->SizePer_StringArena = megabytes(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx->InitSize_Fallback_Allocator_Bucket_Size == 0) {
|
||||||
|
ctx->InitSize_Fallback_Allocator_Bucket_Size = megabytes(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx->InitSize_StrCacheTable == 0)
|
||||||
|
{
|
||||||
|
ctx->InitSize_StrCacheTable = kilobytes(8);
|
||||||
|
}
|
||||||
|
if (ctx->InitSize_MacrosTable == 0)
|
||||||
|
{
|
||||||
|
ctx->InitSize_MacrosTable = kilobytes(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ctx->Logger == nullptr) {
|
||||||
|
ctx->Logger = & fallback_logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Override the current context (user has to put it back if unwanted).
|
||||||
|
_ctx = ctx;
|
||||||
|
|
||||||
|
// Setup the arrays
|
||||||
|
{
|
||||||
|
ctx->CodePools = array_init_reserve(Pool, ctx->Allocator_DyanmicContainers, ctx->InitSize_CodePoolsArray );
|
||||||
|
if ( ctx->CodePools == nullptr )
|
||||||
|
GEN_FATAL( "gen::init: Failed to initialize the CodePools array" );
|
||||||
|
|
||||||
|
ctx->StringArenas = array_init_reserve(Arena, ctx->Allocator_DyanmicContainers, ctx->InitSize_StringArenasArray );
|
||||||
|
if ( ctx->StringArenas == nullptr )
|
||||||
|
GEN_FATAL( "gen::init: Failed to initialize the StringArenas array" );
|
||||||
|
}
|
||||||
|
// Setup the code pool and code entries arena.
|
||||||
|
{
|
||||||
|
Pool code_pool = pool_init( ctx->Allocator_Pool, ctx->CodePool_NumBlocks, size_of(AST) );
|
||||||
|
if ( code_pool.PhysicalStart == nullptr )
|
||||||
|
GEN_FATAL( "gen::init: Failed to initialize the code pool" );
|
||||||
|
array_append( ctx->CodePools, code_pool );
|
||||||
|
|
||||||
|
// TODO(Ed): Eventually the string arenas needs to be phased out for a dedicated string slab allocator
|
||||||
|
Arena strbuilder_arena = arena_init_from_allocator( ctx->Allocator_StrCache, ctx->SizePer_StringArena );
|
||||||
|
if ( strbuilder_arena.PhysicalStart == nullptr )
|
||||||
|
GEN_FATAL( "gen::init: Failed to initialize the string arena" );
|
||||||
|
array_append( ctx->StringArenas, strbuilder_arena );
|
||||||
|
}
|
||||||
|
// Setup the hash tables
|
||||||
|
{
|
||||||
|
ctx->StrCache = hashtable_init_reserve(StrCached, ctx->Allocator_DyanmicContainers, ctx->InitSize_StrCacheTable);
|
||||||
|
if ( ctx->StrCache.Entries == nullptr )
|
||||||
|
GEN_FATAL( "gen::init: Failed to initialize the StringCache");
|
||||||
|
|
||||||
|
ctx->Macros = hashtable_init_reserve(Macro, ctx->Allocator_DyanmicContainers, ctx->InitSize_MacrosTable);
|
||||||
|
if (ctx->Macros.Hashes == nullptr || ctx->Macros.Entries == nullptr) {
|
||||||
|
GEN_FATAL( "gen::init: Failed to initialize the PreprocessMacros table" );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
define_constants();
|
||||||
|
parser_init(ctx);
|
||||||
|
|
||||||
|
++ context_counter;
|
||||||
|
}
|
||||||
|
|
||||||
|
void deinit(Context* ctx)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(context_counter);
|
||||||
|
GEN_ASSERT_MSG(context_counter > 0, "Attempted to deinit a context that for some reason wan't accounted for!");
|
||||||
|
usize index = 0;
|
||||||
|
usize left = array_num(ctx->CodePools);
|
||||||
|
do
|
||||||
|
{
|
||||||
|
Pool* code_pool = & ctx->CodePools[index];
|
||||||
|
pool_free(code_pool);
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
while ( left--, left );
|
||||||
|
|
||||||
|
index = 0;
|
||||||
|
left = array_num(ctx->StringArenas);
|
||||||
|
do
|
||||||
|
{
|
||||||
|
Arena* strbuilder_arena = & ctx->StringArenas[index];
|
||||||
|
arena_free(strbuilder_arena);
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
while ( left--, left );
|
||||||
|
|
||||||
|
hashtable_destroy(ctx->StrCache);
|
||||||
|
|
||||||
|
array_free( ctx->CodePools);
|
||||||
|
array_free( ctx->StringArenas);
|
||||||
|
|
||||||
|
hashtable_destroy(ctx->Macros);
|
||||||
|
|
||||||
|
left = array_num( ctx->Fallback_AllocatorBuckets);
|
||||||
|
if (left)
|
||||||
|
{
|
||||||
|
index = 0;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
Arena* bucket = & ctx->Fallback_AllocatorBuckets[ index ];
|
||||||
|
arena_free(bucket);
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
while ( left--, left );
|
||||||
|
array_free( ctx->Fallback_AllocatorBuckets);
|
||||||
|
}
|
||||||
|
parser_deinit(ctx);
|
||||||
|
|
||||||
|
if (_ctx == ctx)
|
||||||
|
_ctx = nullptr;
|
||||||
|
-- context_counter;
|
||||||
|
|
||||||
|
Context wipe = {};
|
||||||
|
* ctx = wipe;
|
||||||
|
}
|
||||||
|
|
||||||
|
Context* get_context() {
|
||||||
|
return _ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
void reset(Context* ctx)
|
||||||
|
{
|
||||||
|
s32 index = 0;
|
||||||
|
s32 left = array_num(ctx->CodePools);
|
||||||
|
do
|
||||||
|
{
|
||||||
|
Pool* code_pool = & ctx->CodePools[index];
|
||||||
|
pool_clear(code_pool);
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
while ( left--, left );
|
||||||
|
|
||||||
|
index = 0;
|
||||||
|
left = array_num(ctx->StringArenas);
|
||||||
|
do
|
||||||
|
{
|
||||||
|
Arena* strbuilder_arena = & ctx->StringArenas[index];
|
||||||
|
strbuilder_arena->TotalUsed = 0;;
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
while ( left--, left );
|
||||||
|
|
||||||
|
hashtable_clear(ctx->StrCache);
|
||||||
|
hashtable_clear(ctx->Macros);
|
||||||
|
define_constants();
|
||||||
|
}
|
||||||
|
|
||||||
|
void set_context(Context* new_ctx) {
|
||||||
|
GEN_ASSERT(new_ctx);
|
||||||
|
_ctx = new_ctx;
|
||||||
|
}
|
||||||
|
|
||||||
|
AllocatorInfo get_cached_str_allocator( s32 str_length )
|
||||||
|
{
|
||||||
|
Arena* last = array_back(_ctx->StringArenas);
|
||||||
|
usize size_req = str_length + sizeof(StrBuilderHeader) + sizeof(char*);
|
||||||
|
if ( last->TotalUsed + scast(ssize, size_req) > last->TotalSize )
|
||||||
|
{
|
||||||
|
Arena new_arena = arena_init_from_allocator( _ctx->Allocator_StrCache, _ctx->SizePer_StringArena );
|
||||||
|
if ( ! array_append( _ctx->StringArenas, new_arena ) )
|
||||||
|
GEN_FATAL( "gen::get_cached_str_allocator: Failed to allocate a new string arena" );
|
||||||
|
|
||||||
|
last = array_back( _ctx->StringArenas);
|
||||||
|
}
|
||||||
|
return arena_allocator_info(last);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Will either make or retrive a code string.
|
||||||
|
StrCached cache_str( Str str )
|
||||||
|
{
|
||||||
|
if (str.Len > _ctx->Max_StrCacheLength) {
|
||||||
|
// Do not cache the string, just shove into the arena and and return it.
|
||||||
|
Str result = strbuilder_to_str( strbuilder_make_str( get_cached_str_allocator( str.Len ), str ));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
u64 key = crc32( str.Ptr, str.Len ); {
|
||||||
|
StrCached* result = hashtable_get( _ctx->StrCache, key );
|
||||||
|
if ( result )
|
||||||
|
return * result;
|
||||||
|
}
|
||||||
|
Str result = strbuilder_to_str( strbuilder_make_str( get_cached_str_allocator( str.Len ), str ));
|
||||||
|
hashtable_set( _ctx->StrCache, key, result );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Used internally to retireve a Code object form the CodePool.
|
||||||
|
Code make_code()
|
||||||
|
{
|
||||||
|
Pool* allocator = array_back( _ctx->CodePools);
|
||||||
|
if ( allocator->FreeList == nullptr )
|
||||||
|
{
|
||||||
|
Pool code_pool = pool_init( _ctx->Allocator_Pool, _ctx->CodePool_NumBlocks, sizeof(AST) );
|
||||||
|
|
||||||
|
if ( code_pool.PhysicalStart == nullptr )
|
||||||
|
GEN_FATAL( "gen::make_code: Failed to allocate a new code pool - CodePool allcoator returned nullptr." );
|
||||||
|
|
||||||
|
if ( ! array_append( _ctx->CodePools, code_pool ) )
|
||||||
|
GEN_FATAL( "gen::make_code: Failed to allocate a new code pool - CodePools failed to append new pool." );
|
||||||
|
|
||||||
|
allocator = array_back( _ctx->CodePools);
|
||||||
|
}
|
||||||
|
Code result = { rcast( AST*, alloc( pool_allocator_info(allocator), sizeof(AST) )) };
|
||||||
|
mem_set( rcast(void*, cast(AST*, result)), 0, sizeof(AST) );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
Macro* lookup_macro( Str name ) {
|
||||||
|
u32 key = crc32( name.Ptr, name.Len );
|
||||||
|
return hashtable_get( _ctx->Macros, key );
|
||||||
|
}
|
||||||
|
|
||||||
|
void register_macro( Macro macro ) {
|
||||||
|
GEN_ASSERT_NOT_NULL(macro.Name.Ptr);
|
||||||
|
GEN_ASSERT(macro.Name.Len > 0);
|
||||||
|
u32 key = crc32( macro.Name.Ptr, macro.Name.Len );
|
||||||
|
macro.Name = cache_str(macro.Name);
|
||||||
|
hashtable_set( _ctx->Macros, key, macro );
|
||||||
|
}
|
||||||
|
|
||||||
|
void register_macros( s32 num, ... )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(num > 0);
|
||||||
|
va_list va;
|
||||||
|
va_start(va, num);
|
||||||
|
do
|
||||||
|
{
|
||||||
|
Macro macro = va_arg(va, Macro);
|
||||||
|
GEN_ASSERT_NOT_NULL(macro.Name.Ptr);
|
||||||
|
GEN_ASSERT(macro.Name.Len > 0);
|
||||||
|
macro.Name = cache_str(macro.Name);
|
||||||
|
|
||||||
|
u32 key = crc32( macro.Name.Ptr, macro.Name.Len );
|
||||||
|
hashtable_set( _ctx->Macros, key, macro );
|
||||||
|
}
|
||||||
|
while (num--, num > 0);
|
||||||
|
va_end(va);
|
||||||
|
}
|
||||||
|
|
||||||
|
void register_macros_arr( s32 num, Macro* macros )
|
||||||
|
{
|
||||||
|
GEN_ASSERT(num > 0);
|
||||||
|
do
|
||||||
|
{
|
||||||
|
Macro macro = * macros;
|
||||||
|
GEN_ASSERT_NOT_NULL(macro.Name.Ptr);
|
||||||
|
GEN_ASSERT(macro.Name.Len > 0);
|
||||||
|
macro.Name = cache_str(macro.Name);
|
||||||
|
|
||||||
|
u32 key = crc32( macro.Name.Ptr, macro.Name.Len );
|
||||||
|
hashtable_set( _ctx->Macros, key, macro );
|
||||||
|
++ macros;
|
||||||
|
}
|
||||||
|
while (num--, num > 0);
|
||||||
|
}
|
||||||
@@ -0,0 +1,490 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
#pragma once
|
||||||
|
#include "ast_types.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Gen Interface
|
||||||
|
/*
|
||||||
|
/ \ | \ | \ / \
|
||||||
|
| ▓▓▓▓▓▓\ ______ _______ \▓▓▓▓▓▓_______ _| ▓▓_ ______ ______ | ▓▓▓▓▓▓\ ______ _______ ______
|
||||||
|
| ▓▓ __\▓▓/ \| \ | ▓▓ | \| ▓▓ \ / \ / \| ▓▓_ \▓▓| \ / \/ \
|
||||||
|
| ▓▓| \ ▓▓▓▓▓▓\ ▓▓▓▓▓▓▓\ | ▓▓ | ▓▓▓▓▓▓▓\\▓▓▓▓▓▓ | ▓▓▓▓▓▓\ ▓▓▓▓▓▓\ ▓▓ \ \▓▓▓▓▓▓\ ▓▓▓▓▓▓▓ ▓▓▓▓▓▓\
|
||||||
|
| ▓▓ \▓▓▓▓ ▓▓ ▓▓ ▓▓ | ▓▓ | ▓▓ | ▓▓ | ▓▓ | ▓▓ __| ▓▓ ▓▓ ▓▓ \▓▓ ▓▓▓▓ / ▓▓ ▓▓ | ▓▓ ▓▓
|
||||||
|
| ▓▓__| ▓▓ ▓▓▓▓▓▓▓▓ ▓▓ | ▓▓ _| ▓▓_| ▓▓ | ▓▓ | ▓▓| \ ▓▓▓▓▓▓▓▓ ▓▓ | ▓▓ | ▓▓▓▓▓▓▓ ▓▓_____| ▓▓▓▓▓▓▓▓
|
||||||
|
\▓▓ ▓▓\▓▓ \ ▓▓ | ▓▓ | ▓▓ \ ▓▓ | ▓▓ \▓▓ ▓▓\▓▓ \ ▓▓ | ▓▓ \▓▓ ▓▓\▓▓ \\▓▓ \
|
||||||
|
\▓▓▓▓▓▓ \▓▓▓▓▓▓▓\▓▓ \▓▓ \▓▓▓▓▓▓\▓▓ \▓▓ \▓▓▓▓ \▓▓▓▓▓▓▓\▓▓ \▓▓ \▓▓▓▓▓▓▓ \▓▓▓▓▓▓▓ \▓▓▓▓▓▓▓
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Note(Ed): This is subject to heavily change
|
||||||
|
// with upcoming changes to the library's fallback (default) allocations strategy;
|
||||||
|
// and major changes to lexer/parser context usage.
|
||||||
|
struct Context
|
||||||
|
{
|
||||||
|
// User Configuration
|
||||||
|
|
||||||
|
// Persistent Data Allocation
|
||||||
|
AllocatorInfo Allocator_DyanmicContainers; // By default will use a genral slab allocator (TODO(Ed): Currently does not)
|
||||||
|
AllocatorInfo Allocator_Pool; // By default will use the growing vmem reserve (TODO(Ed): Currently does not)
|
||||||
|
AllocatorInfo Allocator_StrCache; // By default will use a dedicated slab allocator (TODO(Ed): Currently does not)
|
||||||
|
|
||||||
|
// Temporary Allocation
|
||||||
|
AllocatorInfo Allocator_Temp;
|
||||||
|
|
||||||
|
// LoggerCallaback* log_callback; // TODO(Ed): Impl user logger callback as an option.
|
||||||
|
|
||||||
|
// Initalization config
|
||||||
|
u32 Max_CommentLineLength; // Used by def_comment
|
||||||
|
u32 Max_StrCacheLength; // Any cached string longer than this is always allocated again.
|
||||||
|
|
||||||
|
u32 InitSize_BuilderBuffer;
|
||||||
|
u32 InitSize_CodePoolsArray;
|
||||||
|
u32 InitSize_StringArenasArray;
|
||||||
|
|
||||||
|
u32 CodePool_NumBlocks;
|
||||||
|
|
||||||
|
// TODO(Ed): Review these... (No longer needed if using the proper allocation strategy)
|
||||||
|
u32 InitSize_LexerTokens;
|
||||||
|
u32 SizePer_StringArena;
|
||||||
|
|
||||||
|
u32 InitSize_StrCacheTable;
|
||||||
|
u32 InitSize_MacrosTable;
|
||||||
|
|
||||||
|
// TODO(Ed): Symbol Table
|
||||||
|
// Keep track of all resolved symbols (naemspaced identifiers)
|
||||||
|
|
||||||
|
// Logging
|
||||||
|
|
||||||
|
LoggerProc* Logger;
|
||||||
|
|
||||||
|
// Parser
|
||||||
|
|
||||||
|
// Used by the lexer to persistently treat all these identifiers as preprocessor defines.
|
||||||
|
// Populate with strings via gen::cache_str.
|
||||||
|
// Functional defines must have format: id( ;at minimum to indicate that the define is only valid with arguments.
|
||||||
|
MacroTable Macros;
|
||||||
|
|
||||||
|
// Backend
|
||||||
|
|
||||||
|
// The fallback allocator is utilized if any fo the three above allocators is not specified by the user.
|
||||||
|
u32 InitSize_Fallback_Allocator_Bucket_Size;
|
||||||
|
Array(Arena) Fallback_AllocatorBuckets;
|
||||||
|
|
||||||
|
StringTable token_fmt_map;
|
||||||
|
|
||||||
|
// Array(Token) LexerTokens;
|
||||||
|
|
||||||
|
Array(Pool) CodePools;
|
||||||
|
Array(Arena) StringArenas;
|
||||||
|
|
||||||
|
StringTable StrCache;
|
||||||
|
|
||||||
|
// TODO(Ed): Active parse context vs a parse result need to be separated conceptually
|
||||||
|
ParseContext parser;
|
||||||
|
|
||||||
|
// TODO(Ed): Formatting - This will eventually be in a separate struct when in the process of serialization of the builder.
|
||||||
|
s32 temp_serialize_indent;
|
||||||
|
};
|
||||||
|
|
||||||
|
// TODO(Ed): Eventually this library should opt out of an implicit context for baseline implementation
|
||||||
|
// This would automatically make it viable for multi-threaded purposes among other things
|
||||||
|
// An implicit context interface will be provided instead as wrapper procedures as convience.
|
||||||
|
GEN_API extern Context* _ctx;
|
||||||
|
|
||||||
|
// TODO(Ed): Swap all usage of this with logger_fmt (then rename logger_fmt to log_fmt)
|
||||||
|
inline
|
||||||
|
ssize log_fmt(char const* fmt, ...)
|
||||||
|
{
|
||||||
|
ssize res;
|
||||||
|
va_list va;
|
||||||
|
|
||||||
|
va_start(va, fmt);
|
||||||
|
res = c_str_fmt_out_va(fmt, va);
|
||||||
|
va_end(va);
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void logger_fmt(Context* ctx, LogLevel level, char const* fmt, ...)
|
||||||
|
{
|
||||||
|
local_persist thread_local
|
||||||
|
PrintF_Buffer buf = struct_zero_init();
|
||||||
|
|
||||||
|
va_list va;
|
||||||
|
va_start(va, fmt);
|
||||||
|
ssize res = c_str_fmt_va(buf, GEN_PRINTF_MAXLEN, fmt, va) -1;
|
||||||
|
va_end(va);
|
||||||
|
|
||||||
|
StrBuilder msg = strbuilder_make_length(ctx->Allocator_Temp, buf, res);
|
||||||
|
|
||||||
|
LogEntry entry = { strbuilder_to_str(msg), level };
|
||||||
|
ctx->Logger(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize the library. There first ctx initialized must exist for lifetime of other contextes that come after as its the one that
|
||||||
|
GEN_API void init(Context* ctx);
|
||||||
|
|
||||||
|
// Currently manually free's the arenas, code for checking for leaks.
|
||||||
|
// However on Windows at least, it doesn't need to occur as the OS will clean up after the process.
|
||||||
|
GEN_API void deinit(Context* ctx);
|
||||||
|
|
||||||
|
// Retrieves the active context (not usually needed, but here in case...)
|
||||||
|
GEN_API Context* get_context();
|
||||||
|
|
||||||
|
// Clears the allocations, but doesn't free the memory, then calls init() again.
|
||||||
|
// Ease of use.
|
||||||
|
GEN_API void reset(Context* ctx);
|
||||||
|
|
||||||
|
GEN_API void set_context(Context* ctx);
|
||||||
|
|
||||||
|
// Mostly intended for the parser
|
||||||
|
GEN_API Macro* lookup_macro( Str Name );
|
||||||
|
|
||||||
|
// Alternative way to add a preprocess define entry for the lexer & parser to utilize
|
||||||
|
// if the user doesn't want to use def_define
|
||||||
|
// Macros are tracked by name so if the name already exists the entry will be overwritten.
|
||||||
|
GEN_API void register_macro( Macro macro );
|
||||||
|
|
||||||
|
// Ease of use batch registration
|
||||||
|
GEN_API void register_macros( s32 num, ... );
|
||||||
|
GEN_API void register_macros_arr( s32 num, Macro* macros );
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
forceinline void register_macros( s32 num, Macro* macros ) { return register_macros_arr(num, macros); }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Used internally to retrive or make string allocations.
|
||||||
|
// Strings are stored in a series of string arenas of fixed size (SizePer_StringArena)
|
||||||
|
GEN_API StrCached cache_str( Str str );
|
||||||
|
|
||||||
|
/*
|
||||||
|
This provides a fresh Code AST.
|
||||||
|
The gen interface use this as their method from getting a new AST object from the CodePool.
|
||||||
|
Use this if you want to make your own API for formatting the supported Code Types.
|
||||||
|
*/
|
||||||
|
GEN_API Code make_code();
|
||||||
|
|
||||||
|
// Set these before calling gen's init() procedure.
|
||||||
|
|
||||||
|
#pragma region Upfront
|
||||||
|
|
||||||
|
GEN_API CodeAttributes def_attributes( Str content );
|
||||||
|
GEN_API CodeComment def_comment ( Str content );
|
||||||
|
|
||||||
|
struct Opts_def_struct {
|
||||||
|
CodeBody body;
|
||||||
|
CodeTypename parent;
|
||||||
|
AccessSpec parent_access;
|
||||||
|
CodeAttributes attributes;
|
||||||
|
CodeTypename* interfaces;
|
||||||
|
s32 num_interfaces;
|
||||||
|
CodeSpecifiers specifiers; // Only used for final specifier for now.
|
||||||
|
ModuleFlag mflags;
|
||||||
|
};
|
||||||
|
GEN_API CodeClass def_class( Str name, Opts_def_struct opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_constructor {
|
||||||
|
CodeParams params;
|
||||||
|
Code initializer_list;
|
||||||
|
Code body;
|
||||||
|
};
|
||||||
|
GEN_API CodeConstructor def_constructor( Opts_def_constructor opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_define {
|
||||||
|
CodeDefineParams params;
|
||||||
|
Str content;
|
||||||
|
MacroFlags flags;
|
||||||
|
b32 dont_register_to_preprocess_macros;
|
||||||
|
};
|
||||||
|
GEN_API CodeDefine def_define( Str name, MacroType type, Opts_def_define opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_destructor {
|
||||||
|
Code body;
|
||||||
|
CodeSpecifiers specifiers;
|
||||||
|
};
|
||||||
|
GEN_API CodeDestructor def_destructor( Opts_def_destructor opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_enum {
|
||||||
|
CodeBody body;
|
||||||
|
CodeTypename type;
|
||||||
|
EnumT specifier;
|
||||||
|
CodeAttributes attributes;
|
||||||
|
ModuleFlag mflags;
|
||||||
|
Code type_macro;
|
||||||
|
};
|
||||||
|
GEN_API CodeEnum def_enum( Str name, Opts_def_enum opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
GEN_API CodeExec def_execution ( Str content );
|
||||||
|
GEN_API CodeExtern def_extern_link( Str name, CodeBody body );
|
||||||
|
GEN_API CodeFriend def_friend ( Code code );
|
||||||
|
|
||||||
|
struct Opts_def_function {
|
||||||
|
CodeParams params;
|
||||||
|
CodeTypename ret_type;
|
||||||
|
CodeBody body;
|
||||||
|
CodeSpecifiers specs;
|
||||||
|
CodeAttributes attrs;
|
||||||
|
ModuleFlag mflags;
|
||||||
|
};
|
||||||
|
GEN_API CodeFn def_function( Str name, Opts_def_function opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_include { b32 foreign; };
|
||||||
|
struct Opts_def_module { ModuleFlag mflags; };
|
||||||
|
struct Opts_def_namespace { ModuleFlag mflags; };
|
||||||
|
GEN_API CodeInclude def_include ( Str content, Opts_def_include opts GEN_PARAM_DEFAULT );
|
||||||
|
GEN_API CodeModule def_module ( Str name, Opts_def_module opts GEN_PARAM_DEFAULT );
|
||||||
|
GEN_API CodeNS def_namespace( Str name, CodeBody body, Opts_def_namespace opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_operator {
|
||||||
|
CodeParams params;
|
||||||
|
CodeTypename ret_type;
|
||||||
|
CodeBody body;
|
||||||
|
CodeSpecifiers specifiers;
|
||||||
|
CodeAttributes attributes;
|
||||||
|
ModuleFlag mflags;
|
||||||
|
};
|
||||||
|
GEN_API CodeOperator def_operator( Operator op, Str nspace, Opts_def_operator opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_operator_cast {
|
||||||
|
CodeBody body;
|
||||||
|
CodeSpecifiers specs;
|
||||||
|
};
|
||||||
|
GEN_API CodeOpCast def_operator_cast( CodeTypename type, Opts_def_operator_cast opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_param { Code value; };
|
||||||
|
GEN_API CodeParams def_param ( CodeTypename type, Str name, Opts_def_param opts GEN_PARAM_DEFAULT );
|
||||||
|
GEN_API CodePragma def_pragma( Str directive );
|
||||||
|
|
||||||
|
GEN_API CodePreprocessCond def_preprocess_cond( EPreprocessCond type, Str content );
|
||||||
|
|
||||||
|
GEN_API CodeSpecifiers def_specifier( Specifier specifier );
|
||||||
|
|
||||||
|
GEN_API CodeStruct def_struct( Str name, Opts_def_struct opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_template { ModuleFlag mflags; };
|
||||||
|
GEN_API CodeTemplate def_template( CodeParams params, Code definition, Opts_def_template opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_type {
|
||||||
|
ETypenameTag type_tag;
|
||||||
|
Code array_expr;
|
||||||
|
CodeSpecifiers specifiers;
|
||||||
|
CodeAttributes attributes;
|
||||||
|
};
|
||||||
|
GEN_API CodeTypename def_type( Str name, Opts_def_type opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_typedef {
|
||||||
|
CodeAttributes attributes;
|
||||||
|
ModuleFlag mflags;
|
||||||
|
};
|
||||||
|
GEN_API CodeTypedef def_typedef( Str name, Code type, Opts_def_typedef opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_union {
|
||||||
|
CodeAttributes attributes;
|
||||||
|
ModuleFlag mflags;
|
||||||
|
};
|
||||||
|
GEN_API CodeUnion def_union( Str name, CodeBody body, Opts_def_union opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
struct Opts_def_using {
|
||||||
|
CodeAttributes attributes;
|
||||||
|
ModuleFlag mflags;
|
||||||
|
};
|
||||||
|
GEN_API CodeUsing def_using( Str name, CodeTypename type, Opts_def_using opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
GEN_API CodeUsing def_using_namespace( Str name );
|
||||||
|
|
||||||
|
struct Opts_def_variable
|
||||||
|
{
|
||||||
|
Code value;
|
||||||
|
CodeSpecifiers specifiers;
|
||||||
|
CodeAttributes attributes;
|
||||||
|
ModuleFlag mflags;
|
||||||
|
};
|
||||||
|
GEN_API CodeVar def_variable( CodeTypename type, Str name, Opts_def_variable opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
// Constructs an empty body. Use AST::validate_body() to check if the body is was has valid entries.
|
||||||
|
CodeBody def_body( CodeType type );
|
||||||
|
|
||||||
|
// There are two options for defining a struct body, either varadically provided with the args macro to auto-deduce the arg num,
|
||||||
|
/// or provide as an array of Code objects.
|
||||||
|
|
||||||
|
GEN_API CodeBody def_class_body ( s32 num, ... );
|
||||||
|
GEN_API CodeBody def_class_body_arr ( s32 num, Code* codes );
|
||||||
|
GEN_API CodeDefineParams def_define_params ( s32 num, ... );
|
||||||
|
GEN_API CodeDefineParams def_define_params_arr ( s32 num, CodeDefineParams* codes );
|
||||||
|
GEN_API CodeBody def_enum_body ( s32 num, ... );
|
||||||
|
GEN_API CodeBody def_enum_body_arr ( s32 num, Code* codes );
|
||||||
|
GEN_API CodeBody def_export_body ( s32 num, ... );
|
||||||
|
GEN_API CodeBody def_export_body_arr ( s32 num, Code* codes);
|
||||||
|
GEN_API CodeBody def_extern_link_body ( s32 num, ... );
|
||||||
|
GEN_API CodeBody def_extern_link_body_arr ( s32 num, Code* codes );
|
||||||
|
GEN_API CodeBody def_function_body ( s32 num, ... );
|
||||||
|
GEN_API CodeBody def_function_body_arr ( s32 num, Code* codes );
|
||||||
|
GEN_API CodeBody def_global_body ( s32 num, ... );
|
||||||
|
GEN_API CodeBody def_global_body_arr ( s32 num, Code* codes );
|
||||||
|
GEN_API CodeBody def_namespace_body ( s32 num, ... );
|
||||||
|
GEN_API CodeBody def_namespace_body_arr ( s32 num, Code* codes );
|
||||||
|
GEN_API CodeParams def_params ( s32 num, ... );
|
||||||
|
GEN_API CodeParams def_params_arr ( s32 num, CodeParams* params );
|
||||||
|
GEN_API CodeSpecifiers def_specifiers ( s32 num, ... );
|
||||||
|
GEN_API CodeSpecifiers def_specifiers_arr ( s32 num, Specifier* specs );
|
||||||
|
GEN_API CodeBody def_struct_body ( s32 num, ... );
|
||||||
|
GEN_API CodeBody def_struct_body_arr ( s32 num, Code* codes );
|
||||||
|
GEN_API CodeBody def_union_body ( s32 num, ... );
|
||||||
|
GEN_API CodeBody def_union_body_arr ( s32 num, Code* codes );
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
forceinline CodeBody def_class_body ( s32 num, Code* codes ) { return def_class_body_arr(num, codes); }
|
||||||
|
forceinline CodeDefineParams def_define_params ( s32 num, CodeDefineParams* codes ) { return def_define_params_arr(num, codes); }
|
||||||
|
forceinline CodeBody def_enum_body ( s32 num, Code* codes ) { return def_enum_body_arr(num, codes); }
|
||||||
|
forceinline CodeBody def_export_body ( s32 num, Code* codes) { return def_export_body_arr(num, codes); }
|
||||||
|
forceinline CodeBody def_extern_link_body( s32 num, Code* codes ) { return def_extern_link_body_arr(num, codes); }
|
||||||
|
forceinline CodeBody def_function_body ( s32 num, Code* codes ) { return def_function_body_arr(num, codes); }
|
||||||
|
forceinline CodeBody def_global_body ( s32 num, Code* codes ) { return def_global_body_arr(num, codes); }
|
||||||
|
forceinline CodeBody def_namespace_body ( s32 num, Code* codes ) { return def_namespace_body_arr(num, codes); }
|
||||||
|
forceinline CodeParams def_params ( s32 num, CodeParams* params ) { return def_params_arr(num, params); }
|
||||||
|
forceinline CodeSpecifiers def_specifiers ( s32 num, Specifier* specs ) { return def_specifiers_arr(num, specs); }
|
||||||
|
forceinline CodeBody def_struct_body ( s32 num, Code* codes ) { return def_struct_body_arr(num, codes); }
|
||||||
|
forceinline CodeBody def_union_body ( s32 num, Code* codes ) { return def_union_body_arr(num, codes); }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Upfront
|
||||||
|
|
||||||
|
#pragma region Parsing
|
||||||
|
|
||||||
|
struct ParseStackNode
|
||||||
|
{
|
||||||
|
ParseStackNode* prev;
|
||||||
|
|
||||||
|
TokenSlice tokens;
|
||||||
|
Token* start;
|
||||||
|
Str name; // The name of the AST node (if parsed)
|
||||||
|
Str proc_name; // The name of the procedure
|
||||||
|
Code code_rel; // Relevant AST node
|
||||||
|
// TODO(Ed): When an error occurs, the parse stack is not released and instead the scope is left dangling.
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ParseInfo
|
||||||
|
{
|
||||||
|
ParseMessage* messages;
|
||||||
|
LexedInfo lexed;
|
||||||
|
Code result;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ParseOpts
|
||||||
|
{
|
||||||
|
AllocatorInfo backing_msgs;
|
||||||
|
AllocatorInfo backing_tokens;
|
||||||
|
AllocatorInfo backing_ast;
|
||||||
|
};
|
||||||
|
|
||||||
|
ParseInfo wip_parse_str( LexedInfo lexed, ParseOpts* opts GEN_PARAM_DEFAULT );
|
||||||
|
|
||||||
|
GEN_API CodeClass parse_class ( Str class_def );
|
||||||
|
GEN_API CodeConstructor parse_constructor ( Str constructor_def );
|
||||||
|
GEN_API CodeDefine parse_define ( Str define_def );
|
||||||
|
GEN_API CodeDestructor parse_destructor ( Str destructor_def );
|
||||||
|
GEN_API CodeEnum parse_enum ( Str enum_def );
|
||||||
|
GEN_API CodeBody parse_export_body ( Str export_def );
|
||||||
|
GEN_API CodeExtern parse_extern_link ( Str exten_link_def );
|
||||||
|
GEN_API CodeFriend parse_friend ( Str friend_def );
|
||||||
|
GEN_API CodeFn parse_function ( Str fn_def );
|
||||||
|
GEN_API CodeBody parse_global_body ( Str body_def );
|
||||||
|
GEN_API CodeNS parse_namespace ( Str namespace_def );
|
||||||
|
GEN_API CodeOperator parse_operator ( Str operator_def );
|
||||||
|
GEN_API CodeOpCast parse_operator_cast( Str operator_def );
|
||||||
|
GEN_API CodeStruct parse_struct ( Str struct_def );
|
||||||
|
GEN_API CodeTemplate parse_template ( Str template_def );
|
||||||
|
GEN_API CodeTypename parse_type ( Str type_def );
|
||||||
|
GEN_API CodeTypedef parse_typedef ( Str typedef_def );
|
||||||
|
GEN_API CodeUnion parse_union ( Str union_def );
|
||||||
|
GEN_API CodeUsing parse_using ( Str using_def );
|
||||||
|
GEN_API CodeVar parse_variable ( Str var_def );
|
||||||
|
|
||||||
|
#pragma endregion Parsing
|
||||||
|
|
||||||
|
#pragma region Untyped text
|
||||||
|
|
||||||
|
GEN_API ssize token_fmt_va( char* buf, usize buf_size, s32 num_tokens, va_list va );
|
||||||
|
//! Do not use directly. Use the token_fmt macro instead.
|
||||||
|
Str token_fmt_impl( ssize, ... );
|
||||||
|
|
||||||
|
GEN_API Code untyped_str ( Str content);
|
||||||
|
GEN_API Code untyped_fmt ( char const* fmt, ... );
|
||||||
|
GEN_API Code untyped_token_fmt( s32 num_tokens, char const* fmt, ... );
|
||||||
|
GEN_API Code untyped_toks ( TokenSlice tokens );
|
||||||
|
|
||||||
|
#pragma endregion Untyped text
|
||||||
|
|
||||||
|
#pragma region Macros
|
||||||
|
|
||||||
|
#ifndef gen_main
|
||||||
|
#define gen_main main
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef name
|
||||||
|
// Convienence for defining any name used with the gen api.
|
||||||
|
// Lets you provide the length and string literal to the functions without the need for the DSL.
|
||||||
|
# if GEN_COMPILER_C
|
||||||
|
# define name( Id_ ) (Str){ stringize(Id_), sizeof(stringize( Id_ )) - 1 }
|
||||||
|
# else
|
||||||
|
# define name( Id_ ) Str { stringize(Id_), sizeof(stringize( Id_ )) - 1 }
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef code
|
||||||
|
// Same as name just used to indicate intention of literal for code instead of names.
|
||||||
|
# if GEN_COMPILER_C
|
||||||
|
# define code( ... ) (Str){ stringize( __VA_ARGS__ ), sizeof(stringize(__VA_ARGS__)) - 1 }
|
||||||
|
# else
|
||||||
|
# define code( ... ) Str { stringize( __VA_ARGS__ ), sizeof(stringize(__VA_ARGS__)) - 1 }
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef args
|
||||||
|
// Provides the number of arguments while passing args inplace.
|
||||||
|
#define args( ... ) num_args( __VA_ARGS__ ), __VA_ARGS__
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef code_str
|
||||||
|
// Just wrappers over common untyped code definition constructions.
|
||||||
|
#define code_str( ... ) GEN_NS untyped_str( code( __VA_ARGS__ ) )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef code_fmt
|
||||||
|
#define code_fmt( ... ) GEN_NS untyped_str( token_fmt( __VA_ARGS__ ) )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef parse_fmt
|
||||||
|
#define parse_fmt( type, ... ) GEN_NS parse_##type( token_fmt( __VA_ARGS__ ) )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef token_fmt
|
||||||
|
/*
|
||||||
|
Takes a format string (char const*) and a list of tokens (Str) and returns a Str of the formatted string.
|
||||||
|
Tokens are provided in '<'identifier'>' format where '<' '>' are just angle brackets (you can change it in token_fmt_va)
|
||||||
|
---------------------------------------------------------
|
||||||
|
Example - A string with:
|
||||||
|
typedef <type> <name> <name>;
|
||||||
|
Will have a token_fmt arguments populated with:
|
||||||
|
"type", str_for_type,
|
||||||
|
"name", str_for_name,
|
||||||
|
and:
|
||||||
|
stringize( typedef <type> <name> <name>; )
|
||||||
|
-----------------------------------------------------------
|
||||||
|
So the full call for this example would be:
|
||||||
|
token_fmt(
|
||||||
|
"type", str_for_type
|
||||||
|
, "name", str_for_name
|
||||||
|
, stringize(
|
||||||
|
typedef <type> <name> <name>
|
||||||
|
));
|
||||||
|
!----------------------------------------------------------
|
||||||
|
! Note: token_fmt_va is whitespace sensitive for the tokens.
|
||||||
|
! This can be alleviated by skipping whitespace between brackets but it was choosen to not have that implementation by default.
|
||||||
|
*/
|
||||||
|
#define token_fmt( ... ) GEN_NS token_fmt_impl( (num_args( __VA_ARGS__ ) + 1) / 2, __VA_ARGS__ )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Macros
|
||||||
|
|
||||||
|
#pragma endregion Gen Interface
|
||||||
@@ -0,0 +1,473 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
#pragma once
|
||||||
|
#include "gen/etoktype.hpp"
|
||||||
|
#include "interface.upfront.cpp"
|
||||||
|
#include "lexer.cpp"
|
||||||
|
#include "parser.cpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Publically Exposed Interface
|
||||||
|
|
||||||
|
ParseInfo wip_parse_str(LexedInfo lexed, ParseOpts* opts)
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
if (lexed.tokens.num == 0 && lexed.tokens.ptr == nullptr) {
|
||||||
|
check_parse_args(lexed.text);
|
||||||
|
lexed = lex(ctx, lexed.text);
|
||||||
|
}
|
||||||
|
ParseInfo info = struct_zero(ParseInfo);
|
||||||
|
info.lexed = lexed;
|
||||||
|
|
||||||
|
// TODO(Ed): ParseInfo should be set to the parser context.
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
|
||||||
|
ParseStackNode scope = NullScope;
|
||||||
|
parser_push(& ctx->parser, & scope);
|
||||||
|
|
||||||
|
CodeBody result = parse_global_nspace(ctx,CT_Global_Body);
|
||||||
|
|
||||||
|
parser_pop(& ctx->parser);
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeClass parse_class( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
ParseStackNode scope = NullScope;
|
||||||
|
parser_push(& ctx->parser, & scope);
|
||||||
|
CodeClass result = (CodeClass) parse_class_struct( ctx, Tok_Decl_Class, parser_not_inplace_def );
|
||||||
|
parser_pop(& ctx->parser);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeConstructor parse_constructor(Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
ParseStackNode scope = NullScope;
|
||||||
|
parser_push(& ctx->parser, & scope);
|
||||||
|
|
||||||
|
// TODO(Ed): Constructors can have prefix attributes
|
||||||
|
|
||||||
|
CodeSpecifiers specifiers = NullCode;
|
||||||
|
Specifier specs_found[ 16 ] = { Spec_NumSpecifiers };
|
||||||
|
s32 NumSpecifiers = 0;
|
||||||
|
|
||||||
|
while ( left && tok_is_specifier(currtok) )
|
||||||
|
{
|
||||||
|
Specifier spec = str_to_specifier( currtok.Text );
|
||||||
|
|
||||||
|
b32 ignore_spec = false;
|
||||||
|
|
||||||
|
switch ( spec )
|
||||||
|
{
|
||||||
|
case Spec_Constexpr :
|
||||||
|
case Spec_Explicit:
|
||||||
|
case Spec_Inline :
|
||||||
|
case Spec_ForceInline :
|
||||||
|
case Spec_NeverInline :
|
||||||
|
break;
|
||||||
|
|
||||||
|
case Spec_Const :
|
||||||
|
ignore_spec = true;
|
||||||
|
break;
|
||||||
|
|
||||||
|
default :
|
||||||
|
log_failure( "Invalid specifier %s for variable\n%S", spec_to_str( spec ), parser_to_strbuilder(& ctx->parser, ctx->Allocator_Temp) );
|
||||||
|
parser_pop(& ctx->parser);
|
||||||
|
return InvalidCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every specifier after would be considered part of the type type signature
|
||||||
|
if (ignore_spec)
|
||||||
|
break;
|
||||||
|
|
||||||
|
specs_found[ NumSpecifiers ] = spec;
|
||||||
|
NumSpecifiers++;
|
||||||
|
eat( currtok.Type );
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( NumSpecifiers ) {
|
||||||
|
specifiers = def_specifiers_arr( NumSpecifiers, specs_found );
|
||||||
|
// <specifiers> ...
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeConstructor result = parser_parse_constructor(ctx, specifiers);
|
||||||
|
parser_pop(& ctx->parser);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeDefine parse_define( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
ParseStackNode scope = NullScope;
|
||||||
|
parser_push(& ctx->parser, & scope);
|
||||||
|
CodeDefine result = parser_parse_define(ctx);
|
||||||
|
parser_pop(& ctx->parser);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeDestructor parse_destructor( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
// TODO(Ed): Destructors can have prefix attributes
|
||||||
|
// TODO(Ed): Destructors can have virtual
|
||||||
|
|
||||||
|
CodeDestructor result = parser_parse_destructor(ctx, NullCode);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeEnum parse_enum( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr ) {
|
||||||
|
return InvalidCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
return parser_parse_enum(ctx, parser_not_inplace_def);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeBody parse_export_body( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return parser_parse_export_body(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeExtern parse_extern_link( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return parser_parse_extern_link(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeFriend parse_friend( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return parser_parse_friend(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeFn parse_function( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return (CodeFn) parser_parse_function(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeBody parse_global_body( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
ParseStackNode scope = NullScope;
|
||||||
|
parser_push(& ctx->parser, & scope);
|
||||||
|
CodeBody result = parse_global_nspace(ctx, CT_Global_Body );
|
||||||
|
parser_pop(& ctx->parser);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeNS parse_namespace( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return parser_parse_namespace(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeOperator parse_operator( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return (CodeOperator) parser_parse_operator(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeOpCast parse_operator_cast( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return parser_parse_operator_cast(ctx, NullCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeStruct parse_struct( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
ParseStackNode scope = NullScope;
|
||||||
|
parser_push(& ctx->parser, & scope);
|
||||||
|
CodeStruct result = (CodeStruct) parse_class_struct( ctx, Tok_Decl_Struct, parser_not_inplace_def );
|
||||||
|
parser_pop(& ctx->parser);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeTemplate parse_template( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return parser_parse_template(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeTypename parse_type( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return parser_parse_type( ctx, parser_not_from_template, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeTypedef parse_typedef( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return parser_parse_typedef(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeUnion parse_union( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return parser_parse_union(ctx, parser_not_inplace_def);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeUsing parse_using( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return parser_parse_using(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
CodeVar parse_variable( Str def )
|
||||||
|
{
|
||||||
|
// TODO(Ed): Lift this.
|
||||||
|
Context* ctx = _ctx;
|
||||||
|
|
||||||
|
check_parse_args( def );
|
||||||
|
|
||||||
|
ctx->parser = struct_zero(ParseContext);
|
||||||
|
|
||||||
|
LexedInfo lexed = lex(ctx, def);
|
||||||
|
ctx->parser.tokens = lexed.tokens;
|
||||||
|
if ( ctx->parser.tokens.ptr == nullptr )
|
||||||
|
return InvalidCode;
|
||||||
|
|
||||||
|
return parser_parse_variable(ctx);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Undef helper macros
|
||||||
|
#undef check_parse_args
|
||||||
|
#undef currtok_noskip
|
||||||
|
#undef currtok
|
||||||
|
#undef peektok
|
||||||
|
#undef prevtok
|
||||||
|
#undef nexttok
|
||||||
|
#undef nexttok_noskip
|
||||||
|
#undef eat
|
||||||
|
#undef left
|
||||||
|
#undef check
|
||||||
|
#undef push_scope
|
||||||
|
#undef NullScope
|
||||||
|
#undef def_assign
|
||||||
|
|
||||||
|
// Here for C Variant
|
||||||
|
#undef lex_dont_skip_formatting
|
||||||
|
#undef lex_skip_formatting
|
||||||
|
|
||||||
|
#undef parser_inplace_def
|
||||||
|
#undef parser_not_inplace_def
|
||||||
|
#undef parser_dont_consume_braces
|
||||||
|
#undef parser_consume_braces
|
||||||
|
#undef parser_not_from_template
|
||||||
|
#undef parser_use_parenthesis
|
||||||
|
#undef parser_strip_formatting_dont_preserve_newlines
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
#pragma once
|
||||||
|
#include "interface.parsing.cpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
ssize token_fmt_va( char* buf, usize buf_size, s32 num_tokens, va_list va )
|
||||||
|
{
|
||||||
|
char const* buf_begin = buf;
|
||||||
|
ssize remaining = buf_size;
|
||||||
|
|
||||||
|
if (_ctx->token_fmt_map.Hashes == nullptr) {
|
||||||
|
_ctx->token_fmt_map = hashtable_init(Str, _ctx->Allocator_DyanmicContainers );
|
||||||
|
}
|
||||||
|
// Populate token pairs
|
||||||
|
{
|
||||||
|
s32 left = num_tokens - 1;
|
||||||
|
|
||||||
|
while ( left-- )
|
||||||
|
{
|
||||||
|
char const* token = va_arg( va, char const* );
|
||||||
|
Str value = va_arg( va, Str );
|
||||||
|
|
||||||
|
u32 key = crc32( token, c_str_len(token) );
|
||||||
|
hashtable_set( _ctx->token_fmt_map, key, value );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
char const* fmt = va_arg( va, char const* );
|
||||||
|
char current = *fmt;
|
||||||
|
|
||||||
|
while ( current )
|
||||||
|
{
|
||||||
|
ssize len = 0;
|
||||||
|
|
||||||
|
while ( current && current != '<' && remaining )
|
||||||
|
{
|
||||||
|
* buf = * fmt;
|
||||||
|
buf++;
|
||||||
|
fmt++;
|
||||||
|
remaining--;
|
||||||
|
|
||||||
|
current = * fmt;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( current == '<' )
|
||||||
|
{
|
||||||
|
char const* scanner = fmt + 1;
|
||||||
|
|
||||||
|
s32 tok_len = 0;
|
||||||
|
|
||||||
|
while ( *scanner != '>' )
|
||||||
|
{
|
||||||
|
tok_len++;
|
||||||
|
scanner++;
|
||||||
|
}
|
||||||
|
|
||||||
|
char const* token = fmt + 1;
|
||||||
|
|
||||||
|
u32 key = crc32( token, tok_len );
|
||||||
|
Str* value = hashtable_get(_ctx->token_fmt_map, key );
|
||||||
|
|
||||||
|
if ( value )
|
||||||
|
{
|
||||||
|
ssize left = value->Len;
|
||||||
|
char const* str = value->Ptr;
|
||||||
|
|
||||||
|
while ( left-- )
|
||||||
|
{
|
||||||
|
* buf = * str;
|
||||||
|
buf++;
|
||||||
|
str++;
|
||||||
|
remaining--;
|
||||||
|
}
|
||||||
|
|
||||||
|
scanner++;
|
||||||
|
fmt = scanner;
|
||||||
|
current = * fmt;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
* buf = * fmt;
|
||||||
|
buf++;
|
||||||
|
fmt++;
|
||||||
|
remaining--;
|
||||||
|
|
||||||
|
current = * fmt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hashtable_clear(_ctx->token_fmt_map);
|
||||||
|
ssize result = buf_size - remaining;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
Code untyped_str( Str content )
|
||||||
|
{
|
||||||
|
if ( content.Len == 0 )
|
||||||
|
{
|
||||||
|
log_failure( "untyped_str: empty string" );
|
||||||
|
return InvalidCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
Code
|
||||||
|
result = make_code();
|
||||||
|
result->Name = cache_str( content );
|
||||||
|
result->Type = CT_Untyped;
|
||||||
|
result->Content = result->Name;
|
||||||
|
|
||||||
|
if ( result->Name.Len == 0 )
|
||||||
|
{
|
||||||
|
log_failure( "untyped_str: could not cache string" );
|
||||||
|
return InvalidCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
Code untyped_fmt( char const* fmt, ...)
|
||||||
|
{
|
||||||
|
if ( fmt == nullptr )
|
||||||
|
{
|
||||||
|
log_failure( "untyped_fmt: null format string" );
|
||||||
|
return InvalidCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
local_persist thread_local
|
||||||
|
char buf[GEN_PRINTF_MAXLEN] = { 0 };
|
||||||
|
|
||||||
|
va_list va;
|
||||||
|
va_start(va, fmt);
|
||||||
|
ssize length = c_str_fmt_va(buf, GEN_PRINTF_MAXLEN, fmt, va);
|
||||||
|
va_end(va);
|
||||||
|
Str content = { buf, length };
|
||||||
|
|
||||||
|
Code
|
||||||
|
result = make_code();
|
||||||
|
result->Type = CT_Untyped;
|
||||||
|
result->Content = cache_str( content );
|
||||||
|
|
||||||
|
if ( result->Name.Len == 0 )
|
||||||
|
{
|
||||||
|
log_failure( "untyped_fmt: could not cache string" );
|
||||||
|
return InvalidCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
Code untyped_token_fmt( s32 num_tokens, char const* fmt, ... )
|
||||||
|
{
|
||||||
|
if ( num_tokens == 0 )
|
||||||
|
{
|
||||||
|
log_failure( "untyped_token_fmt: zero tokens" );
|
||||||
|
return InvalidCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
local_persist thread_local
|
||||||
|
char buf[GEN_PRINTF_MAXLEN] = { 0 };
|
||||||
|
|
||||||
|
va_list va;
|
||||||
|
va_start(va, fmt);
|
||||||
|
ssize length = token_fmt_va(buf, GEN_PRINTF_MAXLEN, num_tokens, va);
|
||||||
|
va_end(va);
|
||||||
|
|
||||||
|
Str buf_str = { buf, length };
|
||||||
|
|
||||||
|
Code
|
||||||
|
result = make_code();
|
||||||
|
result->Type = CT_Untyped;
|
||||||
|
result->Content = cache_str( buf_str );
|
||||||
|
|
||||||
|
if ( result->Name.Len == 0 )
|
||||||
|
{
|
||||||
|
log_failure( "untyped_fmt: could not cache string" );
|
||||||
|
return InvalidCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
Code untyped_toks( TokenSlice tokens )
|
||||||
|
{
|
||||||
|
if ( tokens.num == 0 ) {
|
||||||
|
log_failure( "untyped_toks: empty token slice" );
|
||||||
|
return InvalidCode;
|
||||||
|
}
|
||||||
|
Code
|
||||||
|
result = make_code();
|
||||||
|
result->Type = CT_Untyped;
|
||||||
|
result->ContentToks = tokens;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,112 @@
|
|||||||
|
// These macros are used in the swtich cases within parser.cpp
|
||||||
|
|
||||||
|
#define GEN_PARSER_CLASS_STRUCT_BODY_ALLOWED_MEMBER_TOK_SPECIFIER_CASES \
|
||||||
|
case Tok_Spec_Consteval: \
|
||||||
|
case Tok_Spec_Constexpr: \
|
||||||
|
case Tok_Spec_Constinit: \
|
||||||
|
case Tok_Spec_Explicit: \
|
||||||
|
case Tok_Spec_ForceInline: \
|
||||||
|
case Tok_Spec_Inline: \
|
||||||
|
case Tok_Spec_Mutable: \
|
||||||
|
case Tok_Spec_NeverInline: \
|
||||||
|
case Tok_Spec_Static: \
|
||||||
|
case Tok_Spec_Volatile: \
|
||||||
|
case Tok_Spec_Virtual
|
||||||
|
|
||||||
|
#define GEN_PARSER_CLASS_STRUCT_BODY_ALLOWED_MEMBER_SPECIFIER_CASES \
|
||||||
|
case Spec_Constexpr: \
|
||||||
|
case Spec_Constinit: \
|
||||||
|
case Spec_Explicit: \
|
||||||
|
case Spec_Inline: \
|
||||||
|
case Spec_ForceInline: \
|
||||||
|
case Spec_Mutable: \
|
||||||
|
case Spec_NeverInline: \
|
||||||
|
case Spec_Static: \
|
||||||
|
case Spec_Volatile: \
|
||||||
|
case Spec_Virtual
|
||||||
|
|
||||||
|
#define GEN_PARSER_CLASS_GLOBAL_NSPACE_ALLOWED_MEMBER_TOK_SPECIFIER_CASES \
|
||||||
|
case Tok_Spec_Consteval: \
|
||||||
|
case Tok_Spec_Constexpr: \
|
||||||
|
case Tok_Spec_Constinit: \
|
||||||
|
case Tok_Spec_Extern: \
|
||||||
|
case Tok_Spec_ForceInline: \
|
||||||
|
case Tok_Spec_Global: \
|
||||||
|
case Tok_Spec_Inline: \
|
||||||
|
case Tok_Spec_Internal_Linkage: \
|
||||||
|
case Tok_Spec_NeverInline: \
|
||||||
|
case Tok_Spec_Static
|
||||||
|
|
||||||
|
#define GEN_PARSER_CLASS_GLOBAL_NSPACE_ALLOWED_MEMBER_SPECIFIER_CASES \
|
||||||
|
case Spec_Constexpr: \
|
||||||
|
case Spec_Constinit: \
|
||||||
|
case Spec_ForceInline: \
|
||||||
|
case Spec_Global: \
|
||||||
|
case Spec_External_Linkage: \
|
||||||
|
case Spec_Internal_Linkage: \
|
||||||
|
case Spec_Inline: \
|
||||||
|
case Spec_Mutable: \
|
||||||
|
case Spec_NeverInline: \
|
||||||
|
case Spec_Static: \
|
||||||
|
case Spec_Volatile
|
||||||
|
|
||||||
|
#define GEN_PARSER_FRIEND_ALLOWED_SPECIFIER_CASES \
|
||||||
|
case Spec_Const: \
|
||||||
|
case Spec_Inline: \
|
||||||
|
case Spec_ForceInline
|
||||||
|
|
||||||
|
#define GEN_PARSER_FUNCTION_ALLOWED_SPECIFIER_CASES \
|
||||||
|
case Spec_Const: \
|
||||||
|
case Spec_Consteval: \
|
||||||
|
case Spec_Constexpr: \
|
||||||
|
case Spec_External_Linkage: \
|
||||||
|
case Spec_Internal_Linkage: \
|
||||||
|
case Spec_ForceInline: \
|
||||||
|
case Spec_Inline: \
|
||||||
|
case Spec_NeverInline: \
|
||||||
|
case Spec_Static
|
||||||
|
|
||||||
|
#define GEN_PARSER_OPERATOR_ALLOWED_SPECIFIER_CASES \
|
||||||
|
case Spec_Const: \
|
||||||
|
case Spec_Constexpr: \
|
||||||
|
case Spec_ForceInline: \
|
||||||
|
case Spec_Inline: \
|
||||||
|
case Spec_NeverInline: \
|
||||||
|
case Spec_Static
|
||||||
|
|
||||||
|
#define GEN_PARSER_TEMPLATE_ALLOWED_SPECIFIER_CASES \
|
||||||
|
case Spec_Const: \
|
||||||
|
case Spec_Constexpr: \
|
||||||
|
case Spec_Constinit: \
|
||||||
|
case Spec_External_Linkage: \
|
||||||
|
case Spec_Global: \
|
||||||
|
case Spec_Inline: \
|
||||||
|
case Spec_ForceInline: \
|
||||||
|
case Spec_Local_Persist: \
|
||||||
|
case Spec_Mutable: \
|
||||||
|
case Spec_Static: \
|
||||||
|
case Spec_Thread_Local: \
|
||||||
|
case Spec_Volatile
|
||||||
|
|
||||||
|
#define GEN_PARSER_VARIABLE_ALLOWED_SPECIFIER_CASES \
|
||||||
|
case Spec_Const: \
|
||||||
|
case Spec_Constexpr: \
|
||||||
|
case Spec_Constinit: \
|
||||||
|
case Spec_External_Linkage: \
|
||||||
|
case Spec_Global: \
|
||||||
|
case Spec_Inline: \
|
||||||
|
case Spec_Local_Persist: \
|
||||||
|
case Spec_Mutable: \
|
||||||
|
case Spec_Restrict: \
|
||||||
|
case Spec_Static: \
|
||||||
|
case Spec_Thread_Local: \
|
||||||
|
case Spec_Volatile
|
||||||
|
|
||||||
|
#define GEN_PARSER_TYPENAME_ALLOWED_SUFFIX_SPECIFIER_CASES \
|
||||||
|
case Spec_Const: \
|
||||||
|
case Spec_Ptr: \
|
||||||
|
case Spec_Restrict: \
|
||||||
|
case Spec_Ref: \
|
||||||
|
case Spec_RValue
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
#pragma once
|
||||||
|
#include "types.hpp"
|
||||||
|
#include "gen/ecodetypes.hpp"
|
||||||
|
#include "gen/eoperator.hpp"
|
||||||
|
#include "gen/especifier.hpp"
|
||||||
|
#include "gen/etoktype.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
enum TokFlags : u32
|
||||||
|
{
|
||||||
|
TF_Operator = bit(0),
|
||||||
|
TF_Assign = bit(1),
|
||||||
|
TF_Identifier = bit(2),
|
||||||
|
TF_Preprocess = bit(3),
|
||||||
|
TF_Preprocess_Cond = bit(4),
|
||||||
|
TF_Attribute = bit(5),
|
||||||
|
TF_AccessOperator = bit(6),
|
||||||
|
TF_AccessSpecifier = bit(7),
|
||||||
|
TF_Specifier = bit(8),
|
||||||
|
TF_EndDefinition = bit(9), // Either ; or }
|
||||||
|
TF_Formatting = bit(10),
|
||||||
|
TF_Literal = bit(11),
|
||||||
|
TF_Macro_Functional = bit(12),
|
||||||
|
TF_Macro_Expects_Body = bit(13),
|
||||||
|
|
||||||
|
TF_Null = 0,
|
||||||
|
TF_UnderlyingType = GEN_U32_MAX,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Token
|
||||||
|
{
|
||||||
|
Str Text;
|
||||||
|
TokType Type;
|
||||||
|
s32 Line;
|
||||||
|
s32 Column;
|
||||||
|
u32 Flags;
|
||||||
|
};
|
||||||
|
|
||||||
|
constexpr Token NullToken { {}, Tok_Invalid, 0, 0, TF_Null };
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
AccessSpec tok_to_access_specifier(Token tok) {
|
||||||
|
return scast(AccessSpec, tok.Type);
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool tok_is_valid( Token tok ) {
|
||||||
|
return tok.Text.Ptr && tok.Text.Len && tok.Type != Tok_Invalid;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool tok_is_access_operator(Token tok) {
|
||||||
|
return bitfield_is_set( u32, tok.Flags, TF_AccessOperator );
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool tok_is_access_specifier(Token tok) {
|
||||||
|
return bitfield_is_set( u32, tok.Flags, TF_AccessSpecifier );
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool tok_is_attribute(Token tok) {
|
||||||
|
return bitfield_is_set( u32, tok.Flags, TF_Attribute );
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool tok_is_operator(Token tok) {
|
||||||
|
return bitfield_is_set( u32, tok.Flags, TF_Operator );
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool tok_is_preprocessor(Token tok) {
|
||||||
|
return bitfield_is_set( u32, tok.Flags, TF_Preprocess );
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool tok_is_preprocess_cond(Token tok) {
|
||||||
|
return bitfield_is_set( u32, tok.Flags, TF_Preprocess_Cond );
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool tok_is_specifier(Token tok) {
|
||||||
|
return bitfield_is_set( u32, tok.Flags, TF_Specifier );
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool tok_is_end_definition(Token tok) {
|
||||||
|
return bitfield_is_set( u32, tok.Flags, TF_EndDefinition );
|
||||||
|
}
|
||||||
|
|
||||||
|
StrBuilder tok_to_strbuilder(AllocatorInfo ainfo, Token tok);
|
||||||
|
|
||||||
|
struct TokenSlice
|
||||||
|
{
|
||||||
|
Token* ptr;
|
||||||
|
s32 num;
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
forceinline operator Token* () const { return ptr; }
|
||||||
|
forceinline Token& operator[]( ssize index ) const { return ptr[index]; }
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
Str token_range_to_str(Token start, Token end)
|
||||||
|
{
|
||||||
|
Str result = {
|
||||||
|
start.Text.Ptr,
|
||||||
|
(scast(sptr, rcast(uptr, end.Text.Ptr)) + end.Text.Len) - scast(sptr, rcast(uptr, start.Text.Ptr))
|
||||||
|
};
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct TokArray
|
||||||
|
{
|
||||||
|
Array(Token) Arr;
|
||||||
|
s32 Idx;
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef struct LexerMessage LexerMessage;
|
||||||
|
struct LexerMessage
|
||||||
|
{
|
||||||
|
LexerMessage* next;
|
||||||
|
Str content;
|
||||||
|
LogLevel level;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LexContext
|
||||||
|
{
|
||||||
|
AllocatorInfo allocator_temp;
|
||||||
|
LexerMessage* messages;
|
||||||
|
Str content;
|
||||||
|
s32 left;
|
||||||
|
char const* scanner;
|
||||||
|
s32 line;
|
||||||
|
s32 column;
|
||||||
|
Token token;
|
||||||
|
Array(Token) tokens;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LexedInfo
|
||||||
|
{
|
||||||
|
LexerMessage* messages;
|
||||||
|
Str text;
|
||||||
|
TokenSlice tokens;
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef struct ParseStackNode ParseStackNode;
|
||||||
|
|
||||||
|
typedef struct ParseMessage ParseMessage;
|
||||||
|
struct ParseMessage
|
||||||
|
{
|
||||||
|
ParseMessage* Next;
|
||||||
|
ParseStackNode* Scope;
|
||||||
|
Str Content;
|
||||||
|
LogLevel Level;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ParseContext
|
||||||
|
{
|
||||||
|
ParseMessage* messages;
|
||||||
|
ParseStackNode* scope;
|
||||||
|
// TokArray Tokens;
|
||||||
|
TokenSlice tokens;
|
||||||
|
s32 token_id;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum MacroType : u16
|
||||||
|
{
|
||||||
|
MT_Expression, // A macro is assumed to be a expression if not resolved.
|
||||||
|
MT_Statement,
|
||||||
|
MT_Typename,
|
||||||
|
MT_Block_Start, // Not Supported yet
|
||||||
|
MT_Block_End, // Not Supported yet
|
||||||
|
MT_Case_Statement, // Not Supported yet
|
||||||
|
|
||||||
|
MT_UnderlyingType = GEN_U16_MAX,
|
||||||
|
};
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
TokType macrotype_to_toktype( MacroType type ) {
|
||||||
|
switch ( type ) {
|
||||||
|
case MT_Statement : return Tok_Preprocess_Macro_Stmt;
|
||||||
|
case MT_Expression : return Tok_Preprocess_Macro_Expr;
|
||||||
|
case MT_Typename : return Tok_Preprocess_Macro_Typename;
|
||||||
|
}
|
||||||
|
// All others unsupported for now.
|
||||||
|
return Tok_Invalid;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
Str macrotype_to_str( MacroType type )
|
||||||
|
{
|
||||||
|
local_persist
|
||||||
|
Str lookup[] = {
|
||||||
|
{ "Statement", sizeof("Statement") - 1 },
|
||||||
|
{ "Expression", sizeof("Expression") - 1 },
|
||||||
|
{ "Typename", sizeof("Typename") - 1 },
|
||||||
|
{ "Block_Start", sizeof("Block_Start") - 1 },
|
||||||
|
{ "Block_End", sizeof("Block_End") - 1 },
|
||||||
|
{ "Case_Statement", sizeof("Case_Statement") - 1 },
|
||||||
|
};
|
||||||
|
local_persist
|
||||||
|
Str invalid = { "Invalid", sizeof("Invalid") };
|
||||||
|
if ( type > MT_Case_Statement )
|
||||||
|
return invalid;
|
||||||
|
|
||||||
|
return lookup[ type ];
|
||||||
|
}
|
||||||
|
|
||||||
|
enum EMacroFlags : u16
|
||||||
|
{
|
||||||
|
// Macro has parameters (args expected to be passed)
|
||||||
|
MF_Functional = bit(0),
|
||||||
|
|
||||||
|
// Expects to assign a braced scope to its body.
|
||||||
|
MF_Expects_Body = bit(1),
|
||||||
|
|
||||||
|
// lex__eat wil treat this macro as an identifier if the parser attempts to consume it as one.
|
||||||
|
// This is a kludge because we don't support push/pop macro pragmas rn.
|
||||||
|
MF_Allow_As_Identifier = bit(2),
|
||||||
|
|
||||||
|
// When parsing identifiers, it will allow the consumption of the macro parameters (as its expected to be a part of constructing the identifier)
|
||||||
|
// Example of a decarator macro from stb_sprintf.h:
|
||||||
|
// STBSP__PUBLICDEC int STB_SPRINTF_DECORATE(sprintf)(char* buf, char const *fmt, ...) STBSP__ATTRIBUTE_FORMAT(2,3);
|
||||||
|
// ^^ STB_SPRINTF_DECORATE is decorating sprintf
|
||||||
|
MF_Identifier_Decorator = bit(3),
|
||||||
|
|
||||||
|
// lex__eat wil treat this macro as an attribute if the parser attempts to consume it as one.
|
||||||
|
// This a kludge because unreal has a macro that behaves as both a 'statement' and an attribute (UE_DEPRECATED, PRAGMA_ENABLE_DEPRECATION_WARNINGS, etc)
|
||||||
|
// TODO(Ed): We can keep the MF_Allow_As_Attribute flag for macros, however, we need to add the ability of AST_Attributes to chain themselves.
|
||||||
|
// Its thats already a thing in the standard language anyway
|
||||||
|
// & it would allow UE_DEPRECATED, (UE_PROPERTY / UE_FUNCTION) to chain themselves as attributes of a resolved member function/variable definition
|
||||||
|
MF_Allow_As_Attribute = bit(4),
|
||||||
|
|
||||||
|
// When a macro is encountered after attributes and specifiers while parsing a function, or variable:
|
||||||
|
// It will consume the macro and treat it as resolving the definition.
|
||||||
|
// (MUST BE OF MT_Statement TYPE)
|
||||||
|
MF_Allow_As_Definition = bit(5),
|
||||||
|
|
||||||
|
// Created for Unreal's PURE_VIRTUAL
|
||||||
|
MF_Allow_As_Specifier = bit(6),
|
||||||
|
|
||||||
|
MF_Null = 0,
|
||||||
|
MF_UnderlyingType = GEN_U16_MAX,
|
||||||
|
};
|
||||||
|
typedef u16 MacroFlags;
|
||||||
|
|
||||||
|
struct Macro
|
||||||
|
{
|
||||||
|
StrCached Name;
|
||||||
|
MacroType Type;
|
||||||
|
MacroFlags Flags;
|
||||||
|
};
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
b32 macro_is_functional( Macro macro ) {
|
||||||
|
return bitfield_is_set( b16, macro.Flags, MF_Functional );
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
b32 macro_expects_body( Macro macro ) {
|
||||||
|
return bitfield_is_set( b16, macro.Flags, MF_Expects_Body );
|
||||||
|
}
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP && ! GEN_C_LIKE_CPP
|
||||||
|
forceinline b32 is_functional( Macro macro ) { return bitfield_is_set( b16, macro.Flags, MF_Functional ); }
|
||||||
|
forceinline b32 expects_body ( Macro macro ) { return bitfield_is_set( b16, macro.Flags, MF_Expects_Body ); }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
typedef HashTable(Macro) MacroTable;
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#if ! defined(GEN_DONT_ENFORCE_GEN_TIME_GUARD) && ! defined(GEN_TIME)
|
||||||
|
# error Gen.hpp : GEN_TIME not defined
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "gen.hpp"
|
||||||
|
|
||||||
|
//! If its desired to roll your own dependencies, define GEN_ROLL_OWN_DEPENDENCIES before including this file.
|
||||||
|
//! Dependencies are derived from the c-zpl library: https://github.com/zpl-c/zpl
|
||||||
|
#ifndef GEN_ROLL_OWN_DEPENDENCIES
|
||||||
|
# include "gen.dep.cpp"
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
#pragma once
|
||||||
|
#include "interface.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region StaticData
|
||||||
|
GEN_API global Context* _ctx;
|
||||||
|
GEN_API global u32 context_counter;
|
||||||
|
|
||||||
|
#pragma region Constants
|
||||||
|
GEN_API global Macro enum_underlying_macro;
|
||||||
|
|
||||||
|
GEN_API global Code Code_Global;
|
||||||
|
GEN_API global Code Code_Invalid;
|
||||||
|
|
||||||
|
GEN_API global Code access_public;
|
||||||
|
GEN_API global Code access_protected;
|
||||||
|
GEN_API global Code access_private;
|
||||||
|
|
||||||
|
GEN_API global CodeAttributes attrib_api_export;
|
||||||
|
GEN_API global CodeAttributes attrib_api_import;
|
||||||
|
|
||||||
|
GEN_API global Code module_global_fragment;
|
||||||
|
GEN_API global Code module_private_fragment;
|
||||||
|
|
||||||
|
GEN_API global Code fmt_newline;
|
||||||
|
|
||||||
|
GEN_API global CodeParams param_varadic;
|
||||||
|
|
||||||
|
GEN_API global CodePragma pragma_once;
|
||||||
|
|
||||||
|
GEN_API global CodePreprocessCond preprocess_else;
|
||||||
|
GEN_API global CodePreprocessCond preprocess_endif;
|
||||||
|
|
||||||
|
GEN_API global CodeSpecifiers spec_const;
|
||||||
|
GEN_API global CodeSpecifiers spec_consteval;
|
||||||
|
GEN_API global CodeSpecifiers spec_constexpr;
|
||||||
|
GEN_API global CodeSpecifiers spec_constinit;
|
||||||
|
GEN_API global CodeSpecifiers spec_extern_linkage;
|
||||||
|
GEN_API global CodeSpecifiers spec_final;
|
||||||
|
GEN_API global CodeSpecifiers spec_forceinline;
|
||||||
|
GEN_API global CodeSpecifiers spec_global;
|
||||||
|
GEN_API global CodeSpecifiers spec_inline;
|
||||||
|
GEN_API global CodeSpecifiers spec_internal_linkage;
|
||||||
|
GEN_API global CodeSpecifiers spec_local_persist;
|
||||||
|
GEN_API global CodeSpecifiers spec_mutable;
|
||||||
|
GEN_API global CodeSpecifiers spec_noexcept;
|
||||||
|
GEN_API global CodeSpecifiers spec_neverinline;
|
||||||
|
GEN_API global CodeSpecifiers spec_override;
|
||||||
|
GEN_API global CodeSpecifiers spec_ptr;
|
||||||
|
GEN_API global CodeSpecifiers spec_pure;
|
||||||
|
GEN_API global CodeSpecifiers spec_ref;
|
||||||
|
GEN_API global CodeSpecifiers spec_register;
|
||||||
|
GEN_API global CodeSpecifiers spec_rvalue;
|
||||||
|
GEN_API global CodeSpecifiers spec_static_member;
|
||||||
|
GEN_API global CodeSpecifiers spec_thread_local;
|
||||||
|
GEN_API global CodeSpecifiers spec_virtual;
|
||||||
|
GEN_API global CodeSpecifiers spec_volatile;
|
||||||
|
|
||||||
|
GEN_API global CodeTypename t_empty;
|
||||||
|
GEN_API global CodeTypename t_auto;
|
||||||
|
GEN_API global CodeTypename t_void;
|
||||||
|
GEN_API global CodeTypename t_int;
|
||||||
|
GEN_API global CodeTypename t_bool;
|
||||||
|
GEN_API global CodeTypename t_char;
|
||||||
|
GEN_API global CodeTypename t_wchar_t;
|
||||||
|
GEN_API global CodeTypename t_class;
|
||||||
|
GEN_API global CodeTypename t_typename;
|
||||||
|
|
||||||
|
#ifdef GEN_DEFINE_LIBRARY_CODE_CONSTANTS
|
||||||
|
GEN_API global CodeTypename t_b32;
|
||||||
|
|
||||||
|
GEN_API global CodeTypename t_s8;
|
||||||
|
GEN_API global CodeTypename t_s16;
|
||||||
|
GEN_API global CodeTypename t_s32;
|
||||||
|
GEN_API global CodeTypename t_s64;
|
||||||
|
|
||||||
|
GEN_API global CodeTypename t_u8;
|
||||||
|
GEN_API global CodeTypename t_u16;
|
||||||
|
GEN_API global CodeTypename t_u32;
|
||||||
|
GEN_API global CodeTypename t_u64;
|
||||||
|
|
||||||
|
GEN_API global CodeTypename t_ssize;
|
||||||
|
GEN_API global CodeTypename t_usize;
|
||||||
|
|
||||||
|
GEN_API global CodeTypename t_f32;
|
||||||
|
GEN_API global CodeTypename t_f64;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Constants
|
||||||
|
|
||||||
|
#pragma endregion StaticData
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
#pragma once
|
||||||
|
#include "dependencies/platform.hpp"
|
||||||
|
#include "dependencies/macros.hpp"
|
||||||
|
#include "dependencies/basic_types.hpp"
|
||||||
|
#include "dependencies/debug.hpp"
|
||||||
|
#include "dependencies/memory.hpp"
|
||||||
|
#include "dependencies/string_ops.hpp"
|
||||||
|
#include "dependencies/printing.hpp"
|
||||||
|
#include "dependencies/containers.hpp"
|
||||||
|
#include "dependencies/hashing.hpp"
|
||||||
|
#include "dependencies/strings.hpp"
|
||||||
|
#include "dependencies/filesystem.hpp"
|
||||||
|
#include "dependencies/timing.hpp"
|
||||||
|
#include "dependencies/parsing.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
________ __ __ ________
|
||||||
|
| \ | \ | \ | \
|
||||||
|
| ▓▓▓▓▓▓▓▓_______ __ __ ______ ____ _______ | ▓▓\ | ▓▓ \▓▓▓▓▓▓▓▓__ __ ______ ______ _______
|
||||||
|
| ▓▓__ | \| \ | \ \ \ / \ | ▓▓▓\| ▓▓ | ▓▓ | \ | \/ \ / \ / \
|
||||||
|
| ▓▓ \ | ▓▓▓▓▓▓▓\ ▓▓ | ▓▓ ▓▓▓▓▓▓\▓▓▓▓\ ▓▓▓▓▓▓▓ | ▓▓▓▓\ ▓▓ | ▓▓ | ▓▓ | ▓▓ ▓▓▓▓▓▓\ ▓▓▓▓▓▓\ ▓▓▓▓▓▓▓
|
||||||
|
| ▓▓▓▓▓ | ▓▓ | ▓▓ ▓▓ | ▓▓ ▓▓ | ▓▓ | ▓▓\▓▓ \ | ▓▓\▓▓ ▓▓ | ▓▓ | ▓▓ | ▓▓ ▓▓ | ▓▓ ▓▓ ▓▓\▓▓ \
|
||||||
|
| ▓▓_____| ▓▓ | ▓▓ ▓▓__/ ▓▓ ▓▓ | ▓▓ | ▓▓_\▓▓▓▓▓▓\ | ▓▓ \▓▓▓▓ | ▓▓ | ▓▓__/ ▓▓ ▓▓__/ ▓▓ ▓▓▓▓▓▓▓▓_\▓▓▓▓▓▓\
|
||||||
|
| ▓▓ \ ▓▓ | ▓▓\▓▓ ▓▓ ▓▓ | ▓▓ | ▓▓ ▓▓ | ▓▓ \▓▓▓ | ▓▓ \▓▓ ▓▓ ▓▓ ▓▓\▓▓ \ ▓▓
|
||||||
|
\▓▓▓▓▓▓▓▓\▓▓ \▓▓ \▓▓▓▓▓▓ \▓▓ \▓▓ \▓▓\▓▓▓▓▓▓▓ \▓▓ \▓▓ \▓▓ _\▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓ \▓▓▓▓▓▓▓\▓▓▓▓▓▓▓
|
||||||
|
| \__| ▓▓ ▓▓
|
||||||
|
\▓▓ ▓▓ ▓▓
|
||||||
|
\▓▓▓▓▓▓ \▓▓
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
enum LogLevel //: u32
|
||||||
|
{
|
||||||
|
LL_Null,
|
||||||
|
LL_Note,
|
||||||
|
LL_Warning,
|
||||||
|
LL_Error,
|
||||||
|
LL_Fatal,
|
||||||
|
LL_UnderlyingType = GEN_U32_MAX,
|
||||||
|
};
|
||||||
|
typedef enum LogLevel LogLevel;
|
||||||
|
|
||||||
|
Str loglevel_to_str(LogLevel level)
|
||||||
|
{
|
||||||
|
local_persist
|
||||||
|
Str lookup[] = {
|
||||||
|
{ "Null", sizeof("Null") - 1 },
|
||||||
|
{ "Note", sizeof("Note") - 1 },
|
||||||
|
{ "Warning", sizeof("Info") - 1 },
|
||||||
|
{ "Error", sizeof("Error") - 1 },
|
||||||
|
{ "Fatal", sizeof("Fatal") - 1 },
|
||||||
|
};
|
||||||
|
return lookup[level];
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef struct LogEntry LogEntry;
|
||||||
|
struct LogEntry
|
||||||
|
{
|
||||||
|
Str msg;
|
||||||
|
LogLevel level;
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef void LoggerProc(LogEntry entry);
|
||||||
|
|
||||||
|
// By default this library will either crash or exit if an error is detected while generating codes.
|
||||||
|
// Even if set to not use GEN_FATAL, GEN_FATAL will still be used for memory failures as the library is unusable when they occur.
|
||||||
|
#ifdef GEN_DONT_USE_FATAL
|
||||||
|
#define log_failure log_fmt
|
||||||
|
#else
|
||||||
|
#define log_failure GEN_FATAL
|
||||||
|
#endif
|
||||||
|
|
||||||
|
enum AccessSpec : u32
|
||||||
|
{
|
||||||
|
AccessSpec_Default,
|
||||||
|
AccessSpec_Private,
|
||||||
|
AccessSpec_Protected,
|
||||||
|
AccessSpec_Public,
|
||||||
|
|
||||||
|
AccessSpec_Num_AccessSpec,
|
||||||
|
AccessSpec_Invalid,
|
||||||
|
|
||||||
|
AccessSpec_SizeDef = GEN_U32_MAX,
|
||||||
|
};
|
||||||
|
static_assert( size_of(AccessSpec) == size_of(u32), "AccessSpec not u32 size" );
|
||||||
|
|
||||||
|
inline
|
||||||
|
Str access_spec_to_str( AccessSpec type )
|
||||||
|
{
|
||||||
|
local_persist
|
||||||
|
Str lookup[ (u32)AccessSpec_Num_AccessSpec ] = {
|
||||||
|
{ "", sizeof( "" ) - 1 },
|
||||||
|
{ "private", sizeof("prviate") - 1 },
|
||||||
|
{ "private", sizeof("protected") - 1 },
|
||||||
|
{ "public", sizeof("public") - 1 },
|
||||||
|
};
|
||||||
|
|
||||||
|
Str invalid = { "Invalid", sizeof("Invalid") - 1 };
|
||||||
|
if ( type > AccessSpec_Public )
|
||||||
|
return invalid;
|
||||||
|
|
||||||
|
return lookup[ (u32)type ];
|
||||||
|
}
|
||||||
|
|
||||||
|
enum CodeFlag : u32
|
||||||
|
{
|
||||||
|
CodeFlag_None = 0,
|
||||||
|
CodeFlag_FunctionType = bit(0),
|
||||||
|
CodeFlag_ParamPack = bit(1),
|
||||||
|
CodeFlag_Module_Export = bit(2),
|
||||||
|
CodeFlag_Module_Import = bit(3),
|
||||||
|
|
||||||
|
CodeFlag_SizeDef = GEN_U32_MAX,
|
||||||
|
};
|
||||||
|
static_assert( size_of(CodeFlag) == size_of(u32), "CodeFlag not u32 size" );
|
||||||
|
|
||||||
|
// Used to indicate if enum definitoin is an enum class or regular enum.
|
||||||
|
enum EnumDecl : u8
|
||||||
|
{
|
||||||
|
EnumDecl_Regular,
|
||||||
|
EnumDecl_Class,
|
||||||
|
|
||||||
|
EnumT_SizeDef = GEN_U8_MAX,
|
||||||
|
};
|
||||||
|
typedef u8 EnumT;
|
||||||
|
|
||||||
|
enum ModuleFlag : u32
|
||||||
|
{
|
||||||
|
ModuleFlag_None = 0,
|
||||||
|
ModuleFlag_Export = bit(0),
|
||||||
|
ModuleFlag_Import = bit(1),
|
||||||
|
|
||||||
|
Num_ModuleFlags,
|
||||||
|
ModuleFlag_Invalid,
|
||||||
|
|
||||||
|
ModuleFlag_SizeDef = GEN_U32_MAX,
|
||||||
|
};
|
||||||
|
static_assert( size_of(ModuleFlag) == size_of(u32), "ModuleFlag not u32 size" );
|
||||||
|
|
||||||
|
inline
|
||||||
|
Str module_flag_to_str( ModuleFlag flag )
|
||||||
|
{
|
||||||
|
local_persist
|
||||||
|
Str lookup[ (u32)Num_ModuleFlags ] = {
|
||||||
|
{ "__none__", sizeof("__none__") - 1 },
|
||||||
|
{ "export", sizeof("export") - 1 },
|
||||||
|
{ "import", sizeof("import") - 1 },
|
||||||
|
};
|
||||||
|
|
||||||
|
local_persist
|
||||||
|
Str invalid_flag = { "invalid", sizeof("invalid") };
|
||||||
|
if ( flag > ModuleFlag_Import )
|
||||||
|
return invalid_flag;
|
||||||
|
|
||||||
|
return lookup[ (u32)flag ];
|
||||||
|
}
|
||||||
|
|
||||||
|
enum EPreprocessCond : u32
|
||||||
|
{
|
||||||
|
PreprocessCond_If,
|
||||||
|
PreprocessCond_IfDef,
|
||||||
|
PreprocessCond_IfNotDef,
|
||||||
|
PreprocessCond_ElIf,
|
||||||
|
|
||||||
|
EPreprocessCond_SizeDef = GEN_U32_MAX,
|
||||||
|
};
|
||||||
|
static_assert( size_of(EPreprocessCond) == size_of(u32), "EPreprocessCond not u32 size" );
|
||||||
|
|
||||||
|
enum ETypenameTag : u16
|
||||||
|
{
|
||||||
|
Tag_None,
|
||||||
|
Tag_Class,
|
||||||
|
Tag_Enum,
|
||||||
|
Tag_Struct,
|
||||||
|
Tag_Union,
|
||||||
|
|
||||||
|
Tag_UnderlyingType = GEN_U16_MAX,
|
||||||
|
};
|
||||||
|
static_assert( size_of(ETypenameTag) == size_of(u16), "ETypenameTag is not u16 size");
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "macros.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Basic Types
|
||||||
|
|
||||||
|
#define GEN_U8_MIN 0u
|
||||||
|
#define GEN_U8_MAX 0xffu
|
||||||
|
#define GEN_I8_MIN ( -0x7f - 1 )
|
||||||
|
#define GEN_I8_MAX 0x7f
|
||||||
|
|
||||||
|
#define GEN_U16_MIN 0u
|
||||||
|
#define GEN_U16_MAX 0xffffu
|
||||||
|
#define GEN_I16_MIN ( -0x7fff - 1 )
|
||||||
|
#define GEN_I16_MAX 0x7fff
|
||||||
|
|
||||||
|
#define GEN_U32_MIN 0u
|
||||||
|
#define GEN_U32_MAX 0xffffffffu
|
||||||
|
#define GEN_I32_MIN ( -0x7fffffff - 1 )
|
||||||
|
#define GEN_I32_MAX 0x7fffffff
|
||||||
|
|
||||||
|
#define GEN_U64_MIN 0ull
|
||||||
|
#define GEN_U64_MAX 0xffffffffffffffffull
|
||||||
|
#define GEN_I64_MIN ( -0x7fffffffffffffffll - 1 )
|
||||||
|
#define GEN_I64_MAX 0x7fffffffffffffffll
|
||||||
|
|
||||||
|
#if defined( GEN_ARCH_32_BIT )
|
||||||
|
# define GEN_USIZE_MIN GEN_U32_MIN
|
||||||
|
# define GEN_USIZE_MAX GEN_U32_MAX
|
||||||
|
# define GEN_ISIZE_MIN GEN_S32_MIN
|
||||||
|
# define GEN_ISIZE_MAX GEN_S32_MAX
|
||||||
|
#elif defined( GEN_ARCH_64_BIT )
|
||||||
|
# define GEN_USIZE_MIN GEN_U64_MIN
|
||||||
|
# define GEN_USIZE_MAX GEN_U64_MAX
|
||||||
|
# define GEN_ISIZE_MIN GEN_I64_MIN
|
||||||
|
# define GEN_ISIZE_MAX GEN_I64_MAX
|
||||||
|
#else
|
||||||
|
# error Unknown architecture size. This library only supports 32 bit and 64 bit architectures.
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define GEN_F32_MIN 1.17549435e-38f
|
||||||
|
#define GEN_F32_MAX 3.40282347e+38f
|
||||||
|
#define GEN_F64_MIN 2.2250738585072014e-308
|
||||||
|
#define GEN_F64_MAX 1.7976931348623157e+308
|
||||||
|
|
||||||
|
#if defined( GEN_COMPILER_MSVC )
|
||||||
|
# if _MSC_VER < 1300
|
||||||
|
typedef unsigned char u8;
|
||||||
|
typedef signed char s8;
|
||||||
|
typedef unsigned short u16;
|
||||||
|
typedef signed short s16;
|
||||||
|
typedef unsigned int u32;
|
||||||
|
typedef signed int s32;
|
||||||
|
# else
|
||||||
|
typedef unsigned __int8 u8;
|
||||||
|
typedef signed __int8 s8;
|
||||||
|
typedef unsigned __int16 u16;
|
||||||
|
typedef signed __int16 s16;
|
||||||
|
typedef unsigned __int32 u32;
|
||||||
|
typedef signed __int32 s32;
|
||||||
|
# endif
|
||||||
|
typedef unsigned __int64 u64;
|
||||||
|
typedef signed __int64 s64;
|
||||||
|
#else
|
||||||
|
# include <stdint.h>
|
||||||
|
|
||||||
|
typedef uint8_t u8;
|
||||||
|
typedef int8_t s8;
|
||||||
|
typedef uint16_t u16;
|
||||||
|
typedef int16_t s16;
|
||||||
|
typedef uint32_t u32;
|
||||||
|
typedef int32_t s32;
|
||||||
|
typedef uint64_t u64;
|
||||||
|
typedef int64_t s64;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static_assert( sizeof( u8 ) == sizeof( s8 ), "sizeof(u8) != sizeof(s8)" );
|
||||||
|
static_assert( sizeof( u16 ) == sizeof( s16 ), "sizeof(u16) != sizeof(s16)" );
|
||||||
|
static_assert( sizeof( u32 ) == sizeof( s32 ), "sizeof(u32) != sizeof(s32)" );
|
||||||
|
static_assert( sizeof( u64 ) == sizeof( s64 ), "sizeof(u64) != sizeof(s64)" );
|
||||||
|
|
||||||
|
static_assert( sizeof( u8 ) == 1, "sizeof(u8) != 1" );
|
||||||
|
static_assert( sizeof( u16 ) == 2, "sizeof(u16) != 2" );
|
||||||
|
static_assert( sizeof( u32 ) == 4, "sizeof(u32) != 4" );
|
||||||
|
static_assert( sizeof( u64 ) == 8, "sizeof(u64) != 8" );
|
||||||
|
|
||||||
|
typedef size_t usize;
|
||||||
|
typedef ptrdiff_t ssize;
|
||||||
|
|
||||||
|
static_assert( sizeof( usize ) == sizeof( ssize ), "sizeof(usize) != sizeof(ssize)" );
|
||||||
|
|
||||||
|
// NOTE: (u)zpl_intptr is only here for semantic reasons really as this library will only support 32/64 bit OSes.
|
||||||
|
#if defined( _WIN64 )
|
||||||
|
typedef signed __int64 sptr;
|
||||||
|
typedef unsigned __int64 uptr;
|
||||||
|
#elif defined( _WIN32 )
|
||||||
|
// NOTE; To mark types changing their size, e.g. zpl_intptr
|
||||||
|
# ifndef _W64
|
||||||
|
# if ! defined( __midl ) && ( defined( _X86_ ) || defined( _M_IX86 ) ) && _MSC_VER >= 1300
|
||||||
|
# define _W64 __w64
|
||||||
|
# else
|
||||||
|
# define _W64
|
||||||
|
# endif
|
||||||
|
# endif
|
||||||
|
typedef _W64 signed int sptr;
|
||||||
|
typedef _W64 unsigned int uptr;
|
||||||
|
#else
|
||||||
|
typedef uintptr_t uptr;
|
||||||
|
typedef intptr_t sptr;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static_assert( sizeof( uptr ) == sizeof( sptr ), "sizeof(uptr) != sizeof(sptr)" );
|
||||||
|
|
||||||
|
typedef float f32;
|
||||||
|
typedef double f64;
|
||||||
|
|
||||||
|
static_assert( sizeof( f32 ) == 4, "sizeof(f32) != 4" );
|
||||||
|
static_assert( sizeof( f64 ) == 8, "sizeof(f64) != 8" );
|
||||||
|
|
||||||
|
typedef s8 b8;
|
||||||
|
typedef s16 b16;
|
||||||
|
typedef s32 b32;
|
||||||
|
|
||||||
|
typedef void* mem_ptr;
|
||||||
|
typedef void const* mem_ptr_const ;
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
template<typename Type> uptr to_uptr( Type* ptr ) { return (uptr)ptr; }
|
||||||
|
template<typename Type> sptr to_sptr( Type* ptr ) { return (sptr)ptr; }
|
||||||
|
|
||||||
|
template<typename Type> mem_ptr to_mem_ptr ( Type ptr ) { return (mem_ptr) ptr; }
|
||||||
|
template<typename Type> mem_ptr_const to_mem_ptr_const( Type ptr ) { return (mem_ptr_const)ptr; }
|
||||||
|
#else
|
||||||
|
#define to_uptr( ptr ) ((uptr)(ptr))
|
||||||
|
#define to_sptr( ptr ) ((sptr)(ptr))
|
||||||
|
|
||||||
|
#define to_mem_ptr( ptr) ((mem_ptr)ptr)
|
||||||
|
#define to_mem_ptr_const( ptr) ((mem_ptr)ptr)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Basic Types
|
||||||
@@ -0,0 +1,826 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "printing.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Containers
|
||||||
|
|
||||||
|
template<class TType> struct RemoveConst { typedef TType Type; };
|
||||||
|
template<class TType> struct RemoveConst<const TType> { typedef TType Type; };
|
||||||
|
template<class TType> struct RemoveConst<const TType[]> { typedef TType Type[]; };
|
||||||
|
template<class TType, usize Size> struct RemoveConst<const TType[Size]> { typedef TType Type[Size]; };
|
||||||
|
|
||||||
|
template<class TType> using TRemoveConst = typename RemoveConst<TType>::Type;
|
||||||
|
|
||||||
|
template <class TType> struct RemovePtr { typedef TType Type; };
|
||||||
|
template <class TType> struct RemovePtr<TType*> { typedef TType Type; };
|
||||||
|
|
||||||
|
template <class TType> using TRemovePtr = typename RemovePtr<TType>::Type;
|
||||||
|
|
||||||
|
#pragma region Slice
|
||||||
|
#if 0
|
||||||
|
#define Slice(Type) Slice<Type>
|
||||||
|
|
||||||
|
template<class Type> struct Slice;
|
||||||
|
|
||||||
|
template<class Type>
|
||||||
|
Type* slice_get(Slice<Type> self, ssize id) {
|
||||||
|
GEN_ASSERT(id > -1);
|
||||||
|
GEN_ASSERT(id < self.len);
|
||||||
|
return self.ptr[id];
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type>
|
||||||
|
struct Slice
|
||||||
|
{
|
||||||
|
Type* ptr;
|
||||||
|
ssize len;
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
forceinline operator Token* () const { return ptr; }
|
||||||
|
forceinline Token& operator[]( ssize index ) const { return ptr[index]; }
|
||||||
|
|
||||||
|
forceinline Type* begin() { return ptr; }
|
||||||
|
forceinline Type* end() { return ptr + len; }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if ! GEN_C_LIKE_CPP && GEN_COMPILER_CPP
|
||||||
|
forceinline Type& back() { return ptr[len - 1]; }
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
#endif
|
||||||
|
#pragma endregion Slice
|
||||||
|
|
||||||
|
#pragma region Array
|
||||||
|
#define Array(Type) Array<Type>
|
||||||
|
|
||||||
|
// #define array_init(Type, ...) array_init <Type>(__VA_ARGS__)
|
||||||
|
// #define array_init_reserve(Type, ...) array_init_reserve<Type>(__VA_ARGS__)
|
||||||
|
|
||||||
|
struct ArrayHeader;
|
||||||
|
|
||||||
|
template<class Type> struct Array;
|
||||||
|
#define get_array_underlying_type(array) typename TRemovePtr<typeof(array)>:: DataType
|
||||||
|
|
||||||
|
usize array_grow_formula(ssize value);
|
||||||
|
|
||||||
|
template<class Type> Array<Type> array_init (AllocatorInfo allocator);
|
||||||
|
template<class Type> Array<Type> array_init_reserve (AllocatorInfo allocator, ssize capacity);
|
||||||
|
template<class Type> bool array_append_array (Array<Type>* array, Array<Type> other);
|
||||||
|
template<class Type> bool array_append (Array<Type>* array, Type value);
|
||||||
|
template<class Type> bool array_append_items (Array<Type>* array, Type* items, usize item_num);
|
||||||
|
template<class Type> bool array_append_at (Array<Type>* array, Type item, usize idx);
|
||||||
|
template<class Type> bool array_append_items_at(Array<Type>* array, Type* items, usize item_num, usize idx);
|
||||||
|
template<class Type> Type* array_back (Array<Type> array);
|
||||||
|
template<class Type> void array_clear (Array<Type> array);
|
||||||
|
template<class Type> bool array_fill (Array<Type> array, usize begin, usize end, Type value);
|
||||||
|
template<class Type> void array_free (Array<Type>* array);
|
||||||
|
template<class Type> bool arary_grow (Array<Type>* array, usize min_capacity);
|
||||||
|
template<class Type> usize array_num (Array<Type> array);
|
||||||
|
template<class Type> void arary_pop (Array<Type> array);
|
||||||
|
template<class Type> void arary_remove_at (Array<Type> array, usize idx);
|
||||||
|
template<class Type> bool arary_reserve (Array<Type>* array, usize new_capacity);
|
||||||
|
template<class Type> bool arary_resize (Array<Type>* array, usize num);
|
||||||
|
template<class Type> bool arary_set_capacity (Array<Type>* array, usize new_capacity);
|
||||||
|
template<class Type> ArrayHeader* arary_get_header (Array<Type> array);
|
||||||
|
|
||||||
|
struct ArrayHeader {
|
||||||
|
AllocatorInfo Allocator;
|
||||||
|
usize Capacity;
|
||||||
|
usize Num;
|
||||||
|
};
|
||||||
|
|
||||||
|
template<class Type>
|
||||||
|
struct Array
|
||||||
|
{
|
||||||
|
Type* Data;
|
||||||
|
|
||||||
|
#if ! GEN_C_LIKE_CPP
|
||||||
|
#pragma region Member Mapping
|
||||||
|
forceinline static Array init(AllocatorInfo allocator) { return array_init<Type>(allocator); }
|
||||||
|
forceinline static Array init_reserve(AllocatorInfo allocator, ssize capacity) { return array_init_reserve<Type>(allocator, capacity); }
|
||||||
|
forceinline static usize grow_formula(ssize value) { return array_grow_formula<Type>(value); }
|
||||||
|
|
||||||
|
forceinline bool append(Array other) { return array_append_array<Type>(this, other); }
|
||||||
|
forceinline bool append(Type value) { return array_append<Type>(this, value); }
|
||||||
|
forceinline bool append(Type* items, usize item_num) { return array_append_items<Type>(this, items, item_num); }
|
||||||
|
forceinline bool append_at(Type item, usize idx) { return array_append_at<Type>(this, item, idx); }
|
||||||
|
forceinline bool append_at(Type* items, usize item_num, usize idx) { return array_append_items_at<Type>(this, items, item_num, idx); }
|
||||||
|
forceinline Type* back() { return array_back<Type>(* this); }
|
||||||
|
forceinline void clear() { array_clear<Type>(* this); }
|
||||||
|
forceinline bool fill(usize begin, usize end, Type value) { return array_fill<Type>(* this, begin, end, value); }
|
||||||
|
forceinline void free() { array_free<Type>(this); }
|
||||||
|
forceinline ArrayHeader* get_header() { return array_get_header<Type>(* this); }
|
||||||
|
forceinline bool grow(usize min_capacity) { return array_grow<Type>(this, min_capacity); }
|
||||||
|
forceinline usize num() { return array_num<Type>(*this); }
|
||||||
|
forceinline void pop() { array_pop<Type>(* this); }
|
||||||
|
forceinline void remove_at(usize idx) { array_remove_at<Type>(* this, idx); }
|
||||||
|
forceinline bool reserve(usize new_capacity) { return array_reserve<Type>(this, new_capacity); }
|
||||||
|
forceinline bool resize(usize num) { return array_resize<Type>(this, num); }
|
||||||
|
forceinline bool set_capacity(usize new_capacity) { return array_set_capacity<Type>(this, new_capacity); }
|
||||||
|
#pragma endregion Member Mapping
|
||||||
|
#endif
|
||||||
|
|
||||||
|
forceinline operator Type*() { return Data; }
|
||||||
|
forceinline operator Type const*() const { return Data; }
|
||||||
|
forceinline Type* begin() { return Data; }
|
||||||
|
forceinline Type* end() { return Data + get_header()->Num; }
|
||||||
|
|
||||||
|
forceinline Type& operator[](ssize index) { return Data[index]; }
|
||||||
|
forceinline Type const& operator[](ssize index) const { return Data[index]; }
|
||||||
|
|
||||||
|
using DataType = Type;
|
||||||
|
};
|
||||||
|
|
||||||
|
#if 0
|
||||||
|
template<class Type> bool append(Array<Type>& array, Array<Type> other) { return append( & array, other ); }
|
||||||
|
template<class Type> bool append(Array<Type>& array, Type value) { return append( & array, value ); }
|
||||||
|
template<class Type> bool append(Array<Type>& array, Type* items, usize item_num) { return append( & array, items, item_num ); }
|
||||||
|
template<class Type> bool append_at(Array<Type>& array, Type item, usize idx) { return append_at( & array, item, idx ); }
|
||||||
|
template<class Type> bool append_at(Array<Type>& array, Type* items, usize item_num, usize idx) { return append_at( & array, items, item_num, idx ); }
|
||||||
|
template<class Type> void free(Array<Type>& array) { return free( & array ); }
|
||||||
|
template<class Type> bool grow(Array<Type>& array, usize min_capacity) { return grow( & array, min_capacity); }
|
||||||
|
template<class Type> bool reserve(Array<Type>& array, usize new_capacity) { return reserve( & array, new_capacity); }
|
||||||
|
template<class Type> bool resize(Array<Type>& array, usize num) { return resize( & array, num); }
|
||||||
|
template<class Type> bool set_capacity(Array<Type>& array, usize new_capacity) { return set_capacity( & array, new_capacity); }
|
||||||
|
|
||||||
|
template<class Type> forceinline Type* begin(Array<Type>& array) { return array; }
|
||||||
|
template<class Type> forceinline Type* end(Array<Type>& array) { return array + array_get_header(array)->Num; }
|
||||||
|
template<class Type> forceinline Type* next(Array<Type>& array, Type* entry) { return entry + 1; }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
template<class Type> forceinline Type* array_begin(Array<Type> array) { return array; }
|
||||||
|
template<class Type> forceinline Type* array_end(Array<Type> array) { return array + array_get_header(array)->Num; }
|
||||||
|
template<class Type> forceinline Type* array_next(Array<Type> array, Type* entry) { return ++ entry; }
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
Array<Type> array_init(AllocatorInfo allocator) {
|
||||||
|
return array_init_reserve<Type>(allocator, array_grow_formula(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
Array<Type> array_init_reserve(AllocatorInfo allocator, ssize capacity)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(capacity > 0);
|
||||||
|
ArrayHeader* header = rcast(ArrayHeader*, alloc(allocator, sizeof(ArrayHeader) + sizeof(Type) * capacity));
|
||||||
|
|
||||||
|
if (header == nullptr)
|
||||||
|
return {nullptr};
|
||||||
|
|
||||||
|
header->Allocator = allocator;
|
||||||
|
header->Capacity = capacity;
|
||||||
|
header->Num = 0;
|
||||||
|
|
||||||
|
return {rcast(Type*, header + 1)};
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
usize array_grow_formula(ssize value) {
|
||||||
|
return 2 * value + 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
bool array_append_array(Array<Type>* array, Array<Type> other) {
|
||||||
|
return array_append_items(array, (Type*)other, array_num(other));
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
bool array_append(Array<Type>* array, Type value)
|
||||||
|
{
|
||||||
|
GEN_ASSERT( array != nullptr);
|
||||||
|
GEN_ASSERT(* array != nullptr);
|
||||||
|
ArrayHeader* header = array_get_header(* array);
|
||||||
|
|
||||||
|
if (header->Num == header->Capacity)
|
||||||
|
{
|
||||||
|
if ( ! array_grow(array, header->Capacity))
|
||||||
|
return false;
|
||||||
|
header = array_get_header(* array);
|
||||||
|
}
|
||||||
|
|
||||||
|
(*array)[ header->Num] = value;
|
||||||
|
header->Num++;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
bool array_append_items(Array<Type>* array, Type* items, usize item_num)
|
||||||
|
{
|
||||||
|
GEN_ASSERT( array != nullptr);
|
||||||
|
GEN_ASSERT(* array != nullptr);
|
||||||
|
GEN_ASSERT(items != nullptr);
|
||||||
|
GEN_ASSERT(item_num > 0);
|
||||||
|
ArrayHeader* header = array_get_header(* array);
|
||||||
|
|
||||||
|
if (header->Num + item_num > header->Capacity)
|
||||||
|
{
|
||||||
|
if ( ! array_grow(array, header->Capacity + item_num))
|
||||||
|
return false;
|
||||||
|
header = array_get_header(* array);
|
||||||
|
}
|
||||||
|
|
||||||
|
mem_copy((Type*)array + header->Num, items, item_num * sizeof(Type));
|
||||||
|
header->Num += item_num;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
bool array_append_at(Array<Type>* array, Type item, usize idx)
|
||||||
|
{
|
||||||
|
GEN_ASSERT( array != nullptr);
|
||||||
|
GEN_ASSERT(* array != nullptr);
|
||||||
|
ArrayHeader* header = array_get_header(* array);
|
||||||
|
|
||||||
|
ssize slot = idx;
|
||||||
|
if (slot >= (ssize)(header->Num))
|
||||||
|
slot = header->Num - 1;
|
||||||
|
|
||||||
|
if (slot < 0)
|
||||||
|
slot = 0;
|
||||||
|
|
||||||
|
if (header->Capacity < header->Num + 1)
|
||||||
|
{
|
||||||
|
if ( ! array_grow(array, header->Capacity + 1))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
header = array_get_header(* array);
|
||||||
|
}
|
||||||
|
|
||||||
|
Type* target = &(*array)[slot];
|
||||||
|
|
||||||
|
mem_move(target + 1, target, (header->Num - slot) * sizeof(Type));
|
||||||
|
header->Num++;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
bool array_append_items_at(Array<Type>* array, Type* items, usize item_num, usize idx)
|
||||||
|
{
|
||||||
|
GEN_ASSERT( array != nullptr);
|
||||||
|
GEN_ASSERT(* array != nullptr);
|
||||||
|
ArrayHeader* header = get_header(array);
|
||||||
|
|
||||||
|
if (idx >= header->Num)
|
||||||
|
{
|
||||||
|
return array_append_items(array, items, item_num);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item_num > header->Capacity)
|
||||||
|
{
|
||||||
|
if (! grow(array, header->Capacity + item_num))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
header = get_header(array);
|
||||||
|
}
|
||||||
|
|
||||||
|
Type* target = array.Data + idx + item_num;
|
||||||
|
Type* src = array.Data + idx;
|
||||||
|
|
||||||
|
mem_move(target, src, (header->Num - idx) * sizeof(Type));
|
||||||
|
mem_copy(src, items, item_num * sizeof(Type));
|
||||||
|
header->Num += item_num;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
Type* array_back(Array<Type> array)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(array != nullptr);
|
||||||
|
|
||||||
|
ArrayHeader* header = array_get_header(array);
|
||||||
|
if (header->Num <= 0)
|
||||||
|
return nullptr;
|
||||||
|
|
||||||
|
return & (array)[header->Num - 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
void array_clear(Array<Type> array) {
|
||||||
|
GEN_ASSERT(array != nullptr);
|
||||||
|
ArrayHeader* header = array_get_header(array);
|
||||||
|
header->Num = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
bool array_fill(Array<Type> array, usize begin, usize end, Type value)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(array != nullptr);
|
||||||
|
GEN_ASSERT(begin <= end);
|
||||||
|
ArrayHeader* header = array_get_header(array);
|
||||||
|
|
||||||
|
if (begin < 0 || end > header->Num)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
for (ssize idx = ssize(begin); idx < ssize(end); idx++) {
|
||||||
|
array[idx] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> forceinline
|
||||||
|
void array_free(Array<Type>* array) {
|
||||||
|
GEN_ASSERT( array != nullptr);
|
||||||
|
GEN_ASSERT(* array != nullptr);
|
||||||
|
ArrayHeader* header = array_get_header(* array);
|
||||||
|
allocator_free(header->Allocator, header);
|
||||||
|
Type** Data = (Type**)array;
|
||||||
|
*Data = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> forceinline
|
||||||
|
ArrayHeader* array_get_header(Array<Type> array) {
|
||||||
|
GEN_ASSERT(array != nullptr);
|
||||||
|
Type* Data = array;
|
||||||
|
|
||||||
|
using NonConstType = TRemoveConst<Type>;
|
||||||
|
return rcast(ArrayHeader*, const_cast<NonConstType*>(Data)) - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> forceinline
|
||||||
|
bool array_grow(Array<Type>* array, usize min_capacity)
|
||||||
|
{
|
||||||
|
GEN_ASSERT( array != nullptr);
|
||||||
|
GEN_ASSERT(* array != nullptr);
|
||||||
|
GEN_ASSERT( min_capacity > 0 );
|
||||||
|
ArrayHeader* header = array_get_header(* array);
|
||||||
|
usize new_capacity = array_grow_formula(header->Capacity);
|
||||||
|
|
||||||
|
if (new_capacity < min_capacity)
|
||||||
|
new_capacity = min_capacity;
|
||||||
|
|
||||||
|
return array_set_capacity(array, new_capacity);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> forceinline
|
||||||
|
usize array_num(Array<Type> array) {
|
||||||
|
GEN_ASSERT(array != nullptr);
|
||||||
|
return array_get_header(array)->Num;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> forceinline
|
||||||
|
void array_pop(Array<Type> array) {
|
||||||
|
GEN_ASSERT(array != nullptr);
|
||||||
|
ArrayHeader* header = array_get_header(array);
|
||||||
|
GEN_ASSERT(header->Num > 0);
|
||||||
|
header->Num--;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
void array_remove_at(Array<Type> array, usize idx)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(array != nullptr);
|
||||||
|
ArrayHeader* header = array_get_header(array);
|
||||||
|
GEN_ASSERT(idx < header->Num);
|
||||||
|
|
||||||
|
mem_move(array + idx, array + idx + 1, sizeof(Type) * (header->Num - idx - 1));
|
||||||
|
header->Num--;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
bool array_reserve(Array<Type>* array, usize new_capacity)
|
||||||
|
{
|
||||||
|
GEN_ASSERT( array != nullptr);
|
||||||
|
GEN_ASSERT(* array != nullptr);
|
||||||
|
ArrayHeader* header = array_get_header(array);
|
||||||
|
|
||||||
|
if (header->Capacity < new_capacity)
|
||||||
|
return set_capacity(array, new_capacity);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
bool array_resize(Array<Type>* array, usize num)
|
||||||
|
{
|
||||||
|
GEN_ASSERT( array != nullptr);
|
||||||
|
GEN_ASSERT(* array != nullptr);
|
||||||
|
ArrayHeader* header = array_get_header(* array);
|
||||||
|
|
||||||
|
if (header->Capacity < num) {
|
||||||
|
if (! array_grow( array, num))
|
||||||
|
return false;
|
||||||
|
header = array_get_header(* array);
|
||||||
|
}
|
||||||
|
|
||||||
|
header->Num = num;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class Type> inline
|
||||||
|
bool array_set_capacity(Array<Type>* array, usize new_capacity)
|
||||||
|
{
|
||||||
|
GEN_ASSERT( array != nullptr);
|
||||||
|
GEN_ASSERT(* array != nullptr);
|
||||||
|
ArrayHeader* header = array_get_header(* array);
|
||||||
|
|
||||||
|
if (new_capacity == header->Capacity)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (new_capacity < header->Num)
|
||||||
|
{
|
||||||
|
header->Num = new_capacity;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize size = sizeof(ArrayHeader) + sizeof(Type) * new_capacity;
|
||||||
|
ArrayHeader* new_header = rcast(ArrayHeader*, alloc(header->Allocator, size));
|
||||||
|
|
||||||
|
if (new_header == nullptr)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
mem_move(new_header, header, sizeof(ArrayHeader) + sizeof(Type) * header->Num);
|
||||||
|
|
||||||
|
new_header->Capacity = new_capacity;
|
||||||
|
|
||||||
|
allocator_free(header->Allocator, header);
|
||||||
|
|
||||||
|
Type** Data = (Type**)array;
|
||||||
|
* Data = rcast(Type*, new_header + 1);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// These are intended for use in the base library of gencpp and the C-variant of the library
|
||||||
|
// It provides a interoperability between the C++ and C implementation of arrays. (not letting these do any crazy substiution though)
|
||||||
|
// They are undefined in gen.hpp and gen.cpp at the end of the files.
|
||||||
|
// The cpp library expects the user to use the regular calls as they can resolve the type fine.
|
||||||
|
|
||||||
|
#define array_init(type, allocator) array_init <type> (allocator )
|
||||||
|
#define array_init_reserve(type, allocator, cap) array_init_reserve <type> (allocator, cap)
|
||||||
|
#define array_append_array(array, other) array_append_array < get_array_underlying_type(array) > (& array, other )
|
||||||
|
#define array_append(array, value) array_append < get_array_underlying_type(array) > (& array, value )
|
||||||
|
#define array_append_items(array, items, item_num) array_append_items < get_array_underlying_type(array) > (& array, items, item_num )
|
||||||
|
#define array_append_at(array, item, idx ) array_append_at < get_array_underlying_type(array) > (& array, item, idx )
|
||||||
|
#define array_append_at_items(array, items, item_num, idx) array_append_at_items< get_array_underlying_type(array) > (& items, item_num, idx )
|
||||||
|
#define array_back(array) array_back < get_array_underlying_type(array) > (array )
|
||||||
|
#define array_clear(array) array_clear < get_array_underlying_type(array) > (array )
|
||||||
|
#define array_fill(array, begin, end, value) array_fill < get_array_underlying_type(array) > (array, begin, end, value )
|
||||||
|
#define array_free(array) array_free < get_array_underlying_type(array) > (& array )
|
||||||
|
#define arary_grow(array, min_capacity) arary_grow < get_array_underlying_type(array) > (& array, min_capacity)
|
||||||
|
#define array_num(array) array_num < get_array_underlying_type(array) > (array )
|
||||||
|
#define arary_pop(array) arary_pop < get_array_underlying_type(array) > (array )
|
||||||
|
#define arary_remove_at(array, idx) arary_remove_at < get_array_underlying_type(array) > (idx)
|
||||||
|
#define arary_reserve(array, new_capacity) arary_reserve < get_array_underlying_type(array) > (& array, new_capacity )
|
||||||
|
#define arary_resize(array, num) arary_resize < get_array_underlying_type(array) > (& array, num)
|
||||||
|
#define arary_set_capacity(new_capacity) arary_set_capacity < get_array_underlying_type(array) > (& array, new_capacity )
|
||||||
|
#define arary_get_header(array) arary_get_header < get_array_underlying_type(array) > (array )
|
||||||
|
|
||||||
|
#pragma endregion Array
|
||||||
|
|
||||||
|
#pragma region HashTable
|
||||||
|
#define HashTable(Type) HashTable<Type>
|
||||||
|
|
||||||
|
template<class Type> struct HashTable;
|
||||||
|
|
||||||
|
#ifndef get_hashtable_underlying_type
|
||||||
|
#define get_hashtable_underlying_type(table) typename TRemovePtr<typeof(table)>:: DataType
|
||||||
|
#endif
|
||||||
|
|
||||||
|
struct HashTableFindResult {
|
||||||
|
ssize HashIndex;
|
||||||
|
ssize PrevIndex;
|
||||||
|
ssize EntryIndex;
|
||||||
|
};
|
||||||
|
|
||||||
|
template<class Type>
|
||||||
|
struct HashTableEntry {
|
||||||
|
u64 Key;
|
||||||
|
ssize Next;
|
||||||
|
Type Value;
|
||||||
|
};
|
||||||
|
|
||||||
|
#define HashTableEntry(Type) HashTableEntry<Type>
|
||||||
|
|
||||||
|
template<class Type> HashTable<Type> hashtable_init (AllocatorInfo allocator);
|
||||||
|
template<class Type> HashTable<Type> hashtable_init_reserve(AllocatorInfo allocator, usize num);
|
||||||
|
template<class Type> void hashtable_clear (HashTable<Type> table);
|
||||||
|
template<class Type> void hashtable_destroy (HashTable<Type>* table);
|
||||||
|
template<class Type> Type* hashtable_get (HashTable<Type> table, u64 key);
|
||||||
|
template<class Type> void hashtable_grow (HashTable<Type>* table);
|
||||||
|
template<class Type> void hashtable_rehash (HashTable<Type>* table, ssize new_num);
|
||||||
|
template<class Type> void hashtable_rehash_fast (HashTable<Type> table);
|
||||||
|
template<class Type> void hashtable_remove (HashTable<Type> table, u64 key);
|
||||||
|
template<class Type> void hashtable_remove_entry(HashTable<Type> table, ssize idx);
|
||||||
|
template<class Type> void hashtable_set (HashTable<Type>* table, u64 key, Type value);
|
||||||
|
template<class Type> ssize hashtable_slot (HashTable<Type> table, u64 key);
|
||||||
|
template<class Type> void hashtable_map (HashTable<Type> table, void (*map_proc)(u64 key, Type value));
|
||||||
|
template<class Type> void hashtable_map_mut (HashTable<Type> table, void (*map_proc)(u64 key, Type* value));
|
||||||
|
|
||||||
|
template<class Type> ssize hashtable__add_entry (HashTable<Type>* table, u64 key);
|
||||||
|
template<class Type> HashTableFindResult hashtable__find (HashTable<Type> table, u64 key);
|
||||||
|
template<class Type> bool hashtable__full (HashTable<Type> table);
|
||||||
|
|
||||||
|
static constexpr f32 HashTable_CriticalLoadScale = 0.7f;
|
||||||
|
|
||||||
|
template<typename Type>
|
||||||
|
struct HashTable
|
||||||
|
{
|
||||||
|
Array<ssize> Hashes;
|
||||||
|
Array<HashTableEntry<Type>> Entries;
|
||||||
|
|
||||||
|
#if ! GEN_C_LIKE_CPP
|
||||||
|
#pragma region Member Mapping
|
||||||
|
forceinline static HashTable init(AllocatorInfo allocator) { return hashtable_init<Type>(allocator); }
|
||||||
|
forceinline static HashTable init_reserve(AllocatorInfo allocator, usize num) { return hashtable_init_reserve<Type>(allocator, num); }
|
||||||
|
|
||||||
|
forceinline void clear() { clear<Type>(*this); }
|
||||||
|
forceinline void destroy() { destroy<Type>(*this); }
|
||||||
|
forceinline Type* get(u64 key) { return get<Type>(*this, key); }
|
||||||
|
forceinline void grow() { grow<Type>(*this); }
|
||||||
|
forceinline void rehash(ssize new_num) { rehash<Type>(*this, new_num); }
|
||||||
|
forceinline void rehash_fast() { rehash_fast<Type>(*this); }
|
||||||
|
forceinline void remove(u64 key) { remove<Type>(*this, key); }
|
||||||
|
forceinline void remove_entry(ssize idx) { remove_entry<Type>(*this, idx); }
|
||||||
|
forceinline void set(u64 key, Type value) { set<Type>(*this, key, value); }
|
||||||
|
forceinline ssize slot(u64 key) { return slot<Type>(*this, key); }
|
||||||
|
forceinline void map(void (*proc)(u64, Type)) { map<Type>(*this, proc); }
|
||||||
|
forceinline void map_mut(void (*proc)(u64, Type*)) { map_mut<Type>(*this, proc); }
|
||||||
|
#pragma endregion Member Mapping
|
||||||
|
#endif
|
||||||
|
|
||||||
|
using DataType = Type;
|
||||||
|
};
|
||||||
|
|
||||||
|
#if GEN_SUPPORT_CPP_REFERENCES
|
||||||
|
template<class Type> void destroy (HashTable<Type>& table) { destroy(& table); }
|
||||||
|
template<class Type> void grow (HashTable<Type>& table) { grow(& table); }
|
||||||
|
template<class Type> void rehash (HashTable<Type>& table, ssize new_num) { rehash(& table, new_num); }
|
||||||
|
template<class Type> void set (HashTable<Type>& table, u64 key, Type value) { set(& table, key, value); }
|
||||||
|
template<class Type> ssize add_entry(HashTable<Type>& table, u64 key) { add_entry(& table, key); }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
template<typename Type> inline
|
||||||
|
HashTable<Type> hashtable_init(AllocatorInfo allocator) {
|
||||||
|
HashTable<Type> result = hashtable_init_reserve<Type>(allocator, 8);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> inline
|
||||||
|
HashTable<Type> hashtable_init_reserve(AllocatorInfo allocator, usize num)
|
||||||
|
{
|
||||||
|
HashTable<Type> result = { { nullptr }, { nullptr } };
|
||||||
|
|
||||||
|
result.Hashes = array_init_reserve<ssize>(allocator, num);
|
||||||
|
array_get_header(result.Hashes)->Num = num;
|
||||||
|
array_resize(& result.Hashes, num);
|
||||||
|
array_fill(result.Hashes, 0, num, (ssize)-1);
|
||||||
|
|
||||||
|
result.Entries = array_init_reserve<HashTableEntry<Type>>(allocator, num);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> forceinline
|
||||||
|
void hashtable_clear(HashTable<Type> table) {
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Entries);
|
||||||
|
array_clear(table.Entries);
|
||||||
|
array_fill(table.Hashes, 0, array_num(table.Hashes), (ssize)-1);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> forceinline
|
||||||
|
void hashtable_destroy(HashTable<Type>* table) {
|
||||||
|
GEN_ASSERT_NOT_NULL(table->Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table->Entries);
|
||||||
|
if (table->Hashes && array_get_header(table->Hashes)->Capacity) {
|
||||||
|
array_free(table->Hashes);
|
||||||
|
array_free(table->Entries);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> forceinline
|
||||||
|
Type* hashtable_get(HashTable<Type> table, u64 key) {
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Entries);
|
||||||
|
ssize idx = hashtable__find(table, key).EntryIndex;
|
||||||
|
if (idx >= 0)
|
||||||
|
return & table.Entries[idx].Value;
|
||||||
|
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> forceinline
|
||||||
|
void hashtable_map(HashTable<Type> table, void (*map_proc)(u64 key, Type value)) {
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Entries);
|
||||||
|
GEN_ASSERT_NOT_NULL(map_proc);
|
||||||
|
|
||||||
|
for (ssize idx = 0; idx < ssize(num(table.Entries)); ++idx) {
|
||||||
|
map_proc(table.Entries[idx].Key, table.Entries[idx].Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> forceinline
|
||||||
|
void hashtable_map_mut(HashTable<Type> table, void (*map_proc)(u64 key, Type* value)) {
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Entries);
|
||||||
|
GEN_ASSERT_NOT_NULL(map_proc);
|
||||||
|
|
||||||
|
for (ssize idx = 0; idx < ssize(num(table.Entries)); ++idx) {
|
||||||
|
map_proc(table.Entries[idx].Key, & table.Entries[idx].Value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> forceinline
|
||||||
|
void hashtable_grow(HashTable<Type>* table) {
|
||||||
|
GEN_ASSERT_NOT_NULL(table);
|
||||||
|
GEN_ASSERT_NOT_NULL(table->Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table->Entries);
|
||||||
|
ssize new_num = array_grow_formula( array_num(table->Entries));
|
||||||
|
hashtable_rehash(table, new_num);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> inline
|
||||||
|
void hashtable_rehash(HashTable<Type>* table, ssize new_num)
|
||||||
|
{
|
||||||
|
GEN_ASSERT_NOT_NULL(table);
|
||||||
|
GEN_ASSERT_NOT_NULL(table->Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table->Entries);
|
||||||
|
ssize last_added_index;
|
||||||
|
HashTable<Type> new_ht = hashtable_init_reserve<Type>( array_get_header(table->Hashes)->Allocator, new_num);
|
||||||
|
|
||||||
|
for (ssize idx = 0; idx < ssize( array_num(table->Entries)); ++idx)
|
||||||
|
{
|
||||||
|
HashTableFindResult find_result;
|
||||||
|
HashTableEntry<Type>& entry = table->Entries[idx];
|
||||||
|
|
||||||
|
find_result = hashtable__find(new_ht, entry.Key);
|
||||||
|
last_added_index = hashtable__add_entry(& new_ht, entry.Key);
|
||||||
|
|
||||||
|
if (find_result.PrevIndex < 0)
|
||||||
|
new_ht.Hashes[find_result.HashIndex] = last_added_index;
|
||||||
|
else
|
||||||
|
new_ht.Entries[find_result.PrevIndex].Next = last_added_index;
|
||||||
|
|
||||||
|
new_ht.Entries[last_added_index].Next = find_result.EntryIndex;
|
||||||
|
new_ht.Entries[last_added_index].Value = entry.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
hashtable_destroy(table);
|
||||||
|
* table = new_ht;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> inline
|
||||||
|
void hashtable_rehash_fast(HashTable<Type> table)
|
||||||
|
{
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Entries);
|
||||||
|
ssize idx;
|
||||||
|
|
||||||
|
for (idx = 0; idx < ssize(num(table.Entries)); idx++)
|
||||||
|
table.Entries[idx].Next = -1;
|
||||||
|
|
||||||
|
for (idx = 0; idx < ssize(num(table.Hashes)); idx++)
|
||||||
|
table.Hashes[idx] = -1;
|
||||||
|
|
||||||
|
for (idx = 0; idx < ssize(num(table.Entries)); idx++)
|
||||||
|
{
|
||||||
|
HashTableEntry<Type>* entry;
|
||||||
|
HashTableFindResult find_result;
|
||||||
|
|
||||||
|
entry = &table.Entries[idx];
|
||||||
|
find_result = find(table, entry->Key);
|
||||||
|
|
||||||
|
if (find_result.PrevIndex < 0)
|
||||||
|
table.Hashes[find_result.HashIndex] = idx;
|
||||||
|
else
|
||||||
|
table.Entries[find_result.PrevIndex].Next = idx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> forceinline
|
||||||
|
void hashtable_remove(HashTable<Type> table, u64 key) {
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Entries);
|
||||||
|
HashTableFindResult find_result = find(table, key);
|
||||||
|
|
||||||
|
if (find_result.EntryIndex >= 0) {
|
||||||
|
remove_at(table.Entries, find_result.EntryIndex);
|
||||||
|
rehash_fast(table);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> forceinline
|
||||||
|
void hashtable_remove_entry(HashTable<Type> table, ssize idx) {
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Entries);
|
||||||
|
remove_at(table.Entries, idx);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> inline
|
||||||
|
void hashtable_set(HashTable<Type>* table, u64 key, Type value)
|
||||||
|
{
|
||||||
|
GEN_ASSERT_NOT_NULL(table);
|
||||||
|
GEN_ASSERT_NOT_NULL(table->Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table->Entries);
|
||||||
|
ssize idx;
|
||||||
|
HashTableFindResult find_result;
|
||||||
|
|
||||||
|
if (hashtable_full(* table))
|
||||||
|
hashtable_grow(table);
|
||||||
|
|
||||||
|
find_result = hashtable__find(* table, key);
|
||||||
|
if (find_result.EntryIndex >= 0) {
|
||||||
|
idx = find_result.EntryIndex;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
idx = hashtable__add_entry(table, key);
|
||||||
|
|
||||||
|
if (find_result.PrevIndex >= 0) {
|
||||||
|
table->Entries[find_result.PrevIndex].Next = idx;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
table->Hashes[find_result.HashIndex] = idx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
table->Entries[idx].Value = value;
|
||||||
|
|
||||||
|
if (hashtable_full(* table))
|
||||||
|
hashtable_grow(table);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> forceinline
|
||||||
|
ssize hashtable_slot(HashTable<Type> table, u64 key) {
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Entries);
|
||||||
|
for (ssize idx = 0; idx < ssize(num(table.Hashes)); ++idx)
|
||||||
|
if (table.Hashes[idx] == key)
|
||||||
|
return idx;
|
||||||
|
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> forceinline
|
||||||
|
ssize hashtable__add_entry(HashTable<Type>* table, u64 key) {
|
||||||
|
GEN_ASSERT_NOT_NULL(table);
|
||||||
|
GEN_ASSERT_NOT_NULL(table->Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table->Entries);
|
||||||
|
ssize idx;
|
||||||
|
HashTableEntry<Type> entry = { key, -1 };
|
||||||
|
|
||||||
|
idx = array_num(table->Entries);
|
||||||
|
array_append( table->Entries, entry);
|
||||||
|
return idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> inline
|
||||||
|
HashTableFindResult hashtable__find(HashTable<Type> table, u64 key)
|
||||||
|
{
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Entries);
|
||||||
|
HashTableFindResult result = { -1, -1, -1 };
|
||||||
|
|
||||||
|
if (array_num(table.Hashes) > 0)
|
||||||
|
{
|
||||||
|
result.HashIndex = key % array_num(table.Hashes);
|
||||||
|
result.EntryIndex = table.Hashes[result.HashIndex];
|
||||||
|
|
||||||
|
while (result.EntryIndex >= 0)
|
||||||
|
{
|
||||||
|
if (table.Entries[result.EntryIndex].Key == key)
|
||||||
|
break;
|
||||||
|
|
||||||
|
result.PrevIndex = result.EntryIndex;
|
||||||
|
result.EntryIndex = table.Entries[result.EntryIndex].Next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename Type> forceinline
|
||||||
|
b32 hashtable_full(HashTable<Type> table) {
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Hashes);
|
||||||
|
GEN_ASSERT_NOT_NULL(table.Entries);
|
||||||
|
usize critical_load = usize(HashTable_CriticalLoadScale * f32(array_num(table.Hashes)));
|
||||||
|
b32 result = array_num(table.Entries) > critical_load;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
#define hashtable_init(type, allocator) hashtable_init <type >(allocator)
|
||||||
|
#define hashtable_init_reserve(type, allocator, num) hashtable_init_reserve<type >(allocator, num)
|
||||||
|
#define hashtable_clear(table) hashtable_clear < get_hashtable_underlying_type(table) >(table)
|
||||||
|
#define hashtable_destroy(table) hashtable_destroy < get_hashtable_underlying_type(table) >(& table)
|
||||||
|
#define hashtable_get(table, key) hashtable_get < get_hashtable_underlying_type(table) >(table, key)
|
||||||
|
#define hashtable_grow(table) hashtable_grow < get_hashtable_underlying_type(table) >(& table)
|
||||||
|
#define hashtable_rehash(table, new_num) hashtable_rehash < get_hashtable_underlying_type(table) >(& table, new_num)
|
||||||
|
#define hashtable_rehash_fast(table) hashtable_rehash_fast < get_hashtable_underlying_type(table) >(table)
|
||||||
|
#define hashtable_remove(table, key) hashtable_remove < get_hashtable_underlying_type(table) >(table, key)
|
||||||
|
#define hashtable_remove_entry(table, idx) hashtable_remove_entry< get_hashtable_underlying_type(table) >(table, idx)
|
||||||
|
#define hashtable_set(table, key, value) hashtable_set < get_hashtable_underlying_type(table) >(& table, key, value)
|
||||||
|
#define hashtable_slot(table, key) hashtable_slot < get_hashtable_underlying_type(table) >(table, key)
|
||||||
|
#define hashtable_map(table, map_proc) hashtable_map < get_hashtable_underlying_type(table) >(table, map_proc)
|
||||||
|
#define hashtable_map_mut(table, map_proc) hashtable_map_mut < get_hashtable_underlying_type(table) >(table, map_proc)
|
||||||
|
|
||||||
|
//#define hashtable_add_entry(table, key) hashtable_add_entry < get_hashtable_underlying_type(table) >(& table, key)
|
||||||
|
//#define hashtable_find(table, key) hashtable_find < get_hashtable_underlying_type(table) >(table, key)
|
||||||
|
//#define hashtable_full(table) hashtable_full < get_hashtable_underlying_type(table) >(table)
|
||||||
|
|
||||||
|
#pragma endregion HashTable
|
||||||
|
|
||||||
|
#pragma endregion Containers
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "src_start.cpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Debug
|
||||||
|
|
||||||
|
void assert_handler( char const* condition, char const* file, char const* function, s32 line, char const* msg, ... )
|
||||||
|
{
|
||||||
|
_printf_err( "%s - %s:(%d): Assert Failure: ", file, function, line );
|
||||||
|
|
||||||
|
if ( condition )
|
||||||
|
_printf_err( "`%s` \n", condition );
|
||||||
|
|
||||||
|
if ( msg )
|
||||||
|
{
|
||||||
|
va_list va;
|
||||||
|
va_start( va, msg );
|
||||||
|
_printf_err_va( msg, va );
|
||||||
|
va_end( va );
|
||||||
|
}
|
||||||
|
|
||||||
|
_printf_err( "%s", "\n" );
|
||||||
|
}
|
||||||
|
|
||||||
|
s32 assert_crash( char const* condition )
|
||||||
|
{
|
||||||
|
GEN_PANIC( condition );
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined( GEN_SYSTEM_WINDOWS )
|
||||||
|
void process_exit( u32 code )
|
||||||
|
{
|
||||||
|
ExitProcess( code );
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
# include <stdlib.h>
|
||||||
|
|
||||||
|
void process_exit( u32 code )
|
||||||
|
{
|
||||||
|
exit( code );
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Debug
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "basic_types.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Debug
|
||||||
|
|
||||||
|
#if GEN_BUILD_DEBUG
|
||||||
|
# if defined( GEN_COMPILER_MSVC )
|
||||||
|
# if _MSC_VER < 1300
|
||||||
|
// #pragma message("GEN_BUILD_DEBUG: __asm int 3")
|
||||||
|
# define GEN_DEBUG_TRAP() __asm int 3 /* Trap to debugger! */
|
||||||
|
# else
|
||||||
|
// #pragma message("GEN_BUILD_DEBUG: __debugbreak()")
|
||||||
|
# define GEN_DEBUG_TRAP() __debugbreak()
|
||||||
|
# endif
|
||||||
|
# elif defined( GEN_COMPILER_TINYC )
|
||||||
|
# define GEN_DEBUG_TRAP() process_exit( 1 )
|
||||||
|
# else
|
||||||
|
# define GEN_DEBUG_TRAP() __builtin_trap()
|
||||||
|
# endif
|
||||||
|
#else
|
||||||
|
// #pragma message("GEN_BUILD_DEBUG: omitted")
|
||||||
|
# define GEN_DEBUG_TRAP()
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define GEN_ASSERT( cond ) GEN_ASSERT_MSG( cond, NULL )
|
||||||
|
|
||||||
|
#define GEN_ASSERT_MSG( cond, msg, ... ) \
|
||||||
|
do \
|
||||||
|
{ \
|
||||||
|
if ( ! ( cond ) ) \
|
||||||
|
{ \
|
||||||
|
assert_handler( #cond, __FILE__, __func__, scast( s64, __LINE__ ), msg, ##__VA_ARGS__ ); \
|
||||||
|
GEN_DEBUG_TRAP(); \
|
||||||
|
} \
|
||||||
|
} while ( 0 )
|
||||||
|
|
||||||
|
#define GEN_ASSERT_NOT_NULL( ptr ) GEN_ASSERT_MSG( ( ptr ) != NULL, #ptr " must not be NULL" )
|
||||||
|
|
||||||
|
// NOTE: Things that shouldn't happen with a message!
|
||||||
|
#define GEN_PANIC( msg, ... ) GEN_ASSERT_MSG( 0, msg, ##__VA_ARGS__ )
|
||||||
|
|
||||||
|
#if GEN_BUILD_DEBUG
|
||||||
|
#define GEN_FATAL( ... ) \
|
||||||
|
do \
|
||||||
|
{ \
|
||||||
|
local_persist thread_local \
|
||||||
|
char buf[GEN_PRINTF_MAXLEN] = { 0 }; \
|
||||||
|
\
|
||||||
|
c_str_fmt(buf, GEN_PRINTF_MAXLEN, __VA_ARGS__); \
|
||||||
|
GEN_PANIC(buf); \
|
||||||
|
} \
|
||||||
|
while (0)
|
||||||
|
#else
|
||||||
|
|
||||||
|
# define GEN_FATAL( ... ) \
|
||||||
|
do \
|
||||||
|
{ \
|
||||||
|
c_str_fmt_out_err( __VA_ARGS__ ); \
|
||||||
|
GEN_DEBUG_TRAP(); \
|
||||||
|
process_exit(1); \
|
||||||
|
} \
|
||||||
|
while (0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
GEN_API void assert_handler( char const* condition, char const* file, char const* function, s32 line, char const* msg, ... );
|
||||||
|
GEN_API s32 assert_crash( char const* condition );
|
||||||
|
GEN_API void process_exit( u32 code );
|
||||||
|
|
||||||
|
#pragma endregion Debug
|
||||||
@@ -0,0 +1,659 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "strings.cpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region File Handling
|
||||||
|
|
||||||
|
#if defined( GEN_SYSTEM_WINDOWS ) || defined( GEN_SYSTEM_CYGWIN )
|
||||||
|
|
||||||
|
internal
|
||||||
|
wchar_t* _alloc_utf8_to_ucs2( AllocatorInfo a, char const* text, ssize* w_len_ )
|
||||||
|
{
|
||||||
|
wchar_t* w_text = NULL;
|
||||||
|
ssize len = 0, w_len = 0, w_len1 = 0;
|
||||||
|
if ( text == NULL )
|
||||||
|
{
|
||||||
|
if ( w_len_ )
|
||||||
|
*w_len_ = w_len;
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
len = c_str_len( text );
|
||||||
|
if ( len == 0 )
|
||||||
|
{
|
||||||
|
if ( w_len_ )
|
||||||
|
*w_len_ = w_len;
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
w_len = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, text, scast( int, len), NULL, 0 );
|
||||||
|
if ( w_len == 0 )
|
||||||
|
{
|
||||||
|
if ( w_len_ )
|
||||||
|
*w_len_ = w_len;
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
w_text = alloc_array( a, wchar_t, w_len + 1 );
|
||||||
|
w_len1 = MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, text, scast( int, len), w_text, scast( int, w_len) );
|
||||||
|
if ( w_len1 == 0 )
|
||||||
|
{
|
||||||
|
allocator_free( a, w_text );
|
||||||
|
if ( w_len_ )
|
||||||
|
*w_len_ = 0;
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
w_text[ w_len ] = 0;
|
||||||
|
if ( w_len_ )
|
||||||
|
*w_len_ = w_len;
|
||||||
|
return w_text;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
GEN_FILE_SEEK_PROC( _win32_file_seek )
|
||||||
|
{
|
||||||
|
LARGE_INTEGER li_offset;
|
||||||
|
li_offset.QuadPart = offset;
|
||||||
|
if ( ! SetFilePointerEx( fd.p, li_offset, &li_offset, whence ) )
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( new_offset )
|
||||||
|
*new_offset = li_offset.QuadPart;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
GEN_FILE_READ_AT_PROC( _win32_file_read )
|
||||||
|
{
|
||||||
|
// unused( stop_at_newline );
|
||||||
|
b32 result = false;
|
||||||
|
_win32_file_seek( fd, offset, ESeekWhence_BEGIN, NULL );
|
||||||
|
DWORD size_ = scast( DWORD, ( size > GEN_I32_MAX ? GEN_I32_MAX : size ));
|
||||||
|
DWORD bytes_read_;
|
||||||
|
if ( ReadFile( fd.p, buffer, size_, &bytes_read_, NULL ) )
|
||||||
|
{
|
||||||
|
if ( bytes_read )
|
||||||
|
*bytes_read = bytes_read_;
|
||||||
|
result = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
GEN_FILE_WRITE_AT_PROC( _win32_file_write )
|
||||||
|
{
|
||||||
|
DWORD size_ = scast( DWORD, ( size > GEN_I32_MAX ? GEN_I32_MAX : size ));
|
||||||
|
DWORD bytes_written_;
|
||||||
|
_win32_file_seek( fd, offset, ESeekWhence_BEGIN, NULL );
|
||||||
|
if ( WriteFile( fd.p, buffer, size_, &bytes_written_, NULL ) )
|
||||||
|
{
|
||||||
|
if ( bytes_written )
|
||||||
|
*bytes_written = bytes_written_;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
GEN_FILE_CLOSE_PROC( _win32_file_close )
|
||||||
|
{
|
||||||
|
CloseHandle( fd.p );
|
||||||
|
}
|
||||||
|
|
||||||
|
FileOperations const default_file_operations = { _win32_file_read, _win32_file_write, _win32_file_seek, _win32_file_close };
|
||||||
|
|
||||||
|
neverinline
|
||||||
|
GEN_FILE_OPEN_PROC( _win32_file_open )
|
||||||
|
{
|
||||||
|
DWORD desired_access;
|
||||||
|
DWORD creation_disposition;
|
||||||
|
void* handle;
|
||||||
|
wchar_t* w_text;
|
||||||
|
|
||||||
|
switch ( mode & GEN_FILE_MODES )
|
||||||
|
{
|
||||||
|
case EFileMode_READ :
|
||||||
|
desired_access = GENERIC_READ;
|
||||||
|
creation_disposition = OPEN_EXISTING;
|
||||||
|
break;
|
||||||
|
case EFileMode_WRITE :
|
||||||
|
desired_access = GENERIC_WRITE;
|
||||||
|
creation_disposition = CREATE_ALWAYS;
|
||||||
|
break;
|
||||||
|
case EFileMode_APPEND :
|
||||||
|
desired_access = GENERIC_WRITE;
|
||||||
|
creation_disposition = OPEN_ALWAYS;
|
||||||
|
break;
|
||||||
|
case EFileMode_READ | EFileMode_RW :
|
||||||
|
desired_access = GENERIC_READ | GENERIC_WRITE;
|
||||||
|
creation_disposition = OPEN_EXISTING;
|
||||||
|
break;
|
||||||
|
case EFileMode_WRITE | EFileMode_RW :
|
||||||
|
desired_access = GENERIC_READ | GENERIC_WRITE;
|
||||||
|
creation_disposition = CREATE_ALWAYS;
|
||||||
|
break;
|
||||||
|
case EFileMode_APPEND | EFileMode_RW :
|
||||||
|
desired_access = GENERIC_READ | GENERIC_WRITE;
|
||||||
|
creation_disposition = OPEN_ALWAYS;
|
||||||
|
break;
|
||||||
|
default :
|
||||||
|
GEN_PANIC( "Invalid file mode" );
|
||||||
|
return EFileError_INVALID;
|
||||||
|
}
|
||||||
|
|
||||||
|
w_text = _alloc_utf8_to_ucs2( heap(), filename, NULL );
|
||||||
|
handle = CreateFileW( w_text, desired_access, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, creation_disposition, FILE_ATTRIBUTE_NORMAL, NULL );
|
||||||
|
|
||||||
|
allocator_free( heap(), w_text );
|
||||||
|
|
||||||
|
if ( handle == INVALID_HANDLE_VALUE )
|
||||||
|
{
|
||||||
|
DWORD err = GetLastError();
|
||||||
|
switch ( err )
|
||||||
|
{
|
||||||
|
case ERROR_FILE_NOT_FOUND :
|
||||||
|
return EFileError_NOT_EXISTS;
|
||||||
|
case ERROR_FILE_EXISTS :
|
||||||
|
return EFileError_EXISTS;
|
||||||
|
case ERROR_ALREADY_EXISTS :
|
||||||
|
return EFileError_EXISTS;
|
||||||
|
case ERROR_ACCESS_DENIED :
|
||||||
|
return EFileError_PERMISSION;
|
||||||
|
}
|
||||||
|
return EFileError_INVALID;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( mode & EFileMode_APPEND )
|
||||||
|
{
|
||||||
|
LARGE_INTEGER offset = { { 0 } };
|
||||||
|
if ( ! SetFilePointerEx( handle, offset, NULL, ESeekWhence_END ) )
|
||||||
|
{
|
||||||
|
CloseHandle( handle );
|
||||||
|
return EFileError_INVALID;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fd->p = handle;
|
||||||
|
*ops = default_file_operations;
|
||||||
|
return EFileError_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
#else // POSIX
|
||||||
|
# include <fcntl.h>
|
||||||
|
|
||||||
|
internal
|
||||||
|
GEN_FILE_SEEK_PROC( _posix_file_seek )
|
||||||
|
{
|
||||||
|
# if defined( GEN_SYSTEM_OSX )
|
||||||
|
s64 res = lseek( fd.i, offset, whence );
|
||||||
|
# else // TODO(ZaKlaus): @fixme lseek64
|
||||||
|
s64 res = lseek( fd.i, offset, whence );
|
||||||
|
# endif
|
||||||
|
if ( res < 0 )
|
||||||
|
return false;
|
||||||
|
if ( new_offset )
|
||||||
|
*new_offset = res;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
GEN_FILE_READ_AT_PROC( _posix_file_read )
|
||||||
|
{
|
||||||
|
unused( stop_at_newline );
|
||||||
|
ssize res = pread( fd.i, buffer, size, offset );
|
||||||
|
if ( res < 0 )
|
||||||
|
return false;
|
||||||
|
if ( bytes_read )
|
||||||
|
*bytes_read = res;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
GEN_FILE_WRITE_AT_PROC( _posix_file_write )
|
||||||
|
{
|
||||||
|
ssize res;
|
||||||
|
s64 curr_offset = 0;
|
||||||
|
_posix_file_seek( fd, 0, ESeekWhence_CURRENT, &curr_offset );
|
||||||
|
if ( curr_offset == offset )
|
||||||
|
{
|
||||||
|
// NOTE: Writing to stdout et al. doesn't like pwrite for numerous reasons
|
||||||
|
res = write( scast( int, fd.i), buffer, size );
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
res = pwrite( scast( int, fd.i), buffer, size, offset );
|
||||||
|
}
|
||||||
|
if ( res < 0 )
|
||||||
|
return false;
|
||||||
|
if ( bytes_written )
|
||||||
|
*bytes_written = res;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
GEN_FILE_CLOSE_PROC( _posix_file_close )
|
||||||
|
{
|
||||||
|
close( fd.i );
|
||||||
|
}
|
||||||
|
|
||||||
|
FileOperations const default_file_operations = { _posix_file_read, _posix_file_write, _posix_file_seek, _posix_file_close };
|
||||||
|
|
||||||
|
neverinline
|
||||||
|
GEN_FILE_OPEN_PROC( _posix_file_open )
|
||||||
|
{
|
||||||
|
s32 os_mode;
|
||||||
|
switch ( mode & GEN_FILE_MODES )
|
||||||
|
{
|
||||||
|
case EFileMode_READ :
|
||||||
|
os_mode = O_RDONLY;
|
||||||
|
break;
|
||||||
|
case EFileMode_WRITE :
|
||||||
|
os_mode = O_WRONLY | O_CREAT | O_TRUNC;
|
||||||
|
break;
|
||||||
|
case EFileMode_APPEND :
|
||||||
|
os_mode = O_WRONLY | O_APPEND | O_CREAT;
|
||||||
|
break;
|
||||||
|
case EFileMode_READ | EFileMode_RW :
|
||||||
|
os_mode = O_RDWR;
|
||||||
|
break;
|
||||||
|
case EFileMode_WRITE | EFileMode_RW :
|
||||||
|
os_mode = O_RDWR | O_CREAT | O_TRUNC;
|
||||||
|
break;
|
||||||
|
case EFileMode_APPEND | EFileMode_RW :
|
||||||
|
os_mode = O_RDWR | O_APPEND | O_CREAT;
|
||||||
|
break;
|
||||||
|
default :
|
||||||
|
GEN_PANIC( "Invalid file mode" );
|
||||||
|
return EFileError_INVALID;
|
||||||
|
}
|
||||||
|
|
||||||
|
fd->i = open( filename, os_mode, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH );
|
||||||
|
if ( fd->i < 0 )
|
||||||
|
{
|
||||||
|
// TODO : More file errors
|
||||||
|
return EFileError_INVALID;
|
||||||
|
}
|
||||||
|
|
||||||
|
*ops = default_file_operations;
|
||||||
|
return EFileError_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// POSIX
|
||||||
|
#endif
|
||||||
|
|
||||||
|
internal void _dirinfo_free_entry( DirEntry* entry );
|
||||||
|
|
||||||
|
// TODO(zpl) : Is this a bad idea?
|
||||||
|
global b32 _std_file_set = false;
|
||||||
|
global FileInfo _std_files[ EFileStandard_COUNT ] = {
|
||||||
|
{
|
||||||
|
{ nullptr, nullptr, nullptr, nullptr },
|
||||||
|
{ nullptr },
|
||||||
|
0,
|
||||||
|
nullptr,
|
||||||
|
0,
|
||||||
|
nullptr
|
||||||
|
} };
|
||||||
|
|
||||||
|
#if defined( GEN_SYSTEM_WINDOWS ) || defined( GEN_SYSTEM_CYGWIN )
|
||||||
|
|
||||||
|
FileInfo* file_get_standard( FileStandardType std )
|
||||||
|
{
|
||||||
|
if ( ! _std_file_set )
|
||||||
|
{
|
||||||
|
# define GEN__SET_STD_FILE( type, v ) \
|
||||||
|
_std_files[ type ].fd.p = v; \
|
||||||
|
_std_files[ type ].ops = default_file_operations
|
||||||
|
GEN__SET_STD_FILE( EFileStandard_INPUT, GetStdHandle( STD_INPUT_HANDLE ) );
|
||||||
|
GEN__SET_STD_FILE( EFileStandard_OUTPUT, GetStdHandle( STD_OUTPUT_HANDLE ) );
|
||||||
|
GEN__SET_STD_FILE( EFileStandard_ERROR, GetStdHandle( STD_ERROR_HANDLE ) );
|
||||||
|
# undef GEN__SET_STD_FILE
|
||||||
|
_std_file_set = true;
|
||||||
|
}
|
||||||
|
return &_std_files[ std ];
|
||||||
|
}
|
||||||
|
|
||||||
|
#else // POSIX
|
||||||
|
|
||||||
|
FileInfo* file_get_standard( FileStandardType std )
|
||||||
|
{
|
||||||
|
if ( ! _std_file_set )
|
||||||
|
{
|
||||||
|
# define GEN__SET_STD_FILE( type, v ) \
|
||||||
|
_std_files[ type ].fd.i = v; \
|
||||||
|
_std_files[ type ].ops = default_file_operations
|
||||||
|
GEN__SET_STD_FILE( EFileStandard_INPUT, 0 );
|
||||||
|
GEN__SET_STD_FILE( EFileStandard_OUTPUT, 1 );
|
||||||
|
GEN__SET_STD_FILE( EFileStandard_ERROR, 2 );
|
||||||
|
# undef GEN__SET_STD_FILE
|
||||||
|
_std_file_set = true;
|
||||||
|
}
|
||||||
|
return &_std_files[ std ];
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
FileError file_close( FileInfo* f )
|
||||||
|
{
|
||||||
|
if ( ! f )
|
||||||
|
return EFileError_INVALID;
|
||||||
|
|
||||||
|
if ( f->filename )
|
||||||
|
allocator_free( heap(), ccast( char*, f->filename ));
|
||||||
|
|
||||||
|
#if defined( GEN_SYSTEM_WINDOWS )
|
||||||
|
if ( f->fd.p == INVALID_HANDLE_VALUE )
|
||||||
|
return EFileError_INVALID;
|
||||||
|
#else
|
||||||
|
if ( f->fd.i < 0 )
|
||||||
|
return EFileError_INVALID;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
if ( f->is_temp )
|
||||||
|
{
|
||||||
|
f->ops.close( f->fd );
|
||||||
|
return EFileError_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( ! f->ops.read_at )
|
||||||
|
f->ops = default_file_operations;
|
||||||
|
f->ops.close( f->fd );
|
||||||
|
|
||||||
|
#if 0
|
||||||
|
if ( f->Dir )
|
||||||
|
{
|
||||||
|
_dirinfo_free_entry( f->Dir );
|
||||||
|
mfree( f->Dir );
|
||||||
|
f->Dir = NULL;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
return EFileError_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
FileError file_new( FileInfo* f, FileDescriptor fd, FileOperations ops, char const* filename )
|
||||||
|
{
|
||||||
|
FileError err = EFileError_NONE;
|
||||||
|
ssize len = c_str_len( filename );
|
||||||
|
|
||||||
|
f->ops = ops;
|
||||||
|
f->fd = fd;
|
||||||
|
f->dir = nullptr;
|
||||||
|
f->last_write_time = 0;
|
||||||
|
f->filename = alloc_array( heap(), char, len + 1 );
|
||||||
|
mem_copy( ccast( char*, f->filename), ccast( char*, filename), len + 1 );
|
||||||
|
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
FileError file_open( FileInfo* f, char const* filename )
|
||||||
|
{
|
||||||
|
return file_open_mode( f, EFileMode_READ, filename );
|
||||||
|
}
|
||||||
|
|
||||||
|
FileError file_open_mode( FileInfo* f, FileMode mode, char const* filename )
|
||||||
|
{
|
||||||
|
FileInfo file_ =
|
||||||
|
{
|
||||||
|
{ nullptr, nullptr, nullptr, nullptr },
|
||||||
|
{ nullptr },
|
||||||
|
0,
|
||||||
|
nullptr,
|
||||||
|
0,
|
||||||
|
nullptr
|
||||||
|
};
|
||||||
|
|
||||||
|
*f = file_;
|
||||||
|
FileError err;
|
||||||
|
|
||||||
|
#if defined( GEN_SYSTEM_WINDOWS ) || defined( GEN_SYSTEM_CYGWIN )
|
||||||
|
err = _win32_file_open( &f->fd, &f->ops, mode, filename );
|
||||||
|
#else
|
||||||
|
err = _posix_file_open( &f->fd, &f->ops, mode, filename );
|
||||||
|
#endif
|
||||||
|
|
||||||
|
if ( err == EFileError_NONE )
|
||||||
|
return file_new( f, f->fd, f->ops, filename );
|
||||||
|
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
s64 file_size( FileInfo* f )
|
||||||
|
{
|
||||||
|
s64 size = 0;
|
||||||
|
s64 prev_offset = file_tell( f );
|
||||||
|
|
||||||
|
file_seek_to_end( f );
|
||||||
|
size = file_tell( f );
|
||||||
|
|
||||||
|
file_seek( f, prev_offset );
|
||||||
|
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
FileContents file_read_contents( AllocatorInfo a, b32 zero_terminate, char const* filepath )
|
||||||
|
{
|
||||||
|
FileContents result;
|
||||||
|
FileInfo file ;
|
||||||
|
|
||||||
|
result.allocator = a;
|
||||||
|
|
||||||
|
if ( file_open( &file, filepath ) == EFileError_NONE )
|
||||||
|
{
|
||||||
|
ssize fsize = scast( ssize , file_size( &file ));
|
||||||
|
if ( fsize > 0 )
|
||||||
|
{
|
||||||
|
result.data = alloc( a, zero_terminate ? fsize + 1 : fsize );
|
||||||
|
result.size = fsize;
|
||||||
|
file_read_at( &file, result.data, result.size, 0 );
|
||||||
|
if ( zero_terminate )
|
||||||
|
{
|
||||||
|
u8* str = rcast( u8*, result.data);
|
||||||
|
str[ fsize ] = '\0';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file_close( &file );
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef struct _memory_fd _memory_fd;
|
||||||
|
struct _memory_fd
|
||||||
|
{
|
||||||
|
u8 magic;
|
||||||
|
u8* buf; //< zpl_array OR plain buffer if we can't write
|
||||||
|
ssize cursor;
|
||||||
|
AllocatorInfo allocator;
|
||||||
|
|
||||||
|
FileStreamFlags flags;
|
||||||
|
ssize cap;
|
||||||
|
};
|
||||||
|
|
||||||
|
#define GEN__FILE_STREAM_FD_MAGIC 37
|
||||||
|
|
||||||
|
FileDescriptor _file_stream_fd_make( _memory_fd* d );
|
||||||
|
_memory_fd* _file_stream_from_fd( FileDescriptor fd );
|
||||||
|
|
||||||
|
inline
|
||||||
|
FileDescriptor _file_stream_fd_make( _memory_fd* d )
|
||||||
|
{
|
||||||
|
FileDescriptor fd = { 0 };
|
||||||
|
fd.p = ( void* )d;
|
||||||
|
return fd;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
_memory_fd* _file_stream_from_fd( FileDescriptor fd )
|
||||||
|
{
|
||||||
|
_memory_fd* d = ( _memory_fd* )fd.p;
|
||||||
|
GEN_ASSERT( d->magic == GEN__FILE_STREAM_FD_MAGIC );
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
b8 file_stream_new( FileInfo* file, AllocatorInfo allocator )
|
||||||
|
{
|
||||||
|
GEN_ASSERT_NOT_NULL( file );
|
||||||
|
|
||||||
|
_memory_fd* d = ( _memory_fd* )alloc( allocator, size_of( _memory_fd ) );
|
||||||
|
|
||||||
|
if ( ! d )
|
||||||
|
return false;
|
||||||
|
|
||||||
|
zero_item( file );
|
||||||
|
d->magic = GEN__FILE_STREAM_FD_MAGIC;
|
||||||
|
d->allocator = allocator;
|
||||||
|
d->flags = EFileStream_CLONE_WRITABLE;
|
||||||
|
d->cap = 0;
|
||||||
|
d->buf = array_init( u8, allocator );
|
||||||
|
|
||||||
|
if ( ! d->buf )
|
||||||
|
return false;
|
||||||
|
|
||||||
|
file->ops = memory_file_operations;
|
||||||
|
file->fd = _file_stream_fd_make( d );
|
||||||
|
file->dir = NULL;
|
||||||
|
file->last_write_time = 0;
|
||||||
|
file->filename = NULL;
|
||||||
|
file->is_temp = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
b8 file_stream_open( FileInfo* file, AllocatorInfo allocator, u8* buffer, ssize size, FileStreamFlags flags )
|
||||||
|
{
|
||||||
|
GEN_ASSERT_NOT_NULL( file );
|
||||||
|
_memory_fd* d = ( _memory_fd* )alloc( allocator, size_of( _memory_fd ) );
|
||||||
|
if ( ! d )
|
||||||
|
return false;
|
||||||
|
zero_item( file );
|
||||||
|
d->magic = GEN__FILE_STREAM_FD_MAGIC;
|
||||||
|
d->allocator = allocator;
|
||||||
|
d->flags = flags;
|
||||||
|
if ( d->flags & EFileStream_CLONE_WRITABLE )
|
||||||
|
{
|
||||||
|
Array(u8) arr = array_init_reserve(u8, allocator, size );
|
||||||
|
d->buf = arr;
|
||||||
|
|
||||||
|
if ( ! d->buf )
|
||||||
|
return false;
|
||||||
|
|
||||||
|
mem_copy( d->buf, buffer, size );
|
||||||
|
d->cap = size;
|
||||||
|
|
||||||
|
array_get_header(arr)->Num = size;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
d->buf = buffer;
|
||||||
|
d->cap = size;
|
||||||
|
}
|
||||||
|
file->ops = memory_file_operations;
|
||||||
|
file->fd = _file_stream_fd_make( d );
|
||||||
|
file->dir = NULL;
|
||||||
|
file->last_write_time = 0;
|
||||||
|
file->filename = NULL;
|
||||||
|
file->is_temp = true;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
u8* file_stream_buf( FileInfo* file, ssize* size )
|
||||||
|
{
|
||||||
|
GEN_ASSERT_NOT_NULL( file );
|
||||||
|
_memory_fd* d = _file_stream_from_fd( file->fd );
|
||||||
|
if ( size )
|
||||||
|
*size = d->cap;
|
||||||
|
return d->buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
GEN_FILE_SEEK_PROC( _memory_file_seek )
|
||||||
|
{
|
||||||
|
_memory_fd* d = _file_stream_from_fd( fd );
|
||||||
|
ssize buflen = d->cap;
|
||||||
|
|
||||||
|
if ( whence == ESeekWhence_BEGIN )
|
||||||
|
d->cursor = 0;
|
||||||
|
else if ( whence == ESeekWhence_END )
|
||||||
|
d->cursor = buflen;
|
||||||
|
|
||||||
|
d->cursor = max( 0, clamp( d->cursor + offset, 0, buflen ) );
|
||||||
|
if ( new_offset )
|
||||||
|
*new_offset = d->cursor;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
GEN_FILE_READ_AT_PROC( _memory_file_read )
|
||||||
|
{
|
||||||
|
// unused( stop_at_newline );
|
||||||
|
_memory_fd* d = _file_stream_from_fd( fd );
|
||||||
|
mem_copy( buffer, d->buf + offset, size );
|
||||||
|
if ( bytes_read )
|
||||||
|
*bytes_read = size;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
GEN_FILE_WRITE_AT_PROC( _memory_file_write )
|
||||||
|
{
|
||||||
|
_memory_fd* d = _file_stream_from_fd( fd );
|
||||||
|
|
||||||
|
if ( ! ( d->flags & ( EFileStream_CLONE_WRITABLE | EFileStream_WRITABLE ) ) )
|
||||||
|
return false;
|
||||||
|
|
||||||
|
ssize buflen = d->cap;
|
||||||
|
ssize extralen = max( 0, size - ( buflen - offset ) );
|
||||||
|
ssize rwlen = size - extralen;
|
||||||
|
ssize new_cap = buflen + extralen;
|
||||||
|
|
||||||
|
if ( d->flags & EFileStream_CLONE_WRITABLE )
|
||||||
|
{
|
||||||
|
Array(u8) arr = { d->buf };
|
||||||
|
|
||||||
|
if ( array_get_header(arr)->Capacity < scast(usize, new_cap) )
|
||||||
|
{
|
||||||
|
if ( ! array_grow( & arr, ( s64 )( new_cap ) ) )
|
||||||
|
return false;
|
||||||
|
d->buf = arr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mem_copy( d->buf + offset, buffer, rwlen );
|
||||||
|
|
||||||
|
if ( ( d->flags & EFileStream_CLONE_WRITABLE ) && extralen > 0 )
|
||||||
|
{
|
||||||
|
Array(u8) arr = { d->buf };
|
||||||
|
|
||||||
|
mem_copy( d->buf + offset + rwlen, pointer_add_const( buffer, rwlen ), extralen );
|
||||||
|
d->cap = new_cap;
|
||||||
|
array_get_header(arr)->Capacity = new_cap;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
extralen = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( bytes_written )
|
||||||
|
*bytes_written = ( rwlen + extralen );
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal
|
||||||
|
GEN_FILE_CLOSE_PROC( _memory_file_close )
|
||||||
|
{
|
||||||
|
_memory_fd* d = _file_stream_from_fd( fd );
|
||||||
|
AllocatorInfo allocator = d->allocator;
|
||||||
|
|
||||||
|
if ( d->flags & EFileStream_CLONE_WRITABLE )
|
||||||
|
{
|
||||||
|
Array(u8) arr = { d->buf };
|
||||||
|
array_free(arr);
|
||||||
|
}
|
||||||
|
|
||||||
|
allocator_free( allocator, d );
|
||||||
|
}
|
||||||
|
|
||||||
|
FileOperations const memory_file_operations = { _memory_file_read, _memory_file_write, _memory_file_seek, _memory_file_close };
|
||||||
|
|
||||||
|
#pragma endregion File Handling
|
||||||
@@ -0,0 +1,386 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "strings.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region File Handling
|
||||||
|
|
||||||
|
enum FileModeFlag
|
||||||
|
{
|
||||||
|
EFileMode_READ = bit( 0 ),
|
||||||
|
EFileMode_WRITE = bit( 1 ),
|
||||||
|
EFileMode_APPEND = bit( 2 ),
|
||||||
|
EFileMode_RW = bit( 3 ),
|
||||||
|
GEN_FILE_MODES = EFileMode_READ | EFileMode_WRITE | EFileMode_APPEND | EFileMode_RW,
|
||||||
|
};
|
||||||
|
|
||||||
|
// NOTE: Only used internally and for the file operations
|
||||||
|
enum SeekWhenceType
|
||||||
|
{
|
||||||
|
ESeekWhence_BEGIN = 0,
|
||||||
|
ESeekWhence_CURRENT = 1,
|
||||||
|
ESeekWhence_END = 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum FileError
|
||||||
|
{
|
||||||
|
EFileError_NONE,
|
||||||
|
EFileError_INVALID,
|
||||||
|
EFileError_INVALID_FILENAME,
|
||||||
|
EFileError_EXISTS,
|
||||||
|
EFileError_NOT_EXISTS,
|
||||||
|
EFileError_PERMISSION,
|
||||||
|
EFileError_TRUNCATION_FAILURE,
|
||||||
|
EFileError_NOT_EMPTY,
|
||||||
|
EFileError_NAME_TOO_LONG,
|
||||||
|
EFileError_UNKNOWN,
|
||||||
|
};
|
||||||
|
|
||||||
|
union FileDescriptor
|
||||||
|
{
|
||||||
|
void* p;
|
||||||
|
sptr i;
|
||||||
|
uptr u;
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef u32 FileMode;
|
||||||
|
typedef struct FileOperations FileOperations;
|
||||||
|
|
||||||
|
#define GEN_FILE_OPEN_PROC( name ) FileError name( FileDescriptor* fd, FileOperations* ops, FileMode mode, char const* filename )
|
||||||
|
#define GEN_FILE_READ_AT_PROC( name ) b32 name( FileDescriptor fd, void* buffer, ssize size, s64 offset, ssize* bytes_read, b32 stop_at_newline )
|
||||||
|
#define GEN_FILE_WRITE_AT_PROC( name ) b32 name( FileDescriptor fd, mem_ptr_const buffer, ssize size, s64 offset, ssize* bytes_written )
|
||||||
|
#define GEN_FILE_SEEK_PROC( name ) b32 name( FileDescriptor fd, s64 offset, SeekWhenceType whence, s64* new_offset )
|
||||||
|
#define GEN_FILE_CLOSE_PROC( name ) void name( FileDescriptor fd )
|
||||||
|
|
||||||
|
typedef GEN_FILE_OPEN_PROC( file_open_proc );
|
||||||
|
typedef GEN_FILE_READ_AT_PROC( FileReadProc );
|
||||||
|
typedef GEN_FILE_WRITE_AT_PROC( FileWriteProc );
|
||||||
|
typedef GEN_FILE_SEEK_PROC( FileSeekProc );
|
||||||
|
typedef GEN_FILE_CLOSE_PROC( FileCloseProc );
|
||||||
|
|
||||||
|
struct FileOperations
|
||||||
|
{
|
||||||
|
FileReadProc* read_at;
|
||||||
|
FileWriteProc* write_at;
|
||||||
|
FileSeekProc* seek;
|
||||||
|
FileCloseProc* close;
|
||||||
|
};
|
||||||
|
|
||||||
|
extern FileOperations const default_file_operations;
|
||||||
|
|
||||||
|
typedef u64 FileTime;
|
||||||
|
|
||||||
|
enum DirType
|
||||||
|
{
|
||||||
|
GEN_DIR_TYPE_FILE,
|
||||||
|
GEN_DIR_TYPE_FOLDER,
|
||||||
|
GEN_DIR_TYPE_UNKNOWN,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct DirInfo;
|
||||||
|
|
||||||
|
struct DirEntry
|
||||||
|
{
|
||||||
|
char const* filename;
|
||||||
|
DirInfo* dir_info;
|
||||||
|
u8 type;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct DirInfo
|
||||||
|
{
|
||||||
|
char const* fullpath;
|
||||||
|
DirEntry* entries; // zpl_array
|
||||||
|
|
||||||
|
// Internals
|
||||||
|
char** filenames; // zpl_array
|
||||||
|
StrBuilder buf;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct FileInfo
|
||||||
|
{
|
||||||
|
FileOperations ops;
|
||||||
|
FileDescriptor fd;
|
||||||
|
b32 is_temp;
|
||||||
|
|
||||||
|
char const* filename;
|
||||||
|
FileTime last_write_time;
|
||||||
|
DirEntry* dir;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum FileStandardType
|
||||||
|
{
|
||||||
|
EFileStandard_INPUT,
|
||||||
|
EFileStandard_OUTPUT,
|
||||||
|
EFileStandard_ERROR,
|
||||||
|
|
||||||
|
EFileStandard_COUNT,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get standard file I/O.
|
||||||
|
* @param std Check zpl_file_standard_type
|
||||||
|
* @return File handle to standard I/O
|
||||||
|
*/
|
||||||
|
GEN_API FileInfo* file_get_standard( FileStandardType std );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Closes the file
|
||||||
|
* @param file
|
||||||
|
*/
|
||||||
|
GEN_API FileError file_close( FileInfo* file );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the currently opened file's name
|
||||||
|
* @param file
|
||||||
|
*/
|
||||||
|
inline
|
||||||
|
char const* file_name( FileInfo* file )
|
||||||
|
{
|
||||||
|
return file->filename ? file->filename : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens a file
|
||||||
|
* @param file
|
||||||
|
* @param filename
|
||||||
|
*/
|
||||||
|
GEN_API FileError file_open( FileInfo* file, char const* filename );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens a file using a specified mode
|
||||||
|
* @param file
|
||||||
|
* @param mode Access mode to use
|
||||||
|
* @param filename
|
||||||
|
*/
|
||||||
|
GEN_API FileError file_open_mode( FileInfo* file, FileMode mode, char const* filename );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads from a file
|
||||||
|
* @param file
|
||||||
|
* @param buffer Buffer to read to
|
||||||
|
* @param size Size to read
|
||||||
|
*/
|
||||||
|
b32 file_read( FileInfo* file, void* buffer, ssize size );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads file at a specific offset
|
||||||
|
* @param file
|
||||||
|
* @param buffer Buffer to read to
|
||||||
|
* @param size Size to read
|
||||||
|
* @param offset Offset to read from
|
||||||
|
* @param bytes_read How much data we've actually read
|
||||||
|
*/
|
||||||
|
b32 file_read_at( FileInfo* file, void* buffer, ssize size, s64 offset );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads file safely
|
||||||
|
* @param file
|
||||||
|
* @param buffer Buffer to read to
|
||||||
|
* @param size Size to read
|
||||||
|
* @param offset Offset to read from
|
||||||
|
* @param bytes_read How much data we've actually read
|
||||||
|
*/
|
||||||
|
b32 file_read_at_check( FileInfo* file, void* buffer, ssize size, s64 offset, ssize* bytes_read );
|
||||||
|
|
||||||
|
typedef struct FileContents FileContents;
|
||||||
|
struct FileContents
|
||||||
|
{
|
||||||
|
AllocatorInfo allocator;
|
||||||
|
void* data;
|
||||||
|
ssize size;
|
||||||
|
};
|
||||||
|
|
||||||
|
constexpr b32 file_zero_terminate = true;
|
||||||
|
constexpr b32 file_no_zero_terminate = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads the whole file contents
|
||||||
|
* @param a Allocator to use
|
||||||
|
* @param zero_terminate End the read data with null terminator
|
||||||
|
* @param filepath Path to the file
|
||||||
|
* @return File contents data
|
||||||
|
*/
|
||||||
|
GEN_API FileContents file_read_contents( AllocatorInfo a, b32 zero_terminate, char const* filepath );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a size of the file
|
||||||
|
* @param file
|
||||||
|
* @return File size
|
||||||
|
*/
|
||||||
|
GEN_API s64 file_size( FileInfo* file );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seeks the file cursor from the beginning of file to a specific position
|
||||||
|
* @param file
|
||||||
|
* @param offset Offset to seek to
|
||||||
|
*/
|
||||||
|
s64 file_seek( FileInfo* file, s64 offset );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seeks the file cursor to the end of the file
|
||||||
|
* @param file
|
||||||
|
*/
|
||||||
|
s64 file_seek_to_end( FileInfo* file );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the length from the beginning of the file we've read so far
|
||||||
|
* @param file
|
||||||
|
* @return Our current position in file
|
||||||
|
*/
|
||||||
|
s64 file_tell( FileInfo* file );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes to a file
|
||||||
|
* @param file
|
||||||
|
* @param buffer Buffer to read from
|
||||||
|
* @param size Size to read
|
||||||
|
*/
|
||||||
|
b32 file_write( FileInfo* file, void const* buffer, ssize size );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes to file at a specific offset
|
||||||
|
* @param file
|
||||||
|
* @param buffer Buffer to read from
|
||||||
|
* @param size Size to write
|
||||||
|
* @param offset Offset to write to
|
||||||
|
* @param bytes_written How much data we've actually written
|
||||||
|
*/
|
||||||
|
b32 file_write_at( FileInfo* file, void const* buffer, ssize size, s64 offset );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes to file safely
|
||||||
|
* @param file
|
||||||
|
* @param buffer Buffer to read from
|
||||||
|
* @param size Size to write
|
||||||
|
* @param offset Offset to write to
|
||||||
|
* @param bytes_written How much data we've actually written
|
||||||
|
*/
|
||||||
|
b32 file_write_at_check( FileInfo* file, void const* buffer, ssize size, s64 offset, ssize* bytes_written );
|
||||||
|
|
||||||
|
enum FileStreamFlags : u32
|
||||||
|
{
|
||||||
|
/* Allows us to write to the buffer directly. Beware: you can not append a new data! */
|
||||||
|
EFileStream_WRITABLE = bit( 0 ),
|
||||||
|
|
||||||
|
/* Clones the input buffer so you can write (zpl_file_write*) data into it. */
|
||||||
|
/* Since we work with a clone, the buffer size can dynamically grow as well. */
|
||||||
|
EFileStream_CLONE_WRITABLE = bit( 1 ),
|
||||||
|
|
||||||
|
EFileStream_UNDERLYING = GEN_U32_MAX,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens a new memory stream
|
||||||
|
* @param file
|
||||||
|
* @param allocator
|
||||||
|
*/
|
||||||
|
GEN_API b8 file_stream_new( FileInfo* file, AllocatorInfo allocator );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens a memory stream over an existing buffer
|
||||||
|
* @param file
|
||||||
|
* @param allocator
|
||||||
|
* @param buffer Memory to create stream from
|
||||||
|
* @param size Buffer's size
|
||||||
|
* @param flags
|
||||||
|
*/
|
||||||
|
GEN_API b8 file_stream_open( FileInfo* file, AllocatorInfo allocator, u8* buffer, ssize size, FileStreamFlags flags );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves the stream's underlying buffer and buffer size.
|
||||||
|
* @param file memory stream
|
||||||
|
* @param size (Optional) buffer size
|
||||||
|
*/
|
||||||
|
GEN_API u8* file_stream_buf( FileInfo* file, ssize* size );
|
||||||
|
|
||||||
|
extern FileOperations const memory_file_operations;
|
||||||
|
|
||||||
|
inline
|
||||||
|
s64 file_seek( FileInfo* f, s64 offset )
|
||||||
|
{
|
||||||
|
s64 new_offset = 0;
|
||||||
|
|
||||||
|
if ( ! f->ops.read_at )
|
||||||
|
f->ops = default_file_operations;
|
||||||
|
|
||||||
|
f->ops.seek( f->fd, offset, ESeekWhence_BEGIN, &new_offset );
|
||||||
|
|
||||||
|
return new_offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
s64 file_seek_to_end( FileInfo* f )
|
||||||
|
{
|
||||||
|
s64 new_offset = 0;
|
||||||
|
|
||||||
|
if ( ! f->ops.read_at )
|
||||||
|
f->ops = default_file_operations;
|
||||||
|
|
||||||
|
f->ops.seek( f->fd, 0, ESeekWhence_END, &new_offset );
|
||||||
|
|
||||||
|
return new_offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
s64 file_tell( FileInfo* f )
|
||||||
|
{
|
||||||
|
s64 new_offset = 0;
|
||||||
|
|
||||||
|
if ( ! f->ops.read_at )
|
||||||
|
f->ops = default_file_operations;
|
||||||
|
|
||||||
|
f->ops.seek( f->fd, 0, ESeekWhence_CURRENT, &new_offset );
|
||||||
|
|
||||||
|
return new_offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 file_read( FileInfo* f, void* buffer, ssize size )
|
||||||
|
{
|
||||||
|
s64 cur_offset = file_tell( f );
|
||||||
|
b32 result = file_read_at( f, buffer, size, file_tell( f ) );
|
||||||
|
file_seek( f, cur_offset + size );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 file_read_at( FileInfo* f, void* buffer, ssize size, s64 offset )
|
||||||
|
{
|
||||||
|
return file_read_at_check( f, buffer, size, offset, NULL );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 file_read_at_check( FileInfo* f, void* buffer, ssize size, s64 offset, ssize* bytes_read )
|
||||||
|
{
|
||||||
|
if ( ! f->ops.read_at )
|
||||||
|
f->ops = default_file_operations;
|
||||||
|
return f->ops.read_at( f->fd, buffer, size, offset, bytes_read, false );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 file_write( FileInfo* f, void const* buffer, ssize size )
|
||||||
|
{
|
||||||
|
s64 cur_offset = file_tell( f );
|
||||||
|
b32 result = file_write_at( f, buffer, size, file_tell( f ) );
|
||||||
|
|
||||||
|
file_seek( f, cur_offset + size );
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 file_write_at( FileInfo* f, void const* buffer, ssize size, s64 offset )
|
||||||
|
{
|
||||||
|
return file_write_at_check( f, buffer, size, offset, NULL );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 file_write_at_check( FileInfo* f, void const* buffer, ssize size, s64 offset, ssize* bytes_written )
|
||||||
|
{
|
||||||
|
if ( ! f->ops.read_at )
|
||||||
|
f->ops = default_file_operations;
|
||||||
|
|
||||||
|
return f->ops.write_at( f->fd, buffer, size, offset, bytes_written );
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma endregion File Handling
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "memory.cpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Hashing
|
||||||
|
|
||||||
|
global u32 const _crc32_table[ 256 ] = {
|
||||||
|
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd,
|
||||||
|
0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
|
||||||
|
0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
|
||||||
|
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
|
||||||
|
0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
|
||||||
|
0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
|
||||||
|
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce,
|
||||||
|
0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
|
||||||
|
0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
|
||||||
|
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
|
||||||
|
0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0,
|
||||||
|
0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
|
||||||
|
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703,
|
||||||
|
0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
|
||||||
|
0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
|
||||||
|
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
|
||||||
|
0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5,
|
||||||
|
0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
|
||||||
|
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
|
||||||
|
};
|
||||||
|
|
||||||
|
u32 crc32( void const* data, ssize len )
|
||||||
|
{
|
||||||
|
ssize remaining;
|
||||||
|
u32 result = ~( scast( u32, 0) );
|
||||||
|
u8 const* c = rcast( u8 const*, data);
|
||||||
|
for ( remaining = len; remaining--; c++ )
|
||||||
|
result = ( result >> 8 ) ^ ( _crc32_table[ ( result ^ *c ) & 0xff ] );
|
||||||
|
return ~result;
|
||||||
|
}
|
||||||
|
|
||||||
|
global u64 const _crc64_table[ 256 ] = {
|
||||||
|
0x0000000000000000ull, 0x7ad870c830358979ull, 0xf5b0e190606b12f2ull, 0x8f689158505e9b8bull, 0xc038e5739841b68full, 0xbae095bba8743ff6ull, 0x358804e3f82aa47dull,
|
||||||
|
0x4f50742bc81f2d04ull, 0xab28ecb46814fe75ull, 0xd1f09c7c5821770cull, 0x5e980d24087fec87ull, 0x24407dec384a65feull, 0x6b1009c7f05548faull, 0x11c8790fc060c183ull,
|
||||||
|
0x9ea0e857903e5a08ull, 0xe478989fa00bd371ull, 0x7d08ff3b88be6f81ull, 0x07d08ff3b88be6f8ull, 0x88b81eabe8d57d73ull, 0xf2606e63d8e0f40aull, 0xbd301a4810ffd90eull,
|
||||||
|
0xc7e86a8020ca5077ull, 0x4880fbd87094cbfcull, 0x32588b1040a14285ull, 0xd620138fe0aa91f4ull, 0xacf86347d09f188dull, 0x2390f21f80c18306ull, 0x594882d7b0f40a7full,
|
||||||
|
0x1618f6fc78eb277bull, 0x6cc0863448deae02ull, 0xe3a8176c18803589ull, 0x997067a428b5bcf0ull, 0xfa11fe77117cdf02ull, 0x80c98ebf2149567bull, 0x0fa11fe77117cdf0ull,
|
||||||
|
0x75796f2f41224489ull, 0x3a291b04893d698dull, 0x40f16bccb908e0f4ull, 0xcf99fa94e9567b7full, 0xb5418a5cd963f206ull, 0x513912c379682177ull, 0x2be1620b495da80eull,
|
||||||
|
0xa489f35319033385ull, 0xde51839b2936bafcull, 0x9101f7b0e12997f8ull, 0xebd98778d11c1e81ull, 0x64b116208142850aull, 0x1e6966e8b1770c73ull, 0x8719014c99c2b083ull,
|
||||||
|
0xfdc17184a9f739faull, 0x72a9e0dcf9a9a271ull, 0x08719014c99c2b08ull, 0x4721e43f0183060cull, 0x3df994f731b68f75ull, 0xb29105af61e814feull, 0xc849756751dd9d87ull,
|
||||||
|
0x2c31edf8f1d64ef6ull, 0x56e99d30c1e3c78full, 0xd9810c6891bd5c04ull, 0xa3597ca0a188d57dull, 0xec09088b6997f879ull, 0x96d1784359a27100ull, 0x19b9e91b09fcea8bull,
|
||||||
|
0x636199d339c963f2ull, 0xdf7adabd7a6e2d6full, 0xa5a2aa754a5ba416ull, 0x2aca3b2d1a053f9dull, 0x50124be52a30b6e4ull, 0x1f423fcee22f9be0ull, 0x659a4f06d21a1299ull,
|
||||||
|
0xeaf2de5e82448912ull, 0x902aae96b271006bull, 0x74523609127ad31aull, 0x0e8a46c1224f5a63ull, 0x81e2d7997211c1e8ull, 0xfb3aa75142244891ull, 0xb46ad37a8a3b6595ull,
|
||||||
|
0xceb2a3b2ba0eececull, 0x41da32eaea507767ull, 0x3b024222da65fe1eull, 0xa2722586f2d042eeull, 0xd8aa554ec2e5cb97ull, 0x57c2c41692bb501cull, 0x2d1ab4dea28ed965ull,
|
||||||
|
0x624ac0f56a91f461ull, 0x1892b03d5aa47d18ull, 0x97fa21650afae693ull, 0xed2251ad3acf6feaull, 0x095ac9329ac4bc9bull, 0x7382b9faaaf135e2ull, 0xfcea28a2faafae69ull,
|
||||||
|
0x8632586aca9a2710ull, 0xc9622c4102850a14ull, 0xb3ba5c8932b0836dull, 0x3cd2cdd162ee18e6ull, 0x460abd1952db919full, 0x256b24ca6b12f26dull, 0x5fb354025b277b14ull,
|
||||||
|
0xd0dbc55a0b79e09full, 0xaa03b5923b4c69e6ull, 0xe553c1b9f35344e2ull, 0x9f8bb171c366cd9bull, 0x10e3202993385610ull, 0x6a3b50e1a30ddf69ull, 0x8e43c87e03060c18ull,
|
||||||
|
0xf49bb8b633338561ull, 0x7bf329ee636d1eeaull, 0x012b592653589793ull, 0x4e7b2d0d9b47ba97ull, 0x34a35dc5ab7233eeull, 0xbbcbcc9dfb2ca865ull, 0xc113bc55cb19211cull,
|
||||||
|
0x5863dbf1e3ac9decull, 0x22bbab39d3991495ull, 0xadd33a6183c78f1eull, 0xd70b4aa9b3f20667ull, 0x985b3e827bed2b63ull, 0xe2834e4a4bd8a21aull, 0x6debdf121b863991ull,
|
||||||
|
0x1733afda2bb3b0e8ull, 0xf34b37458bb86399ull, 0x8993478dbb8deae0ull, 0x06fbd6d5ebd3716bull, 0x7c23a61ddbe6f812ull, 0x3373d23613f9d516ull, 0x49aba2fe23cc5c6full,
|
||||||
|
0xc6c333a67392c7e4ull, 0xbc1b436e43a74e9dull, 0x95ac9329ac4bc9b5ull, 0xef74e3e19c7e40ccull, 0x601c72b9cc20db47ull, 0x1ac40271fc15523eull, 0x5594765a340a7f3aull,
|
||||||
|
0x2f4c0692043ff643ull, 0xa02497ca54616dc8ull, 0xdafce7026454e4b1ull, 0x3e847f9dc45f37c0ull, 0x445c0f55f46abeb9ull, 0xcb349e0da4342532ull, 0xb1eceec59401ac4bull,
|
||||||
|
0xfebc9aee5c1e814full, 0x8464ea266c2b0836ull, 0x0b0c7b7e3c7593bdull, 0x71d40bb60c401ac4ull, 0xe8a46c1224f5a634ull, 0x927c1cda14c02f4dull, 0x1d148d82449eb4c6ull,
|
||||||
|
0x67ccfd4a74ab3dbfull, 0x289c8961bcb410bbull, 0x5244f9a98c8199c2ull, 0xdd2c68f1dcdf0249ull, 0xa7f41839ecea8b30ull, 0x438c80a64ce15841ull, 0x3954f06e7cd4d138ull,
|
||||||
|
0xb63c61362c8a4ab3ull, 0xcce411fe1cbfc3caull, 0x83b465d5d4a0eeceull, 0xf96c151de49567b7ull, 0x76048445b4cbfc3cull, 0x0cdcf48d84fe7545ull, 0x6fbd6d5ebd3716b7ull,
|
||||||
|
0x15651d968d029fceull, 0x9a0d8ccedd5c0445ull, 0xe0d5fc06ed698d3cull, 0xaf85882d2576a038ull, 0xd55df8e515432941ull, 0x5a3569bd451db2caull, 0x20ed197575283bb3ull,
|
||||||
|
0xc49581ead523e8c2ull, 0xbe4df122e51661bbull, 0x3125607ab548fa30ull, 0x4bfd10b2857d7349ull, 0x04ad64994d625e4dull, 0x7e7514517d57d734ull, 0xf11d85092d094cbfull,
|
||||||
|
0x8bc5f5c11d3cc5c6ull, 0x12b5926535897936ull, 0x686de2ad05bcf04full, 0xe70573f555e26bc4ull, 0x9ddd033d65d7e2bdull, 0xd28d7716adc8cfb9ull, 0xa85507de9dfd46c0ull,
|
||||||
|
0x273d9686cda3dd4bull, 0x5de5e64efd965432ull, 0xb99d7ed15d9d8743ull, 0xc3450e196da80e3aull, 0x4c2d9f413df695b1ull, 0x36f5ef890dc31cc8ull, 0x79a59ba2c5dc31ccull,
|
||||||
|
0x037deb6af5e9b8b5ull, 0x8c157a32a5b7233eull, 0xf6cd0afa9582aa47ull, 0x4ad64994d625e4daull, 0x300e395ce6106da3ull, 0xbf66a804b64ef628ull, 0xc5bed8cc867b7f51ull,
|
||||||
|
0x8aeeace74e645255ull, 0xf036dc2f7e51db2cull, 0x7f5e4d772e0f40a7ull, 0x05863dbf1e3ac9deull, 0xe1fea520be311aafull, 0x9b26d5e88e0493d6ull, 0x144e44b0de5a085dull,
|
||||||
|
0x6e963478ee6f8124ull, 0x21c640532670ac20ull, 0x5b1e309b16452559ull, 0xd476a1c3461bbed2ull, 0xaeaed10b762e37abull, 0x37deb6af5e9b8b5bull, 0x4d06c6676eae0222ull,
|
||||||
|
0xc26e573f3ef099a9ull, 0xb8b627f70ec510d0ull, 0xf7e653dcc6da3dd4ull, 0x8d3e2314f6efb4adull, 0x0256b24ca6b12f26ull, 0x788ec2849684a65full, 0x9cf65a1b368f752eull,
|
||||||
|
0xe62e2ad306bafc57ull, 0x6946bb8b56e467dcull, 0x139ecb4366d1eea5ull, 0x5ccebf68aecec3a1ull, 0x2616cfa09efb4ad8ull, 0xa97e5ef8cea5d153ull, 0xd3a62e30fe90582aull,
|
||||||
|
0xb0c7b7e3c7593bd8ull, 0xca1fc72bf76cb2a1ull, 0x45775673a732292aull, 0x3faf26bb9707a053ull, 0x70ff52905f188d57ull, 0x0a2722586f2d042eull, 0x854fb3003f739fa5ull,
|
||||||
|
0xff97c3c80f4616dcull, 0x1bef5b57af4dc5adull, 0x61372b9f9f784cd4ull, 0xee5fbac7cf26d75full, 0x9487ca0fff135e26ull, 0xdbd7be24370c7322ull, 0xa10fceec0739fa5bull,
|
||||||
|
0x2e675fb4576761d0ull, 0x54bf2f7c6752e8a9ull, 0xcdcf48d84fe75459ull, 0xb71738107fd2dd20ull, 0x387fa9482f8c46abull, 0x42a7d9801fb9cfd2ull, 0x0df7adabd7a6e2d6ull,
|
||||||
|
0x772fdd63e7936bafull, 0xf8474c3bb7cdf024ull, 0x829f3cf387f8795dull, 0x66e7a46c27f3aa2cull, 0x1c3fd4a417c62355ull, 0x935745fc4798b8deull, 0xe98f353477ad31a7ull,
|
||||||
|
0xa6df411fbfb21ca3ull, 0xdc0731d78f8795daull, 0x536fa08fdfd90e51ull, 0x29b7d047efec8728ull,
|
||||||
|
};
|
||||||
|
|
||||||
|
u64 crc64( void const* data, ssize len )
|
||||||
|
{
|
||||||
|
ssize remaining;
|
||||||
|
u64 result = ( scast( u64, 0) );
|
||||||
|
u8 const* c = rcast( u8 const*, data);
|
||||||
|
for ( remaining = len; remaining--; c++ )
|
||||||
|
result = ( result >> 8 ) ^ ( _crc64_table[ ( result ^ *c ) & 0xff ] );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma endregion Hashing
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
#pragma once
|
||||||
|
#include "containers.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Hashing
|
||||||
|
|
||||||
|
GEN_API u32 crc32( void const* data, ssize len );
|
||||||
|
GEN_API u64 crc64( void const* data, ssize len );
|
||||||
|
|
||||||
|
#pragma endregion Hashing
|
||||||
@@ -0,0 +1,343 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "platform.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Macros
|
||||||
|
|
||||||
|
#ifndef GEN_API
|
||||||
|
#if GEN_COMPILER_MSVC
|
||||||
|
#ifdef GEN_DYN_LINK
|
||||||
|
#ifdef GEN_DYN_EXPORT
|
||||||
|
#define GEN_API __declspec(dllexport)
|
||||||
|
#else
|
||||||
|
#define GEN_API __declspec(dllimport)
|
||||||
|
#endif
|
||||||
|
#else
|
||||||
|
#define GEN_API // Empty for static builds
|
||||||
|
#endif
|
||||||
|
#else
|
||||||
|
#ifdef GEN_DYN_LINK
|
||||||
|
#define GEN_API __attribute__((visibility("default")))
|
||||||
|
#else
|
||||||
|
#define GEN_API // Empty for static builds
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
#endif // GEN_API
|
||||||
|
|
||||||
|
#ifndef global // Global variables
|
||||||
|
# if defined(GEN_STATIC_LINK) || defined(GEN_DYN_LINK)
|
||||||
|
# define global
|
||||||
|
# else
|
||||||
|
# define global static
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
#ifndef internal
|
||||||
|
#define internal static // Internal linkage
|
||||||
|
#endif
|
||||||
|
#ifndef local_persist
|
||||||
|
#define local_persist static // Local Persisting variables
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef bit
|
||||||
|
#define bit( Value ) ( 1 << Value )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef bitfield_is_set
|
||||||
|
#define bitfield_is_set( Type, Field, Mask ) ( (scast(Type, Mask) & scast(Type, Field)) == scast(Type, Mask) )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Mainly intended for forcing the base library to utilize only C-valid constructs or type coercion
|
||||||
|
#ifndef GEN_C_LIKE_CPP
|
||||||
|
#define GEN_C_LIKE_CPP 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
# ifndef cast
|
||||||
|
# define cast( type, value ) (tmpl_cast<type>( value ))
|
||||||
|
# endif
|
||||||
|
#else
|
||||||
|
# ifndef cast
|
||||||
|
# define cast( type, value ) ( (type)(value) )
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
# ifndef ccast
|
||||||
|
# define ccast( type, value ) ( const_cast< type >( (value) ) )
|
||||||
|
# endif
|
||||||
|
# ifndef pcast
|
||||||
|
# define pcast( type, value ) ( * reinterpret_cast< type* >( & ( value ) ) )
|
||||||
|
# endif
|
||||||
|
# ifndef rcast
|
||||||
|
# define rcast( type, value ) reinterpret_cast< type >( value )
|
||||||
|
# endif
|
||||||
|
# ifndef scast
|
||||||
|
# define scast( type, value ) static_cast< type >( value )
|
||||||
|
# endif
|
||||||
|
#else
|
||||||
|
# ifndef ccast
|
||||||
|
# define ccast( type, value ) ( (type)(value) )
|
||||||
|
# endif
|
||||||
|
# ifndef pcast
|
||||||
|
# define pcast( type, value ) ( * (type*)(& value) )
|
||||||
|
# endif
|
||||||
|
# ifndef rcast
|
||||||
|
# define rcast( type, value ) ( (type)(value) )
|
||||||
|
# endif
|
||||||
|
# ifndef scast
|
||||||
|
# define scast( type, value ) ( (type)(value) )
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef stringize
|
||||||
|
#define stringize_va( ... ) #__VA_ARGS__
|
||||||
|
#define stringize( ... ) stringize_va( __VA_ARGS__ )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define src_line_str stringize(__LINE__)
|
||||||
|
|
||||||
|
#ifndef do_once
|
||||||
|
#define do_once() \
|
||||||
|
local_persist int __do_once_counter_##src_line_str = 0; \
|
||||||
|
for(; __do_once_counter_##src_line_str != 1; __do_once_counter_##src_line_str = 1 ) \
|
||||||
|
|
||||||
|
#define do_once_defer( expression ) \
|
||||||
|
local_persist int __do_once_counter_##src_line_str = 0; \
|
||||||
|
for(;__do_once_counter_##src_line_str != 1; __do_once_counter_##src_line_str = 1, (expression)) \
|
||||||
|
|
||||||
|
#define do_once_start \
|
||||||
|
do \
|
||||||
|
{ \
|
||||||
|
local_persist \
|
||||||
|
bool done = false; \
|
||||||
|
if ( done ) \
|
||||||
|
break; \
|
||||||
|
done = true;
|
||||||
|
|
||||||
|
#define do_once_end \
|
||||||
|
} \
|
||||||
|
while(0);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef labeled_scope_start
|
||||||
|
#define labeled_scope_start if ( false ) {
|
||||||
|
#define labeled_scope_end }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef compiler_decorated_func_name
|
||||||
|
# ifdef COMPILER_CLANG
|
||||||
|
# define compiler_decorated_func_name __PRETTY_NAME__
|
||||||
|
# elif defined(COMPILER_MSVC)
|
||||||
|
# define compiler_decorated_func_name __FUNCDNAME__
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef num_args_impl
|
||||||
|
|
||||||
|
// This is essentially an arg couneter version of GEN_SELECT_ARG macros
|
||||||
|
// See section : _Generic function overloading for that usage (explains this heavier case)
|
||||||
|
|
||||||
|
#define num_args_impl( _0, \
|
||||||
|
_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, \
|
||||||
|
_11, _12, _13, _14, _15, _16, _17, _18, _19, _20, \
|
||||||
|
_21, _22, _23, _24, _25, _26, _27, _28, _29, _30, \
|
||||||
|
_31, _32, _33, _34, _35, _36, _37, _38, _39, _40, \
|
||||||
|
_41, _42, _43, _44, _45, _46, _47, _48, _49, _50, \
|
||||||
|
_51, _52, _53, _54, _55, _56, _57, _58, _59, _60, \
|
||||||
|
_61, _62, _63, _64, _65, _66, _67, _68, _69, _70, \
|
||||||
|
_71, _72, _73, _74, _75, _76, _77, _78, _79, _80, \
|
||||||
|
_81, _82, _83, _84, _85, _86, _87, _88, _89, _90, \
|
||||||
|
_91, _92, _93, _94, _95, _96, _97, _98, _99, _100, \
|
||||||
|
N, ... \
|
||||||
|
) N
|
||||||
|
|
||||||
|
// ## deletes preceding comma if _VA_ARGS__ is empty (GCC, Clang)
|
||||||
|
#define num_args(...) \
|
||||||
|
num_args_impl(_, ## __VA_ARGS__, \
|
||||||
|
100, 99, 98, 97, 96, 95, 94, 93, 92, 91, \
|
||||||
|
90, 89, 88, 87, 86, 85, 84, 83, 82, 81, \
|
||||||
|
80, 79, 78, 77, 76, 75, 74, 73, 72, 71, \
|
||||||
|
70, 69, 68, 67, 66, 65, 64, 63, 62, 61, \
|
||||||
|
60, 59, 58, 57, 56, 55, 54, 53, 52, 51, \
|
||||||
|
50, 49, 48, 47, 46, 45, 44, 43, 42, 41, \
|
||||||
|
40, 39, 38, 37, 36, 35, 34, 33, 32, 31, \
|
||||||
|
30, 29, 28, 27, 26, 25, 24, 23, 22, 21, \
|
||||||
|
20, 19, 18, 17, 16, 15, 14, 13, 12, 11, \
|
||||||
|
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, \
|
||||||
|
0 \
|
||||||
|
)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef clamp
|
||||||
|
#define clamp( x, lower, upper ) min( max( ( x ), ( lower ) ), ( upper ) )
|
||||||
|
#endif
|
||||||
|
#ifndef count_of
|
||||||
|
#define count_of( x ) ( ( size_of( x ) / size_of( 0 [ x ] ) ) / ( ( ssize )( ! ( size_of( x ) % size_of( 0 [ x ] ) ) ) ) )
|
||||||
|
#endif
|
||||||
|
#ifndef is_between
|
||||||
|
#define is_between( x, lower, upper ) ( ( ( lower ) <= ( x ) ) && ( ( x ) <= ( upper ) ) )
|
||||||
|
#endif
|
||||||
|
#ifndef size_of
|
||||||
|
#define size_of( x ) ( ssize )( sizeof( x ) )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef max
|
||||||
|
#define max( a, b ) ( (a > b) ? (a) : (b) )
|
||||||
|
#endif
|
||||||
|
#ifndef min
|
||||||
|
#define min( a, b ) ( (a < b) ? (a) : (b) )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_MSVC || GEN_COMPILER_TINYC
|
||||||
|
# define offset_of( Type, element ) ( ( GEN_NS( ssize ) ) & ( ( ( Type* )0 )->element ) )
|
||||||
|
#else
|
||||||
|
# define offset_of( Type, element ) __builtin_offsetof( Type, element )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef forceinline
|
||||||
|
# if GEN_COMPILER_MSVC
|
||||||
|
# define forceinline __forceinline
|
||||||
|
# elif GEN_COMPILER_GCC
|
||||||
|
# define forceinline inline __attribute__((__always_inline__))
|
||||||
|
# elif GEN_COMPILER_CLANG
|
||||||
|
# if __has_attribute(__always_inline__)
|
||||||
|
# define forceinline inline __attribute__((__always_inline__))
|
||||||
|
# else
|
||||||
|
# define forceinline
|
||||||
|
# endif
|
||||||
|
# else
|
||||||
|
# define forceinline
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef neverinline
|
||||||
|
# if GEN_COMPILER_MSVC
|
||||||
|
# define neverinline __declspec( noinline )
|
||||||
|
# elif GEN_COMPILER_GCC
|
||||||
|
# define neverinline __attribute__( ( __noinline__ ) )
|
||||||
|
# elif GEN_COMPILER_CLANG
|
||||||
|
# if __has_attribute(__always_inline__)
|
||||||
|
# define neverinline __attribute__( ( __noinline__ ) )
|
||||||
|
# else
|
||||||
|
# define neverinline
|
||||||
|
# endif
|
||||||
|
# else
|
||||||
|
# define neverinline
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_C
|
||||||
|
#ifndef static_assert
|
||||||
|
#undef static_assert
|
||||||
|
#if GEN_COMPILER_C && __STDC_VERSION__ >= 201112L
|
||||||
|
#define static_assert(condition, message) _Static_assert(condition, message)
|
||||||
|
#else
|
||||||
|
#define static_assert(condition, message) typedef char static_assertion_##__LINE__[(condition)?1:-1]
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
// Already Defined
|
||||||
|
#elif GEN_COMPILER_C && __STDC_VERSION__ >= 201112L
|
||||||
|
# define thread_local _Thread_local
|
||||||
|
#elif GEN_COMPILER_MSVC
|
||||||
|
# define thread_local __declspec(thread)
|
||||||
|
#elif GEN_COMPILER_CLANG
|
||||||
|
# define thread_local __thread
|
||||||
|
#else
|
||||||
|
# error "No thread local support"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if ! defined(typeof) && (!GEN_COMPILER_C || __STDC_VERSION__ < 202311L)
|
||||||
|
# if ! GEN_COMPILER_C
|
||||||
|
# define typeof decltype
|
||||||
|
# elif defined(_MSC_VER)
|
||||||
|
# define typeof __typeof__
|
||||||
|
# elif defined(__GNUC__) || defined(__clang__)
|
||||||
|
# define typeof __typeof__
|
||||||
|
# else
|
||||||
|
# error "Compiler not supported"
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef GEN_API_C_BEGIN
|
||||||
|
# if GEN_COMPILER_C
|
||||||
|
# define GEN_API_C_BEGIN
|
||||||
|
# define GEN_API_C_END
|
||||||
|
# else
|
||||||
|
# define GEN_API_C_BEGIN extern "C" {
|
||||||
|
# define GEN_API_C_END }
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_C
|
||||||
|
# if __STDC_VERSION__ >= 202311L
|
||||||
|
# define enum_underlying(type) : type
|
||||||
|
# else
|
||||||
|
# define enum_underlying(type)
|
||||||
|
# endif
|
||||||
|
#else
|
||||||
|
# define enum_underlying(type) : type
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_C
|
||||||
|
# ifndef nullptr
|
||||||
|
# define nullptr NULL
|
||||||
|
# endif
|
||||||
|
|
||||||
|
# ifndef GEN_REMOVE_PTR
|
||||||
|
# define GEN_REMOVE_PTR(type) typeof(* ( (type) NULL) )
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if ! defined(GEN_PARAM_DEFAULT) && GEN_COMPILER_CPP
|
||||||
|
# define GEN_PARAM_DEFAULT = {}
|
||||||
|
#else
|
||||||
|
# define GEN_PARAM_DEFAULT
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef struct_init
|
||||||
|
# if GEN_COMPILER_CPP
|
||||||
|
# define struct_init(type)
|
||||||
|
# else
|
||||||
|
# define struct_init(type) (type)
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef struct_zero
|
||||||
|
# if GEN_COMPILER_CPP
|
||||||
|
# define struct_zero(type) {}
|
||||||
|
# else
|
||||||
|
# define struct_zero(type) (type) {0}
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef struct_zero_init
|
||||||
|
# if GEN_COMPILER_CPP
|
||||||
|
# define struct_zero_init() {}
|
||||||
|
# else
|
||||||
|
# define struct_zero_init() {0}
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if 0
|
||||||
|
#ifndef GEN_OPTIMIZE_MAPPINGS_BEGIN
|
||||||
|
# define GEN_OPTIMIZE_MAPPINGS_BEGIN _pragma(optimize("gt", on))
|
||||||
|
# define GEN_OPITMIZE_MAPPINGS_END _pragma(optimize("", on))
|
||||||
|
#endif
|
||||||
|
#else
|
||||||
|
# define GEN_OPTIMIZE_MAPPINGS_BEGIN
|
||||||
|
# define GEN_OPITMIZE_MAPPINGS_END
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef get_optional
|
||||||
|
# if GEN_COMPILER_C
|
||||||
|
# define get_optional(opt) opt ? *opt : (typeof(*opt)){0}
|
||||||
|
# else
|
||||||
|
# define get_optional(opt) opt
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Macros
|
||||||
@@ -0,0 +1,522 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "printing.cpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Memory
|
||||||
|
|
||||||
|
void* mem_copy( void* dest, void const* source, ssize n )
|
||||||
|
{
|
||||||
|
if ( dest == nullptr )
|
||||||
|
{
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
return memcpy( dest, source, n );
|
||||||
|
}
|
||||||
|
|
||||||
|
void const* mem_find( void const* data, u8 c, ssize n )
|
||||||
|
{
|
||||||
|
u8 const* s = rcast( u8 const*, data);
|
||||||
|
while ( ( rcast( uptr, s) & ( sizeof( usize ) - 1 ) ) && n && *s != c )
|
||||||
|
{
|
||||||
|
s++;
|
||||||
|
n--;
|
||||||
|
}
|
||||||
|
if ( n && *s != c )
|
||||||
|
{
|
||||||
|
ssize const* w;
|
||||||
|
ssize k = GEN__ONES * c;
|
||||||
|
w = rcast( ssize const*, s);
|
||||||
|
while ( n >= size_of( ssize ) && ! GEN__HAS_ZERO( *w ^ k ) )
|
||||||
|
{
|
||||||
|
w++;
|
||||||
|
n -= size_of( ssize );
|
||||||
|
}
|
||||||
|
s = rcast( u8 const*, w);
|
||||||
|
while ( n && *s != c )
|
||||||
|
{
|
||||||
|
s++;
|
||||||
|
n--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return n ? rcast( void const*, s ) : NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
#define GEN_HEAP_STATS_MAGIC 0xDEADC0DE
|
||||||
|
|
||||||
|
typedef struct _heap_stats _heap_stats;
|
||||||
|
struct _heap_stats
|
||||||
|
{
|
||||||
|
u32 magic;
|
||||||
|
ssize used_memory;
|
||||||
|
ssize alloc_count;
|
||||||
|
};
|
||||||
|
|
||||||
|
global _heap_stats _heap_stats_info;
|
||||||
|
|
||||||
|
void heap_stats_init( void )
|
||||||
|
{
|
||||||
|
zero_item( &_heap_stats_info );
|
||||||
|
_heap_stats_info.magic = GEN_HEAP_STATS_MAGIC;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize heap_stats_used_memory( void )
|
||||||
|
{
|
||||||
|
GEN_ASSERT_MSG( _heap_stats_info.magic == GEN_HEAP_STATS_MAGIC, "heap_stats is not initialised yet, call heap_stats_init first!" );
|
||||||
|
return _heap_stats_info.used_memory;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize heap_stats_alloc_count( void )
|
||||||
|
{
|
||||||
|
GEN_ASSERT_MSG( _heap_stats_info.magic == GEN_HEAP_STATS_MAGIC, "heap_stats is not initialised yet, call heap_stats_init first!" );
|
||||||
|
return _heap_stats_info.alloc_count;
|
||||||
|
}
|
||||||
|
|
||||||
|
void heap_stats_check( void )
|
||||||
|
{
|
||||||
|
GEN_ASSERT_MSG( _heap_stats_info.magic == GEN_HEAP_STATS_MAGIC, "heap_stats is not initialised yet, call heap_stats_init first!" );
|
||||||
|
GEN_ASSERT( _heap_stats_info.used_memory == 0 );
|
||||||
|
GEN_ASSERT( _heap_stats_info.alloc_count == 0 );
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef struct _heap_alloc_info _heap_alloc_info;
|
||||||
|
struct _heap_alloc_info
|
||||||
|
{
|
||||||
|
ssize size;
|
||||||
|
void* physical_start;
|
||||||
|
};
|
||||||
|
|
||||||
|
void* heap_allocator_proc( void* allocator_data, AllocType type, ssize size, ssize alignment, void* old_memory, ssize old_size, u64 flags )
|
||||||
|
{
|
||||||
|
void* ptr = nullptr;
|
||||||
|
// unused( allocator_data );
|
||||||
|
// unused( old_size );
|
||||||
|
if ( ! alignment )
|
||||||
|
alignment = GEN_DEFAULT_MEMORY_ALIGNMENT;
|
||||||
|
|
||||||
|
#ifdef GEN_HEAP_ANALYSIS
|
||||||
|
ssize alloc_info_size = size_of( _heap_alloc_info );
|
||||||
|
ssize alloc_info_remainder = ( alloc_info_size % alignment );
|
||||||
|
ssize track_size = max( alloc_info_size, alignment ) + alloc_info_remainder;
|
||||||
|
switch ( type )
|
||||||
|
{
|
||||||
|
case EAllocation_FREE :
|
||||||
|
{
|
||||||
|
if ( ! old_memory )
|
||||||
|
break;
|
||||||
|
_heap_alloc_info* alloc_info = rcast( _heap_alloc_info*, old_memory) - 1;
|
||||||
|
_heap_stats_info.used_memory -= alloc_info->size;
|
||||||
|
_heap_stats_info.alloc_count--;
|
||||||
|
old_memory = alloc_info->physical_start;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case EAllocation_ALLOC :
|
||||||
|
{
|
||||||
|
size += track_size;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default :
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
switch ( type )
|
||||||
|
{
|
||||||
|
#if defined( GEN_COMPILER_MSVC ) || ( defined( GEN_COMPILER_GCC ) && defined( GEN_SYSTEM_WINDOWS ) ) || ( defined( GEN_COMPILER_TINYC ) && defined( GEN_SYSTEM_WINDOWS ) )
|
||||||
|
case EAllocation_ALLOC :
|
||||||
|
ptr = _aligned_malloc( size, alignment );
|
||||||
|
if ( flags & ALLOCATOR_FLAG_CLEAR_TO_ZERO )
|
||||||
|
zero_size( ptr, size );
|
||||||
|
break;
|
||||||
|
case EAllocation_FREE :
|
||||||
|
_aligned_free( old_memory );
|
||||||
|
break;
|
||||||
|
case EAllocation_RESIZE :
|
||||||
|
{
|
||||||
|
AllocatorInfo a = heap();
|
||||||
|
ptr = default_resize_align( a, old_memory, old_size, size, alignment );
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
#elif defined( GEN_SYSTEM_LINUX ) && ! defined( GEN_CPU_ARM ) && ! defined( GEN_COMPILER_TINYC )
|
||||||
|
case EAllocation_ALLOC :
|
||||||
|
{
|
||||||
|
ptr = aligned_alloc( alignment, ( size + alignment - 1 ) & ~( alignment - 1 ) );
|
||||||
|
|
||||||
|
if ( flags & GEN_ALLOCATOR_FLAG_CLEAR_TO_ZERO )
|
||||||
|
{
|
||||||
|
zero_size( ptr, size );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case EAllocation_FREE :
|
||||||
|
{
|
||||||
|
free( old_memory );
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case EAllocation_RESIZE :
|
||||||
|
{
|
||||||
|
AllocatorInfo a = heap();
|
||||||
|
ptr = default_resize_align( a, old_memory, old_size, size, alignment );
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
#else
|
||||||
|
case EAllocation_ALLOC :
|
||||||
|
{
|
||||||
|
posix_memalign( &ptr, alignment, size );
|
||||||
|
|
||||||
|
if ( flags & GEN_ALLOCATOR_FLAG_CLEAR_TO_ZERO )
|
||||||
|
{
|
||||||
|
zero_size( ptr, size );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case EAllocation_FREE :
|
||||||
|
{
|
||||||
|
free( old_memory );
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case EAllocation_RESIZE :
|
||||||
|
{
|
||||||
|
AllocatorInfo a = heap();
|
||||||
|
ptr = default_resize_align( a, old_memory, old_size, size, alignment );
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
case EAllocation_FREE_ALL :
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef GEN_HEAP_ANALYSIS
|
||||||
|
if ( type == EAllocation_ALLOC )
|
||||||
|
{
|
||||||
|
_heap_alloc_info* alloc_info = rcast( _heap_alloc_info*, rcast( char*, ptr) + alloc_info_remainder );
|
||||||
|
zero_item( alloc_info );
|
||||||
|
alloc_info->size = size - track_size;
|
||||||
|
alloc_info->physical_start = ptr;
|
||||||
|
ptr = rcast( void*, alloc_info + 1 );
|
||||||
|
_heap_stats_info.used_memory += alloc_info->size;
|
||||||
|
_heap_stats_info.alloc_count++;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
return ptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma region VirtualMemory
|
||||||
|
VirtualMemory vm_from_memory( void* data, ssize size )
|
||||||
|
{
|
||||||
|
VirtualMemory vm;
|
||||||
|
vm.data = data;
|
||||||
|
vm.size = size;
|
||||||
|
return vm;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined( GEN_SYSTEM_WINDOWS )
|
||||||
|
VirtualMemory vm_alloc( void* addr, ssize size )
|
||||||
|
{
|
||||||
|
VirtualMemory vm;
|
||||||
|
GEN_ASSERT( size > 0 );
|
||||||
|
vm.data = VirtualAlloc( addr, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE );
|
||||||
|
vm.size = size;
|
||||||
|
return vm;
|
||||||
|
}
|
||||||
|
|
||||||
|
b32 vm_free( VirtualMemory vm )
|
||||||
|
{
|
||||||
|
MEMORY_BASIC_INFORMATION info;
|
||||||
|
while ( vm.size > 0 )
|
||||||
|
{
|
||||||
|
if ( VirtualQuery( vm.data, &info, size_of( info ) ) == 0 )
|
||||||
|
return false;
|
||||||
|
if ( info.BaseAddress != vm.data || info.AllocationBase != vm.data || info.State != MEM_COMMIT || info.RegionSize > scast( usize, vm.size) )
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if ( VirtualFree( vm.data, 0, MEM_RELEASE ) == 0 )
|
||||||
|
return false;
|
||||||
|
vm.data = pointer_add( vm.data, info.RegionSize );
|
||||||
|
vm.size -= info.RegionSize;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
VirtualMemory vm_trim( VirtualMemory vm, ssize lead_size, ssize size )
|
||||||
|
{
|
||||||
|
VirtualMemory new_vm = { 0 };
|
||||||
|
void* ptr;
|
||||||
|
GEN_ASSERT( vm.size >= lead_size + size );
|
||||||
|
|
||||||
|
ptr = pointer_add( vm.data, lead_size );
|
||||||
|
|
||||||
|
vm_free( vm );
|
||||||
|
new_vm = vm_alloc( ptr, size );
|
||||||
|
if ( new_vm.data == ptr )
|
||||||
|
return new_vm;
|
||||||
|
if ( new_vm.data )
|
||||||
|
vm_free( new_vm );
|
||||||
|
return new_vm;
|
||||||
|
}
|
||||||
|
|
||||||
|
b32 vm_purge( VirtualMemory vm )
|
||||||
|
{
|
||||||
|
VirtualAlloc( vm.data, vm.size, MEM_RESET, PAGE_READWRITE );
|
||||||
|
// NOTE: Can this really fail?
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize virtual_memory_page_size( ssize* alignment_out )
|
||||||
|
{
|
||||||
|
SYSTEM_INFO info;
|
||||||
|
GetSystemInfo( &info );
|
||||||
|
if ( alignment_out )
|
||||||
|
*alignment_out = info.dwAllocationGranularity;
|
||||||
|
return info.dwPageSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
#else
|
||||||
|
# include <sys/mman.h>
|
||||||
|
|
||||||
|
# ifndef MAP_ANONYMOUS
|
||||||
|
# define MAP_ANONYMOUS MAP_ANON
|
||||||
|
# endif
|
||||||
|
VirtualMemory vm_alloc( void* addr, ssize size )
|
||||||
|
{
|
||||||
|
VirtualMemory vm;
|
||||||
|
GEN_ASSERT( size > 0 );
|
||||||
|
vm.data = mmap( addr, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0 );
|
||||||
|
vm.size = size;
|
||||||
|
return vm;
|
||||||
|
}
|
||||||
|
|
||||||
|
b32 vm_free( VirtualMemory vm )
|
||||||
|
{
|
||||||
|
munmap( vm.data, vm.size );
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
VirtualMemory vm_trim( VirtualMemory vm, ssize lead_size, ssize size )
|
||||||
|
{
|
||||||
|
void* ptr;
|
||||||
|
ssize trail_size;
|
||||||
|
GEN_ASSERT( vm.size >= lead_size + size );
|
||||||
|
|
||||||
|
ptr = pointer_add( vm.data, lead_size );
|
||||||
|
trail_size = vm.size - lead_size - size;
|
||||||
|
|
||||||
|
if ( lead_size != 0 )
|
||||||
|
vm_free( vm_from_memory(( vm.data, lead_size ) );
|
||||||
|
if ( trail_size != 0 )
|
||||||
|
vm_free( vm_from_memory( ptr, trail_size ) );
|
||||||
|
return vm_from_memory( ptr, size );
|
||||||
|
}
|
||||||
|
|
||||||
|
b32 vm_purge( VirtualMemory vm )
|
||||||
|
{
|
||||||
|
int err = madvise( vm.data, vm.size, MADV_DONTNEED );
|
||||||
|
return err != 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize virtual_memory_page_size( ssize* alignment_out )
|
||||||
|
{
|
||||||
|
// TODO: Is this always true?
|
||||||
|
ssize result = scast( ssize, sysconf( _SC_PAGE_SIZE ));
|
||||||
|
if ( alignment_out )
|
||||||
|
*alignment_out = result;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion VirtualMemory
|
||||||
|
|
||||||
|
void* arena_allocator_proc( void* allocator_data, AllocType type, ssize size, ssize alignment, void* old_memory, ssize old_size, u64 flags )
|
||||||
|
{
|
||||||
|
Arena* arena = rcast(Arena*, allocator_data);
|
||||||
|
void* ptr = NULL;
|
||||||
|
|
||||||
|
// unused( old_size );
|
||||||
|
|
||||||
|
switch ( type )
|
||||||
|
{
|
||||||
|
case EAllocation_ALLOC :
|
||||||
|
{
|
||||||
|
void* end = pointer_add( arena->PhysicalStart, arena->TotalUsed );
|
||||||
|
ssize total_size = align_forward_s64( size, alignment );
|
||||||
|
|
||||||
|
// NOTE: Out of memory
|
||||||
|
if ( arena->TotalUsed + total_size > (ssize) arena->TotalSize )
|
||||||
|
{
|
||||||
|
// zpl__printf_err("%s", "Arena out of memory\n");
|
||||||
|
GEN_FATAL("Arena out of memory! (Possibly could not fit for the largest size Arena!!)");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
ptr = align_forward( end, alignment );
|
||||||
|
arena->TotalUsed += total_size;
|
||||||
|
|
||||||
|
if ( flags & ALLOCATOR_FLAG_CLEAR_TO_ZERO )
|
||||||
|
zero_size( ptr, size );
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case EAllocation_FREE :
|
||||||
|
// NOTE: Free all at once
|
||||||
|
// Use Temp_Arena_Memory if you want to free a block
|
||||||
|
break;
|
||||||
|
|
||||||
|
case EAllocation_FREE_ALL :
|
||||||
|
arena->TotalUsed = 0;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case EAllocation_RESIZE :
|
||||||
|
{
|
||||||
|
// TODO : Check if ptr is on top of stack and just extend
|
||||||
|
AllocatorInfo a = arena->Backing;
|
||||||
|
ptr = default_resize_align( a, old_memory, old_size, size, alignment );
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return ptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void* pool_allocator_proc( void* allocator_data, AllocType type, ssize size, ssize alignment, void* old_memory, ssize old_size, u64 flags )
|
||||||
|
{
|
||||||
|
Pool* pool = rcast( Pool*, allocator_data);
|
||||||
|
void* ptr = NULL;
|
||||||
|
|
||||||
|
// unused( old_size );
|
||||||
|
|
||||||
|
switch ( type )
|
||||||
|
{
|
||||||
|
case EAllocation_ALLOC :
|
||||||
|
{
|
||||||
|
uptr next_free;
|
||||||
|
|
||||||
|
GEN_ASSERT( size == pool->BlockSize );
|
||||||
|
GEN_ASSERT( alignment == pool->BlockAlign );
|
||||||
|
GEN_ASSERT( pool->FreeList != NULL );
|
||||||
|
|
||||||
|
next_free = * rcast( uptr*, pool->FreeList);
|
||||||
|
ptr = pool->FreeList;
|
||||||
|
pool->FreeList = rcast( void*, next_free);
|
||||||
|
pool->TotalSize += pool->BlockSize;
|
||||||
|
|
||||||
|
if ( flags & ALLOCATOR_FLAG_CLEAR_TO_ZERO )
|
||||||
|
zero_size( ptr, size );
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case EAllocation_FREE :
|
||||||
|
{
|
||||||
|
uptr* next;
|
||||||
|
if ( old_memory == NULL )
|
||||||
|
return NULL;
|
||||||
|
|
||||||
|
next = rcast( uptr*, old_memory);
|
||||||
|
*next = rcast( uptr, pool->FreeList);
|
||||||
|
pool->FreeList = old_memory;
|
||||||
|
pool->TotalSize -= pool->BlockSize;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case EAllocation_FREE_ALL :
|
||||||
|
{
|
||||||
|
ssize actual_block_size, block_index;
|
||||||
|
void* curr;
|
||||||
|
uptr* end;
|
||||||
|
|
||||||
|
actual_block_size = pool->BlockSize + pool->BlockAlign;
|
||||||
|
pool->TotalSize = 0;
|
||||||
|
|
||||||
|
// NOTE: Init intrusive freelist
|
||||||
|
curr = pool->PhysicalStart;
|
||||||
|
for ( block_index = 0; block_index < pool->NumBlocks - 1; block_index++ )
|
||||||
|
{
|
||||||
|
uptr* next = rcast( uptr*, curr);
|
||||||
|
* next = rcast( uptr, curr) + actual_block_size;
|
||||||
|
curr = pointer_add( curr, actual_block_size );
|
||||||
|
}
|
||||||
|
|
||||||
|
end = rcast( uptr*, curr);
|
||||||
|
* end = scast( uptr, NULL);
|
||||||
|
pool->FreeList = pool->PhysicalStart;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case EAllocation_RESIZE :
|
||||||
|
// NOTE: Cannot resize
|
||||||
|
GEN_PANIC( "You cannot resize something allocated by with a pool." );
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
Pool pool_init_align( AllocatorInfo backing, ssize num_blocks, ssize block_size, ssize block_align )
|
||||||
|
{
|
||||||
|
Pool pool = {};
|
||||||
|
|
||||||
|
ssize actual_block_size, pool_size, block_index;
|
||||||
|
void *data, *curr;
|
||||||
|
uptr* end;
|
||||||
|
|
||||||
|
zero_item( &pool );
|
||||||
|
|
||||||
|
pool.Backing = backing;
|
||||||
|
pool.BlockSize = block_size;
|
||||||
|
pool.BlockAlign = block_align;
|
||||||
|
pool.NumBlocks = num_blocks;
|
||||||
|
|
||||||
|
actual_block_size = block_size + block_align;
|
||||||
|
pool_size = num_blocks * actual_block_size;
|
||||||
|
|
||||||
|
data = alloc_align( backing, pool_size, block_align );
|
||||||
|
|
||||||
|
// NOTE: Init intrusive freelist
|
||||||
|
curr = data;
|
||||||
|
for ( block_index = 0; block_index < num_blocks - 1; block_index++ )
|
||||||
|
{
|
||||||
|
uptr* next = ( uptr* ) curr;
|
||||||
|
*next = ( uptr ) curr + actual_block_size;
|
||||||
|
curr = pointer_add( curr, actual_block_size );
|
||||||
|
}
|
||||||
|
|
||||||
|
end = ( uptr* ) curr;
|
||||||
|
*end = ( uptr ) NULL;
|
||||||
|
|
||||||
|
pool.PhysicalStart = data;
|
||||||
|
pool.FreeList = data;
|
||||||
|
|
||||||
|
return pool;
|
||||||
|
}
|
||||||
|
|
||||||
|
void pool_clear(Pool* pool)
|
||||||
|
{
|
||||||
|
ssize actual_block_size, block_index;
|
||||||
|
void* curr;
|
||||||
|
uptr* end;
|
||||||
|
|
||||||
|
actual_block_size = pool->BlockSize + pool->BlockAlign;
|
||||||
|
|
||||||
|
curr = pool->PhysicalStart;
|
||||||
|
for ( block_index = 0; block_index < pool->NumBlocks - 1; block_index++ )
|
||||||
|
{
|
||||||
|
uptr* next = ( uptr* ) curr;
|
||||||
|
*next = ( uptr ) curr + actual_block_size;
|
||||||
|
curr = pointer_add( curr, actual_block_size );
|
||||||
|
}
|
||||||
|
|
||||||
|
end = ( uptr* ) curr;
|
||||||
|
*end = ( uptr ) NULL;
|
||||||
|
|
||||||
|
pool->FreeList = pool->PhysicalStart;
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma endregion Memory
|
||||||
@@ -0,0 +1,668 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "debug.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Memory
|
||||||
|
|
||||||
|
#define kilobytes( x ) ( ( x ) * ( s64 )( 1024 ) )
|
||||||
|
#define megabytes( x ) ( kilobytes( x ) * ( s64 )( 1024 ) )
|
||||||
|
#define gigabytes( x ) ( megabytes( x ) * ( s64 )( 1024 ) )
|
||||||
|
#define terabytes( x ) ( gigabytes( x ) * ( s64 )( 1024 ) )
|
||||||
|
|
||||||
|
#define GEN__ONES ( scast( GEN_NS usize, - 1) / GEN_U8_MAX )
|
||||||
|
#define GEN__HIGHS ( GEN__ONES * ( GEN_U8_MAX / 2 + 1 ) )
|
||||||
|
#define GEN__HAS_ZERO( x ) ( ( ( x ) - GEN__ONES ) & ~( x ) & GEN__HIGHS )
|
||||||
|
|
||||||
|
template< class Type >
|
||||||
|
void swap( Type& a, Type& b )
|
||||||
|
{
|
||||||
|
Type tmp = a;
|
||||||
|
a = b;
|
||||||
|
b = tmp;
|
||||||
|
}
|
||||||
|
|
||||||
|
//! Checks if value is power of 2.
|
||||||
|
b32 is_power_of_two( ssize x );
|
||||||
|
|
||||||
|
//! Aligns address to specified alignment.
|
||||||
|
void* align_forward( void* ptr, ssize alignment );
|
||||||
|
|
||||||
|
//! Aligns value to a specified alignment.
|
||||||
|
s64 align_forward_by_value( s64 value, ssize alignment );
|
||||||
|
|
||||||
|
//! Moves pointer forward by bytes.
|
||||||
|
void* pointer_add( void* ptr, ssize bytes );
|
||||||
|
|
||||||
|
//! Moves pointer forward by bytes.
|
||||||
|
void const* pointer_add_const( void const* ptr, ssize bytes );
|
||||||
|
|
||||||
|
//! Calculates difference between two addresses.
|
||||||
|
ssize pointer_diff( void const* begin, void const* end );
|
||||||
|
|
||||||
|
//! Copy non-overlapping memory from source to destination.
|
||||||
|
GEN_API void* mem_copy( void* dest, void const* source, ssize size );
|
||||||
|
|
||||||
|
//! Search for a constant value within the size limit at memory location.
|
||||||
|
GEN_API void const* mem_find( void const* data, u8 byte_value, ssize size );
|
||||||
|
|
||||||
|
//! Copy memory from source to destination.
|
||||||
|
void* mem_move( void* dest, void const* source, ssize size );
|
||||||
|
|
||||||
|
//! Set constant value at memory location with specified size.
|
||||||
|
void* mem_set( void* data, u8 byte_value, ssize size );
|
||||||
|
|
||||||
|
//! @param ptr Memory location to clear up.
|
||||||
|
//! @param size The size to clear up with.
|
||||||
|
void zero_size( void* ptr, ssize size );
|
||||||
|
|
||||||
|
//! Clears up an item.
|
||||||
|
#define zero_item( t ) zero_size( ( t ), size_of( *( t ) ) ) // NOTE: Pass pointer of struct
|
||||||
|
|
||||||
|
//! Clears up an array.
|
||||||
|
#define zero_array( a, count ) zero_size( ( a ), size_of( *( a ) ) * count )
|
||||||
|
|
||||||
|
enum AllocType : u8
|
||||||
|
{
|
||||||
|
EAllocation_ALLOC,
|
||||||
|
EAllocation_FREE,
|
||||||
|
EAllocation_FREE_ALL,
|
||||||
|
EAllocation_RESIZE,
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef void*(AllocatorProc)( void* allocator_data, AllocType type, ssize size, ssize alignment, void* old_memory, ssize old_size, u64 flags );
|
||||||
|
|
||||||
|
struct AllocatorInfo
|
||||||
|
{
|
||||||
|
AllocatorProc* Proc;
|
||||||
|
void* Data;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum AllocFlag
|
||||||
|
{
|
||||||
|
ALLOCATOR_FLAG_CLEAR_TO_ZERO = bit( 0 ),
|
||||||
|
};
|
||||||
|
|
||||||
|
#ifndef GEN_DEFAULT_MEMORY_ALIGNMENT
|
||||||
|
# define GEN_DEFAULT_MEMORY_ALIGNMENT ( 2 * size_of( void* ) )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef GEN_DEFAULT_ALLOCATOR_FLAGS
|
||||||
|
# define GEN_DEFAULT_ALLOCATOR_FLAGS ( ALLOCATOR_FLAG_CLEAR_TO_ZERO )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
//! Allocate memory with default alignment.
|
||||||
|
void* alloc( AllocatorInfo a, ssize size );
|
||||||
|
|
||||||
|
//! Allocate memory with specified alignment.
|
||||||
|
void* alloc_align( AllocatorInfo a, ssize size, ssize alignment );
|
||||||
|
|
||||||
|
//! Free allocated memory.
|
||||||
|
void allocator_free( AllocatorInfo a, void* ptr );
|
||||||
|
|
||||||
|
//! Free all memory allocated by an allocator.
|
||||||
|
void free_all( AllocatorInfo a );
|
||||||
|
|
||||||
|
//! Resize an allocated memory.
|
||||||
|
void* resize( AllocatorInfo a, void* ptr, ssize old_size, ssize new_size );
|
||||||
|
|
||||||
|
//! Resize an allocated memory with specified alignment.
|
||||||
|
void* resize_align( AllocatorInfo a, void* ptr, ssize old_size, ssize new_size, ssize alignment );
|
||||||
|
|
||||||
|
//! Allocate memory for an item.
|
||||||
|
#define alloc_item( allocator_, Type ) ( Type* )alloc( allocator_, size_of( Type ) )
|
||||||
|
|
||||||
|
//! Allocate memory for an array of items.
|
||||||
|
#define alloc_array( allocator_, Type, count ) ( Type* )alloc( allocator_, size_of( Type ) * ( count ) )
|
||||||
|
|
||||||
|
/* heap memory analysis tools */
|
||||||
|
/* define GEN_HEAP_ANALYSIS to enable this feature */
|
||||||
|
/* call zpl_heap_stats_init at the beginning of the entry point */
|
||||||
|
/* you can call zpl_heap_stats_check near the end of the execution to validate any possible leaks */
|
||||||
|
GEN_API void heap_stats_init( void );
|
||||||
|
GEN_API ssize heap_stats_used_memory( void );
|
||||||
|
GEN_API ssize heap_stats_alloc_count( void );
|
||||||
|
GEN_API void heap_stats_check( void );
|
||||||
|
|
||||||
|
//! Allocate/Resize memory using default options.
|
||||||
|
|
||||||
|
//! Use this if you don't need a "fancy" resize allocation
|
||||||
|
void* default_resize_align( AllocatorInfo a, void* ptr, ssize old_size, ssize new_size, ssize alignment );
|
||||||
|
|
||||||
|
GEN_API void* heap_allocator_proc( void* allocator_data, AllocType type, ssize size, ssize alignment, void* old_memory, ssize old_size, u64 flags );
|
||||||
|
|
||||||
|
//! The heap allocator backed by operating system's memory manager.
|
||||||
|
constexpr AllocatorInfo heap( void ) { AllocatorInfo allocator = { heap_allocator_proc, nullptr }; return allocator; }
|
||||||
|
|
||||||
|
struct VirtualMemory
|
||||||
|
{
|
||||||
|
void* data;
|
||||||
|
ssize size;
|
||||||
|
};
|
||||||
|
|
||||||
|
//! Initialize virtual memory from existing data.
|
||||||
|
GEN_API VirtualMemory vm_from_memory( void* data, ssize size );
|
||||||
|
|
||||||
|
//! Allocate virtual memory at address with size.
|
||||||
|
|
||||||
|
//! @param addr The starting address of the region to reserve. If NULL, it lets operating system to decide where to allocate it.
|
||||||
|
//! @param size The size to serve.
|
||||||
|
GEN_API VirtualMemory vm_alloc( void* addr, ssize size );
|
||||||
|
|
||||||
|
//! Release the virtual memory.
|
||||||
|
GEN_API b32 vm_free( VirtualMemory vm );
|
||||||
|
|
||||||
|
//! Trim virtual memory.
|
||||||
|
GEN_API VirtualMemory vm_trim( VirtualMemory vm, ssize lead_size, ssize size );
|
||||||
|
|
||||||
|
//! Purge virtual memory.
|
||||||
|
GEN_API b32 vm_purge( VirtualMemory vm );
|
||||||
|
|
||||||
|
//! Retrieve VM's page size and alignment.
|
||||||
|
GEN_API ssize virtual_memory_page_size( ssize* alignment_out );
|
||||||
|
|
||||||
|
#pragma region Arena
|
||||||
|
struct Arena;
|
||||||
|
|
||||||
|
AllocatorInfo arena_allocator_info( Arena* arena );
|
||||||
|
|
||||||
|
// Remove static keyword and rename allocator_proc
|
||||||
|
GEN_API void* arena_allocator_proc(void* allocator_data, AllocType type, ssize size, ssize alignment, void* old_memory, ssize old_size, u64 flags);
|
||||||
|
|
||||||
|
// Add these declarations after the Arena struct
|
||||||
|
Arena arena_init_from_allocator(AllocatorInfo backing, ssize size);
|
||||||
|
Arena arena_init_from_memory ( void* start, ssize size );
|
||||||
|
|
||||||
|
Arena arena_init_sub (Arena* parent, ssize size);
|
||||||
|
ssize arena_alignment_of (Arena* arena, ssize alignment);
|
||||||
|
void arena_check (Arena* arena);
|
||||||
|
void arena_free (Arena* arena);
|
||||||
|
ssize arena_size_remaining(Arena* arena, ssize alignment);
|
||||||
|
|
||||||
|
// TODO(Ed): Add arena_pos, arena_pop, and arena_pop_to
|
||||||
|
|
||||||
|
struct Arena
|
||||||
|
{
|
||||||
|
AllocatorInfo Backing;
|
||||||
|
void* PhysicalStart;
|
||||||
|
ssize TotalSize;
|
||||||
|
ssize TotalUsed;
|
||||||
|
ssize TempCount;
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP && ! GEN_C_LIKE_CPP
|
||||||
|
#pragma region Member Mapping
|
||||||
|
forceinline operator AllocatorInfo() { return arena_allocator_info(this); }
|
||||||
|
|
||||||
|
forceinline static void* allocator_proc( void* allocator_data, AllocType type, ssize size, ssize alignment, void* old_memory, ssize old_size, u64 flags ) { return arena_allocator_proc( allocator_data, type, size, alignment, old_memory, old_size, flags ); }
|
||||||
|
forceinline static Arena init_from_memory( void* start, ssize size ) { return arena_init_from_memory( start, size ); }
|
||||||
|
forceinline static Arena init_from_allocator( AllocatorInfo backing, ssize size ) { return arena_init_from_allocator( backing, size ); }
|
||||||
|
forceinline static Arena init_sub( Arena& parent, ssize size ) { return arena_init_from_allocator( parent.Backing, size ); }
|
||||||
|
forceinline ssize alignment_of( ssize alignment ) { return arena_alignment_of(this, alignment); }
|
||||||
|
forceinline void free() { return arena_free(this); }
|
||||||
|
forceinline ssize size_remaining( ssize alignment ) { return arena_size_remaining(this, alignment); }
|
||||||
|
|
||||||
|
// This id is defined by Unreal for asserts
|
||||||
|
#pragma push_macro("check")
|
||||||
|
#undef check
|
||||||
|
forceinline void check() { arena_check(this); }
|
||||||
|
#pragma pop_macro("check")
|
||||||
|
|
||||||
|
#pragma endregion Member Mapping
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP && ! GEN_C_LIKE_CPP
|
||||||
|
forceinline AllocatorInfo allocator_info(Arena& arena ) { return arena_allocator_info(& arena); }
|
||||||
|
forceinline Arena init_sub (Arena& parent, ssize size) { return arena_init_sub( & parent, size); }
|
||||||
|
forceinline ssize alignment_of (Arena& arena, ssize alignment) { return arena_alignment_of( & arena, alignment); }
|
||||||
|
forceinline void free (Arena& arena) { return arena_free(& arena); }
|
||||||
|
forceinline ssize size_remaining(Arena& arena, ssize alignment) { return arena_size_remaining(& arena, alignment); }
|
||||||
|
|
||||||
|
// This id is defined by Unreal for asserts
|
||||||
|
#pragma push_macro("check")
|
||||||
|
#undef check
|
||||||
|
forceinline void check(Arena& arena) { return arena_check(& arena); }
|
||||||
|
#pragma pop_macro("check")
|
||||||
|
#endif
|
||||||
|
|
||||||
|
inline
|
||||||
|
AllocatorInfo arena_allocator_info( Arena* arena ) {
|
||||||
|
GEN_ASSERT(arena != nullptr);
|
||||||
|
AllocatorInfo info = { arena_allocator_proc, arena };
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
Arena arena_init_from_memory( void* start, ssize size )
|
||||||
|
{
|
||||||
|
Arena arena = {
|
||||||
|
{ nullptr, nullptr },
|
||||||
|
start,
|
||||||
|
size,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
};
|
||||||
|
return arena;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
Arena arena_init_from_allocator(AllocatorInfo backing, ssize size) {
|
||||||
|
Arena result = {
|
||||||
|
backing,
|
||||||
|
alloc(backing, size),
|
||||||
|
size,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
};
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
Arena arena_init_sub(Arena* parent, ssize size) {
|
||||||
|
GEN_ASSERT(parent != nullptr);
|
||||||
|
return arena_init_from_allocator(parent->Backing, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
ssize arena_alignment_of(Arena* arena, ssize alignment)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(arena != nullptr);
|
||||||
|
ssize alignment_offset, result_pointer, mask;
|
||||||
|
GEN_ASSERT(is_power_of_two(alignment));
|
||||||
|
|
||||||
|
alignment_offset = 0;
|
||||||
|
result_pointer = (ssize)arena->PhysicalStart + arena->TotalUsed;
|
||||||
|
mask = alignment - 1;
|
||||||
|
|
||||||
|
if (result_pointer & mask)
|
||||||
|
alignment_offset = alignment - (result_pointer & mask);
|
||||||
|
|
||||||
|
return alignment_offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void arena_check(Arena* arena)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(arena != nullptr );
|
||||||
|
GEN_ASSERT(arena->TempCount == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void arena_free(Arena* arena)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(arena != nullptr);
|
||||||
|
if (arena->Backing.Proc)
|
||||||
|
{
|
||||||
|
allocator_free(arena->Backing, arena->PhysicalStart);
|
||||||
|
arena->PhysicalStart = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
ssize arena_size_remaining(Arena* arena, ssize alignment)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(arena != nullptr);
|
||||||
|
ssize result = arena->TotalSize - (arena->TotalUsed + arena_alignment_of(arena, alignment));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
#pragma endregion Arena
|
||||||
|
|
||||||
|
#pragma region FixedArena
|
||||||
|
template<s32 Size>
|
||||||
|
struct FixedArena;
|
||||||
|
|
||||||
|
template<s32 Size> FixedArena<Size> fixed_arena_init();
|
||||||
|
template<s32 Size> AllocatorInfo fixed_arena_allocator_info(FixedArena<Size>* fixed_arena );
|
||||||
|
template<s32 Size> ssize fixed_arena_size_remaining(FixedArena<Size>* fixed_arena, ssize alignment);
|
||||||
|
template<s32 Size> void fixed_arena_free(FixedArena<Size>* fixed_arena);
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP && ! GEN_C_LIKE_CPP
|
||||||
|
template<s32 Size> AllocatorInfo allocator_info( FixedArena<Size>& fixed_arena ) { return allocator_info(& fixed_arena); }
|
||||||
|
template<s32 Size> ssize size_remaining(FixedArena<Size>& fixed_arena, ssize alignment) { return size_remaining( & fixed_arena, alignment); }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Just a wrapper around using an arena with memory associated with its scope instead of from an allocator.
|
||||||
|
// Used for static segment or stack allocations.
|
||||||
|
template< s32 Size >
|
||||||
|
struct FixedArena
|
||||||
|
{
|
||||||
|
char memory[Size];
|
||||||
|
Arena arena;
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP && ! GEN_C_LIKE_CPP
|
||||||
|
#pragma region Member Mapping
|
||||||
|
forceinline operator AllocatorInfo() { return fixed_arena_allocator_info(this); }
|
||||||
|
|
||||||
|
forceinline static FixedArena init() { FixedArena result; fixed_arena_init<Size>(result); return result; }
|
||||||
|
forceinline ssize size_remaining(ssize alignment) { fixed_arena_size_remaining(this, alignment); }
|
||||||
|
#pragma endregion Member Mapping
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
template<s32 Size> inline
|
||||||
|
AllocatorInfo fixed_arena_allocator_info( FixedArena<Size>* fixed_arena ) {
|
||||||
|
GEN_ASSERT(fixed_arena);
|
||||||
|
return { arena_allocator_proc, & fixed_arena->arena };
|
||||||
|
}
|
||||||
|
|
||||||
|
template<s32 Size> inline
|
||||||
|
void fixed_arena_init(FixedArena<Size>* result) {
|
||||||
|
zero_size(& result->memory[0], Size);
|
||||||
|
result->arena = arena_init_from_memory(& result->memory[0], Size);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<s32 Size> inline
|
||||||
|
void fixed_arena_free(FixedArena<Size>* fixed_arena) {
|
||||||
|
arena_free( & fixed_arena->arena);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<s32 Size> inline
|
||||||
|
ssize fixed_arena_size_remaining(FixedArena<Size>* fixed_arena, ssize alignment) {
|
||||||
|
return size_remaining(fixed_arena->arena, alignment);
|
||||||
|
}
|
||||||
|
|
||||||
|
using FixedArena_1KB = FixedArena< kilobytes( 1 ) >;
|
||||||
|
using FixedArena_4KB = FixedArena< kilobytes( 4 ) >;
|
||||||
|
using FixedArena_8KB = FixedArena< kilobytes( 8 ) >;
|
||||||
|
using FixedArena_16KB = FixedArena< kilobytes( 16 ) >;
|
||||||
|
using FixedArena_32KB = FixedArena< kilobytes( 32 ) >;
|
||||||
|
using FixedArena_64KB = FixedArena< kilobytes( 64 ) >;
|
||||||
|
using FixedArena_128KB = FixedArena< kilobytes( 128 ) >;
|
||||||
|
using FixedArena_256KB = FixedArena< kilobytes( 256 ) >;
|
||||||
|
using FixedArena_512KB = FixedArena< kilobytes( 512 ) >;
|
||||||
|
using FixedArena_1MB = FixedArena< megabytes( 1 ) >;
|
||||||
|
using FixedArena_2MB = FixedArena< megabytes( 2 ) >;
|
||||||
|
using FixedArena_4MB = FixedArena< megabytes( 4 ) >;
|
||||||
|
#pragma endregion FixedArena
|
||||||
|
|
||||||
|
#pragma region Pool
|
||||||
|
struct Pool;
|
||||||
|
|
||||||
|
GEN_API void* pool_allocator_proc(void* allocator_data, AllocType type, ssize size, ssize alignment, void* old_memory, ssize old_size, u64 flags);
|
||||||
|
|
||||||
|
Pool pool_init(AllocatorInfo backing, ssize num_blocks, ssize block_size);
|
||||||
|
Pool pool_init_align(AllocatorInfo backing, ssize num_blocks, ssize block_size, ssize block_align);
|
||||||
|
AllocatorInfo pool_allocator_info(Pool* pool);
|
||||||
|
GEN_API void pool_clear(Pool* pool);
|
||||||
|
void pool_free(Pool* pool);
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP && ! GEN_C_LIKE_CPP
|
||||||
|
forceinline AllocatorInfo allocator_info(Pool& pool) { return pool_allocator_info(& pool); }
|
||||||
|
forceinline void clear(Pool& pool) { return pool_clear(& pool); }
|
||||||
|
forceinline void free(Pool& pool) { return pool_free(& pool); }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
struct Pool
|
||||||
|
{
|
||||||
|
AllocatorInfo Backing;
|
||||||
|
void* PhysicalStart;
|
||||||
|
void* FreeList;
|
||||||
|
ssize BlockSize;
|
||||||
|
ssize BlockAlign;
|
||||||
|
ssize TotalSize;
|
||||||
|
ssize NumBlocks;
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP && ! GEN_C_LIKE_CPP
|
||||||
|
#pragma region Member Mapping
|
||||||
|
forceinline operator AllocatorInfo() { return pool_allocator_info(this); }
|
||||||
|
|
||||||
|
forceinline static void* allocator_proc(void* allocator_data, AllocType type, ssize size, ssize alignment, void* old_memory, ssize old_size, u64 flags) { return pool_allocator_proc(allocator_data, type, size, alignment, old_memory, old_size, flags); }
|
||||||
|
forceinline static Pool init(AllocatorInfo backing, ssize num_blocks, ssize block_size) { return pool_init(backing, num_blocks, block_size); }
|
||||||
|
forceinline static Pool init_align(AllocatorInfo backing, ssize num_blocks, ssize block_size, ssize block_align) { return pool_init_align(backing, num_blocks, block_size, block_align); }
|
||||||
|
forceinline void clear() { pool_clear( this); }
|
||||||
|
forceinline void free() { pool_free( this); }
|
||||||
|
#pragma endregion
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
inline
|
||||||
|
AllocatorInfo pool_allocator_info(Pool* pool) {
|
||||||
|
AllocatorInfo info = { pool_allocator_proc, pool };
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
Pool pool_init(AllocatorInfo backing, ssize num_blocks, ssize block_size) {
|
||||||
|
return pool_init_align(backing, num_blocks, block_size, GEN_DEFAULT_MEMORY_ALIGNMENT);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void pool_free(Pool* pool) {
|
||||||
|
if(pool->Backing.Proc) {
|
||||||
|
allocator_free(pool->Backing, pool->PhysicalStart);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#pragma endregion Pool
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 is_power_of_two( ssize x ) {
|
||||||
|
if ( x <= 0 )
|
||||||
|
return false;
|
||||||
|
return ! ( x & ( x - 1 ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
mem_ptr align_forward( void* ptr, ssize alignment )
|
||||||
|
{
|
||||||
|
GEN_ASSERT( is_power_of_two( alignment ) );
|
||||||
|
uptr p = to_uptr(ptr);
|
||||||
|
uptr forward = (p + ( alignment - 1 ) ) & ~( alignment - 1 );
|
||||||
|
|
||||||
|
return to_mem_ptr(forward);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline s64 align_forward_s64( s64 value, ssize alignment ) { return value + ( alignment - value % alignment ) % alignment; }
|
||||||
|
|
||||||
|
inline void* pointer_add ( void* ptr, ssize bytes ) { return rcast(void*, rcast( u8*, ptr) + bytes ); }
|
||||||
|
inline void const* pointer_add_const( void const* ptr, ssize bytes ) { return rcast(void const*, rcast( u8 const*, ptr) + bytes ); }
|
||||||
|
|
||||||
|
inline sptr pointer_diff( mem_ptr_const begin, mem_ptr_const end ) {
|
||||||
|
return scast( ssize, rcast( u8 const*, end) - rcast(u8 const*, begin) );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void* mem_move( void* destination, void const* source, ssize byte_count )
|
||||||
|
{
|
||||||
|
if ( destination == NULL )
|
||||||
|
{
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
u8* dest_ptr = rcast( u8*, destination);
|
||||||
|
u8 const* src_ptr = rcast( u8 const*, source);
|
||||||
|
|
||||||
|
if ( dest_ptr == src_ptr )
|
||||||
|
return dest_ptr;
|
||||||
|
|
||||||
|
if ( src_ptr + byte_count <= dest_ptr || dest_ptr + byte_count <= src_ptr ) // NOTE: Non-overlapping
|
||||||
|
return mem_copy( dest_ptr, src_ptr, byte_count );
|
||||||
|
|
||||||
|
if ( dest_ptr < src_ptr )
|
||||||
|
{
|
||||||
|
if ( to_uptr(src_ptr) % size_of( ssize ) == to_uptr(dest_ptr) % size_of( ssize ) )
|
||||||
|
{
|
||||||
|
while ( pcast( uptr, dest_ptr) % size_of( ssize ) )
|
||||||
|
{
|
||||||
|
if ( ! byte_count-- )
|
||||||
|
return destination;
|
||||||
|
|
||||||
|
*dest_ptr++ = *src_ptr++;
|
||||||
|
}
|
||||||
|
while ( byte_count >= size_of( ssize ) )
|
||||||
|
{
|
||||||
|
* rcast(ssize*, dest_ptr) = * rcast(ssize const*, src_ptr);
|
||||||
|
byte_count -= size_of( ssize );
|
||||||
|
dest_ptr += size_of( ssize );
|
||||||
|
src_ptr += size_of( ssize );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for ( ; byte_count; byte_count-- )
|
||||||
|
*dest_ptr++ = *src_ptr++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if ( ( to_uptr(src_ptr) % size_of( ssize ) ) == ( to_uptr(dest_ptr) % size_of( ssize ) ) )
|
||||||
|
{
|
||||||
|
while ( to_uptr( dest_ptr + byte_count ) % size_of( ssize ) )
|
||||||
|
{
|
||||||
|
if ( ! byte_count-- )
|
||||||
|
return destination;
|
||||||
|
|
||||||
|
dest_ptr[ byte_count ] = src_ptr[ byte_count ];
|
||||||
|
}
|
||||||
|
while ( byte_count >= size_of( ssize ) )
|
||||||
|
{
|
||||||
|
byte_count -= size_of( ssize );
|
||||||
|
* rcast(ssize*, dest_ptr + byte_count ) = * rcast( ssize const*, src_ptr + byte_count );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while ( byte_count )
|
||||||
|
byte_count--, dest_ptr[ byte_count ] = src_ptr[ byte_count ];
|
||||||
|
}
|
||||||
|
|
||||||
|
return destination;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void* mem_set( void* destination, u8 fill_byte, ssize byte_count )
|
||||||
|
{
|
||||||
|
if ( destination == NULL )
|
||||||
|
{
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize align_offset;
|
||||||
|
u8* dest_ptr = rcast( u8*, destination);
|
||||||
|
u32 fill_word = ( ( u32 )-1 ) / 255 * fill_byte;
|
||||||
|
|
||||||
|
if ( byte_count == 0 )
|
||||||
|
return destination;
|
||||||
|
|
||||||
|
dest_ptr[ 0 ] = dest_ptr[ byte_count - 1 ] = fill_byte;
|
||||||
|
if ( byte_count < 3 )
|
||||||
|
return destination;
|
||||||
|
|
||||||
|
dest_ptr[ 1 ] = dest_ptr[ byte_count - 2 ] = fill_byte;
|
||||||
|
dest_ptr[ 2 ] = dest_ptr[ byte_count - 3 ] = fill_byte;
|
||||||
|
if ( byte_count < 7 )
|
||||||
|
return destination;
|
||||||
|
|
||||||
|
dest_ptr[ 3 ] = dest_ptr[ byte_count - 4 ] = fill_byte;
|
||||||
|
if ( byte_count < 9 )
|
||||||
|
return destination;
|
||||||
|
|
||||||
|
align_offset = -to_sptr( dest_ptr ) & 3;
|
||||||
|
dest_ptr += align_offset;
|
||||||
|
byte_count -= align_offset;
|
||||||
|
byte_count &= -4;
|
||||||
|
|
||||||
|
* rcast( u32*, ( dest_ptr + 0 ) ) = fill_word;
|
||||||
|
* rcast( u32*, ( dest_ptr + byte_count - 4 ) ) = fill_word;
|
||||||
|
if ( byte_count < 9 )
|
||||||
|
return destination;
|
||||||
|
|
||||||
|
* rcast( u32*, dest_ptr + 4 ) = fill_word;
|
||||||
|
* rcast( u32*, dest_ptr + 8 ) = fill_word;
|
||||||
|
* rcast( u32*, dest_ptr + byte_count - 12 ) = fill_word;
|
||||||
|
* rcast( u32*, dest_ptr + byte_count - 8 ) = fill_word;
|
||||||
|
if ( byte_count < 25 )
|
||||||
|
return destination;
|
||||||
|
|
||||||
|
* rcast( u32*, dest_ptr + 12 ) = fill_word;
|
||||||
|
* rcast( u32*, dest_ptr + 16 ) = fill_word;
|
||||||
|
* rcast( u32*, dest_ptr + 20 ) = fill_word;
|
||||||
|
* rcast( u32*, dest_ptr + 24 ) = fill_word;
|
||||||
|
* rcast( u32*, dest_ptr + byte_count - 28 ) = fill_word;
|
||||||
|
* rcast( u32*, dest_ptr + byte_count - 24 ) = fill_word;
|
||||||
|
* rcast( u32*, dest_ptr + byte_count - 20 ) = fill_word;
|
||||||
|
* rcast( u32*, dest_ptr + byte_count - 16 ) = fill_word;
|
||||||
|
|
||||||
|
align_offset = 24 + to_uptr( dest_ptr ) & 4;
|
||||||
|
dest_ptr += align_offset;
|
||||||
|
byte_count -= align_offset;
|
||||||
|
|
||||||
|
{
|
||||||
|
u64 fill_doubleword = ( scast( u64, fill_word) << 32 ) | fill_word;
|
||||||
|
while ( byte_count > 31 )
|
||||||
|
{
|
||||||
|
* rcast( u64*, dest_ptr + 0 ) = fill_doubleword;
|
||||||
|
* rcast( u64*, dest_ptr + 8 ) = fill_doubleword;
|
||||||
|
* rcast( u64*, dest_ptr + 16 ) = fill_doubleword;
|
||||||
|
* rcast( u64*, dest_ptr + 24 ) = fill_doubleword;
|
||||||
|
|
||||||
|
byte_count -= 32;
|
||||||
|
dest_ptr += 32;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return destination;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void* alloc_align( AllocatorInfo a, ssize size, ssize alignment ) {
|
||||||
|
return a.Proc( a.Data, EAllocation_ALLOC, size, alignment, nullptr, 0, GEN_DEFAULT_ALLOCATOR_FLAGS );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void* alloc( AllocatorInfo a, ssize size ) {
|
||||||
|
return alloc_align( a, size, GEN_DEFAULT_MEMORY_ALIGNMENT );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void allocator_free( AllocatorInfo a, void* ptr ) {
|
||||||
|
if ( ptr != nullptr )
|
||||||
|
a.Proc( a.Data, EAllocation_FREE, 0, 0, ptr, 0, GEN_DEFAULT_ALLOCATOR_FLAGS );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void free_all( AllocatorInfo a ) {
|
||||||
|
a.Proc( a.Data, EAllocation_FREE_ALL, 0, 0, nullptr, 0, GEN_DEFAULT_ALLOCATOR_FLAGS );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void* resize( AllocatorInfo a, void* ptr, ssize old_size, ssize new_size ) {
|
||||||
|
return resize_align( a, ptr, old_size, new_size, GEN_DEFAULT_MEMORY_ALIGNMENT );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void* resize_align( AllocatorInfo a, void* ptr, ssize old_size, ssize new_size, ssize alignment ) {
|
||||||
|
return a.Proc( a.Data, EAllocation_RESIZE, new_size, alignment, ptr, old_size, GEN_DEFAULT_ALLOCATOR_FLAGS );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void* default_resize_align( AllocatorInfo a, void* old_memory, ssize old_size, ssize new_size, ssize alignment )
|
||||||
|
{
|
||||||
|
if ( ! old_memory )
|
||||||
|
return alloc_align( a, new_size, alignment );
|
||||||
|
|
||||||
|
if ( new_size == 0 )
|
||||||
|
{
|
||||||
|
allocator_free( a, old_memory );
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( new_size < old_size )
|
||||||
|
new_size = old_size;
|
||||||
|
|
||||||
|
if ( old_size == new_size )
|
||||||
|
{
|
||||||
|
return old_memory;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
void* new_memory = alloc_align( a, new_size, alignment );
|
||||||
|
if ( ! new_memory )
|
||||||
|
return nullptr;
|
||||||
|
|
||||||
|
mem_move( new_memory, old_memory, min( new_size, old_size ) );
|
||||||
|
allocator_free( a, old_memory );
|
||||||
|
return new_memory;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void zero_size( void* ptr, ssize size ) {
|
||||||
|
mem_set( ptr, 0, size );
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma endregion Memory
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,433 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "timing.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region ADT
|
||||||
|
|
||||||
|
enum ADT_Type : u32
|
||||||
|
{
|
||||||
|
EADT_TYPE_UNINITIALISED, /* node was not initialised, this is a programming error! */
|
||||||
|
EADT_TYPE_ARRAY,
|
||||||
|
EADT_TYPE_OBJECT,
|
||||||
|
EADT_TYPE_STRING,
|
||||||
|
EADT_TYPE_MULTISTRING,
|
||||||
|
EADT_TYPE_INTEGER,
|
||||||
|
EADT_TYPE_REAL,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum ADT_Props : u32
|
||||||
|
{
|
||||||
|
EADT_PROPS_NONE,
|
||||||
|
EADT_PROPS_NAN,
|
||||||
|
EADT_PROPS_NAN_NEG,
|
||||||
|
EADT_PROPS_INFINITY,
|
||||||
|
EADT_PROPS_INFINITY_NEG,
|
||||||
|
EADT_PROPS_FALSE,
|
||||||
|
EADT_PROPS_TRUE,
|
||||||
|
EADT_PROPS_NULL,
|
||||||
|
EADT_PROPS_IS_EXP,
|
||||||
|
EADT_PROPS_IS_HEX,
|
||||||
|
|
||||||
|
// Used internally so that people can fill in real numbers they plan to write.
|
||||||
|
EADT_PROPS_IS_PARSED_REAL,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum ADT_NamingStyle : u32
|
||||||
|
{
|
||||||
|
EADT_NAME_STYLE_DOUBLE_QUOTE,
|
||||||
|
EADT_NAME_STYLE_SINGLE_QUOTE,
|
||||||
|
EADT_NAME_STYLE_NO_QUOTES,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum ADT_AssignStyle : u32
|
||||||
|
{
|
||||||
|
EADT_ASSIGN_STYLE_COLON,
|
||||||
|
EADT_ASSIGN_STYLE_EQUALS,
|
||||||
|
EADT_ASSIGN_STYLE_LINE,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum ADT_DelimStyle : u32
|
||||||
|
{
|
||||||
|
EADT_DELIM_STYLE_COMMA,
|
||||||
|
EADT_DELIM_STYLE_LINE,
|
||||||
|
EADT_DELIM_STYLE_NEWLINE,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum ADT_Error : u32
|
||||||
|
{
|
||||||
|
EADT_ERROR_NONE,
|
||||||
|
EADT_ERROR_INTERNAL,
|
||||||
|
EADT_ERROR_ALREADY_CONVERTED,
|
||||||
|
EADT_ERROR_INVALID_TYPE,
|
||||||
|
EADT_ERROR_OUT_OF_MEMORY,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ADT_Node
|
||||||
|
{
|
||||||
|
char const* name;
|
||||||
|
struct ADT_Node* parent;
|
||||||
|
|
||||||
|
/* properties */
|
||||||
|
ADT_Type type : 4;
|
||||||
|
u8 props : 4;
|
||||||
|
#ifndef GEN_PARSER_DISABLE_ANALYSIS
|
||||||
|
u8 cfg_mode : 1;
|
||||||
|
u8 name_style : 2;
|
||||||
|
u8 assign_style : 2;
|
||||||
|
u8 delim_style : 2;
|
||||||
|
u8 delim_line_width : 4;
|
||||||
|
u8 assign_line_width : 4;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* adt data */
|
||||||
|
union
|
||||||
|
{
|
||||||
|
char const* string;
|
||||||
|
Array(ADT_Node) nodes; ///< zpl_array
|
||||||
|
|
||||||
|
struct
|
||||||
|
{
|
||||||
|
union
|
||||||
|
{
|
||||||
|
f64 real;
|
||||||
|
s64 integer;
|
||||||
|
};
|
||||||
|
|
||||||
|
#ifndef GEN_PARSER_DISABLE_ANALYSIS
|
||||||
|
/* number analysis */
|
||||||
|
s32 base;
|
||||||
|
s32 base2;
|
||||||
|
u8 base2_offset : 4;
|
||||||
|
s8 exp : 4;
|
||||||
|
u8 neg_zero : 1;
|
||||||
|
u8 lead_digit : 1;
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ADT NODE LIMITS
|
||||||
|
* delimiter and assignment segment width is limited to 128 whitespace symbols each.
|
||||||
|
* real number limits decimal position to 128 places.
|
||||||
|
* real number exponent is limited to 64 digits.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialise an ADT object or array
|
||||||
|
*
|
||||||
|
* @param node
|
||||||
|
* @param backing Memory allocator used for descendants
|
||||||
|
* @param name Node's name
|
||||||
|
* @param is_array
|
||||||
|
* @return error code
|
||||||
|
*/
|
||||||
|
GEN_API u8 adt_make_branch( ADT_Node* node, AllocatorInfo backing, char const* name, b32 is_array );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Destroy an ADT branch and its descendants
|
||||||
|
*
|
||||||
|
* @param node
|
||||||
|
* @return error code
|
||||||
|
*/
|
||||||
|
GEN_API u8 adt_destroy_branch( ADT_Node* node );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialise an ADT leaf
|
||||||
|
*
|
||||||
|
* @param node
|
||||||
|
* @param name Node's name
|
||||||
|
* @param type Node's type (use zpl_adt_make_branch for container nodes)
|
||||||
|
* @return error code
|
||||||
|
*/
|
||||||
|
GEN_API u8 adt_make_leaf( ADT_Node* node, char const* name, ADT_Type type );
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Fetch a node using provided URI string.
|
||||||
|
*
|
||||||
|
* This method uses a basic syntax to fetch a node from the ADT. The following features are available
|
||||||
|
* to retrieve the data:
|
||||||
|
*
|
||||||
|
* - "a/b/c" navigates through objects "a" and "b" to get to "c"
|
||||||
|
* - "arr/[foo=123]/bar" iterates over "arr" to find any object with param "foo" that matches the value "123", then gets its field called "bar"
|
||||||
|
* - "arr/3" retrieves the 4th element in "arr"
|
||||||
|
* - "arr/[apple]" retrieves the first element of value "apple" in "arr"
|
||||||
|
*
|
||||||
|
* @param node ADT node
|
||||||
|
* @param uri Locator string as described above
|
||||||
|
* @return zpl_adt_node*
|
||||||
|
*
|
||||||
|
* @see code/apps/examples/json_get.c
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Node* adt_query( ADT_Node* node, char const* uri );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Find a field node within an object by the given name.
|
||||||
|
*
|
||||||
|
* @param node
|
||||||
|
* @param name
|
||||||
|
* @param deep_search Perform search recursively
|
||||||
|
* @return zpl_adt_node * node
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Node* adt_find( ADT_Node* node, char const* name, b32 deep_search );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Allocate an unitialised node within a container at a specified index.
|
||||||
|
*
|
||||||
|
* @param parent
|
||||||
|
* @param index
|
||||||
|
* @return zpl_adt_node * node
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Node* adt_alloc_at( ADT_Node* parent, ssize index );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Allocate an unitialised node within a container.
|
||||||
|
*
|
||||||
|
* @param parent
|
||||||
|
* @return zpl_adt_node * node
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Node* adt_alloc( ADT_Node* parent );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Move an existing node to a new container at a specified index.
|
||||||
|
*
|
||||||
|
* @param node
|
||||||
|
* @param new_parent
|
||||||
|
* @param index
|
||||||
|
* @return zpl_adt_node * node
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Node* adt_move_node_at( ADT_Node* node, ADT_Node* new_parent, ssize index );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Move an existing node to a new container.
|
||||||
|
*
|
||||||
|
* @param node
|
||||||
|
* @param new_parent
|
||||||
|
* @return zpl_adt_node * node
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Node* adt_move_node( ADT_Node* node, ADT_Node* new_parent );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Swap two nodes.
|
||||||
|
*
|
||||||
|
* @param node
|
||||||
|
* @param other_node
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
GEN_API void adt_swap_nodes( ADT_Node* node, ADT_Node* other_node );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Remove node from container.
|
||||||
|
*
|
||||||
|
* @param node
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
GEN_API void adt_remove_node( ADT_Node* node );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialise a node as an object
|
||||||
|
*
|
||||||
|
* @param obj
|
||||||
|
* @param name
|
||||||
|
* @param backing
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
GEN_API b8 adt_set_obj( ADT_Node* obj, char const* name, AllocatorInfo backing );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialise a node as an array
|
||||||
|
*
|
||||||
|
* @param obj
|
||||||
|
* @param name
|
||||||
|
* @param backing
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
GEN_API b8 adt_set_arr( ADT_Node* obj, char const* name, AllocatorInfo backing );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialise a node as a string
|
||||||
|
*
|
||||||
|
* @param obj
|
||||||
|
* @param name
|
||||||
|
* @param value
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
GEN_API b8 adt_set_str( ADT_Node* obj, char const* name, char const* value );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialise a node as a float
|
||||||
|
*
|
||||||
|
* @param obj
|
||||||
|
* @param name
|
||||||
|
* @param value
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
GEN_API b8 adt_set_flt( ADT_Node* obj, char const* name, f64 value );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Initialise a node as a signed integer
|
||||||
|
*
|
||||||
|
* @param obj
|
||||||
|
* @param name
|
||||||
|
* @param value
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
GEN_API b8 adt_set_int( ADT_Node* obj, char const* name, s64 value );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Append a new node to a container as an object
|
||||||
|
*
|
||||||
|
* @param parent
|
||||||
|
* @param name
|
||||||
|
* @return*
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Node* adt_append_obj( ADT_Node* parent, char const* name );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Append a new node to a container as an array
|
||||||
|
*
|
||||||
|
* @param parent
|
||||||
|
* @param name
|
||||||
|
* @return*
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Node* adt_append_arr( ADT_Node* parent, char const* name );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Append a new node to a container as a string
|
||||||
|
*
|
||||||
|
* @param parent
|
||||||
|
* @param name
|
||||||
|
* @param value
|
||||||
|
* @return*
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Node* adt_append_str( ADT_Node* parent, char const* name, char const* value );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Append a new node to a container as a float
|
||||||
|
*
|
||||||
|
* @param parent
|
||||||
|
* @param name
|
||||||
|
* @param value
|
||||||
|
* @return*
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Node* adt_append_flt( ADT_Node* parent, char const* name, f64 value );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Append a new node to a container as a signed integer
|
||||||
|
*
|
||||||
|
* @param parent
|
||||||
|
* @param name
|
||||||
|
* @param value
|
||||||
|
* @return*
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Node* adt_append_int( ADT_Node* parent, char const* name, s64 value );
|
||||||
|
|
||||||
|
/* parser helpers */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Parses a text and stores the result into an unitialised node.
|
||||||
|
*
|
||||||
|
* @param node
|
||||||
|
* @param base
|
||||||
|
* @return*
|
||||||
|
*/
|
||||||
|
GEN_API char* adt_parse_number( ADT_Node* node, char* base );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Parses a text and stores the result into an unitialised node.
|
||||||
|
* This function expects the entire input to be a number.
|
||||||
|
*
|
||||||
|
* @param node
|
||||||
|
* @param base
|
||||||
|
* @return*
|
||||||
|
*/
|
||||||
|
GEN_API char* adt_parse_number_strict( ADT_Node* node, char* base_str );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Parses and converts an existing string node into a number.
|
||||||
|
*
|
||||||
|
* @param node
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Error adt_c_str_to_number( ADT_Node* node );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Parses and converts an existing string node into a number.
|
||||||
|
* This function expects the entire input to be a number.
|
||||||
|
*
|
||||||
|
* @param node
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Error adt_c_str_to_number_strict( ADT_Node* node );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Prints a number into a file stream.
|
||||||
|
*
|
||||||
|
* The provided file handle can also be a memory mapped stream.
|
||||||
|
*
|
||||||
|
* @see zpl_file_stream_new
|
||||||
|
* @param file
|
||||||
|
* @param node
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Error adt_print_number( FileInfo* file, ADT_Node* node );
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @brief Prints a string into a file stream.
|
||||||
|
*
|
||||||
|
* The provided file handle can also be a memory mapped stream.
|
||||||
|
*
|
||||||
|
* @see zpl_file_stream_new
|
||||||
|
* @param file
|
||||||
|
* @param node
|
||||||
|
* @param escaped_chars
|
||||||
|
* @param escape_symbol
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
GEN_API ADT_Error adt_print_string( FileInfo* file, ADT_Node* node, char const* escaped_chars, char const* escape_symbol );
|
||||||
|
|
||||||
|
#pragma endregion ADT
|
||||||
|
|
||||||
|
#pragma region CSV
|
||||||
|
|
||||||
|
enum CSV_Error : u32
|
||||||
|
{
|
||||||
|
ECSV_Error__NONE,
|
||||||
|
ECSV_Error__INTERNAL,
|
||||||
|
ECSV_Error__UNEXPECTED_END_OF_INPUT,
|
||||||
|
ECSV_Error__MISMATCHED_ROWS,
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef ADT_Node CSV_Object;
|
||||||
|
|
||||||
|
u8 csv_parse( CSV_Object* root, char* text, AllocatorInfo allocator, b32 has_header );
|
||||||
|
GEN_API u8 csv_parse_delimiter( CSV_Object* root, char* text, AllocatorInfo allocator, b32 has_header, char delim );
|
||||||
|
void csv_free( CSV_Object* obj );
|
||||||
|
|
||||||
|
void csv_write( FileInfo* file, CSV_Object* obj );
|
||||||
|
StrBuilder csv_write_string( AllocatorInfo a, CSV_Object* obj );
|
||||||
|
GEN_API void csv_write_delimiter( FileInfo* file, CSV_Object* obj, char delim );
|
||||||
|
GEN_API StrBuilder csv_write_strbuilder_delimiter( AllocatorInfo a, CSV_Object* obj, char delim );
|
||||||
|
|
||||||
|
/* inline */
|
||||||
|
|
||||||
|
inline
|
||||||
|
u8 csv_parse( CSV_Object* root, char* text, AllocatorInfo allocator, b32 has_header )
|
||||||
|
{
|
||||||
|
return csv_parse_delimiter( root, text, allocator, has_header, ',' );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void csv_write( FileInfo* file, CSV_Object* obj )
|
||||||
|
{
|
||||||
|
csv_write_delimiter( file, obj, ',' );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder csv_write_string( AllocatorInfo a, CSV_Object* obj )
|
||||||
|
{
|
||||||
|
return csv_write_strbuilder_delimiter( a, obj, ',' );
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma endregion CSV
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Platform Detection
|
||||||
|
|
||||||
|
/* Platform architecture */
|
||||||
|
|
||||||
|
#if defined( _WIN64 ) || defined( __x86_64__ ) || defined( _M_X64 ) || defined( __64BIT__ ) || defined( __powerpc64__ ) || defined( __ppc64__ ) || defined( __aarch64__ )
|
||||||
|
# ifndef GEN_ARCH_64_BIT
|
||||||
|
# define GEN_ARCH_64_BIT 1
|
||||||
|
# endif
|
||||||
|
#else
|
||||||
|
# ifndef GEN_ARCH_32_BItxt_StrCaT
|
||||||
|
# define GEN_ARCH_32_BIT 1
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Platform OS */
|
||||||
|
|
||||||
|
#if defined( _WIN32 ) || defined( _WIN64 )
|
||||||
|
# ifndef GEN_SYSTEM_WINDOWS
|
||||||
|
# define GEN_SYSTEM_WINDOWS 1
|
||||||
|
# endif
|
||||||
|
#elif defined( __APPLE__ ) && defined( __MACH__ )
|
||||||
|
# ifndef GEN_SYSTEM_OSX
|
||||||
|
# define GEN_SYSTEM_OSX 1
|
||||||
|
# endif
|
||||||
|
# ifndef GEN_SYSTEM_MACOS
|
||||||
|
# define GEN_SYSTEM_MACOS 1
|
||||||
|
# endif
|
||||||
|
#elif defined( __unix__ )
|
||||||
|
# ifndef GEN_SYSTEM_UNIX
|
||||||
|
# define GEN_SYSTEM_UNIX 1
|
||||||
|
# endif
|
||||||
|
# if defined( ANDROID ) || defined( __ANDROID__ )
|
||||||
|
# ifndef GEN_SYSTEM_ANDROID
|
||||||
|
# define GEN_SYSTEM_ANDROID 1
|
||||||
|
# endif
|
||||||
|
# ifndef GEN_SYSTEM_LINUX
|
||||||
|
# define GEN_SYSTEM_LINUX 1
|
||||||
|
# endif
|
||||||
|
# elif defined( __linux__ )
|
||||||
|
# ifndef GEN_SYSTEM_LINUX
|
||||||
|
# define GEN_SYSTEM_LINUX 1
|
||||||
|
# endif
|
||||||
|
# elif defined( __FreeBSD__ ) || defined( __FreeBSD_kernel__ )
|
||||||
|
# ifndef GEN_SYSTEM_FREEBSD
|
||||||
|
# define GEN_SYSTEM_FREEBSD 1
|
||||||
|
# endif
|
||||||
|
# elif defined( __OpenBSD__ )
|
||||||
|
# ifndef GEN_SYSTEM_OPENBSD
|
||||||
|
# define GEN_SYSTEM_OPENBSD 1
|
||||||
|
# endif
|
||||||
|
# elif defined( __EMSCRIPTEN__ )
|
||||||
|
# ifndef GEN_SYSTEM_EMSCRIPTEN
|
||||||
|
# define GEN_SYSTEM_EMSCRIPTEN 1
|
||||||
|
# endif
|
||||||
|
# elif defined( __CYGWIN__ )
|
||||||
|
# ifndef GEN_SYSTEM_CYGWIN
|
||||||
|
# define GEN_SYSTEM_CYGWIN 1
|
||||||
|
# endif
|
||||||
|
# else
|
||||||
|
# error This UNIX operating system is not supported
|
||||||
|
# endif
|
||||||
|
#else
|
||||||
|
# error This operating system is not supported
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Platform compiler */
|
||||||
|
|
||||||
|
#if defined( _MSC_VER )
|
||||||
|
# pragma message("Detected MSVC")
|
||||||
|
// # define GEN_COMPILER_CLANG 0
|
||||||
|
# define GEN_COMPILER_MSVC 1
|
||||||
|
// # define GEN_COMPILER_GCC 0
|
||||||
|
#elif defined( __GNUC__ )
|
||||||
|
# pragma message("Detected GCC")
|
||||||
|
// # define GEN_COMPILER_CLANG 0
|
||||||
|
// # define GEN_COMPILER_MSVC 0
|
||||||
|
# define GEN_COMPILER_GCC 1
|
||||||
|
#elif defined( __clang__ )
|
||||||
|
# pragma message("Detected CLANG")
|
||||||
|
# define GEN_COMPILER_CLANG 1
|
||||||
|
// # define GEN_COMPILER_MSVC 0
|
||||||
|
// # define GEN_COMPILER_GCC 0
|
||||||
|
#else
|
||||||
|
# error Unknown compiler
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined( __has_attribute )
|
||||||
|
# define GEN_HAS_ATTRIBUTE( attribute ) __has_attribute( attribute )
|
||||||
|
#else
|
||||||
|
# define GEN_HAS_ATTRIBUTE( attribute ) ( 0 )
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(GEN_GCC_VERSION_CHECK)
|
||||||
|
# undef GEN_GCC_VERSION_CHECK
|
||||||
|
#endif
|
||||||
|
#if defined(GEN_GCC_VERSION)
|
||||||
|
# define GEN_GCC_VERSION_CHECK(major,minor,patch) (GEN_GCC_VERSION >= GEN_VERSION_ENCODE(major, minor, patch))
|
||||||
|
#else
|
||||||
|
# define GEN_GCC_VERSION_CHECK(major,minor,patch) (0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if !defined(GEN_COMPILER_C)
|
||||||
|
# ifdef __cplusplus
|
||||||
|
# define GEN_COMPILER_C 0
|
||||||
|
# define GEN_COMPILER_CPP 1
|
||||||
|
# else
|
||||||
|
# if defined(__STDC__)
|
||||||
|
# define GEN_COMPILER_C 1
|
||||||
|
# define GEN_COMPILER_CPP 0
|
||||||
|
# else
|
||||||
|
// Fallback for very old C compilers
|
||||||
|
# define GEN_COMPILER_C 1
|
||||||
|
# define GEN_COMPILER_CPP 0
|
||||||
|
# endif
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_C
|
||||||
|
#pragma message("GENCPP: Detected C")
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Platform Detection
|
||||||
|
|
||||||
|
#pragma region Mandatory Includes
|
||||||
|
|
||||||
|
# include <stdarg.h>
|
||||||
|
# include <stddef.h>
|
||||||
|
|
||||||
|
# if defined( GEN_SYSTEM_WINDOWS )
|
||||||
|
# include <intrin.h>
|
||||||
|
# endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_C
|
||||||
|
#include <assert.h>
|
||||||
|
#include <stdbool.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Mandatory Includes
|
||||||
|
|
||||||
|
#if GEN_DONT_USE_NAMESPACE || GEN_COMPILER_C
|
||||||
|
# if GEN_COMPILER_C
|
||||||
|
# define GEN_NS
|
||||||
|
# define GEN_NS_BEGIN
|
||||||
|
# define GEN_NS_END
|
||||||
|
# else
|
||||||
|
# define GEN_NS ::
|
||||||
|
# define GEN_NS_BEGIN
|
||||||
|
# define GEN_NS_END
|
||||||
|
# endif
|
||||||
|
#else
|
||||||
|
# define GEN_NS gen::
|
||||||
|
# define GEN_NS_BEGIN namespace gen {
|
||||||
|
# define GEN_NS_END }
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,600 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "string_ops.cpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Printing
|
||||||
|
|
||||||
|
enum
|
||||||
|
{
|
||||||
|
GEN_FMT_MINUS = bit( 0 ),
|
||||||
|
GEN_FMT_PLUS = bit( 1 ),
|
||||||
|
GEN_FMT_ALT = bit( 2 ),
|
||||||
|
GEN_FMT_SPACE = bit( 3 ),
|
||||||
|
GEN_FMT_ZERO = bit( 4 ),
|
||||||
|
|
||||||
|
GEN_FMT_CHAR = bit( 5 ),
|
||||||
|
GEN_FMT_SHORT = bit( 6 ),
|
||||||
|
GEN_FMT_INT = bit( 7 ),
|
||||||
|
GEN_FMT_LONG = bit( 8 ),
|
||||||
|
GEN_FMT_LLONG = bit( 9 ),
|
||||||
|
GEN_FMT_SIZE = bit( 10 ),
|
||||||
|
GEN_FMT_INTPTR = bit( 11 ),
|
||||||
|
|
||||||
|
GEN_FMT_UNSIGNED = bit( 12 ),
|
||||||
|
GEN_FMT_LOWER = bit( 13 ),
|
||||||
|
GEN_FMT_UPPER = bit( 14 ),
|
||||||
|
GEN_FMT_WIDTH = bit( 15 ),
|
||||||
|
|
||||||
|
GEN_FMT_DONE = bit( 30 ),
|
||||||
|
|
||||||
|
GEN_FMT_INTS = GEN_FMT_CHAR | GEN_FMT_SHORT | GEN_FMT_INT | GEN_FMT_LONG | GEN_FMT_LLONG | GEN_FMT_SIZE | GEN_FMT_INTPTR
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef struct _format_info _format_info;
|
||||||
|
struct _format_info
|
||||||
|
{
|
||||||
|
s32 base;
|
||||||
|
s32 flags;
|
||||||
|
s32 width;
|
||||||
|
s32 precision;
|
||||||
|
};
|
||||||
|
|
||||||
|
internal ssize _print_string( char* text, ssize max_len, _format_info* info, char const* str )
|
||||||
|
{
|
||||||
|
ssize res = 0, len = 0;
|
||||||
|
ssize remaining = max_len;
|
||||||
|
char* begin = text;
|
||||||
|
|
||||||
|
if ( str == NULL && max_len >= 6 )
|
||||||
|
{
|
||||||
|
res += c_str_copy_nulpad( text, "(null)", 6 );
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( info && info->precision >= 0 )
|
||||||
|
// Made the design decision for this library that precision is the length of the string.
|
||||||
|
len = info->precision;
|
||||||
|
else
|
||||||
|
len = c_str_len( str );
|
||||||
|
|
||||||
|
if ( info && ( info->width == 0 && info->flags & GEN_FMT_WIDTH ) )
|
||||||
|
{
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( info && ( info->width == 0 || info->flags & GEN_FMT_MINUS ) )
|
||||||
|
{
|
||||||
|
if ( info->precision > 0 )
|
||||||
|
len = info->precision < len ? info->precision : len;
|
||||||
|
if ( res + len > max_len )
|
||||||
|
return res;
|
||||||
|
res += c_str_copy_nulpad( text, str, len );
|
||||||
|
text += res;
|
||||||
|
|
||||||
|
if ( info->width > res )
|
||||||
|
{
|
||||||
|
ssize padding = info->width - len;
|
||||||
|
|
||||||
|
char pad = ( info->flags & GEN_FMT_ZERO ) ? '0' : ' ';
|
||||||
|
while ( padding-- > 0 && remaining-- > 0 )
|
||||||
|
*text++ = pad, res++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if ( info && ( info->width > res ) )
|
||||||
|
{
|
||||||
|
ssize padding = info->width - len;
|
||||||
|
char pad = ( info->flags & GEN_FMT_ZERO ) ? '0' : ' ';
|
||||||
|
while ( padding-- > 0 && remaining-- > 0 )
|
||||||
|
*text++ = pad, res++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( res + len > max_len )
|
||||||
|
return res;
|
||||||
|
res += c_str_copy_nulpad( text, str, len );
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( info )
|
||||||
|
{
|
||||||
|
if ( info->flags & GEN_FMT_UPPER )
|
||||||
|
c_str_to_upper( begin );
|
||||||
|
else if ( info->flags & GEN_FMT_LOWER )
|
||||||
|
c_str_to_lower( begin );
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal ssize _print_char( char* text, ssize max_len, _format_info* info, char arg )
|
||||||
|
{
|
||||||
|
char str[ 2 ] = "";
|
||||||
|
str[ 0 ] = arg;
|
||||||
|
return _print_string( text, max_len, info, str );
|
||||||
|
}
|
||||||
|
|
||||||
|
internal ssize _print_repeated_char( char* text, ssize max_len, _format_info* info, char arg )
|
||||||
|
{
|
||||||
|
ssize res = 0;
|
||||||
|
s32 rem = ( info ) ? ( info->width > 0 ) ? info->width : 1 : 1;
|
||||||
|
res = rem;
|
||||||
|
while ( rem-- > 0 )
|
||||||
|
*text++ = arg;
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal ssize _print_i64( char* text, ssize max_len, _format_info* info, s64 value )
|
||||||
|
{
|
||||||
|
char num[ 130 ];
|
||||||
|
i64_to_str( value, num, info ? info->base : 10 );
|
||||||
|
return _print_string( text, max_len, info, num );
|
||||||
|
}
|
||||||
|
|
||||||
|
internal ssize _print_u64( char* text, ssize max_len, _format_info* info, u64 value )
|
||||||
|
{
|
||||||
|
char num[ 130 ];
|
||||||
|
u64_to_str( value, num, info ? info->base : 10 );
|
||||||
|
return _print_string( text, max_len, info, num );
|
||||||
|
}
|
||||||
|
|
||||||
|
internal ssize _print_f64( char* text, ssize max_len, _format_info* info, b32 is_hexadecimal, f64 arg )
|
||||||
|
{
|
||||||
|
// TODO: Handle exponent notation
|
||||||
|
ssize width, len, remaining = max_len;
|
||||||
|
char* text_begin = text;
|
||||||
|
|
||||||
|
if ( arg )
|
||||||
|
{
|
||||||
|
u64 value;
|
||||||
|
if ( arg < 0 )
|
||||||
|
{
|
||||||
|
if ( remaining > 1 )
|
||||||
|
*text = '-', remaining--;
|
||||||
|
text++;
|
||||||
|
arg = -arg;
|
||||||
|
}
|
||||||
|
else if ( info->flags & GEN_FMT_MINUS )
|
||||||
|
{
|
||||||
|
if ( remaining > 1 )
|
||||||
|
*text = '+', remaining--;
|
||||||
|
text++;
|
||||||
|
}
|
||||||
|
|
||||||
|
value = scast( u64, arg);
|
||||||
|
len = _print_u64( text, remaining, NULL, value );
|
||||||
|
text += len;
|
||||||
|
|
||||||
|
if ( len >= remaining )
|
||||||
|
remaining = min( remaining, 1 );
|
||||||
|
else
|
||||||
|
remaining -= len;
|
||||||
|
arg -= value;
|
||||||
|
|
||||||
|
if ( info->precision < 0 )
|
||||||
|
info->precision = 6;
|
||||||
|
|
||||||
|
if ( ( info->flags & GEN_FMT_ALT ) || info->precision > 0 )
|
||||||
|
{
|
||||||
|
s64 mult = 10;
|
||||||
|
if ( remaining > 1 )
|
||||||
|
*text = '.', remaining--;
|
||||||
|
text++;
|
||||||
|
while ( info->precision-- > 0 )
|
||||||
|
{
|
||||||
|
value = scast( u64, arg * mult );
|
||||||
|
len = _print_u64( text, remaining, NULL, value );
|
||||||
|
text += len;
|
||||||
|
if ( len >= remaining )
|
||||||
|
remaining = min( remaining, 1 );
|
||||||
|
else
|
||||||
|
remaining -= len;
|
||||||
|
arg -= scast( f64, value / mult);
|
||||||
|
mult *= 10;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if ( remaining > 1 )
|
||||||
|
*text = '0', remaining--;
|
||||||
|
text++;
|
||||||
|
if ( info->flags & GEN_FMT_ALT )
|
||||||
|
{
|
||||||
|
if ( remaining > 1 )
|
||||||
|
*text = '.', remaining--;
|
||||||
|
text++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
width = info->width - ( text - text_begin );
|
||||||
|
if ( width > 0 )
|
||||||
|
{
|
||||||
|
char fill = ( info->flags & GEN_FMT_ZERO ) ? '0' : ' ';
|
||||||
|
char* end = text + remaining - 1;
|
||||||
|
len = ( text - text_begin );
|
||||||
|
|
||||||
|
for ( len = ( text - text_begin ); len--; )
|
||||||
|
{
|
||||||
|
if ( ( text_begin + len + width ) < end )
|
||||||
|
*( text_begin + len + width ) = *( text_begin + len );
|
||||||
|
}
|
||||||
|
|
||||||
|
len = width;
|
||||||
|
text += len;
|
||||||
|
if ( len >= remaining )
|
||||||
|
remaining = min( remaining, 1 );
|
||||||
|
else
|
||||||
|
remaining -= len;
|
||||||
|
|
||||||
|
while ( len-- )
|
||||||
|
{
|
||||||
|
if ( text_begin + len < end )
|
||||||
|
text_begin[ len ] = fill;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ( text - text_begin );
|
||||||
|
}
|
||||||
|
|
||||||
|
neverinline ssize c_str_fmt_va( char* text, ssize max_len, char const* fmt, va_list va )
|
||||||
|
{
|
||||||
|
char const* text_begin = text;
|
||||||
|
ssize remaining = max_len, res;
|
||||||
|
|
||||||
|
while ( *fmt )
|
||||||
|
{
|
||||||
|
_format_info info = { 0 };
|
||||||
|
ssize len = 0;
|
||||||
|
info.precision = -1;
|
||||||
|
|
||||||
|
while ( *fmt && *fmt != '%' && remaining )
|
||||||
|
*text++ = *fmt++;
|
||||||
|
|
||||||
|
if ( *fmt == '%' )
|
||||||
|
{
|
||||||
|
do
|
||||||
|
{
|
||||||
|
switch ( *++fmt )
|
||||||
|
{
|
||||||
|
case '-' :
|
||||||
|
{
|
||||||
|
info.flags |= GEN_FMT_MINUS;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case '+' :
|
||||||
|
{
|
||||||
|
info.flags |= GEN_FMT_PLUS;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case '#' :
|
||||||
|
{
|
||||||
|
info.flags |= GEN_FMT_ALT;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case ' ' :
|
||||||
|
{
|
||||||
|
info.flags |= GEN_FMT_SPACE;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case '0' :
|
||||||
|
{
|
||||||
|
info.flags |= ( GEN_FMT_ZERO | GEN_FMT_WIDTH );
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default :
|
||||||
|
{
|
||||||
|
info.flags |= GEN_FMT_DONE;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} while ( ! ( info.flags & GEN_FMT_DONE ) );
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: Optional Width
|
||||||
|
if ( *fmt == '*' )
|
||||||
|
{
|
||||||
|
int width = va_arg( va, int );
|
||||||
|
if ( width < 0 )
|
||||||
|
{
|
||||||
|
info.flags |= GEN_FMT_MINUS;
|
||||||
|
info.width = -width;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
info.width = width;
|
||||||
|
}
|
||||||
|
info.flags |= GEN_FMT_WIDTH;
|
||||||
|
fmt++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
info.width = scast( s32, c_str_to_i64( fmt, ccast( char**, & fmt), 10 ));
|
||||||
|
if ( info.width != 0 )
|
||||||
|
{
|
||||||
|
info.flags |= GEN_FMT_WIDTH;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: Optional Precision
|
||||||
|
if ( *fmt == '.' )
|
||||||
|
{
|
||||||
|
fmt++;
|
||||||
|
if ( *fmt == '*' )
|
||||||
|
{
|
||||||
|
info.precision = va_arg( va, int );
|
||||||
|
fmt++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
info.precision = scast( s32, c_str_to_i64( fmt, ccast( char**, & fmt), 10 ));
|
||||||
|
}
|
||||||
|
info.flags &= ~GEN_FMT_ZERO;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch ( *fmt++ )
|
||||||
|
{
|
||||||
|
case 'h' :
|
||||||
|
if ( *fmt == 'h' )
|
||||||
|
{ // hh => char
|
||||||
|
info.flags |= GEN_FMT_CHAR;
|
||||||
|
fmt++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{ // h => short
|
||||||
|
info.flags |= GEN_FMT_SHORT;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'l' :
|
||||||
|
if ( *fmt == 'l' )
|
||||||
|
{ // ll => long long
|
||||||
|
info.flags |= GEN_FMT_LLONG;
|
||||||
|
fmt++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{ // l => long
|
||||||
|
info.flags |= GEN_FMT_LONG;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'z' : // NOTE: zpl_usize
|
||||||
|
info.flags |= GEN_FMT_UNSIGNED;
|
||||||
|
// fallthrough
|
||||||
|
case 't' : // NOTE: zpl_isize
|
||||||
|
info.flags |= GEN_FMT_SIZE;
|
||||||
|
break;
|
||||||
|
|
||||||
|
default :
|
||||||
|
fmt--;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch ( *fmt )
|
||||||
|
{
|
||||||
|
case 'u' :
|
||||||
|
info.flags |= GEN_FMT_UNSIGNED;
|
||||||
|
// fallthrough
|
||||||
|
case 'd' :
|
||||||
|
case 'i' :
|
||||||
|
info.base = 10;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'o' :
|
||||||
|
info.base = 8;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'x' :
|
||||||
|
info.base = 16;
|
||||||
|
info.flags |= ( GEN_FMT_UNSIGNED | GEN_FMT_LOWER );
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'X' :
|
||||||
|
info.base = 16;
|
||||||
|
info.flags |= ( GEN_FMT_UNSIGNED | GEN_FMT_UPPER );
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'f' :
|
||||||
|
case 'F' :
|
||||||
|
case 'g' :
|
||||||
|
case 'G' :
|
||||||
|
len = _print_f64( text, remaining, &info, 0, va_arg( va, f64 ) );
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'a' :
|
||||||
|
case 'A' :
|
||||||
|
len = _print_f64( text, remaining, &info, 1, va_arg( va, f64 ) );
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'c' :
|
||||||
|
len = _print_char( text, remaining, &info, scast( char, va_arg( va, int ) ));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 's' :
|
||||||
|
len = _print_string( text, remaining, &info, va_arg( va, char* ) );
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'S':
|
||||||
|
{
|
||||||
|
if ( *(fmt + 1) == 'B' )
|
||||||
|
{
|
||||||
|
|
||||||
|
++ fmt;
|
||||||
|
StrBuilder gen_str = { va_arg( va, char*) };
|
||||||
|
|
||||||
|
info.precision = strbuilder_length(gen_str);
|
||||||
|
len = _print_string( text, remaining, &info, gen_str );
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
Str gen_str = va_arg( va, Str);
|
||||||
|
info.precision = gen_str.Len;
|
||||||
|
len = _print_string( text, remaining, &info, gen_str.Ptr );
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'r' :
|
||||||
|
len = _print_repeated_char( text, remaining, &info, va_arg( va, int ) );
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 'p' :
|
||||||
|
info.base = 16;
|
||||||
|
info.flags |= ( GEN_FMT_LOWER | GEN_FMT_UNSIGNED | GEN_FMT_ALT | GEN_FMT_INTPTR );
|
||||||
|
break;
|
||||||
|
|
||||||
|
case '%' :
|
||||||
|
len = _print_char( text, remaining, &info, '%' );
|
||||||
|
break;
|
||||||
|
|
||||||
|
default :
|
||||||
|
fmt--;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt++;
|
||||||
|
|
||||||
|
if ( info.base != 0 )
|
||||||
|
{
|
||||||
|
if ( info.flags & GEN_FMT_UNSIGNED )
|
||||||
|
{
|
||||||
|
u64 value = 0;
|
||||||
|
switch ( info.flags & GEN_FMT_INTS )
|
||||||
|
{
|
||||||
|
case GEN_FMT_CHAR :
|
||||||
|
value = scast( u64, scast( u8, va_arg( va, int )));
|
||||||
|
break;
|
||||||
|
case GEN_FMT_SHORT :
|
||||||
|
value = scast( u64, scast( u16, va_arg( va, int )));
|
||||||
|
break;
|
||||||
|
case GEN_FMT_LONG:
|
||||||
|
value = scast( u64, va_arg( va, unsigned long ));
|
||||||
|
break;
|
||||||
|
case GEN_FMT_LLONG :
|
||||||
|
value = scast( u64, va_arg( va, unsigned long long ));
|
||||||
|
break;
|
||||||
|
case GEN_FMT_SIZE :
|
||||||
|
value = scast( u64, va_arg( va, usize ));
|
||||||
|
break;
|
||||||
|
case GEN_FMT_INTPTR :
|
||||||
|
value = scast( u64, va_arg( va, uptr ));
|
||||||
|
break;
|
||||||
|
default :
|
||||||
|
value = scast( u64, va_arg( va, unsigned int ));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
len = _print_u64( text, remaining, &info, value );
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
s64 value = 0;
|
||||||
|
switch ( info.flags & GEN_FMT_INTS )
|
||||||
|
{
|
||||||
|
case GEN_FMT_CHAR :
|
||||||
|
value = scast( s64, scast( s8, va_arg( va, int )));
|
||||||
|
break;
|
||||||
|
case GEN_FMT_SHORT :
|
||||||
|
value = scast( s64, scast( s16, va_arg( va, int )));
|
||||||
|
break;
|
||||||
|
case GEN_FMT_LONG :
|
||||||
|
value = scast( s64, va_arg( va, long ));
|
||||||
|
break;
|
||||||
|
case GEN_FMT_LLONG :
|
||||||
|
value = scast( s64, va_arg( va, long long ));
|
||||||
|
break;
|
||||||
|
case GEN_FMT_SIZE :
|
||||||
|
value = scast( s64, va_arg( va, usize ));
|
||||||
|
break;
|
||||||
|
case GEN_FMT_INTPTR :
|
||||||
|
value = scast( s64, va_arg( va, uptr ));
|
||||||
|
break;
|
||||||
|
default :
|
||||||
|
value = scast( s64, va_arg( va, int ));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
len = _print_i64( text, remaining, &info, value );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
text += len;
|
||||||
|
if ( len >= remaining )
|
||||||
|
remaining = min( remaining, 1 );
|
||||||
|
else
|
||||||
|
remaining -= len;
|
||||||
|
}
|
||||||
|
|
||||||
|
*text++ = '\0';
|
||||||
|
res = ( text - text_begin );
|
||||||
|
return ( res >= max_len || res < 0 ) ? -1 : res;
|
||||||
|
}
|
||||||
|
|
||||||
|
char* c_str_fmt_buf_va( char const* fmt, va_list va )
|
||||||
|
{
|
||||||
|
local_persist thread_local char buffer[ GEN_PRINTF_MAXLEN ];
|
||||||
|
c_str_fmt_va( buffer, size_of( buffer ), fmt, va );
|
||||||
|
return buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
char* c_str_fmt_buf( char const* fmt, ... )
|
||||||
|
{
|
||||||
|
va_list va;
|
||||||
|
char* str;
|
||||||
|
va_start( va, fmt );
|
||||||
|
str = c_str_fmt_buf_va( fmt, va );
|
||||||
|
va_end( va );
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize c_str_fmt_file_va( FileInfo* f, char const* fmt, va_list va )
|
||||||
|
{
|
||||||
|
local_persist thread_local char buf[ GEN_PRINTF_MAXLEN ];
|
||||||
|
ssize len = c_str_fmt_va( buf, size_of( buf ), fmt, va );
|
||||||
|
b32 res = file_write( f, buf, len - 1 ); // NOTE: prevent extra whitespace
|
||||||
|
return res ? len : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize c_str_fmt_file( FileInfo* f, char const* fmt, ... )
|
||||||
|
{
|
||||||
|
ssize res;
|
||||||
|
va_list va;
|
||||||
|
va_start( va, fmt );
|
||||||
|
res = c_str_fmt_file_va( f, fmt, va );
|
||||||
|
va_end( va );
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize c_str_fmt( char* str, ssize n, char const* fmt, ... )
|
||||||
|
{
|
||||||
|
ssize res;
|
||||||
|
va_list va;
|
||||||
|
va_start( va, fmt );
|
||||||
|
res = c_str_fmt_va( str, n, fmt, va );
|
||||||
|
va_end( va );
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize c_str_fmt_out_va( char const* fmt, va_list va )
|
||||||
|
{
|
||||||
|
return c_str_fmt_file_va( file_get_standard( EFileStandard_OUTPUT ), fmt, va );
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize c_str_fmt_out_err_va( char const* fmt, va_list va )
|
||||||
|
{
|
||||||
|
return c_str_fmt_file_va( file_get_standard( EFileStandard_ERROR ), fmt, va );
|
||||||
|
}
|
||||||
|
|
||||||
|
ssize c_str_fmt_out_err( char const* fmt, ... )
|
||||||
|
{
|
||||||
|
ssize res;
|
||||||
|
va_list va;
|
||||||
|
va_start( va, fmt );
|
||||||
|
res = c_str_fmt_out_err_va( fmt, va );
|
||||||
|
va_end( va );
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma endregion Printing
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "string_ops.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Printing
|
||||||
|
|
||||||
|
typedef struct FileInfo FileInfo;
|
||||||
|
|
||||||
|
#ifndef GEN_PRINTF_MAXLEN
|
||||||
|
# define GEN_PRINTF_MAXLEN kilobytes(128)
|
||||||
|
#endif
|
||||||
|
typedef char PrintF_Buffer[GEN_PRINTF_MAXLEN];
|
||||||
|
|
||||||
|
// NOTE: A locally persisting buffer is used internally
|
||||||
|
GEN_API char* c_str_fmt_buf ( char const* fmt, ... );
|
||||||
|
GEN_API char* c_str_fmt_buf_va ( char const* fmt, va_list va );
|
||||||
|
GEN_API ssize c_str_fmt ( char* str, ssize n, char const* fmt, ... );
|
||||||
|
GEN_API ssize c_str_fmt_va ( char* str, ssize n, char const* fmt, va_list va );
|
||||||
|
GEN_API ssize c_str_fmt_out_va ( char const* fmt, va_list va );
|
||||||
|
GEN_API ssize c_str_fmt_out_err ( char const* fmt, ... );
|
||||||
|
GEN_API ssize c_str_fmt_out_err_va( char const* fmt, va_list va );
|
||||||
|
GEN_API ssize c_str_fmt_file ( FileInfo* f, char const* fmt, ... );
|
||||||
|
GEN_API ssize c_str_fmt_file_va ( FileInfo* f, char const* fmt, va_list va );
|
||||||
|
|
||||||
|
constexpr
|
||||||
|
char const* Msg_Invalid_Value = "INVALID VALUE PROVIDED";
|
||||||
|
|
||||||
|
#pragma endregion Printing
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "header_start.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Macros and Includes
|
||||||
|
|
||||||
|
# include <stdio.h>
|
||||||
|
// NOTE: Ensure we use standard methods for these calls if we use GEN_PICO
|
||||||
|
# if ! defined( GEN_PICO_CUSTOM_ROUTINES )
|
||||||
|
# if ! defined( GEN_MODULE_CORE )
|
||||||
|
# define _strlen strlen
|
||||||
|
# define _printf_err( fmt, ... ) fprintf( stderr, fmt, __VA_ARGS__ )
|
||||||
|
# define _printf_err_va( fmt, va ) vfprintf( stderr, fmt, va )
|
||||||
|
# else
|
||||||
|
# define _strlen c_str_len
|
||||||
|
# define _printf_err( fmt, ... ) c_str_fmt_out_err( fmt, __VA_ARGS__ )
|
||||||
|
# define _printf_err_va( fmt, va ) c_str_fmt_out_err_va( fmt, va )
|
||||||
|
# endif
|
||||||
|
# endif
|
||||||
|
#
|
||||||
|
# include <errno.h>
|
||||||
|
#
|
||||||
|
# if defined( GEN_SYSTEM_UNIX ) || defined( GEN_SYSTEM_MACOS )
|
||||||
|
# include <unistd.h>
|
||||||
|
# elif defined( GEN_SYSTEM_WINDOWS )
|
||||||
|
# if ! defined( GEN_NO_WINDOWS_H )
|
||||||
|
# ifndef WIN32_LEAN_AND_MEAN
|
||||||
|
# ifndef NOMINMAX
|
||||||
|
# define NOMINMAX
|
||||||
|
# endif
|
||||||
|
#
|
||||||
|
# define WIN32_LEAN_AND_MEAN
|
||||||
|
# define WIN32_MEAN_AND_LEAN
|
||||||
|
# define VC_EXTRALEAN
|
||||||
|
# endif
|
||||||
|
# include <windows.h>
|
||||||
|
# undef NOMINMAX
|
||||||
|
# undef WIN32_LEAN_AND_MEAN
|
||||||
|
# undef WIN32_MEAN_AND_LEAN
|
||||||
|
# undef VC_EXTRALEAN
|
||||||
|
# endif
|
||||||
|
# endif
|
||||||
|
|
||||||
|
#include <sys/stat.h>
|
||||||
|
|
||||||
|
#ifdef GEN_SYSTEM_MACOS
|
||||||
|
# include <copyfile.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GEN_SYSTEM_CYGWIN
|
||||||
|
# include <windows.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined( GEN_SYSTEM_WINDOWS ) && ! defined( GEN_COMPILER_GCC )
|
||||||
|
# include <io.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined( GEN_SYSTEM_LINUX )
|
||||||
|
# include <sys/types.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef GEN_BENCHMARK
|
||||||
|
// Timing includes
|
||||||
|
#if defined( GEN_SYSTEM_MACOS ) || GEN_SYSTEM_UNIX
|
||||||
|
# include <time.h>
|
||||||
|
# include <sys/time.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined( GEN_SYSTEM_MACOS )
|
||||||
|
# include <mach/mach.h>
|
||||||
|
# include <mach/mach_time.h>
|
||||||
|
# include <mach/clock.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined( GEN_SYSTEM_EMSCRIPTEN )
|
||||||
|
# include <emscripten.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined( GEN_SYSTEM_WINDOWS )
|
||||||
|
# include <timezoneapi.h>
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Macros and Includes
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "debug.cpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region String Ops
|
||||||
|
|
||||||
|
internal
|
||||||
|
ssize _scan_zpl_i64( const char* text, s32 base, s64* value )
|
||||||
|
{
|
||||||
|
const char* text_begin = text;
|
||||||
|
s64 result = 0;
|
||||||
|
b32 negative = false;
|
||||||
|
|
||||||
|
if ( *text == '-' )
|
||||||
|
{
|
||||||
|
negative = true;
|
||||||
|
text++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( base == 16 && c_str_compare_len( text, "0x", 2 ) == 0 )
|
||||||
|
text += 2;
|
||||||
|
|
||||||
|
for ( ;; )
|
||||||
|
{
|
||||||
|
s64 v;
|
||||||
|
if ( char_is_digit( *text ) )
|
||||||
|
v = *text - '0';
|
||||||
|
else if ( base == 16 && char_is_hex_digit( *text ) )
|
||||||
|
v = hex_digit_to_int( *text );
|
||||||
|
else
|
||||||
|
break;
|
||||||
|
|
||||||
|
result *= base;
|
||||||
|
result += v;
|
||||||
|
text++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( value )
|
||||||
|
{
|
||||||
|
if ( negative )
|
||||||
|
result = -result;
|
||||||
|
*value = result;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ( text - text_begin );
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO : Are these good enough for characters?
|
||||||
|
global const char _num_to_char_table[] =
|
||||||
|
"0123456789"
|
||||||
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||||
|
"abcdefghijklmnopqrstuvwxyz"
|
||||||
|
"@$";
|
||||||
|
|
||||||
|
s64 c_str_to_i64( const char* str, char** end_ptr, s32 base )
|
||||||
|
{
|
||||||
|
ssize len;
|
||||||
|
s64 value;
|
||||||
|
|
||||||
|
if ( ! base )
|
||||||
|
{
|
||||||
|
if ( ( c_str_len( str ) > 2 ) && ( c_str_compare_len( str, "0x", 2 ) == 0 ) )
|
||||||
|
base = 16;
|
||||||
|
else
|
||||||
|
base = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
len = _scan_zpl_i64( str, base, &value );
|
||||||
|
if ( end_ptr )
|
||||||
|
*end_ptr = ( char* )str + len;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
void i64_to_str( s64 value, char* string, s32 base )
|
||||||
|
{
|
||||||
|
char* buf = string;
|
||||||
|
b32 negative = false;
|
||||||
|
u64 v;
|
||||||
|
|
||||||
|
if ( value < 0 )
|
||||||
|
{
|
||||||
|
negative = true;
|
||||||
|
value = -value;
|
||||||
|
}
|
||||||
|
|
||||||
|
v = scast( u64, value);
|
||||||
|
if ( v != 0 )
|
||||||
|
{
|
||||||
|
while ( v > 0 )
|
||||||
|
{
|
||||||
|
*buf++ = _num_to_char_table[ v % base ];
|
||||||
|
v /= base;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
*buf++ = '0';
|
||||||
|
}
|
||||||
|
if ( negative )
|
||||||
|
*buf++ = '-';
|
||||||
|
*buf = '\0';
|
||||||
|
c_str_reverse( string );
|
||||||
|
}
|
||||||
|
|
||||||
|
void u64_to_str( u64 value, char* string, s32 base )
|
||||||
|
{
|
||||||
|
char* buf = string;
|
||||||
|
|
||||||
|
if ( value )
|
||||||
|
{
|
||||||
|
while ( value > 0 )
|
||||||
|
{
|
||||||
|
*buf++ = _num_to_char_table[ value % base ];
|
||||||
|
value /= base;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
*buf++ = '0';
|
||||||
|
}
|
||||||
|
*buf = '\0';
|
||||||
|
|
||||||
|
c_str_reverse( string );
|
||||||
|
}
|
||||||
|
|
||||||
|
f64 c_str_to_f64( const char* str, char** end_ptr )
|
||||||
|
{
|
||||||
|
f64 result, value, sign, scale;
|
||||||
|
s32 frac;
|
||||||
|
|
||||||
|
while ( char_is_space( *str ) )
|
||||||
|
{
|
||||||
|
str++;
|
||||||
|
}
|
||||||
|
|
||||||
|
sign = 1.0;
|
||||||
|
if ( *str == '-' )
|
||||||
|
{
|
||||||
|
sign = -1.0;
|
||||||
|
str++;
|
||||||
|
}
|
||||||
|
else if ( *str == '+' )
|
||||||
|
{
|
||||||
|
str++;
|
||||||
|
}
|
||||||
|
|
||||||
|
for ( value = 0.0; char_is_digit( *str ); str++ )
|
||||||
|
{
|
||||||
|
value = value * 10.0 + ( *str - '0' );
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( *str == '.' )
|
||||||
|
{
|
||||||
|
f64 pow10 = 10.0;
|
||||||
|
str++;
|
||||||
|
while ( char_is_digit( *str ) )
|
||||||
|
{
|
||||||
|
value += ( *str - '0' ) / pow10;
|
||||||
|
pow10 *= 10.0;
|
||||||
|
str++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
frac = 0;
|
||||||
|
scale = 1.0;
|
||||||
|
if ( ( *str == 'e' ) || ( *str == 'E' ) )
|
||||||
|
{
|
||||||
|
u32 exp;
|
||||||
|
|
||||||
|
str++;
|
||||||
|
if ( *str == '-' )
|
||||||
|
{
|
||||||
|
frac = 1;
|
||||||
|
str++;
|
||||||
|
}
|
||||||
|
else if ( *str == '+' )
|
||||||
|
{
|
||||||
|
str++;
|
||||||
|
}
|
||||||
|
|
||||||
|
for ( exp = 0; char_is_digit( *str ); str++ )
|
||||||
|
{
|
||||||
|
exp = exp * 10 + ( *str - '0' );
|
||||||
|
}
|
||||||
|
if ( exp > 308 )
|
||||||
|
exp = 308;
|
||||||
|
|
||||||
|
while ( exp >= 50 )
|
||||||
|
{
|
||||||
|
scale *= 1e50;
|
||||||
|
exp -= 50;
|
||||||
|
}
|
||||||
|
while ( exp >= 8 )
|
||||||
|
{
|
||||||
|
scale *= 1e8;
|
||||||
|
exp -= 8;
|
||||||
|
}
|
||||||
|
while ( exp > 0 )
|
||||||
|
{
|
||||||
|
scale *= 10.0;
|
||||||
|
exp -= 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result = sign * ( frac ? ( value / scale ) : ( value * scale ) );
|
||||||
|
|
||||||
|
if ( end_ptr )
|
||||||
|
* end_ptr = rcast( char*, ccast(char*, str) );
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma endregion String Ops
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "memory.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region String Ops
|
||||||
|
|
||||||
|
const char* char_first_occurence( const char* str, char c );
|
||||||
|
|
||||||
|
b32 char_is_alpha( char c );
|
||||||
|
b32 char_is_alphanumeric( char c );
|
||||||
|
b32 char_is_digit( char c );
|
||||||
|
b32 char_is_hex_digit( char c );
|
||||||
|
b32 char_is_space( char c );
|
||||||
|
char char_to_lower( char c );
|
||||||
|
char char_to_upper( char c );
|
||||||
|
|
||||||
|
s32 digit_to_int( char c );
|
||||||
|
s32 hex_digit_to_int( char c );
|
||||||
|
|
||||||
|
s32 c_str_compare( const char* s1, const char* s2 );
|
||||||
|
s32 c_str_compare_len( const char* s1, const char* s2, ssize len );
|
||||||
|
char* c_str_copy( char* dest, const char* source, ssize len );
|
||||||
|
ssize c_str_copy_nulpad( char* dest, const char* source, ssize len );
|
||||||
|
ssize c_str_len( const char* str );
|
||||||
|
ssize c_str_len_capped( const char* str, ssize max_len );
|
||||||
|
char* c_str_reverse( char* str ); // NOTE: ASCII only
|
||||||
|
char const* c_str_skip( char const* str, char c );
|
||||||
|
char const* c_str_skip_any( char const* str, char const* char_list );
|
||||||
|
char const* c_str_trim( char const* str, b32 catch_newline );
|
||||||
|
|
||||||
|
// NOTE: ASCII only
|
||||||
|
void c_str_to_lower( char* str );
|
||||||
|
void c_str_to_upper( char* str );
|
||||||
|
|
||||||
|
GEN_API s64 c_str_to_i64( const char* str, char** end_ptr, s32 base );
|
||||||
|
GEN_API void i64_to_str( s64 value, char* string, s32 base );
|
||||||
|
GEN_API void u64_to_str( u64 value, char* string, s32 base );
|
||||||
|
GEN_API f64 c_str_to_f64( const char* str, char** end_ptr );
|
||||||
|
|
||||||
|
inline
|
||||||
|
const char* char_first_occurence( const char* s, char c )
|
||||||
|
{
|
||||||
|
char ch = c;
|
||||||
|
for ( ; *s != ch; s++ )
|
||||||
|
{
|
||||||
|
if ( *s == '\0' )
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 char_is_alpha( char c )
|
||||||
|
{
|
||||||
|
if ( ( c >= 'A' && c <= 'Z' ) || ( c >= 'a' && c <= 'z' ) )
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 char_is_alphanumeric( char c )
|
||||||
|
{
|
||||||
|
return char_is_alpha( c ) || char_is_digit( c );
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 char_is_digit( char c )
|
||||||
|
{
|
||||||
|
if ( c >= '0' && c <= '9' )
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 char_is_hex_digit( char c )
|
||||||
|
{
|
||||||
|
if ( char_is_digit( c ) || ( c >= 'a' && c <= 'f' ) || ( c >= 'A' && c <= 'F' ) )
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 char_is_space( char c )
|
||||||
|
{
|
||||||
|
if ( c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v' )
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
char char_to_lower( char c )
|
||||||
|
{
|
||||||
|
if ( c >= 'A' && c <= 'Z' )
|
||||||
|
return 'a' + ( c - 'A' );
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline char char_to_upper( char c )
|
||||||
|
{
|
||||||
|
if ( c >= 'a' && c <= 'z' )
|
||||||
|
return 'A' + ( c - 'a' );
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
s32 digit_to_int( char c )
|
||||||
|
{
|
||||||
|
return char_is_digit( c ) ? c - '0' : c - 'W';
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
s32 hex_digit_to_int( char c )
|
||||||
|
{
|
||||||
|
if ( char_is_digit( c ) )
|
||||||
|
return digit_to_int( c );
|
||||||
|
else if ( is_between( c, 'a', 'f' ) )
|
||||||
|
return c - 'a' + 10;
|
||||||
|
else if ( is_between( c, 'A', 'F' ) )
|
||||||
|
return c - 'A' + 10;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
s32 c_str_compare( const char* s1, const char* s2 )
|
||||||
|
{
|
||||||
|
while ( *s1 && ( *s1 == *s2 ) )
|
||||||
|
{
|
||||||
|
s1++, s2++;
|
||||||
|
}
|
||||||
|
return *( u8* )s1 - *( u8* )s2;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
s32 c_str_compare_len( const char* s1, const char* s2, ssize len )
|
||||||
|
{
|
||||||
|
for ( ; len > 0; s1++, s2++, len-- )
|
||||||
|
{
|
||||||
|
if ( *s1 != *s2 )
|
||||||
|
return ( ( s1 < s2 ) ? -1 : +1 );
|
||||||
|
else if ( *s1 == '\0' )
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
char* c_str_copy( char* dest, const char* source, ssize len )
|
||||||
|
{
|
||||||
|
GEN_ASSERT_NOT_NULL( dest );
|
||||||
|
if ( source )
|
||||||
|
{
|
||||||
|
char* str = dest;
|
||||||
|
while ( len > 0 && *source )
|
||||||
|
{
|
||||||
|
*str++ = *source++;
|
||||||
|
len--;
|
||||||
|
}
|
||||||
|
while ( len > 0 )
|
||||||
|
{
|
||||||
|
*str++ = '\0';
|
||||||
|
len--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dest;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
ssize c_str_copy_nulpad( char* dest, const char* source, ssize len )
|
||||||
|
{
|
||||||
|
ssize result = 0;
|
||||||
|
GEN_ASSERT_NOT_NULL( dest );
|
||||||
|
if ( source )
|
||||||
|
{
|
||||||
|
const char* source_start = source;
|
||||||
|
char* str = dest;
|
||||||
|
while ( len > 0 && *source )
|
||||||
|
{
|
||||||
|
*str++ = *source++;
|
||||||
|
len--;
|
||||||
|
}
|
||||||
|
while ( len > 0 )
|
||||||
|
{
|
||||||
|
*str++ = '\0';
|
||||||
|
len--;
|
||||||
|
}
|
||||||
|
|
||||||
|
result = source - source_start;
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
ssize c_str_len( const char* str )
|
||||||
|
{
|
||||||
|
if ( str == NULL )
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const char* p = str;
|
||||||
|
while ( *str )
|
||||||
|
str++;
|
||||||
|
return str - p;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
ssize c_str_len_capped( const char* str, ssize max_len )
|
||||||
|
{
|
||||||
|
const char* end = rcast(const char*, mem_find( str, 0, max_len ));
|
||||||
|
if ( end )
|
||||||
|
return end - str;
|
||||||
|
return max_len;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
char* c_str_reverse( char* str )
|
||||||
|
{
|
||||||
|
ssize len = c_str_len( str );
|
||||||
|
char* a = str + 0;
|
||||||
|
char* b = str + len - 1;
|
||||||
|
len /= 2;
|
||||||
|
while ( len-- )
|
||||||
|
{
|
||||||
|
swap( *a, *b );
|
||||||
|
a++, b--;
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
char const* c_str_skip( char const* str, char c )
|
||||||
|
{
|
||||||
|
while ( *str && *str != c )
|
||||||
|
{
|
||||||
|
++str;
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
char const* c_str_skip_any( char const* str, char const* char_list )
|
||||||
|
{
|
||||||
|
char const* closest_ptr = rcast( char const*, pointer_add_const( rcast(mem_ptr_const, str), c_str_len( str ) ));
|
||||||
|
ssize char_list_count = c_str_len( char_list );
|
||||||
|
for ( ssize i = 0; i < char_list_count; i++ )
|
||||||
|
{
|
||||||
|
char const* p = c_str_skip( str, char_list[ i ] );
|
||||||
|
closest_ptr = min( closest_ptr, p );
|
||||||
|
}
|
||||||
|
return closest_ptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
char const* c_str_trim( char const* str, b32 catch_newline )
|
||||||
|
{
|
||||||
|
while ( *str && char_is_space( *str ) && ( ! catch_newline || ( catch_newline && *str != '\n' ) ) )
|
||||||
|
{
|
||||||
|
++str;
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void c_str_to_lower( char* str )
|
||||||
|
{
|
||||||
|
if ( ! str )
|
||||||
|
return;
|
||||||
|
while ( *str )
|
||||||
|
{
|
||||||
|
*str = char_to_lower( *str );
|
||||||
|
str++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void c_str_to_upper( char* str )
|
||||||
|
{
|
||||||
|
if ( ! str )
|
||||||
|
return;
|
||||||
|
while ( *str )
|
||||||
|
{
|
||||||
|
*str = char_to_upper( *str );
|
||||||
|
str++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma endregion String Ops
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "hashing.cpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region StrBuilder
|
||||||
|
|
||||||
|
StrBuilder strbuilder_make_length( AllocatorInfo allocator, char const* str, ssize length )
|
||||||
|
{
|
||||||
|
ssize const header_size = sizeof( StrBuilderHeader );
|
||||||
|
|
||||||
|
s32 alloc_size = header_size + length + 1;
|
||||||
|
void* allocation = alloc( allocator, alloc_size );
|
||||||
|
|
||||||
|
if ( allocation == nullptr ) {
|
||||||
|
StrBuilder null_string = {nullptr};
|
||||||
|
return null_string;
|
||||||
|
}
|
||||||
|
|
||||||
|
StrBuilderHeader*
|
||||||
|
header = rcast(StrBuilderHeader*, allocation);
|
||||||
|
header->Allocator = allocator;
|
||||||
|
header->Capacity = length;
|
||||||
|
header->Length = length;
|
||||||
|
|
||||||
|
StrBuilder result = { rcast( char*, allocation) + header_size };
|
||||||
|
|
||||||
|
if ( length && str )
|
||||||
|
mem_copy( result, str, length );
|
||||||
|
else
|
||||||
|
mem_set( result, 0, alloc_size - header_size );
|
||||||
|
|
||||||
|
result[ length ] = '\0';
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
StrBuilder strbuilder_make_reserve( AllocatorInfo allocator, ssize capacity )
|
||||||
|
{
|
||||||
|
ssize const header_size = sizeof( StrBuilderHeader );
|
||||||
|
|
||||||
|
s32 alloc_size = header_size + capacity + 1;
|
||||||
|
void* allocation = alloc( allocator, alloc_size );
|
||||||
|
|
||||||
|
if ( allocation == nullptr ) {
|
||||||
|
StrBuilder null_string = {nullptr};
|
||||||
|
return null_string;
|
||||||
|
}
|
||||||
|
mem_set( allocation, 0, alloc_size );
|
||||||
|
|
||||||
|
StrBuilderHeader*
|
||||||
|
header = rcast(StrBuilderHeader*, allocation);
|
||||||
|
header->Allocator = allocator;
|
||||||
|
header->Capacity = capacity;
|
||||||
|
header->Length = 0;
|
||||||
|
|
||||||
|
StrBuilder result = { rcast(char*, allocation) + header_size };
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool strbuilder_make_space_for(StrBuilder* str, char const* to_append, ssize add_len)
|
||||||
|
{
|
||||||
|
ssize available = strbuilder_avail_space(* str);
|
||||||
|
|
||||||
|
if (available >= add_len) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ssize new_len, old_size, new_size;
|
||||||
|
void* ptr;
|
||||||
|
void* new_ptr;
|
||||||
|
|
||||||
|
AllocatorInfo allocator = strbuilder_get_header(* str)->Allocator;
|
||||||
|
StrBuilderHeader* header = nullptr;
|
||||||
|
|
||||||
|
new_len = strbuilder_grow_formula(strbuilder_length(* str) + add_len);
|
||||||
|
ptr = strbuilder_get_header(* str);
|
||||||
|
old_size = size_of(StrBuilderHeader) + strbuilder_length(* str) + 1;
|
||||||
|
new_size = size_of(StrBuilderHeader) + new_len + 1;
|
||||||
|
|
||||||
|
new_ptr = resize(allocator, ptr, old_size, new_size);
|
||||||
|
|
||||||
|
if (new_ptr == nullptr)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
header = rcast(StrBuilderHeader*, new_ptr);
|
||||||
|
header->Allocator = allocator;
|
||||||
|
header->Capacity = new_len;
|
||||||
|
|
||||||
|
char** Data = rcast(char**, str);
|
||||||
|
* Data = rcast(char*, header + 1);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool strbuilder_append_c_str_len(StrBuilder* str, char const* c_str_to_append, ssize append_length)
|
||||||
|
{
|
||||||
|
GEN_ASSERT(str != nullptr);
|
||||||
|
if ( rcast(sptr, c_str_to_append) > 0)
|
||||||
|
{
|
||||||
|
ssize curr_len = strbuilder_length(* str);
|
||||||
|
|
||||||
|
if ( ! strbuilder_make_space_for(str, c_str_to_append, append_length))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
StrBuilderHeader* header = strbuilder_get_header(* str);
|
||||||
|
|
||||||
|
char* Data = * str;
|
||||||
|
mem_copy( Data + curr_len, c_str_to_append, append_length);
|
||||||
|
|
||||||
|
Data[curr_len + append_length] = '\0';
|
||||||
|
|
||||||
|
header->Length = curr_len + append_length;
|
||||||
|
}
|
||||||
|
return c_str_to_append != nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void strbuilder_trim(StrBuilder str, char const* cut_set)
|
||||||
|
{
|
||||||
|
ssize len = 0;
|
||||||
|
|
||||||
|
char* start_pos = str;
|
||||||
|
char* end_pos = scast(char*, str) + strbuilder_length(str) - 1;
|
||||||
|
|
||||||
|
while (start_pos <= end_pos && char_first_occurence(cut_set, *start_pos))
|
||||||
|
start_pos++;
|
||||||
|
|
||||||
|
while (end_pos > start_pos && char_first_occurence(cut_set, *end_pos))
|
||||||
|
end_pos--;
|
||||||
|
|
||||||
|
len = scast(ssize, (start_pos > end_pos) ? 0 : ((end_pos - start_pos) + 1));
|
||||||
|
|
||||||
|
if (str != start_pos)
|
||||||
|
mem_move(str, start_pos, len);
|
||||||
|
|
||||||
|
str[len] = '\0';
|
||||||
|
|
||||||
|
strbuilder_get_header(str)->Length = len;
|
||||||
|
}
|
||||||
|
|
||||||
|
StrBuilder strbuilder_visualize_whitespace(StrBuilder const str)
|
||||||
|
{
|
||||||
|
StrBuilderHeader* header = (StrBuilderHeader*)(scast(char const*, str) - sizeof(StrBuilderHeader));
|
||||||
|
StrBuilder result = strbuilder_make_reserve(header->Allocator, strbuilder_length(str) * 2); // Assume worst case for space requirements.
|
||||||
|
|
||||||
|
for (char const* c = strbuilder_begin(str); c != strbuilder_end(str); c = strbuilder_next(str, c))
|
||||||
|
switch ( * c )
|
||||||
|
{
|
||||||
|
case ' ':
|
||||||
|
strbuilder_append_str(& result, txt("·"));
|
||||||
|
break;
|
||||||
|
case '\t':
|
||||||
|
strbuilder_append_str(& result, txt("→"));
|
||||||
|
break;
|
||||||
|
case '\n':
|
||||||
|
strbuilder_append_str(& result, txt("↵"));
|
||||||
|
break;
|
||||||
|
case '\r':
|
||||||
|
strbuilder_append_str(& result, txt("⏎"));
|
||||||
|
break;
|
||||||
|
case '\v':
|
||||||
|
strbuilder_append_str(& result, txt("⇕"));
|
||||||
|
break;
|
||||||
|
case '\f':
|
||||||
|
strbuilder_append_str(& result, txt("⌂"));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
strbuilder_append_char(& result, * c);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma endregion StrBuilder
|
||||||
@@ -0,0 +1,627 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "hashing.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Strings
|
||||||
|
|
||||||
|
struct Str;
|
||||||
|
|
||||||
|
Str to_str_from_c_str (char const* bad_string);
|
||||||
|
bool str_are_equal (Str lhs, Str rhs);
|
||||||
|
char const* str_back (Str str);
|
||||||
|
bool str_contains (Str str, Str substring);
|
||||||
|
Str str_duplicate (Str str, AllocatorInfo allocator);
|
||||||
|
b32 str_starts_with (Str str, Str substring);
|
||||||
|
Str str_visualize_whitespace(Str str, AllocatorInfo allocator);
|
||||||
|
|
||||||
|
// Constant string with length.
|
||||||
|
struct Str
|
||||||
|
{
|
||||||
|
char const* Ptr;
|
||||||
|
ssize Len;
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
forceinline operator char const* () const { return Ptr; }
|
||||||
|
forceinline char const& operator[]( ssize index ) const { return Ptr[index]; }
|
||||||
|
|
||||||
|
#if ! GEN_C_LIKE_CPP
|
||||||
|
forceinline bool is_equal (Str rhs) const { return str_are_equal(* this, rhs); }
|
||||||
|
forceinline char const* back () const { return str_back(* this); }
|
||||||
|
forceinline bool contains (Str substring) const { return str_contains(* this, substring); }
|
||||||
|
forceinline Str duplicate (AllocatorInfo allocator) const { return str_duplicate(* this, allocator); }
|
||||||
|
forceinline b32 starts_with (Str substring) const { return str_starts_with(* this, substring); }
|
||||||
|
forceinline Str visualize_whitespace(AllocatorInfo allocator) const { return str_visualize_whitespace(* this, allocator); }
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
|
||||||
|
#define cast_to_str( str ) * rcast( Str*, (str) - sizeof(ssize) )
|
||||||
|
|
||||||
|
#ifndef txt
|
||||||
|
# if GEN_COMPILER_CPP
|
||||||
|
# define txt( text ) GEN_NS Str { ( text ), sizeof( text ) - 1 }
|
||||||
|
# else
|
||||||
|
# define txt( text ) (GEN_NS Str){ ( text ), sizeof( text ) - 1 }
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
GEN_API_C_BEGIN
|
||||||
|
forceinline char const* str_begin(Str str) { return str.Ptr; }
|
||||||
|
forceinline char const* str_end (Str str) { return str.Ptr + str.Len; }
|
||||||
|
forceinline char const* str_next (Str str, char const* iter) { return iter + 1; }
|
||||||
|
GEN_API_C_END
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
forceinline char const* begin(Str str) { return str.Ptr; }
|
||||||
|
forceinline char const* end (Str str) { return str.Ptr + str.Len; }
|
||||||
|
forceinline char const* next (Str str, char const* iter) { return iter + 1; }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
inline
|
||||||
|
bool str_are_equal(Str lhs, Str rhs)
|
||||||
|
{
|
||||||
|
if (lhs.Len != rhs.Len)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
for (ssize idx = 0; idx < lhs.Len; ++idx)
|
||||||
|
if (lhs.Ptr[idx] != rhs.Ptr[idx])
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
char const* str_back(Str str) {
|
||||||
|
return & str.Ptr[str.Len - 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
bool str_contains(Str str, Str substring)
|
||||||
|
{
|
||||||
|
if (substring.Len > str.Len)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
ssize main_len = str.Len;
|
||||||
|
ssize sub_len = substring.Len;
|
||||||
|
for (ssize idx = 0; idx <= main_len - sub_len; ++idx)
|
||||||
|
{
|
||||||
|
if (c_str_compare_len(str.Ptr + idx, substring.Ptr, sub_len) == 0)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
b32 str_starts_with(Str str, Str substring) {
|
||||||
|
if (substring.Len > str.Len)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
b32 result = c_str_compare_len(str.Ptr, substring.Ptr, substring.Len) == 0;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
Str to_str_from_c_str( char const* bad_str ) {
|
||||||
|
Str result = { bad_str, c_str_len( bad_str ) };
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dynamic StrBuilder
|
||||||
|
// This is directly based off the ZPL string api.
|
||||||
|
// They used a header pattern
|
||||||
|
// I kept it for simplicty of porting but its not necessary to keep it that way.
|
||||||
|
#pragma region StrBuilder
|
||||||
|
struct StrBuilderHeader;
|
||||||
|
|
||||||
|
#if GEN_COMPILER_C
|
||||||
|
typedef char* StrBuilder;
|
||||||
|
#else
|
||||||
|
struct StrBuilder;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
forceinline usize strbuilder_grow_formula(usize value);
|
||||||
|
|
||||||
|
GEN_API StrBuilder strbuilder_make_reserve (AllocatorInfo allocator, ssize capacity);
|
||||||
|
GEN_API StrBuilder strbuilder_make_length (AllocatorInfo allocator, char const* str, ssize length);
|
||||||
|
GEN_API bool strbuilder_make_space_for (StrBuilder* str, char const* to_append, ssize add_len);
|
||||||
|
GEN_API bool strbuilder_append_c_str_len (StrBuilder* str, char const* c_str_to_append, ssize length);
|
||||||
|
GEN_API void strbuilder_trim (StrBuilder str, char const* cut_set);
|
||||||
|
GEN_API StrBuilder strbuilder_visualize_whitespace(StrBuilder const str);
|
||||||
|
|
||||||
|
StrBuilder strbuilder_make_c_str (AllocatorInfo allocator, char const* str);
|
||||||
|
StrBuilder strbuilder_make_str (AllocatorInfo allocator, Str str);
|
||||||
|
StrBuilder strbuilder_fmt (AllocatorInfo allocator, char* buf, ssize buf_size, char const* fmt, ...);
|
||||||
|
StrBuilder strbuilder_fmt_buf (AllocatorInfo allocator, char const* fmt, ...);
|
||||||
|
StrBuilder strbuilder_join (AllocatorInfo allocator, char const** parts, ssize num_parts, char const* glue);
|
||||||
|
bool strbuilder_are_equal (StrBuilder const lhs, StrBuilder const rhs);
|
||||||
|
bool strbuilder_are_equal_str (StrBuilder const lhs, Str rhs);
|
||||||
|
bool strbuilder_append_char (StrBuilder* str, char c);
|
||||||
|
bool strbuilder_append_c_str (StrBuilder* str, char const* c_str_to_append);
|
||||||
|
bool strbuilder_append_str (StrBuilder* str, Str c_str_to_append);
|
||||||
|
bool strbuilder_append_string (StrBuilder* str, StrBuilder const other);
|
||||||
|
bool strbuilder_append_fmt (StrBuilder* str, char const* fmt, ...);
|
||||||
|
ssize strbuilder_avail_space (StrBuilder const str);
|
||||||
|
char* strbuilder_back (StrBuilder str);
|
||||||
|
bool strbuilder_contains_str (StrBuilder const str, Str substring);
|
||||||
|
bool strbuilder_contains_string (StrBuilder const str, StrBuilder const substring);
|
||||||
|
ssize strbuilder_capacity (StrBuilder const str);
|
||||||
|
void strbuilder_clear (StrBuilder str);
|
||||||
|
StrBuilder strbuilder_duplicate (StrBuilder const str, AllocatorInfo allocator);
|
||||||
|
void strbuilder_free (StrBuilder* str);
|
||||||
|
StrBuilderHeader* strbuilder_get_header (StrBuilder str);
|
||||||
|
ssize strbuilder_length (StrBuilder const str);
|
||||||
|
b32 strbuilder_starts_with_str (StrBuilder const str, Str substring);
|
||||||
|
b32 strbuilder_starts_with_string (StrBuilder const str, StrBuilder substring);
|
||||||
|
void strbuilder_skip_line (StrBuilder str);
|
||||||
|
void strbuilder_strip_space (StrBuilder str);
|
||||||
|
Str strbuilder_to_str (StrBuilder str);
|
||||||
|
void strbuilder_trim_space (StrBuilder str);
|
||||||
|
|
||||||
|
struct StrBuilderHeader {
|
||||||
|
AllocatorInfo Allocator;
|
||||||
|
ssize Capacity;
|
||||||
|
ssize Length;
|
||||||
|
};
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
struct StrBuilder
|
||||||
|
{
|
||||||
|
char* Data;
|
||||||
|
|
||||||
|
forceinline operator char*() { return Data; }
|
||||||
|
forceinline operator char const*() const { return Data; }
|
||||||
|
forceinline operator Str() const { return { Data, strbuilder_length(* this) }; }
|
||||||
|
|
||||||
|
StrBuilder const& operator=(StrBuilder const& other) const {
|
||||||
|
if (this == &other)
|
||||||
|
return *this;
|
||||||
|
|
||||||
|
StrBuilder* this_ = ccast(StrBuilder*, this);
|
||||||
|
this_->Data = other.Data;
|
||||||
|
|
||||||
|
return *this;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline char& operator[](ssize index) { return Data[index]; }
|
||||||
|
forceinline char const& operator[](ssize index) const { return Data[index]; }
|
||||||
|
|
||||||
|
forceinline bool operator==(std::nullptr_t) const { return Data == nullptr; }
|
||||||
|
forceinline bool operator!=(std::nullptr_t) const { return Data != nullptr; }
|
||||||
|
friend forceinline bool operator==(std::nullptr_t, const StrBuilder str) { return str.Data == nullptr; }
|
||||||
|
friend forceinline bool operator!=(std::nullptr_t, const StrBuilder str) { return str.Data != nullptr; }
|
||||||
|
|
||||||
|
#if ! GEN_C_LIKE_CPP
|
||||||
|
forceinline char* begin() const { return Data; }
|
||||||
|
forceinline char* end() const { return Data + strbuilder_length(* this); }
|
||||||
|
|
||||||
|
#pragma region Member Mapping
|
||||||
|
forceinline static StrBuilder make(AllocatorInfo allocator, char const* str) { return strbuilder_make_c_str(allocator, str); }
|
||||||
|
forceinline static StrBuilder make(AllocatorInfo allocator, Str str) { return strbuilder_make_str(allocator, str); }
|
||||||
|
forceinline static StrBuilder make_reserve(AllocatorInfo allocator, ssize cap) { return strbuilder_make_reserve(allocator, cap); }
|
||||||
|
forceinline static StrBuilder make_length(AllocatorInfo a, char const* s, ssize l) { return strbuilder_make_length(a, s, l); }
|
||||||
|
forceinline static StrBuilder join(AllocatorInfo a, char const** p, ssize n, char const* g) { return strbuilder_join(a, p, n, g); }
|
||||||
|
forceinline static usize grow_formula(usize value) { return strbuilder_grow_formula(value); }
|
||||||
|
|
||||||
|
static
|
||||||
|
StrBuilder fmt(AllocatorInfo allocator, char* buf, ssize buf_size, char const* fmt, ...) {
|
||||||
|
va_list va;
|
||||||
|
va_start(va, fmt);
|
||||||
|
ssize res = c_str_fmt_va(buf, buf_size, fmt, va) - 1;
|
||||||
|
va_end(va);
|
||||||
|
return strbuilder_make_length(allocator, buf, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
static
|
||||||
|
StrBuilder fmt_buf(AllocatorInfo allocator, char const* fmt, ...) {
|
||||||
|
local_persist thread_local
|
||||||
|
char buf[GEN_PRINTF_MAXLEN] = { 0 };
|
||||||
|
va_list va;
|
||||||
|
va_start(va, fmt);
|
||||||
|
ssize res = c_str_fmt_va(buf, GEN_PRINTF_MAXLEN, fmt, va) - 1;
|
||||||
|
va_end(va);
|
||||||
|
return strbuilder_make_length(allocator, buf, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline bool make_space_for(char const* str, ssize add_len) { return strbuilder_make_space_for(this, str, add_len); }
|
||||||
|
forceinline bool append(char c) { return strbuilder_append_char(this, c); }
|
||||||
|
forceinline bool append(char const* str) { return strbuilder_append_c_str(this, str); }
|
||||||
|
forceinline bool append(char const* str, ssize length) { return strbuilder_append_c_str_len(this, str, length); }
|
||||||
|
forceinline bool append(Str str) { return strbuilder_append_str(this, str); }
|
||||||
|
forceinline bool append(const StrBuilder other) { return strbuilder_append_string(this, other); }
|
||||||
|
forceinline ssize avail_space() const { return strbuilder_avail_space(* this); }
|
||||||
|
forceinline char* back() { return strbuilder_back(* this); }
|
||||||
|
forceinline bool contains(Str substring) const { return strbuilder_contains_str(* this, substring); }
|
||||||
|
forceinline bool contains(StrBuilder const& substring) const { return strbuilder_contains_string(* this, substring); }
|
||||||
|
forceinline ssize capacity() const { return strbuilder_capacity(* this); }
|
||||||
|
forceinline void clear() { strbuilder_clear(* this); }
|
||||||
|
forceinline StrBuilder duplicate(AllocatorInfo allocator) const { return strbuilder_duplicate(* this, allocator); }
|
||||||
|
forceinline void free() { strbuilder_free(this); }
|
||||||
|
forceinline bool is_equal(StrBuilder const& other) const { return strbuilder_are_equal(* this, other); }
|
||||||
|
forceinline bool is_equal(Str other) const { return strbuilder_are_equal_str(* this, other); }
|
||||||
|
forceinline ssize length() const { return strbuilder_length(* this); }
|
||||||
|
forceinline b32 starts_with(Str substring) const { return strbuilder_starts_with_str(* this, substring); }
|
||||||
|
forceinline b32 starts_with(StrBuilder substring) const { return strbuilder_starts_with_string(* this, substring); }
|
||||||
|
forceinline void skip_line() { strbuilder_skip_line(* this); }
|
||||||
|
forceinline void strip_space() { strbuilder_strip_space(* this); }
|
||||||
|
forceinline Str to_str() { return { Data, strbuilder_length(*this) }; }
|
||||||
|
forceinline void trim(char const* cut_set) { strbuilder_trim(* this, cut_set); }
|
||||||
|
forceinline void trim_space() { strbuilder_trim_space(* this); }
|
||||||
|
forceinline StrBuilder visualize_whitespace() const { return strbuilder_visualize_whitespace(* this); }
|
||||||
|
forceinline StrBuilderHeader& get_header() { return * strbuilder_get_header(* this); }
|
||||||
|
|
||||||
|
bool append_fmt(char const* fmt, ...) {
|
||||||
|
ssize res;
|
||||||
|
char buf[GEN_PRINTF_MAXLEN] = { 0 };
|
||||||
|
|
||||||
|
va_list va;
|
||||||
|
va_start(va, fmt);
|
||||||
|
res = c_str_fmt_va(buf, count_of(buf) - 1, fmt, va) - 1;
|
||||||
|
va_end(va);
|
||||||
|
|
||||||
|
return strbuilder_append_c_str_len(this, buf, res);
|
||||||
|
}
|
||||||
|
#pragma endregion Member Mapping
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
#endif
|
||||||
|
|
||||||
|
forceinline char* strbuilder_begin(StrBuilder str) { return ((char*) str); }
|
||||||
|
forceinline char* strbuilder_end (StrBuilder str) { return ((char*) str + strbuilder_length(str)); }
|
||||||
|
forceinline char* strbuilder_next (StrBuilder str, char const* iter) { return ((char*) iter + 1); }
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP && ! GEN_C_LIKE_CPP
|
||||||
|
forceinline char* begin(StrBuilder str) { return ((char*) str); }
|
||||||
|
forceinline char* end (StrBuilder str) { return ((char*) str + strbuilder_length(str)); }
|
||||||
|
forceinline char* next (StrBuilder str, char* iter) { return ((char*) iter + 1); }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP && ! GEN_C_LIKE_CPP
|
||||||
|
forceinline bool make_space_for(StrBuilder& str, char const* to_append, ssize add_len);
|
||||||
|
forceinline bool append(StrBuilder& str, char c);
|
||||||
|
forceinline bool append(StrBuilder& str, char const* c_str_to_append);
|
||||||
|
forceinline bool append(StrBuilder& str, char const* c_str_to_append, ssize length);
|
||||||
|
forceinline bool append(StrBuilder& str, Str c_str_to_append);
|
||||||
|
forceinline bool append(StrBuilder& str, const StrBuilder other);
|
||||||
|
forceinline bool append_fmt(StrBuilder& str, char const* fmt, ...);
|
||||||
|
forceinline char& back(StrBuilder& str);
|
||||||
|
forceinline void clear(StrBuilder& str);
|
||||||
|
forceinline void free(StrBuilder& str);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
usize strbuilder_grow_formula(usize value) {
|
||||||
|
// Using a very aggressive growth formula to reduce time mem_copying with recursive calls to append in this library.
|
||||||
|
return 4 * value + 8;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
StrBuilder strbuilder_make_c_str(AllocatorInfo allocator, char const* str) {
|
||||||
|
ssize length = str ? c_str_len(str) : 0;
|
||||||
|
return strbuilder_make_length(allocator, str, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
StrBuilder strbuilder_make_str(AllocatorInfo allocator, Str str) {
|
||||||
|
return strbuilder_make_length(allocator, str.Ptr, str.Len);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder strbuilder_fmt(AllocatorInfo allocator, char* buf, ssize buf_size, char const* fmt, ...) {
|
||||||
|
va_list va;
|
||||||
|
va_start(va, fmt);
|
||||||
|
ssize res = c_str_fmt_va(buf, buf_size, fmt, va) - 1;
|
||||||
|
va_end(va);
|
||||||
|
|
||||||
|
return strbuilder_make_length(allocator, buf, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder strbuilder_fmt_buf(AllocatorInfo allocator, char const* fmt, ...)
|
||||||
|
{
|
||||||
|
local_persist thread_local
|
||||||
|
PrintF_Buffer buf = struct_zero_init();
|
||||||
|
|
||||||
|
va_list va;
|
||||||
|
va_start(va, fmt);
|
||||||
|
ssize res = c_str_fmt_va(buf, GEN_PRINTF_MAXLEN, fmt, va) -1;
|
||||||
|
va_end(va);
|
||||||
|
|
||||||
|
return strbuilder_make_length(allocator, buf, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
StrBuilder strbuilder_join(AllocatorInfo allocator, char const** parts, ssize num_parts, char const* glue)
|
||||||
|
{
|
||||||
|
StrBuilder result = strbuilder_make_c_str(allocator, "");
|
||||||
|
|
||||||
|
for (ssize idx = 0; idx < num_parts; ++idx)
|
||||||
|
{
|
||||||
|
strbuilder_append_c_str(& result, parts[idx]);
|
||||||
|
|
||||||
|
if (idx < num_parts - 1)
|
||||||
|
strbuilder_append_c_str(& result, glue);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool strbuilder_append_char(StrBuilder* str, char c) {
|
||||||
|
GEN_ASSERT(str != nullptr);
|
||||||
|
return strbuilder_append_c_str_len( str, (char const*)& c, (ssize)1);
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool strbuilder_append_c_str(StrBuilder* str, char const* c_str_to_append) {
|
||||||
|
GEN_ASSERT(str != nullptr);
|
||||||
|
return strbuilder_append_c_str_len(str, c_str_to_append, c_str_len(c_str_to_append));
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool strbuilder_append_str(StrBuilder* str, Str c_str_to_append) {
|
||||||
|
GEN_ASSERT(str != nullptr);
|
||||||
|
return strbuilder_append_c_str_len(str, c_str_to_append.Ptr, c_str_to_append.Len);
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
bool strbuilder_append_string(StrBuilder* str, StrBuilder const other) {
|
||||||
|
GEN_ASSERT(str != nullptr);
|
||||||
|
return strbuilder_append_c_str_len(str, (char const*)other, strbuilder_length(other));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
bool strbuilder_append_fmt(StrBuilder* str, char const* fmt, ...) {
|
||||||
|
GEN_ASSERT(str != nullptr);
|
||||||
|
ssize res;
|
||||||
|
char buf[GEN_PRINTF_MAXLEN] = { 0 };
|
||||||
|
|
||||||
|
va_list va;
|
||||||
|
va_start(va, fmt);
|
||||||
|
res = c_str_fmt_va(buf, count_of(buf) - 1, fmt, va) - 1;
|
||||||
|
va_end(va);
|
||||||
|
|
||||||
|
return strbuilder_append_c_str_len(str, (char const*)buf, res);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
bool strbuilder_are_equal_string(StrBuilder const lhs, StrBuilder const rhs)
|
||||||
|
{
|
||||||
|
if (strbuilder_length(lhs) != strbuilder_length(rhs))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
for (ssize idx = 0; idx < strbuilder_length(lhs); ++idx)
|
||||||
|
if (lhs[idx] != rhs[idx])
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
bool strbuilder_are_equal_str(StrBuilder const lhs, Str rhs)
|
||||||
|
{
|
||||||
|
if (strbuilder_length(lhs) != (rhs.Len))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
for (ssize idx = 0; idx < strbuilder_length(lhs); ++idx)
|
||||||
|
if (lhs[idx] != rhs.Ptr[idx])
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
ssize strbuilder_avail_space(StrBuilder const str) {
|
||||||
|
StrBuilderHeader const* header = rcast(StrBuilderHeader const*, scast(char const*, str) - sizeof(StrBuilderHeader));
|
||||||
|
return header->Capacity - header->Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
char* strbuilder_back(StrBuilder str) {
|
||||||
|
return & (str)[strbuilder_length(str) - 1];
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
bool strbuilder_contains_StrC(StrBuilder const str, Str substring)
|
||||||
|
{
|
||||||
|
StrBuilderHeader const* header = rcast(StrBuilderHeader const*, scast(char const*, str) - sizeof(StrBuilderHeader));
|
||||||
|
|
||||||
|
if (substring.Len > header->Length)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
ssize main_len = header->Length;
|
||||||
|
ssize sub_len = substring.Len;
|
||||||
|
|
||||||
|
for (ssize idx = 0; idx <= main_len - sub_len; ++idx)
|
||||||
|
{
|
||||||
|
if (c_str_compare_len(str + idx, substring.Ptr, sub_len) == 0)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
bool strbuilder_contains_string(StrBuilder const str, StrBuilder const substring)
|
||||||
|
{
|
||||||
|
StrBuilderHeader const* header = rcast(StrBuilderHeader const*, scast(char const*, str) - sizeof(StrBuilderHeader));
|
||||||
|
|
||||||
|
if (strbuilder_length(substring) > header->Length)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
ssize main_len = header->Length;
|
||||||
|
ssize sub_len = strbuilder_length(substring);
|
||||||
|
|
||||||
|
for (ssize idx = 0; idx <= main_len - sub_len; ++idx)
|
||||||
|
{
|
||||||
|
if (c_str_compare_len(str + idx, substring, sub_len) == 0)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
ssize strbuilder_capacity(StrBuilder const str) {
|
||||||
|
StrBuilderHeader const* header = rcast(StrBuilderHeader const*, scast(char const*, str) - sizeof(StrBuilderHeader));
|
||||||
|
return header->Capacity;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
void strbuilder_clear(StrBuilder str) {
|
||||||
|
strbuilder_get_header(str)->Length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
StrBuilder strbuilder_duplicate(StrBuilder const str, AllocatorInfo allocator) {
|
||||||
|
return strbuilder_make_length(allocator, str, strbuilder_length(str));
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
void strbuilder_free(StrBuilder* str) {
|
||||||
|
GEN_ASSERT(str != nullptr);
|
||||||
|
if (! (* str))
|
||||||
|
return;
|
||||||
|
|
||||||
|
StrBuilderHeader* header = strbuilder_get_header(* str);
|
||||||
|
allocator_free(header->Allocator, header);
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
StrBuilderHeader* strbuilder_get_header(StrBuilder str) {
|
||||||
|
return (StrBuilderHeader*)(scast(char*, str) - sizeof(StrBuilderHeader));
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
ssize strbuilder_length(StrBuilder const str)
|
||||||
|
{
|
||||||
|
StrBuilderHeader const* header = rcast(StrBuilderHeader const*, scast(char const*, str) - sizeof(StrBuilderHeader));
|
||||||
|
return header->Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
b32 strbuilder_starts_with_str(StrBuilder const str, Str substring) {
|
||||||
|
if (substring.Len > strbuilder_length(str))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
b32 result = c_str_compare_len(str, substring.Ptr, substring.Len) == 0;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
b32 strbuilder_starts_with_string(StrBuilder const str, StrBuilder substring) {
|
||||||
|
if (strbuilder_length(substring) > strbuilder_length(str))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
b32 result = c_str_compare_len(str, substring, strbuilder_length(substring) - 1) == 0;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void strbuilder_skip_line(StrBuilder str)
|
||||||
|
{
|
||||||
|
#define current (*scanner)
|
||||||
|
char* scanner = str;
|
||||||
|
while (current != '\r' && current != '\n') {
|
||||||
|
++scanner;
|
||||||
|
}
|
||||||
|
|
||||||
|
s32 new_length = scanner - str;
|
||||||
|
|
||||||
|
if (current == '\r') {
|
||||||
|
new_length += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
mem_move((char*)str, scanner, new_length);
|
||||||
|
|
||||||
|
StrBuilderHeader* header = strbuilder_get_header(str);
|
||||||
|
header->Length = new_length;
|
||||||
|
#undef current
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
void strbuilder_strip_space(StrBuilder str)
|
||||||
|
{
|
||||||
|
char* write_pos = str;
|
||||||
|
char* read_pos = str;
|
||||||
|
|
||||||
|
while (* read_pos)
|
||||||
|
{
|
||||||
|
if (! char_is_space(* read_pos))
|
||||||
|
{
|
||||||
|
* write_pos = * read_pos;
|
||||||
|
write_pos++;
|
||||||
|
}
|
||||||
|
read_pos++;
|
||||||
|
}
|
||||||
|
write_pos[0] = '\0'; // Null-terminate the modified string
|
||||||
|
|
||||||
|
// Update the length if needed
|
||||||
|
strbuilder_get_header(str)->Length = write_pos - str;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
Str strbuilder_to_str(StrBuilder str) {
|
||||||
|
Str result = { (char const*)str, strbuilder_length(str) };
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
void strbuilder_trim_space(StrBuilder str) {
|
||||||
|
strbuilder_trim(str, " \t\r\n\v\f");
|
||||||
|
}
|
||||||
|
|
||||||
|
#pragma endregion StrBuilder
|
||||||
|
|
||||||
|
#if GEN_COMPILER_CPP
|
||||||
|
struct StrBuilder_POD {
|
||||||
|
char* Data;
|
||||||
|
};
|
||||||
|
static_assert( sizeof( StrBuilder_POD ) == sizeof( StrBuilder ), "StrBuilder is not a POD" );
|
||||||
|
#endif
|
||||||
|
|
||||||
|
forceinline
|
||||||
|
Str str_duplicate(Str str, AllocatorInfo allocator) {
|
||||||
|
Str result = strbuilder_to_str( strbuilder_make_length(allocator, str.Ptr, str.Len));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline
|
||||||
|
Str str_visualize_whitespace(Str str, AllocatorInfo allocator)
|
||||||
|
{
|
||||||
|
StrBuilder result = strbuilder_make_reserve(allocator, str.Len * 2); // Assume worst case for space requirements.
|
||||||
|
for (char const* c = str_begin(str); c != str_end(str); c = str_next(str, c))
|
||||||
|
switch ( * c )
|
||||||
|
{
|
||||||
|
case ' ':
|
||||||
|
strbuilder_append_str(& result, txt("·"));
|
||||||
|
break;
|
||||||
|
case '\t':
|
||||||
|
strbuilder_append_str(& result, txt("→"));
|
||||||
|
break;
|
||||||
|
case '\n':
|
||||||
|
strbuilder_append_str(& result, txt("↵"));
|
||||||
|
break;
|
||||||
|
case '\r':
|
||||||
|
strbuilder_append_str(& result, txt("⏎"));
|
||||||
|
break;
|
||||||
|
case '\v':
|
||||||
|
strbuilder_append_str(& result, txt("⇕"));
|
||||||
|
break;
|
||||||
|
case '\f':
|
||||||
|
strbuilder_append_str(& result, txt("⌂"));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
strbuilder_append_char(& result, * c);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return strbuilder_to_str(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Represents strings cached with the string table.
|
||||||
|
// Should never be modified, if changed string is desired, cache_string( str ) another.
|
||||||
|
typedef Str StrCached;
|
||||||
|
|
||||||
|
// Implements basic string interning. Data structure is based off the ZPL Hashtable.
|
||||||
|
typedef HashTable(StrCached) StringTable;
|
||||||
|
#pragma endregion Strings
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "filesystem.cpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Timing
|
||||||
|
|
||||||
|
#ifdef GEN_BENCHMARK
|
||||||
|
#if defined( GEN_COMPILER_MSVC ) && ! defined( __clang__ )
|
||||||
|
u64 read_cpu_time_stamp_counter( void )
|
||||||
|
{
|
||||||
|
return __rdtsc();
|
||||||
|
}
|
||||||
|
#elif defined( __i386__ )
|
||||||
|
u64 read_cpu_time_stamp_counter( void )
|
||||||
|
{
|
||||||
|
u64 x;
|
||||||
|
__asm__ volatile( ".byte 0x0f, 0x31" : "=A"( x ) );
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
#elif defined( __x86_64__ )
|
||||||
|
u64 read_cpu_time_stamp_counter( void )
|
||||||
|
{
|
||||||
|
u32 hi, lo;
|
||||||
|
__asm__ __volatile__( "rdtsc" : "=a"( lo ), "=d"( hi ) );
|
||||||
|
return scast( u64, lo ) | ( scast( u64, hi ) << 32 );
|
||||||
|
}
|
||||||
|
#elif defined( __powerpc__ )
|
||||||
|
u64 read_cpu_time_stamp_counter( void )
|
||||||
|
{
|
||||||
|
u64 result = 0;
|
||||||
|
u32 upper, lower, tmp;
|
||||||
|
__asm__ volatile(
|
||||||
|
"0: \n"
|
||||||
|
"\tmftbu %0 \n"
|
||||||
|
"\tmftb %1 \n"
|
||||||
|
"\tmftbu %2 \n"
|
||||||
|
"\tcmpw %2,%0 \n"
|
||||||
|
"\tbne 0b \n"
|
||||||
|
: "=r"( upper ), "=r"( lower ), "=r"( tmp )
|
||||||
|
);
|
||||||
|
result = upper;
|
||||||
|
result = result << 32;
|
||||||
|
result = result | lower;
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
#elif defined( GEN_SYSTEM_EMSCRIPTEN )
|
||||||
|
u64 read_cpu_time_stamp_counter( void )
|
||||||
|
{
|
||||||
|
return ( u64 )( emscripten_get_now() * 1e+6 );
|
||||||
|
}
|
||||||
|
#elif defined( GEN_CPU_ARM ) && ! defined( GEN_COMPILER_TINYC )
|
||||||
|
u64 read_cpu_time_stamp_counter( void )
|
||||||
|
{
|
||||||
|
# if defined( __aarch64__ )
|
||||||
|
int64_t r = 0;
|
||||||
|
asm volatile( "mrs %0, cntvct_el0" : "=r"( r ) );
|
||||||
|
# elif ( __ARM_ARCH >= 6 )
|
||||||
|
uint32_t r = 0;
|
||||||
|
uint32_t pmccntr;
|
||||||
|
uint32_t pmuseren;
|
||||||
|
uint32_t pmcntenset;
|
||||||
|
|
||||||
|
// Read the user mode perf monitor counter access permissions.
|
||||||
|
asm volatile( "mrc p15, 0, %0, c9, c14, 0" : "=r"( pmuseren ) );
|
||||||
|
if ( pmuseren & 1 )
|
||||||
|
{ // Allows reading perfmon counters for user mode code.
|
||||||
|
asm volatile( "mrc p15, 0, %0, c9, c12, 1" : "=r"( pmcntenset ) );
|
||||||
|
if ( pmcntenset & 0x80000000ul )
|
||||||
|
{ // Is it counting?
|
||||||
|
asm volatile( "mrc p15, 0, %0, c9, c13, 0" : "=r"( pmccntr ) );
|
||||||
|
// The counter is set up to count every 64th cycle
|
||||||
|
return ( ( int64_t )pmccntr ) * 64; // Should optimize to << 6
|
||||||
|
}
|
||||||
|
}
|
||||||
|
# else
|
||||||
|
# error "No suitable method for read_cpu_time_stamp_counter for this cpu type"
|
||||||
|
# endif
|
||||||
|
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
u64 read_cpu_time_stamp_counter( void )
|
||||||
|
{
|
||||||
|
GEN_PANIC( "read_cpu_time_stamp_counter is not supported on this particular setup" );
|
||||||
|
return -0;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined( GEN_SYSTEM_WINDOWS ) || defined( GEN_SYSTEM_CYGWIN )
|
||||||
|
|
||||||
|
u64 time_rel_ms( void )
|
||||||
|
{
|
||||||
|
local_persist LARGE_INTEGER win32_perf_count_freq = {};
|
||||||
|
u64 result;
|
||||||
|
LARGE_INTEGER counter;
|
||||||
|
local_persist LARGE_INTEGER win32_perf_counter = {};
|
||||||
|
if ( ! win32_perf_count_freq.QuadPart )
|
||||||
|
{
|
||||||
|
QueryPerformanceFrequency( &win32_perf_count_freq );
|
||||||
|
GEN_ASSERT( win32_perf_count_freq.QuadPart != 0 );
|
||||||
|
QueryPerformanceCounter( &win32_perf_counter );
|
||||||
|
}
|
||||||
|
|
||||||
|
QueryPerformanceCounter( &counter );
|
||||||
|
|
||||||
|
result = ( counter.QuadPart - win32_perf_counter.QuadPart ) * 1000 / ( win32_perf_count_freq.QuadPart );
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
#else
|
||||||
|
|
||||||
|
# if defined( GEN_SYSTEM_LINUX ) || defined( GEN_SYSTEM_FREEBSD ) || defined( GEN_SYSTEM_OPENBSD ) || defined( GEN_SYSTEM_EMSCRIPTEN )
|
||||||
|
u64 _unix_gettime( void )
|
||||||
|
{
|
||||||
|
struct timespec t;
|
||||||
|
u64 result;
|
||||||
|
|
||||||
|
clock_gettime( 1 /*CLOCK_MONOTONIC*/, &t );
|
||||||
|
result = 1000 * t.tv_sec + 1.0e-6 * t.tv_nsec;
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
# endif
|
||||||
|
|
||||||
|
u64 time_rel_ms( void )
|
||||||
|
{
|
||||||
|
# if defined( GEN_SYSTEM_OSX )
|
||||||
|
u64 result;
|
||||||
|
|
||||||
|
local_persist u64 timebase = 0;
|
||||||
|
local_persist u64 timestart = 0;
|
||||||
|
|
||||||
|
if ( ! timestart )
|
||||||
|
{
|
||||||
|
mach_timebase_info_data_t tb = { 0 };
|
||||||
|
mach_timebase_info( &tb );
|
||||||
|
timebase = tb.numer;
|
||||||
|
timebase /= tb.denom;
|
||||||
|
timestart = mach_absolute_time();
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: mach_absolute_time() returns things in nanoseconds
|
||||||
|
result = 1.0e-6 * ( mach_absolute_time() - timestart ) * timebase;
|
||||||
|
return result;
|
||||||
|
# else
|
||||||
|
local_persist u64 unix_timestart = 0.0;
|
||||||
|
|
||||||
|
if ( ! unix_timestart )
|
||||||
|
{
|
||||||
|
unix_timestart = _unix_gettime();
|
||||||
|
}
|
||||||
|
|
||||||
|
u64 now = _unix_gettime();
|
||||||
|
|
||||||
|
return ( now - unix_timestart );
|
||||||
|
# endif
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
f64 time_rel( void )
|
||||||
|
{
|
||||||
|
return ( f64 )( time_rel_ms() * 1e-3 );
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Timing
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
#ifdef INTELLISENSE_DIRECTIVES
|
||||||
|
# pragma once
|
||||||
|
# include "filesystem.hpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma region Timing
|
||||||
|
|
||||||
|
#ifdef GEN_BENCHMARK
|
||||||
|
//! Return CPU timestamp.
|
||||||
|
GEN_API u64 read_cpu_time_stamp_counter( void );
|
||||||
|
|
||||||
|
//! Return relative time (in seconds) since the application start.
|
||||||
|
GEN_API f64 time_rel( void );
|
||||||
|
|
||||||
|
//! Return relative time since the application start.
|
||||||
|
GEN_API u64 time_rel_ms( void );
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#pragma endregion Timing
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
#include "helpers/push_ignores.inline.hpp"
|
||||||
|
|
||||||
|
// ReSharper disable CppClangTidyClangDiagnosticSwitchEnum
|
||||||
|
|
||||||
|
#if ! defined(GEN_DONT_ENFORCE_GEN_TIME_GUARD) && ! defined(GEN_TIME)
|
||||||
|
# error Gen.hpp : GEN_TIME not defined
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "gen.hpp"
|
||||||
|
|
||||||
|
// These are intended for use in the base library of gencpp and the C-variant of the library
|
||||||
|
// It provides a interoperability between the C++ and C interfacing for containers. (not letting these do any crazy substiution though)
|
||||||
|
// They are undefined in gen.hpp and gen.cpp at the end of the files.
|
||||||
|
// We cpp library expects the user to use the regular calls as they can resolve the type fine.
|
||||||
|
|
||||||
|
#include "helpers/push_container_defines.inline.hpp"
|
||||||
|
|
||||||
|
//! If its desired to roll your own dependencies, define GEN_ROLL_OWN_DEPENDENCIES before including this file.
|
||||||
|
//! Dependencies are derived from the c-zpl library: https://github.com/zpl-c/zpl
|
||||||
|
#ifndef GEN_ROLL_OWN_DEPENDENCIES
|
||||||
|
# include "gen.dep.cpp"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
GEN_NS_BEGIN
|
||||||
|
|
||||||
|
#include "components/static_data.cpp"
|
||||||
|
|
||||||
|
#include "components/ast_case_macros.cpp"
|
||||||
|
#include "components/ast.cpp"
|
||||||
|
#include "components/code_serialization.cpp"
|
||||||
|
|
||||||
|
#include "components/interface.cpp"
|
||||||
|
#include "components/interface.upfront.cpp"
|
||||||
|
#include "components/lexer.cpp"
|
||||||
|
#include "components/parser_case_macros.cpp"
|
||||||
|
#include "components/parser.cpp"
|
||||||
|
#include "components/interface.parsing.cpp"
|
||||||
|
#include "components/interface.untyped.cpp"
|
||||||
|
|
||||||
|
#include "auxiliary/builder.cpp"
|
||||||
|
#include "auxiliary/scanner.cpp"
|
||||||
|
|
||||||
|
GEN_NS_END
|
||||||
|
|
||||||
|
#include "helpers/pop_container_defines.inline.hpp"
|
||||||
|
#include "helpers/pop_ignores.inline.hpp"
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
// This file is intended to be included within gen.cpp (There is no pragma diagnostic ignores)
|
||||||
|
#include "gen.dep.hpp"
|
||||||
|
|
||||||
|
#include "dependencies/src_start.cpp"
|
||||||
|
|
||||||
|
GEN_NS_BEGIN
|
||||||
|
|
||||||
|
#include "dependencies/debug.cpp"
|
||||||
|
#include "dependencies/string_ops.cpp"
|
||||||
|
#include "dependencies/printing.cpp"
|
||||||
|
#include "dependencies/memory.cpp"
|
||||||
|
#include "dependencies/hashing.cpp"
|
||||||
|
#include "dependencies/strings.cpp"
|
||||||
|
#include "dependencies/filesystem.cpp"
|
||||||
|
#include "dependencies/timing.cpp"
|
||||||
|
#include "dependencies/parsing.cpp"
|
||||||
|
|
||||||
|
GEN_NS_END
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
// This file is intended to be included within gen.hpp (There is no pragma diagnostic ignores)
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "dependencies/platform.hpp"
|
||||||
|
|
||||||
|
GEN_NS_BEGIN
|
||||||
|
|
||||||
|
#include "dependencies/macros.hpp"
|
||||||
|
#include "dependencies/basic_types.hpp"
|
||||||
|
#include "dependencies/debug.hpp"
|
||||||
|
#include "dependencies/memory.hpp"
|
||||||
|
#include "dependencies/string_ops.hpp"
|
||||||
|
#include "dependencies/printing.hpp"
|
||||||
|
#include "dependencies/containers.hpp"
|
||||||
|
#include "dependencies/hashing.hpp"
|
||||||
|
#include "dependencies/strings.hpp"
|
||||||
|
#include "dependencies/filesystem.hpp"
|
||||||
|
#include "dependencies/timing.hpp"
|
||||||
|
#include "dependencies/parsing.hpp"
|
||||||
|
|
||||||
|
GEN_NS_END
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
/*
|
||||||
|
gencpp: An attempt at "simple" staged metaprogramming for c/c++.
|
||||||
|
|
||||||
|
See Readme.md for more information from the project repository.
|
||||||
|
|
||||||
|
Public Address:
|
||||||
|
https://github.com/Ed94/gencpp
|
||||||
|
*/
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "helpers/push_ignores.inline.hpp"
|
||||||
|
#include "components/header_start.hpp"
|
||||||
|
|
||||||
|
GEN_NS_BEGIN
|
||||||
|
|
||||||
|
#include "components/types.hpp"
|
||||||
|
#include "components/gen/ecodetypes.hpp"
|
||||||
|
#include "components/gen/eoperator.hpp"
|
||||||
|
#include "components/gen/especifier.hpp"
|
||||||
|
#include "components/gen/etoktype.hpp"
|
||||||
|
#include "components/parser_types.hpp"
|
||||||
|
|
||||||
|
#include "components/ast.hpp"
|
||||||
|
#include "components/code_types.hpp"
|
||||||
|
#include "components/ast_types.hpp"
|
||||||
|
|
||||||
|
#include "components/interface.hpp"
|
||||||
|
|
||||||
|
#include "components/constants.hpp"
|
||||||
|
#include "components/inlines.hpp"
|
||||||
|
#include "components/gen/ast_inlines.hpp"
|
||||||
|
|
||||||
|
#include "auxiliary/builder.hpp"
|
||||||
|
#include "auxiliary/scanner.hpp"
|
||||||
|
|
||||||
|
GEN_NS_END
|
||||||
|
|
||||||
|
#include "helpers/pop_container_defines.inline.hpp"
|
||||||
|
#include "helpers/pop_ignores.inline.hpp"
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import sys
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
sys.path.append(str(Path(__file__).parent.parent))
|
||||||
|
|
||||||
|
from src.mcp_client import ts_cpp_get_definition, ts_cpp_get_signature, ts_cpp_get_code_outline, ts_cpp_get_skeleton
|
||||||
|
from src.aggregate import build_tier3_context
|
||||||
|
|
||||||
|
def test_gencpp_full_suite():
|
||||||
|
base_dir = Path("tests/assets/gencpp_samples")
|
||||||
|
|
||||||
|
# Test all .hpp files in components
|
||||||
|
components_dir = base_dir / "components"
|
||||||
|
hpp_files = list(components_dir.glob("*.hpp"))
|
||||||
|
hpp_files.extend(list((base_dir / "dependencies").glob("*.hpp")))
|
||||||
|
hpp_files.extend(list(base_dir.glob("*.hpp")))
|
||||||
|
hpp_files.extend(list((base_dir / "auxiliary").glob("*.hpp")))
|
||||||
|
|
||||||
|
print(f"Testing {len(hpp_files)} .hpp files from gencpp/base...")
|
||||||
|
|
||||||
|
failures = []
|
||||||
|
|
||||||
|
for hpp_file in hpp_files:
|
||||||
|
filename = hpp_file.name
|
||||||
|
print(f"\n=== Testing {filename} ===")
|
||||||
|
|
||||||
|
# 1. Skeleton should work without errors
|
||||||
|
skeleton = ts_cpp_get_skeleton(str(hpp_file))
|
||||||
|
if skeleton.startswith("ERROR:"):
|
||||||
|
failures.append(f"{filename}: skeleton failed")
|
||||||
|
print(f" [FAIL] skeleton: {skeleton[:100]}")
|
||||||
|
else:
|
||||||
|
print(f" [PASS] skeleton ({len(skeleton)} chars)")
|
||||||
|
|
||||||
|
# 2. Outline should work without errors
|
||||||
|
outline = ts_cpp_get_code_outline(str(hpp_file))
|
||||||
|
if outline.startswith("ERROR:"):
|
||||||
|
failures.append(f"{filename}: outline failed")
|
||||||
|
print(f" [FAIL] outline: {outline[:100]}")
|
||||||
|
else:
|
||||||
|
lines = outline.strip().split('\n')
|
||||||
|
print(f" [PASS] outline ({len(lines)} entries)")
|
||||||
|
|
||||||
|
# 3. Get definitions for key symbols from outlines
|
||||||
|
for line in outline.strip().split('\n')[:5]: # Test first 5 symbols
|
||||||
|
if '[' in line:
|
||||||
|
# Extract symbol name
|
||||||
|
parts = line.split('] ')
|
||||||
|
if len(parts) > 1:
|
||||||
|
symbol = parts[1].split(' ')[0].split('(')[0]
|
||||||
|
# Handle nested types
|
||||||
|
symbol = symbol.replace('::', '.')
|
||||||
|
|
||||||
|
# Try different lookup styles
|
||||||
|
for lookup in [symbol, symbol.split('.')[-1] if '.' in symbol else symbol]:
|
||||||
|
defn = ts_cpp_get_definition(str(hpp_file), lookup)
|
||||||
|
if not defn.startswith("ERROR"):
|
||||||
|
print(f" [PASS] get_definition({lookup}): {defn[:50]}...")
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
print(f" [INFO] get_definition({symbol}) not found (may be expected)")
|
||||||
|
|
||||||
|
# Test aggregation with AST masking on a sample file
|
||||||
|
print("\n=== Testing AST Masking with aggregation ===")
|
||||||
|
ast_hpp = base_dir / "components" / "ast.hpp"
|
||||||
|
if ast_hpp.exists():
|
||||||
|
item = {
|
||||||
|
"path": ast_hpp,
|
||||||
|
"entry": str(ast_hpp),
|
||||||
|
"content": ast_hpp.read_text(encoding="utf-8"),
|
||||||
|
"ast_mask": {"AST": "def", "Code::append": "sig"},
|
||||||
|
"auto_aggregate": True,
|
||||||
|
"force_full": False,
|
||||||
|
"tier": None
|
||||||
|
}
|
||||||
|
|
||||||
|
res = build_tier3_context([item], Path("."), [], [], [])
|
||||||
|
if "(Masked)" in res and "struct AST" in res:
|
||||||
|
print(f" [PASS] AST masking works")
|
||||||
|
else:
|
||||||
|
failures.append("AST masking: missing expected content")
|
||||||
|
print(f" [FAIL] AST masking result unexpected")
|
||||||
|
|
||||||
|
print(f"\n=== SUMMARY ===")
|
||||||
|
if failures:
|
||||||
|
print(f"FAILURES ({len(failures)}):")
|
||||||
|
for f in failures:
|
||||||
|
print(f" - {f}")
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
print("ALL TESTS PASSED")
|
||||||
|
return True
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
success = test_gencpp_full_suite()
|
||||||
|
sys.exit(0 if success else 1)
|
||||||
Reference in New Issue
Block a user