Compare commits

...

6 Commits

Author SHA1 Message Date
Ed_
9b059dca47 C-library Finished setting up header dependencies ( 2024-12-06 00:33:58 -05:00
Ed_
46562d54e7 parser: added support for enum_underlying macro 2024-12-06 00:33:53 -05:00
Ed_
ec07c70dcf verified the C hashtable has parity with the C++ templated gencpp hashtable. 2024-12-05 23:02:26 -05:00
Ed_
63dd77237a update version (forgot) 2024-12-05 21:37:39 -05:00
Ed_
cf3908c6f0 Added alpha warning message to header_start.hpp files. 2024-12-05 21:37:07 -05:00
Ed_
266163557f Finished draft pass verifying containers.array.hpp is equivalent to container.hpp's array.
gen_generic_selection_function_macro now works generically
Imprvoed _Generic function overloading examples
2024-12-05 21:01:04 -05:00
27 changed files with 785 additions and 404 deletions

View File

@ -142,7 +142,6 @@ int gen_main()
Code debug = scan_file( project_dir "dependencies/debug.hpp" ); Code debug = scan_file( project_dir "dependencies/debug.hpp" );
Code string_ops = scan_file( project_dir "dependencies/string_ops.hpp" ); Code string_ops = scan_file( project_dir "dependencies/string_ops.hpp" );
Code hashing = scan_file( project_dir "dependencies/hashing.hpp" ); Code hashing = scan_file( project_dir "dependencies/hashing.hpp" );
Code filesystem = scan_file( project_dir "dependencies/filesystem.hpp" );
Code timing = scan_file( project_dir "dependencies/timing.hpp" ); Code timing = scan_file( project_dir "dependencies/timing.hpp" );
CodeBody parsed_memory = parse_file( project_dir "dependencies/memory.hpp" ); CodeBody parsed_memory = parse_file( project_dir "dependencies/memory.hpp" );
@ -387,6 +386,44 @@ int gen_main()
} }
} }
CodeBody parsed_filesystem = parse_file( project_dir "dependencies/filesystem.hpp" );
CodeBody filesystem = def_body(CT_Global_Body);
for ( Code entry = parsed_filesystem.begin(); entry != parsed_filesystem.end(); ++ entry )
{
switch (entry->Type)
{
case CT_Preprocess_IfDef:
{
b32 found = ignore_preprocess_cond_block(txt("GEN_INTELLISENSE_DIRECTIVES"), entry, parsed_filesystem, filesystem );
if (found) break;
filesystem.append(entry);
}
break;
case CT_Variable:
{
CodeVar var = cast(CodeVar, entry);
if (var->Specs.has(Spec_Constexpr) > -1)
{
CodeDefine define = def_define(entry->Name, entry->Value->Content);
filesystem.append(define);
continue;
}
//if ( strc_contains(entry->Name, txt("Msg_Invalid_Value")))
//{
// CodeDefine define = def_define(entry->Name, entry->Value->Content);
// printing.append(define);
// continue;
//}
filesystem.append(entry);
}
break;
default:
filesystem.append(entry);
break;
}
}
CodeBody containers = def_body(CT_Global_Body); CodeBody containers = def_body(CT_Global_Body);
{ {
CodeBody array_ssize = gen_array(txt("ssize"), txt("Array_ssize")); CodeBody array_ssize = gen_array(txt("ssize"), txt("Array_ssize"));
@ -397,8 +434,9 @@ int gen_main()
containers.append( gen_array_base() ); containers.append( gen_array_base() );
containers.append( gen_array_generic_selection_interface()); containers.append( gen_array_generic_selection_interface());
containers.append( gen_hashtable_base() ); containers.append( gen_hashtable_base() );
containers.append(fmt_newline); containers.append(fmt_newline);
containers.append( gen_hashtable_generic_selection_interface());
containers.append(array_ssize); containers.append(array_ssize);
containers.append( def_pragma(code(endregion Containers))); containers.append( def_pragma(code(endregion Containers)));
@ -420,8 +458,8 @@ int gen_main()
header.print( dump_to_scratch_and_retireve(containers)); header.print( dump_to_scratch_and_retireve(containers));
header.print( hashing ); header.print( hashing );
header.print( dump_to_scratch_and_retireve(strings)); header.print( dump_to_scratch_and_retireve(strings));
// header.print( filesystem ); header.print( dump_to_scratch_and_retireve(filesystem));
// header.print( timing ); header.print( timing );
header.print_fmt( "\nGEN_NS_END\n" ); header.print_fmt( "\nGEN_NS_END\n" );
header.print_fmt( roll_own_dependencies_guard_end ); header.print_fmt( roll_own_dependencies_guard_end );
#pragma endregion Print Dependencies #pragma endregion Print Dependencies

View File

@ -5,7 +5,7 @@
using namespace gen; using namespace gen;
// Used to know what slot the array will be for generic selection // Used to know what slot the array will be for generic selection
global s32 ArrayDefinitionCounter = 0; global s32 Array_DefinitionCounter = 0;
CodeBody gen_array_base() CodeBody gen_array_base()
{ {
@ -34,15 +34,19 @@ CodeBody gen_array( StrC type, StrC array_name )
#pragma push_macro( "GEN_ASSERT" ) #pragma push_macro( "GEN_ASSERT" )
#pragma push_macro( "rcast" ) #pragma push_macro( "rcast" )
#pragma push_macro( "cast" ) #pragma push_macro( "cast" )
#pragma push_macro( "typeof" )
#pragma push_macro( "forceinline" )
#undef GEN_ASSERT #undef GEN_ASSERT
#undef rcast #undef rcast
#undef cast #undef cast
#undef typeof
#undef forceinline
CodeBody result = parse_global_body( token_fmt( "array_type", (StrC)array_type, "fn", (StrC)fn, "type", (StrC)type CodeBody result = parse_global_body( token_fmt( "array_type", (StrC)array_type, "fn", (StrC)fn, "type", (StrC)type
, stringize( , stringize(
typedef <type>* <array_type>; typedef <type>* <array_type>;
void <fn>_init ( <array_type>* self, AllocatorInfo allocator ); <array_type> <fn>_init ( AllocatorInfo allocator );
void <fn>_init_reserve ( <array_type>* self, AllocatorInfo allocator, usize capacity ); <array_type> <fn>_init_reserve ( AllocatorInfo allocator, usize capacity );
bool <fn>_append_array ( <array_type>* self, <array_type> other ); bool <fn>_append_array ( <array_type>* self, <array_type> other );
bool <fn>_append ( <array_type>* self, <type> value ); bool <fn>_append ( <array_type>* self, <type> value );
bool <fn>_append_items ( <array_type>* self, <type>* items, usize item_num ); bool <fn>_append_items ( <array_type>* self, <type>* items, usize item_num );
@ -60,33 +64,40 @@ CodeBody gen_array( StrC type, StrC array_name )
bool <fn>_resize ( <array_type>* self, usize num ); bool <fn>_resize ( <array_type>* self, usize num );
bool <fn>_set_capacity ( <array_type>* self, usize new_capacity ); bool <fn>_set_capacity ( <array_type>* self, usize new_capacity );
void <fn>_init( <array_type>* self, AllocatorInfo allocator ) forceinline
<array_type> <fn>_init( AllocatorInfo allocator )
{ {
size_t initial_size = array_grow_formula(0); size_t initial_size = array_grow_formula(0);
array_init_reserve( * self, allocator, initial_size ); return array_init_reserve( <array_type>, allocator, initial_size );
} }
void <fn>_init_reserve( <array_type>* self, AllocatorInfo allocator, usize capacity ) inline
<array_type> <fn>_init_reserve( AllocatorInfo allocator, usize capacity )
{ {
GEN_ASSERT(capacity > 0);
ArrayHeader* header = rcast(ArrayHeader*, alloc(allocator, sizeof(ArrayHeader) + sizeof(<type>) * capacity)); ArrayHeader* header = rcast(ArrayHeader*, alloc(allocator, sizeof(ArrayHeader) + sizeof(<type>) * capacity));
if (header == nullptr) if (header == nullptr)
self = nullptr; return nullptr;
header->Allocator = allocator; header->Allocator = allocator;
header->Capacity = capacity; header->Capacity = capacity;
header->Num = 0; header->Num = 0;
self = rcast(<array_type>*, header + 1); return rcast(<type>*, header + 1);
} }
forceinline
bool <fn>_append_array( <array_type>* self, <array_type> other ) bool <fn>_append_array( <array_type>* self, <array_type> other )
{ {
return array_append_items( * self, (<array_type>)other, <fn>_num(other)); return array_append_items( * self, (<array_type>)other, <fn>_num(other));
} }
inline
bool <fn>_append( <array_type>* self, <type> value ) bool <fn>_append( <array_type>* self, <type> value )
{ {
GEN_ASSERT( self != nullptr);
GEN_ASSERT(* self != nullptr);
ArrayHeader* header = array_get_header( * self ); ArrayHeader* header = array_get_header( * self );
if ( header->Num == header->Capacity ) if ( header->Num == header->Capacity )
@ -103,8 +114,13 @@ CodeBody gen_array( StrC type, StrC array_name )
return true; return true;
} }
inline
bool <fn>_append_items( <array_type>* self, <type>* items, usize item_num ) bool <fn>_append_items( <array_type>* self, <type>* items, usize item_num )
{ {
GEN_ASSERT( self != nullptr);
GEN_ASSERT(* self != nullptr);
GEN_ASSERT(items != nullptr);
GEN_ASSERT(item_num > 0);
ArrayHeader* header = array_get_header( * self ); ArrayHeader* header = array_get_header( * self );
if ( header->Num + item_num > header->Capacity ) if ( header->Num + item_num > header->Capacity )
@ -121,8 +137,11 @@ CodeBody gen_array( StrC type, StrC array_name )
return true; return true;
} }
inline
bool <fn>_append_at( <array_type>* self, <type> item, usize idx ) bool <fn>_append_at( <array_type>* self, <type> item, usize idx )
{ {
GEN_ASSERT( self != nullptr);
GEN_ASSERT(* self != nullptr);
ArrayHeader* header = array_get_header( * self ); ArrayHeader* header = array_get_header( * self );
if ( idx >= header->Num ) if ( idx >= header->Num )
@ -147,8 +166,11 @@ CodeBody gen_array( StrC type, StrC array_name )
return true; return true;
} }
inline
bool <fn>_append_items_at( <array_type>* self, <type>* items, usize item_num, usize idx ) bool <fn>_append_items_at( <array_type>* self, <type>* items, usize item_num, usize idx )
{ {
GEN_ASSERT( self != nullptr);
GEN_ASSERT(* self != nullptr);
ArrayHeader* header = array_get_header( * self ); ArrayHeader* header = array_get_header( * self );
if ( idx >= header->Num ) if ( idx >= header->Num )
@ -174,8 +196,10 @@ CodeBody gen_array( StrC type, StrC array_name )
return true; return true;
} }
inline
<type>* <fn>_back( <array_type> self ) <type>* <fn>_back( <array_type> self )
{ {
GEN_ASSERT(self != nullptr);
ArrayHeader* header = array_get_header( self ); ArrayHeader* header = array_get_header( self );
if ( header->Num == 0 ) if ( header->Num == 0 )
@ -184,14 +208,19 @@ CodeBody gen_array( StrC type, StrC array_name )
return self + header->Num - 1; return self + header->Num - 1;
} }
inline
void <fn>_clear( <array_type> self ) void <fn>_clear( <array_type> self )
{ {
GEN_ASSERT(self != nullptr);
ArrayHeader* header = array_get_header( self ); ArrayHeader* header = array_get_header( self );
header->Num = 0; header->Num = 0;
} }
inline
bool <fn>_fill( <array_type> self, usize begin, usize end, <type> value ) bool <fn>_fill( <array_type> self, usize begin, usize end, <type> value )
{ {
GEN_ASSERT(self != nullptr);
GEN_ASSERT(begin <= end);
ArrayHeader* header = array_get_header( self ); ArrayHeader* header = array_get_header( self );
if ( begin < 0 || end >= header->Num ) if ( begin < 0 || end >= header->Num )
@ -203,17 +232,24 @@ CodeBody gen_array( StrC type, StrC array_name )
return true; return true;
} }
inline
void <fn>_free( <array_type>* self ) void <fn>_free( <array_type>* self )
{ {
GEN_ASSERT( self != nullptr);
GEN_ASSERT(* self != nullptr);
ArrayHeader* header = array_get_header( * self ); ArrayHeader* header = array_get_header( * self );
allocator_free( header->Allocator, header ); allocator_free( header->Allocator, header );
self = NULL; self = NULL;
} }
inline
bool <fn>_grow( <array_type>* self, usize min_capacity ) bool <fn>_grow( <array_type>* self, usize min_capacity )
{ {
ArrayHeader* header = array_get_header( *self ); GEN_ASSERT( self != nullptr);
usize new_capacity = array_grow_formula( header->Capacity ); GEN_ASSERT(* self != nullptr);
GEN_ASSERT( min_capacity > 0 );
ArrayHeader* header = array_get_header( *self );
usize new_capacity = array_grow_formula( header->Capacity );
if ( new_capacity < min_capacity ) if ( new_capacity < min_capacity )
new_capacity = min_capacity; new_capacity = min_capacity;
@ -221,13 +257,17 @@ CodeBody gen_array( StrC type, StrC array_name )
return array_set_capacity( self, new_capacity ); return array_set_capacity( self, new_capacity );
} }
forceinline
usize <fn>_num( <array_type> self ) usize <fn>_num( <array_type> self )
{ {
GEN_ASSERT( self != nullptr);
return array_get_header(self)->Num; return array_get_header(self)->Num;
} }
inline
<type> <fn>_pop( <array_type> self ) <type> <fn>_pop( <array_type> self )
{ {
GEN_ASSERT( self != nullptr);
ArrayHeader* header = array_get_header( self ); ArrayHeader* header = array_get_header( self );
GEN_ASSERT( header->Num > 0 ); GEN_ASSERT( header->Num > 0 );
@ -236,8 +276,10 @@ CodeBody gen_array( StrC type, StrC array_name )
return result; return result;
} }
forceinline
void <fn>_remove_at( <array_type> self, usize idx ) void <fn>_remove_at( <array_type> self, usize idx )
{ {
GEN_ASSERT( self != nullptr);
ArrayHeader* header = array_get_header( self ); ArrayHeader* header = array_get_header( self );
GEN_ASSERT( idx < header->Num ); GEN_ASSERT( idx < header->Num );
@ -245,8 +287,12 @@ CodeBody gen_array( StrC type, StrC array_name )
header->Num--; header->Num--;
} }
inline
bool <fn>_reserve( <array_type>* self, usize new_capacity ) bool <fn>_reserve( <array_type>* self, usize new_capacity )
{ {
GEN_ASSERT( self != nullptr);
GEN_ASSERT(* self != nullptr);
GEN_ASSERT(new_capacity > 0);
ArrayHeader* header = array_get_header( * self ); ArrayHeader* header = array_get_header( * self );
if ( header->Capacity < new_capacity ) if ( header->Capacity < new_capacity )
@ -255,8 +301,12 @@ CodeBody gen_array( StrC type, StrC array_name )
return true; return true;
} }
inline
bool <fn>_resize( <array_type>* self, usize num ) bool <fn>_resize( <array_type>* self, usize num )
{ {
GEN_ASSERT( self != nullptr);
GEN_ASSERT(* self != nullptr);
GEN_ASSERT(num > 0);
ArrayHeader* header = array_get_header( * self ); ArrayHeader* header = array_get_header( * self );
if ( header->Capacity < num ) if ( header->Capacity < num )
@ -271,26 +321,34 @@ CodeBody gen_array( StrC type, StrC array_name )
return true; return true;
} }
inline
bool <fn>_set_capacity( <array_type>* self, usize new_capacity ) bool <fn>_set_capacity( <array_type>* self, usize new_capacity )
{ {
GEN_ASSERT( self != nullptr);
GEN_ASSERT(* self != nullptr);
GEN_ASSERT( new_capacity > 0 );
ArrayHeader* header = array_get_header( * self ); ArrayHeader* header = array_get_header( * self );
if ( new_capacity == header->Capacity ) if ( new_capacity == header->Capacity )
return true; return true;
if ( new_capacity < header->Num ) if ( new_capacity < header->Num )
{
header->Num = new_capacity; header->Num = new_capacity;
return true;
}
usize size = sizeof( ArrayHeader ) + sizeof( <type> ) * new_capacity; usize size = sizeof( ArrayHeader ) + sizeof( <type> ) * new_capacity;
ArrayHeader* new_header = cast( ArrayHeader*, alloc( header->Allocator, size )); ArrayHeader* new_header = cast( ArrayHeader*, alloc( header->Allocator, size ));
if ( new_header == NULL ) if ( new_header == NULL )
return false; return false;
mem_move( new_header, header, sizeof( ArrayHeader ) + sizeof( <type> ) * header->Num ); mem_move( new_header, header, sizeof( ArrayHeader ) + sizeof( <type> ) * header->Num );
new_header->Capacity = new_capacity;
allocator_free( header->Allocator, & header ); allocator_free( header->Allocator, & header );
new_header->Capacity = new_capacity;
* self = cast( <type>*, new_header + 1 ); * self = cast( <type>*, new_header + 1 );
return true; return true;
} }
@ -298,9 +356,11 @@ CodeBody gen_array( StrC type, StrC array_name )
#pragma pop_macro( "GEN_ASSERT" ) #pragma pop_macro( "GEN_ASSERT" )
#pragma pop_macro( "rcast" ) #pragma pop_macro( "rcast" )
#pragma pop_macro( "cast" ) #pragma pop_macro( "cast" )
#pragma pop_macro( "typeof" )
#pragma pop_macro( "forceinline" )
++ ArrayDefinitionCounter; ++ Array_DefinitionCounter;
StrC slot_str = String::fmt_buf(GlobalAllocator, "%d", ArrayDefinitionCounter).to_strc(); StrC slot_str = String::fmt_buf(GlobalAllocator, "%d", Array_DefinitionCounter).to_strc();
Code generic_interface_slot = untyped_str(token_fmt( "type_delimiter", (StrC)array_type, "slot", (StrC)slot_str, Code generic_interface_slot = untyped_str(token_fmt( "type_delimiter", (StrC)array_type, "slot", (StrC)slot_str,
R"(#define GENERIC_SLOT_<slot>__array_init <type_delimiter>, <type_delimiter>_init R"(#define GENERIC_SLOT_<slot>__array_init <type_delimiter>, <type_delimiter>_init
@ -335,67 +395,23 @@ R"(#define GENERIC_SLOT_<slot>__array_init <type_delimiter>, <type_deli
)); ));
}; };
constexpr bool array_by_ref = true;
Code gen_array_generic_selection_function_macro( StrC macro_name, bool by_ref = false )
{
local_persist
String define_builder = String::make_reserve(GlobalAllocator, kilobytes(64));
define_builder.clear();
StrC macro_begin = token_fmt( "macro_name", (StrC)macro_name,
R"(#define <macro_name>(selector_arg, ...) _Generic( \
(selector_arg), /* Select Via Expression*/ \
/* Extendibility slots: */ \
)"
);
define_builder.append(macro_begin);
for ( s32 slot = 1; slot <= ArrayDefinitionCounter; ++ slot )
{
StrC slot_str = String::fmt_buf(GlobalAllocator, "%d", slot).to_strc();
if (slot == ArrayDefinitionCounter)
{
define_builder.append( token_fmt( "macro_name", macro_name, "slot", slot_str,
R"( GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT_LAST( GENERIC_SLOT_<slot>__<macro_name> ) \
)"
));
continue;
}
define_builder.append( token_fmt( "macro_name", macro_name, "slot", slot_str,
R"( GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( GENERIC_SLOT_<slot>__<macro_name> ) \
)"
));
}
if (by_ref)
define_builder.append(txt(")\tGEN_RESOLVED_FUNCTION_CALL( & selector_arg, __VA_ARGS__ )"));
else
define_builder.append(txt(")\tGEN_RESOLVED_FUNCTION_CALL( selector_arg, __VA_ARGS__ )"));
// Add gap for next definition
define_builder.append(txt("\n\n"));
Code macro = untyped_str(define_builder.to_strc());
return macro;
}
CodeBody gen_array_generic_selection_interface() CodeBody gen_array_generic_selection_interface()
{ {
CodeBody interface_defines = def_body(CT_Global_Body); CodeBody interface_defines = def_body(CT_Global_Body);
interface_defines.append( gen_array_generic_selection_function_macro(txt("array_init"), array_by_ref) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_init"), GenericSel_Direct_Type ));
interface_defines.append( gen_array_generic_selection_function_macro(txt("array_init_reserve"), array_by_ref) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_init_reserve"), GenericSel_Direct_Type ));
interface_defines.append( gen_array_generic_selection_function_macro(txt("array_append"), array_by_ref) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_append"), GenericSel_By_Ref ));
interface_defines.append( gen_array_generic_selection_function_macro(txt("array_append_items"), array_by_ref) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_append_items"), GenericSel_By_Ref ));
interface_defines.append( gen_array_generic_selection_function_macro(txt("array_back")) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_back"), GenericSel_Default, GenericSel_One_Arg ));
interface_defines.append( gen_array_generic_selection_function_macro(txt("array_clear")) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_clear"), GenericSel_Default, GenericSel_One_Arg ));
interface_defines.append( gen_array_generic_selection_function_macro(txt("array_fill")) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_fill")) );
interface_defines.append( gen_array_generic_selection_function_macro(txt("array_free"), array_by_ref) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_free"), GenericSel_By_Ref, GenericSel_One_Arg ) );
interface_defines.append( gen_array_generic_selection_function_macro(txt("array_grow")) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_grow")) );
interface_defines.append( gen_array_generic_selection_function_macro(txt("array_num")) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_num"), GenericSel_Default, GenericSel_One_Arg ));
interface_defines.append( gen_array_generic_selection_function_macro(txt("arary_pop")) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_pop"), GenericSel_Default, GenericSel_One_Arg ));
interface_defines.append( gen_array_generic_selection_function_macro(txt("array_remove_at")) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_remove_at")) );
interface_defines.append( gen_array_generic_selection_function_macro(txt("arary_reserve"), array_by_ref) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_reserve"), GenericSel_By_Ref) );
interface_defines.append( gen_array_generic_selection_function_macro(txt("array_set_capacity")) ); interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_resize"), GenericSel_By_Ref) );
interface_defines.append( gen_generic_selection_function_macro( Array_DefinitionCounter, txt("array_set_capacity")) );
return interface_defines; return interface_defines;
} }

View File

@ -5,11 +5,13 @@
using namespace gen; using namespace gen;
global s32 HashTable_DefinitionCounter = 0;
CodeBody gen_hashtable_base() CodeBody gen_hashtable_base()
{ {
CodeBody struct_def = parse_global_body( code( CodeBody struct_def = parse_global_body( code(
typedef struct HT_FindResult HT_FindResult; typedef struct HT_FindResult_Def HT_FindResult;
struct HT_FindResult struct HT_FindResult_Def
{ {
ssize HashIndex; ssize HashIndex;
ssize PrevIndex; ssize PrevIndex;
@ -22,7 +24,8 @@ R"(#define HashTable(_type) struct _type
)" )"
)); ));
return def_global_body(args(struct_def, define_type)); Code define_critical_load_scale = untyped_str(txt("#define HashTable_CriticalLoadScale 0.7f\n"));
return def_global_body(args(struct_def, define_type, define_critical_load_scale));
} }
CodeBody gen_hashtable( StrC type, StrC hashtable_name ) CodeBody gen_hashtable( StrC type, StrC hashtable_name )
@ -46,8 +49,7 @@ CodeBody gen_hashtable( StrC type, StrC hashtable_name )
stringize( stringize(
typedef struct HashTable_<type> <tbl_type>; typedef struct HashTable_<type> <tbl_type>;
typedef struct HTE_<tbl_name> HTE_<tbl_name>; typedef struct HTE_<tbl_name> HTE_<tbl_name>;
struct HTE_<tbl_name> struct HTE_<tbl_name> {
{
u64 Key; u64 Key;
ssize Next; ssize Next;
<type> Value; <type> Value;
@ -61,8 +63,17 @@ CodeBody gen_hashtable( StrC type, StrC hashtable_name )
#pragma push_macro( "GEN_ASSERT" ) #pragma push_macro( "GEN_ASSERT" )
#pragma push_macro( "GEN_ASSERT_NOT_NULL" ) #pragma push_macro( "GEN_ASSERT_NOT_NULL" )
#pragma push_macro( "rcast" )
#pragma push_macro( "cast" )
#pragma push_macro( "typeof" )
#pragma push_macro( "forceinline" )
#undef GEN_ASSERT #undef GEN_ASSERT
#undef GEN_ASSERT_NOT_NULL #undef GEN_ASSERT_NOT_NULL
#undef GEN_ASSERT
#undef rcast
#undef cast
#undef typeof
#undef forceinline
CodeBody hashtable_def = parse_global_body( token_fmt( CodeBody hashtable_def = parse_global_body( token_fmt(
"type", (StrC) type, "type", (StrC) type,
"tbl_name", (StrC) hashtable_name, "tbl_name", (StrC) hashtable_name,
@ -72,146 +83,151 @@ CodeBody gen_hashtable( StrC type, StrC hashtable_name )
"array_entry", (StrC) entry_array_name, "array_entry", (StrC) entry_array_name,
"fn_array", (StrC) entry_array_fn_ns, "fn_array", (StrC) entry_array_fn_ns,
stringize( stringize(
struct HashTable_<type> struct HashTable_<type> {
{
Array_ssize Hashes; Array_ssize Hashes;
<array_entry> Entries; <array_entry> Entries;
}; };
<tbl_type> <fn>_make ( AllocatorInfo allocator ); <tbl_type> <fn>_init ( AllocatorInfo allocator );
<tbl_type> <fn>_make_reserve( AllocatorInfo allocator, ssize num ); <tbl_type> <fn>_init_reserve( AllocatorInfo allocator, ssize num );
void <fn>_clear ( <tbl_type> self ); void <fn>_clear ( <tbl_type> self );
void <fn>_destroy ( <tbl_type> self ); void <fn>_destroy ( <tbl_type>* self );
<type>* <fn>_get ( <tbl_type> self, u64 key ); <type>* <fn>_get ( <tbl_type> self, u64 key );
void <fn>_map ( <tbl_type> self, <tbl_type>_MapProc map_proc ); void <fn>_map ( <tbl_type> self, <tbl_type>_MapProc map_proc );
void <fn>_map_mut ( <tbl_type> self, <tbl_type>_MapMutProc map_proc ); void <fn>_map_mut ( <tbl_type> self, <tbl_type>_MapMutProc map_proc );
void <fn>_grow ( <tbl_type>* self ); void <fn>_grow ( <tbl_type>* self );
void <fn>_rehash ( <tbl_type>* self, ssize new_num ); void <fn>_rehash ( <tbl_type>* self, ssize new_num );
void <fn>_rehash_fast ( <tbl_type> self ); void <fn>_rehash_fast ( <tbl_type> self );
void <fn>_remove ( <tbl_type> self, u64 key ); void <fn>_remove ( <tbl_type> self, u64 key );
void <fn>_remove_entry( <tbl_type> self, ssize idx ); void <fn>_remove_entry( <tbl_type> self, ssize idx );
void <fn>_set ( <tbl_type>* self, u64 key, <type> value ); void <fn>_set ( <tbl_type>* self, u64 key, <type> value );
ssize <fn>_slot ( <tbl_type> self, u64 key ); ssize <fn>_slot ( <tbl_type> self, u64 key );
ssize <fn>__add_entry( <tbl_type> self, u64 key ); ssize <fn>__add_entry( <tbl_type>* self, u64 key );
HT_FindResult <fn>__find ( <tbl_type> self, u64 key ); HT_FindResult <fn>__find ( <tbl_type> self, u64 key );
b32 <fn>__full ( <tbl_type> self ); b32 <fn>__full ( <tbl_type> self );
<tbl_type> <fn>_make( AllocatorInfo allocator ) <tbl_type> <fn>init( AllocatorInfo allocator )
{ {
<tbl_type> <tbl_type> result = hashtable_init_reserve(<tbl_type>, allocator, 8);
result = { NULL, NULL };
array_init(result.Hashes, allocator );
array_init(result.Entries, allocator );
return result; return result;
} }
<tbl_type> <fn>_make_reserve( AllocatorInfo allocator, ssize num ) <tbl_type> <fn>_init_reserve( AllocatorInfo allocator, ssize num )
{ {
<tbl_type> <tbl_type> result = { NULL, NULL };
result = { NULL, NULL }; result.Hashes = array_init_reserve(Array_ssize, allocator, num );
array_init_reserve(result.Hashes, allocator, num ); array_get_header(result.Hashes)->Num = num;
array_init_reserve(result.Entries, allocator, num ); array_resize(result.Hashes, num);
array_fill(result.Hashes, 0, num, -1);
result.Entries = array_init_reserve(<array_entry>, allocator, num );
return result; return result;
} }
void <fn>_clear( <tbl_type> self ) void <fn>_clear( <tbl_type> self )
{ {
for ( ssize idx = 0; idx < array_get_header( self.Hashes )->Num; idx++ ) GEN_ASSERT_NOT_NULL(self.Hashes);
self.Hashes[idx] = -1; GEN_ASSERT_NOT_NULL(self.Entries);
array_clear( self.Hashes );
array_clear( self.Entries ); array_clear( self.Entries );
s32 what = array_num(self.Hashes);
array_fill( self.Hashes, 0, what, (ssize)-1 );
} }
void <fn>_destroy( <tbl_type> self ) void <fn>_destroy( <tbl_type>* self )
{ {
if ( self.Hashes && self.Entries ) GEN_ASSERT_NOT_NULL(self);
{ GEN_ASSERT_NOT_NULL(self->Hashes);
array_free( self.Hashes ); GEN_ASSERT_NOT_NULL(self->Entries);
array_free( self.Entries ); if ( self->Hashes && array_get_header(self->Hashes)->Capacity) {
array_free( self->Hashes );
array_free( self->Entries );
} }
} }
<type>* <fn>_get( <tbl_type> self, u64 key ) <type>* <fn>_get( <tbl_type> self, u64 key )
{ {
GEN_ASSERT_NOT_NULL(self.Hashes);
GEN_ASSERT_NOT_NULL(self.Entries);
ssize idx = <fn>__find( self, key ).EntryIndex; ssize idx = <fn>__find( self, key ).EntryIndex;
if ( idx > 0 ) if ( idx > 0 )
return & self.Entries[idx].Value; return & self.Entries[idx].Value;
return NULL; return nullptr;
} }
void <fn>_map( <tbl_type> self, <tbl_type>_MapProc map_proc ) void <fn>_map( <tbl_type> self, <tbl_type>_MapProc map_proc )
{ {
GEN_ASSERT_NOT_NULL(self.Hashes);
GEN_ASSERT_NOT_NULL(self.Entries);
GEN_ASSERT_NOT_NULL( map_proc ); GEN_ASSERT_NOT_NULL( map_proc );
for ( ssize idx = 0; idx < array_get_header( self.Entries )->Num; idx++ ) for ( ssize idx = 0; idx < array_get_header( self.Entries )->Num; idx++ ) {
{
map_proc( self, self.Entries[idx].Key, self.Entries[idx].Value ); map_proc( self, self.Entries[idx].Key, self.Entries[idx].Value );
} }
} }
void <fn>_map_mut( <tbl_type> self, <tbl_type>_MapMutProc map_proc ) void <fn>_map_mut( <tbl_type> self, <tbl_type>_MapMutProc map_proc )
{ {
GEN_ASSERT_NOT_NULL(self.Hashes);
GEN_ASSERT_NOT_NULL(self.Entries);
GEN_ASSERT_NOT_NULL( map_proc ); GEN_ASSERT_NOT_NULL( map_proc );
for ( ssize idx = 0; idx < array_get_header( self.Entries )->Num; idx++ ) for ( ssize idx = 0; idx < array_get_header( self.Entries )->Num; idx++ ) {
{
map_proc( self, self.Entries[idx].Key, & self.Entries[idx].Value ); map_proc( self, self.Entries[idx].Key, & self.Entries[idx].Value );
} }
} }
void <fn>_grow( <tbl_type>* self ) void <fn>_grow( <tbl_type>* self )
{ {
GEN_ASSERT_NOT_NULL(self);
GEN_ASSERT_NOT_NULL(self->Hashes);
GEN_ASSERT_NOT_NULL(self->Entries);
ssize new_num = array_grow_formula( array_get_header( self->Entries )->Num ); ssize new_num = array_grow_formula( array_get_header( self->Entries )->Num );
<fn>_rehash( self, new_num ); hashtable_rehash( self, new_num );
} }
void <fn>_rehash( <tbl_type>* self, ssize new_num ) void <fn>_rehash( <tbl_type>* self, ssize new_num )
{ {
GEN_ASSERT_NOT_NULL(self);
GEN_ASSERT_NOT_NULL(self->Hashes);
GEN_ASSERT_NOT_NULL(self->Entries);
GEN_ASSERT( new_num > 0 );
ssize idx; ssize idx;
ssize last_added_index; ssize last_added_index;
ArrayHeader* old_hash_header = array_get_header( self->Hashes ); ArrayHeader* old_hash_header = array_get_header( self->Hashes );
ArrayHeader* old_entries_header = array_get_header( self->Entries ); ArrayHeader* old_entries_header = array_get_header( self->Entries );
<tbl_type> new_tbl = <fn>_make_reserve( old_hash_header->Allocator, old_hash_header->Num ); <tbl_type> new_tbl = hashtable_init_reserve( <tbl_type>, old_hash_header->Allocator, old_hash_header->Num );
ArrayHeader* new_hash_header = array_get_header( new_tbl.Hashes ); ArrayHeader* new_hash_header = array_get_header( new_tbl.Hashes );
for ( idx = 0; idx < new_hash_header->Num; idx++ ) for (ssize idx = 0; idx < cast(ssize, old_hash_header->Num); ++idx)
new_tbl.Hashes[idx] = -1;
for ( idx = 0; idx < old_entries_header->Num; idx++ )
{ {
<entry_type>* entry; <entry_type>* entry = & self->Entries[idx];
HT_FindResult find_result; HT_FindResult find_result;
if ( new_hash_header->Num == 0 ) find_result = <fn>__find( new_tbl, entry->Key);
<fn>_grow( & new_tbl ); last_added_index = <fn>__add_entry( & new_tbl, entry->Key);
entry = & self->Entries[ idx ]; if (find_result.PrevIndex < 0)
find_result = <fn>__find( new_tbl, entry->Key ); new_tbl.Hashes[find_result.HashIndex] = last_added_index;
last_added_index = <fn>__add_entry( new_tbl, entry->Key );
if ( find_result.PrevIndex < 0 )
new_tbl.Hashes[ find_result.HashIndex ] = last_added_index;
else else
new_tbl.Entries[ find_result.PrevIndex ].Next = last_added_index; new_tbl.Entries[find_result.PrevIndex].Next = last_added_index;
new_tbl.Entries[ last_added_index ].Next = find_result.EntryIndex; new_tbl.Entries[last_added_index].Next = find_result.EntryIndex;
new_tbl.Entries[ last_added_index ].Value = entry->Value; new_tbl.Entries[last_added_index].Value = entry->Value;
} }
<fn>_destroy( *self ); <fn>_destroy( self );
* self = new_tbl; * self = new_tbl;
} }
void <fn>_rehash_fast( <tbl_type> self ) void <fn>_rehash_fast( <tbl_type> self )
{ {
GEN_ASSERT_NOT_NULL(self.Hashes);
GEN_ASSERT_NOT_NULL(self.Entries);
ssize idx; ssize idx;
for ( idx = 0; idx < array_get_header( self.Entries )->Num; idx++ ) for ( idx = 0; idx < array_get_header( self.Entries )->Num; idx++ )
@ -237,44 +253,47 @@ CodeBody gen_hashtable( StrC type, StrC hashtable_name )
void <fn>_remove( <tbl_type> self, u64 key ) void <fn>_remove( <tbl_type> self, u64 key )
{ {
GEN_ASSERT_NOT_NULL(self.Hashes);
GEN_ASSERT_NOT_NULL(self.Entries);
HT_FindResult find_result = <fn>__find( self, key ); HT_FindResult find_result = <fn>__find( self, key );
if ( find_result.EntryIndex >= 0 ) if ( find_result.EntryIndex >= 0 ) {
{
array_remove_at( self.Entries, find_result.EntryIndex ); array_remove_at( self.Entries, find_result.EntryIndex );
<fn>_rehash_fast( self ); hashtable_rehash_fast( self );
} }
} }
void <fn>_remove_entry( <tbl_type> self, ssize idx ) void <fn>_remove_entry( <tbl_type> self, ssize idx )
{ {
GEN_ASSERT_NOT_NULL(self.Hashes);
GEN_ASSERT_NOT_NULL(self.Entries);
array_remove_at( self.Entries, idx ); array_remove_at( self.Entries, idx );
} }
void <fn>_set( <tbl_type>* self, u64 key, <type> value ) void <fn>_set( <tbl_type>* self, u64 key, <type> value )
{ {
GEN_ASSERT_NOT_NULL(self);
GEN_ASSERT_NOT_NULL(self->Hashes);
GEN_ASSERT_NOT_NULL(self->Entries);
ssize idx; ssize idx;
HT_FindResult find_result; HT_FindResult find_result;
if ( array_get_header( self->Hashes )->Num == 0 ) if ( array_get_header( self->Hashes )->Num == 0 )
<fn>_grow( self ); hashtable_grow( self );
find_result = <fn>__find( * self, key ); find_result = <fn>__find( * self, key );
if ( find_result.EntryIndex >= 0 ) if ( find_result.EntryIndex >= 0 ) {
{
idx = find_result.EntryIndex; idx = find_result.EntryIndex;
} }
else else
{ {
idx = <fn>__add_entry( * self, key ); idx = <fn>__add_entry( self, key );
if ( find_result.PrevIndex >= 0 ) if ( find_result.PrevIndex >= 0 ) {
{
self->Entries[ find_result.PrevIndex ].Next = idx; self->Entries[ find_result.PrevIndex ].Next = idx;
} }
else else {
{
self->Hashes[ find_result.HashIndex ] = idx; self->Hashes[ find_result.HashIndex ] = idx;
} }
} }
@ -282,11 +301,13 @@ CodeBody gen_hashtable( StrC type, StrC hashtable_name )
self->Entries[ idx ].Value = value; self->Entries[ idx ].Value = value;
if ( <fn>__full( * self ) ) if ( <fn>__full( * self ) )
<fn>_grow( self ); hashtable_grow( self );
} }
ssize <fn>_slot( <tbl_type> self, u64 key ) ssize <fn>_slot( <tbl_type> self, u64 key )
{ {
GEN_ASSERT_NOT_NULL(self.Hashes);
GEN_ASSERT_NOT_NULL(self.Entries);
for ( ssize idx = 0; idx < array_get_header( self.Hashes )->Num; ++idx ) for ( ssize idx = 0; idx < array_get_header( self.Hashes )->Num; ++idx )
if ( self.Hashes[ idx ] == key ) if ( self.Hashes[ idx ] == key )
return idx; return idx;
@ -294,22 +315,26 @@ CodeBody gen_hashtable( StrC type, StrC hashtable_name )
return -1; return -1;
} }
ssize <fn>__add_entry( <tbl_type> self, u64 key ) ssize <fn>__add_entry( <tbl_type>* self, u64 key )
{ {
GEN_ASSERT_NOT_NULL(self);
GEN_ASSERT_NOT_NULL(self->Hashes);
GEN_ASSERT_NOT_NULL(self->Entries);
ssize idx; ssize idx;
<entry_type> entry = { key, -1 }; <entry_type> entry = { key, -1 };
idx = array_get_header( self.Entries )->Num; idx = array_get_header( self->Entries )->Num;
array_append( self.Entries, entry ); array_append( self->Entries, entry );
return idx; return idx;
} }
HT_FindResult <fn>__find( <tbl_type> self, u64 key ) HT_FindResult <fn>__find( <tbl_type> self, u64 key )
{ {
GEN_ASSERT_NOT_NULL(self.Hashes);
GEN_ASSERT_NOT_NULL(self.Entries);
HT_FindResult result = { -1, -1, -1 }; HT_FindResult result = { -1, -1, -1 };
ArrayHeader* hash_header = array_get_header( self.Hashes ); ArrayHeader* hash_header = array_get_header( self.Hashes );
if ( hash_header->Num > 0 ) if ( hash_header->Num > 0 )
{ {
result.HashIndex = key % hash_header->Num; result.HashIndex = key % hash_header->Num;
@ -330,14 +355,46 @@ CodeBody gen_hashtable( StrC type, StrC hashtable_name )
b32 <fn>__full( <tbl_type> self ) b32 <fn>__full( <tbl_type> self )
{ {
GEN_ASSERT_NOT_NULL(self.Hashes);
GEN_ASSERT_NOT_NULL(self.Entries);
ArrayHeader* hash_header = array_get_header( self.Hashes ); ArrayHeader* hash_header = array_get_header( self.Hashes );
ArrayHeader* entries_header = array_get_header( self.Entries ); ArrayHeader* entries_header = array_get_header( self.Entries );
return 0.75f * hash_header->Num < entries_header->Num; usize critical_load = cast(usize, HashTable_CriticalLoadScale * cast(f32, hash_header->Num));
b32 result = entries_header->Num > critical_load;
return result;
} }
))); )));
#pragma pop_macro( "GEN_ASSERT" ) #pragma pop_macro( "GEN_ASSERT" )
#pragma pop_macro( "GEN_ASSERT_NOT_NULL" ) #pragma pop_macro( "GEN_ASSERT_NOT_NULL" )
#pragma pop_macro( "rcast" )
#pragma pop_macro( "cast" )
#pragma pop_macro( "typeof" )
#pragma pop_macro( "forceinline" )
++ HashTable_DefinitionCounter;
StrC slot_str = String::fmt_buf(GlobalAllocator, "%d", Array_DefinitionCounter).to_strc();
Code generic_interface_slot = untyped_str(token_fmt( "type_delimiter", (StrC)tbl_type, "slot", (StrC)slot_str,
R"(#define GENERIC_SLOT_<slot>__hashtable_init <type_delimiter>, <type_delimiter>_init
#define GENERIC_SLOT_<slot>__hashtable_init_reserve <type_delimiter>, <type_delimiter>_init_reserve
#define GENERIC_SLOT_<slot>__hashtable_clear <type_delimiter>, <type_delimiter>_clear
#define GENERIC_SLOT_<slot>__hashtable_destroy <type_delimiter>*, <type_delimiter>_destroy
#define GENERIC_SLOT_<slot>__hashtable_get <type_delimiter>, <type_delimiter>_get
#define GENERIC_SLOT_<slot>__hashtable_map <type_delimiter>, <type_delimiter>_map
#define GENERIC_SLOT_<slot>__hashtable_map_mut <type_delimiter>, <type_delimiter>_map_mut
#define GENERIC_SLOT_<slot>__hashtable_grow <type_delimiter>*, <type_delimiter>_grow
#define GENERIC_SLOT_<slot>__hashtable_rehash <type_delimiter>*, <type_delimiter>_rehash
#define GENERIC_SLOT_<slot>__hashtable_rehash_fast <type_delimiter>, <type_delimiter>_rehash_fast
#define GENERIC_SLOT_<slot>__hashtable_remove_entry <type_delimiter>, <type_delimiter>_remove_entry
#define GENERIC_SLOT_<slot>__hashtable_set <type_delimiter>*, <type_delimiter>_set
#define GENERIC_SLOT_<slot>__hashtable_slot <type_delimiter>, <type_delimiter>_slot
#define GENERIC_SLOT_<slot>__hashtable__add_entry <type_delimiter>*, <type_delimiter>__add_entry
#define GENERIC_SLOT_<slot>__hashtable__find <type_delimiter>, <type_delimiter>__find
#define GENERIC_SLOT_<slot>__hashtable__full <type_delimiter>, <type_delimiter>__full
)"
));
char const* cmt_str = str_fmt_buf( "Name: %.*s Type: %.*s" char const* cmt_str = str_fmt_buf( "Name: %.*s Type: %.*s"
, tbl_type.length(), tbl_type.Data , tbl_type.length(), tbl_type.Data
@ -346,6 +403,8 @@ CodeBody gen_hashtable( StrC type, StrC hashtable_name )
return def_global_body(args( return def_global_body(args(
def_pragma( string_to_strc( string_fmt_buf( GlobalAllocator, "region %S", tbl_type ))), def_pragma( string_to_strc( string_fmt_buf( GlobalAllocator, "region %S", tbl_type ))),
fmt_newline, fmt_newline,
generic_interface_slot,
fmt_newline,
hashtable_types, hashtable_types,
fmt_newline, fmt_newline,
entry_array, entry_array,
@ -355,3 +414,21 @@ CodeBody gen_hashtable( StrC type, StrC hashtable_name )
fmt_newline fmt_newline
)); ));
} }
CodeBody gen_hashtable_generic_selection_interface()
{
CodeBody interface_defines = def_body(CT_Global_Body);
interface_defines.append( gen_generic_selection_function_macro( HashTable_DefinitionCounter, txt("hashtable_init"), GenericSel_Direct_Type ));
interface_defines.append( gen_generic_selection_function_macro( HashTable_DefinitionCounter, txt("hashtable_init_reserve"), GenericSel_Direct_Type ));
interface_defines.append( gen_generic_selection_function_macro( HashTable_DefinitionCounter, txt("hashtable_clear"), GenericSel_Default, GenericSel_One_Arg ));
interface_defines.append( gen_generic_selection_function_macro( HashTable_DefinitionCounter, txt("hashtable_destroy"), GenericSel_By_Ref, GenericSel_One_Arg ) );
interface_defines.append( gen_generic_selection_function_macro( HashTable_DefinitionCounter, txt("hashtable_get") ));
interface_defines.append( gen_generic_selection_function_macro( HashTable_DefinitionCounter, txt("hashtable_grow"), GenericSel_Default, GenericSel_One_Arg ));
interface_defines.append( gen_generic_selection_function_macro( HashTable_DefinitionCounter, txt("hashtable_rehash") ));
interface_defines.append( gen_generic_selection_function_macro( HashTable_DefinitionCounter, txt("hashtable_rehash_fast"), GenericSel_Default, GenericSel_One_Arg ));
interface_defines.append( gen_generic_selection_function_macro( HashTable_DefinitionCounter, txt("hashtable_remove") ));
interface_defines.append( gen_generic_selection_function_macro( HashTable_DefinitionCounter, txt("hashtable_remove_entry") ));
interface_defines.append( gen_generic_selection_function_macro( HashTable_DefinitionCounter, txt("hashtable_set"), GenericSel_By_Ref ));
interface_defines.append( gen_generic_selection_function_macro( HashTable_DefinitionCounter, txt("hashtable_slot") ));
return interface_defines;
}

View File

@ -8,6 +8,12 @@
This is a single header C-Library variant. This is a single header C-Library variant.
Define GEN_IMPLEMENTATION before including this file in a single compilation unit. Define GEN_IMPLEMENTATION before including this file in a single compilation unit.
! ----------------------------------------------------------------------- VERSION: v0.20-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) #if ! defined(GEN_DONT_ENFORCE_GEN_TIME_GUARD) && ! defined(GEN_TIME)
# error Gen.hpp : GEN_TIME not defined # error Gen.hpp : GEN_TIME not defined

View File

@ -1,9 +1,7 @@
// #pragma once #pragma once
// #include "../project/gen.hpp" #include "../project/gen.hpp"
// using namespace gen;
using namespace gen;
b32 ignore_preprocess_cond_block( StrC cond_sig, Code& entry_iter, CodeBody& parsed_body, CodeBody& body ) b32 ignore_preprocess_cond_block( StrC cond_sig, Code& entry_iter, CodeBody& parsed_body, CodeBody& body )
{ {
@ -57,6 +55,90 @@ b32 ignore_preprocess_cond_block( StrC cond_sig, Code& entry_iter, CodeBody& par
return found; return found;
} }
constexpr bool GenericSel_One_Arg = true;
enum GenericSelectionOpts : u32 { GenericSel_Default, GenericSel_By_Ref, GenericSel_Direct_Type };
Code gen_generic_selection_function_macro( s32 num_slots, StrC macro_name, GenericSelectionOpts opts = GenericSel_Default, bool one_arg = false )
{
/* Implements:
#define GEN_FUNCTION_GENERIC_EXAMPLE( selector_arg, ... ) _Generic( \
(selector_arg), \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_2 ) \
... \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT_LAST(FunctionID__ARGS_SIG_N ) \
) GEN_RESOLVED_FUNCTION_CALL( selector_arg )
*/
local_persist
String define_builder = String::make_reserve(GlobalAllocator, kilobytes(64));
define_builder.clear();
StrC macro_begin;
if (opts == GenericSel_Direct_Type) {
macro_begin = token_fmt( "macro_name", (StrC)macro_name,
R"(#define <macro_name>(selector_arg, ...) _Generic( (*(selector_arg*)NULL ), \
)"
);
}
else {
macro_begin = token_fmt( "macro_name", (StrC)macro_name,
R"(#define <macro_name>(selector_arg, ...) _Generic( (selector_arg), \
)"
);
}
define_builder.append(macro_begin);
for ( s32 slot = 1; slot <= num_slots; ++ slot )
{
StrC slot_str = String::fmt_buf(GlobalAllocator, "%d", slot).to_strc();
if (slot == num_slots)
{
define_builder.append( token_fmt( "macro_name", macro_name, "slot", slot_str,
R"( GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT_LAST( GENERIC_SLOT_<slot>__<macro_name> ) \
)"
));
// if ( one_arg )
// define_builder.append(token_fmt( "macro_name", macro_name, stringize(
// default: static_assert(false, "<macro_name>: Failed to select correct function signature (Did you pass the type?)")
// )));
// else
// define_builder.append(token_fmt( "macro_name", macro_name, stringize(
// default: static_assert(false, "<macro_name>: Failed to select correct function signature")
// )));
continue;
}
define_builder.append( token_fmt( "macro_name", macro_name, "slot", slot_str,
R"( GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( GENERIC_SLOT_<slot>__<macro_name> ) \
)"
));
}
if ( ! one_arg )
{
if (opts == GenericSel_By_Ref)
define_builder.append(txt("\t)\tGEN_RESOLVED_FUNCTION_CALL( & selector_arg, __VA_ARGS__ )"));
else if (opts == GenericSel_Direct_Type)
define_builder.append(txt("\t)\tGEN_RESOLVED_FUNCTION_CALL( __VA_ARGS__ )"));
else
define_builder.append(txt("\t)\tGEN_RESOLVED_FUNCTION_CALL( selector_arg, __VA_ARGS__ )"));
}
else
{
if (opts == GenericSel_By_Ref)
define_builder.append(txt("\t)\tGEN_RESOLVED_FUNCTION_CALL( & selector_arg )"));
else if (opts == GenericSel_Direct_Type)
define_builder.append(txt("\t)\tGEN_RESOLVED_FUNCTION_CALL()"));
else
define_builder.append(txt("\t)\tGEN_RESOLVED_FUNCTION_CALL( selector_arg )"));
}
// Add gap for next definition
define_builder.append(txt("\n\n"));
Code macro = untyped_str(define_builder.to_strc());
return macro;
}
CodeFn rename_function_to_unique_symbol(CodeFn fn, StrC optional_prefix = txt("")) CodeFn rename_function_to_unique_symbol(CodeFn fn, StrC optional_prefix = txt(""))
{ {
// Get basic components for the name // Get basic components for the name

View File

@ -8,6 +8,12 @@
This is a single header variant of the library. This is a single header variant of the library.
Define GEN_IMPLEMENTATION before including this file in a single compilation unit. Define GEN_IMPLEMENTATION before including this file in a single compilation unit.
! ----------------------------------------------------------------------- VERSION: v0.20-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) #if ! defined(GEN_DONT_ENFORCE_GEN_TIME_GUARD) && ! defined(GEN_TIME)
# error Gen.hpp : GEN_TIME not defined # error Gen.hpp : GEN_TIME not defined

View File

@ -7,6 +7,12 @@
https://github.com/Ed94/gencpp https://github.com/Ed94/gencpp
This is a variant intended for use with Unreal Engine 5 This is a variant intended for use with Unreal Engine 5
! ----------------------------------------------------------------------- VERSION: v0.20-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) #if ! defined(GEN_DONT_ENFORCE_GEN_TIME_GUARD) && ! defined(GEN_TIME)
# error Gen.hpp : GEN_TIME not defined # error Gen.hpp : GEN_TIME not defined

View File

@ -10,7 +10,7 @@
<IsVirtual>false</IsVirtual> <IsVirtual>false</IsVirtual>
<IsFolder>false</IsFolder> <IsFolder>false</IsFolder>
<BuildCommand>pwsh ./scripts/build.ps1 msvc debug bootstrap</BuildCommand> <BuildCommand>pwsh ./scripts/build.ps1 msvc debug bootstrap</BuildCommand>
<RebuildCommand></RebuildCommand> <RebuildCommand>pwsh ./scripts/build.ps1 msvc debug c_library</RebuildCommand>
<BuildFileCommand></BuildFileCommand> <BuildFileCommand></BuildFileCommand>
<CleanCommand>pwsh ./scripts/clean.ps1</CleanCommand> <CleanCommand>pwsh ./scripts/clean.ps1</CleanCommand>
<BuildWorkingDirectory></BuildWorkingDirectory> <BuildWorkingDirectory></BuildWorkingDirectory>

View File

@ -559,7 +559,11 @@ void to_string( Code self, String* result )
break; break;
case CT_Union: case CT_Union:
to_string( cast(CodeUnion, self), result ); to_string_def( cast(CodeUnion, self), result );
break;
case CT_Union_Fwd:
to_string_fwd( cast(CodeUnion, self), result );
break; break;
case CT_Using: case CT_Using:
@ -778,6 +782,7 @@ bool is_equal( Code self, Code other )
check_member_ast( Attributes ); check_member_ast( Attributes );
check_member_ast( UnderlyingType ); check_member_ast( UnderlyingType );
check_member_ast( Body ); check_member_ast( Body );
check_member_ast( UnderlyingTypeMacro );
return true; return true;
} }
@ -789,6 +794,7 @@ bool is_equal( Code self, Code other )
check_member_str( Name ); check_member_str( Name );
check_member_ast( Attributes ); check_member_ast( Attributes );
check_member_ast( UnderlyingType ); check_member_ast( UnderlyingType );
check_member_ast( UnderlyingTypeMacro );
return true; return true;
} }
@ -1058,6 +1064,13 @@ bool is_equal( Code self, Code other )
return true; return true;
} }
case CT_Union_Fwd:
{
check_member_val( ModuleFlags );
check_member_str( Name );
check_member_ast( Attributes );
}
case CT_Using: case CT_Using:
case CT_Using_Namespace: case CT_Using_Namespace:

View File

@ -155,6 +155,7 @@ Define_Code(Var);
GEN_NS_PARSER_BEGIN GEN_NS_PARSER_BEGIN
struct Token; struct Token;
GEN_NS_PARSER_END GEN_NS_PARSER_END
typedef struct GEN_NS_PARSER Token Token;
#if ! GEN_COMPILER_C #if ! GEN_COMPILER_C
template< class Type> forceinline Type tmpl_cast( Code self ) { return * rcast( Type*, & self ); } template< class Type> forceinline Type tmpl_cast( Code self ) { return * rcast( Type*, & self ); }
@ -319,9 +320,10 @@ struct AST
Code ValueType; // Parameter, Variable Code ValueType; // Parameter, Variable
}; };
union { union {
Code Macro; // Parameter Code Macro; // Parameter
Code BitfieldSize; // Variable (Class/Struct Data Member) Code BitfieldSize; // Variable (Class/Struct Data Member)
Code Params; // Constructor, Function, Operator, Template, Typename Code Params; // Constructor, Function, Operator, Template, Typename
Code UnderlyingTypeMacro; // Enum
}; };
union { union {
Code ArrExpr; // Typename Code ArrExpr; // Typename
@ -363,7 +365,6 @@ struct AST
AccessSpec ParentAccess; AccessSpec ParentAccess;
s32 NumEntries; s32 NumEntries;
s32 VarConstructorInit; // Used by variables to know that initialization is using a constructor expression instead of an assignment expression. s32 VarConstructorInit; // Used by variables to know that initialization is using a constructor expression instead of an assignment expression.
b32 EnumUnderlyingMacro; // Used by enums incase the user wants to wrap underlying type specification in a macro
}; };
}; };
static_assert( sizeof(AST) == AST_POD_Size, "ERROR: AST POD is not size of AST_POD_Size" ); static_assert( sizeof(AST) == AST_POD_Size, "ERROR: AST POD is not size of AST_POD_Size" );

View File

@ -15,7 +15,7 @@ struct AST_Body
char _PAD_[ sizeof(Specifier) * AST_ArrSpecs_Cap + sizeof(AST*) ]; char _PAD_[ sizeof(Specifier) * AST_ArrSpecs_Cap + sizeof(AST*) ];
Code Front; Code Front;
Code Back; Code Back;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -32,7 +32,7 @@ struct AST_Attributes
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -48,7 +48,7 @@ struct AST_BaseClass
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -65,10 +65,10 @@ struct AST_Comment
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
char _PAD_UNUSED_[ sizeof(ModuleFlag) + sizeof(u32) ]; char _PAD_UNUSED_[ sizeof(ModuleFlag) + sizeof(u32) ];
}; };
static_assert( sizeof(AST_Comment) == sizeof(AST), "ERROR: AST_Comment is not the same size as AST"); static_assert( sizeof(AST_Comment) == sizeof(AST), "ERROR: AST_Comment is not the same size as AST");
@ -90,7 +90,7 @@ struct AST_Class
}; };
CodeTypename Prev; CodeTypename Prev;
CodeTypename Next; CodeTypename Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -116,7 +116,7 @@ struct AST_Constructor
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -132,7 +132,7 @@ struct AST_Define
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -156,7 +156,7 @@ struct AST_Destructor
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -181,12 +181,12 @@ struct AST_Enum
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
ModuleFlag ModuleFlags; ModuleFlag ModuleFlags;
b32 EnumUnderlyingMacro; char _PAD_UNUSED_[ sizeof(ModuleFlag) + sizeof(u32) ];
}; };
static_assert( sizeof(AST_Enum) == sizeof(AST), "ERROR: AST_Enum is not the same size as AST"); static_assert( sizeof(AST_Enum) == sizeof(AST), "ERROR: AST_Enum is not the same size as AST");
@ -198,7 +198,7 @@ struct AST_Exec
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -214,7 +214,7 @@ struct AST_Expr
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -229,7 +229,7 @@ struct AST_Expr_Assign
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -244,7 +244,7 @@ struct AST_Expr_Alignof
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -259,7 +259,7 @@ struct AST_Expr_Binary
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -274,7 +274,7 @@ struct AST_Expr_CStyleCast
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -289,7 +289,7 @@ struct AST_Expr_FunctionalCast
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -304,7 +304,7 @@ struct AST_Expr_CppCast
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -319,7 +319,7 @@ struct AST_Expr_ProcCall
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -334,7 +334,7 @@ struct AST_Expr_Decltype
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -349,7 +349,7 @@ struct AST_Expr_Comma
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -364,7 +364,7 @@ struct AST_Expr_AMS
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -379,7 +379,7 @@ struct AST_Expr_Sizeof
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -394,7 +394,7 @@ struct AST_Expr_Subscript
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -409,7 +409,7 @@ struct AST_Expr_Ternary
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -424,7 +424,7 @@ struct AST_Expr_UnaryPrefix
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -439,7 +439,7 @@ struct AST_Expr_UnaryPostfix
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -454,7 +454,7 @@ struct AST_Expr_Element
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -476,7 +476,7 @@ struct AST_Extern
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -492,7 +492,7 @@ struct AST_Include
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -514,7 +514,7 @@ struct AST_Friend
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -539,7 +539,7 @@ struct AST_Fn
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -553,7 +553,7 @@ struct AST_Module
char _PAD_[ sizeof(Specifier) * AST_ArrSpecs_Cap + sizeof(AST*) ]; char _PAD_[ sizeof(Specifier) * AST_ArrSpecs_Cap + sizeof(AST*) ];
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -574,7 +574,7 @@ struct AST_NS
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -600,7 +600,7 @@ struct AST_Operator
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -626,7 +626,7 @@ struct AST_OpCast
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -650,7 +650,7 @@ struct AST_Param
}; };
CodeParam Last; CodeParam Last;
CodeParam Next; CodeParam Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -667,7 +667,7 @@ struct AST_Pragma
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -683,7 +683,7 @@ struct AST_PreprocessCond
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -697,7 +697,7 @@ struct AST_Specifiers
CodeSpecifiers NextSpecs; CodeSpecifiers NextSpecs;
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -714,7 +714,7 @@ struct AST_Stmt
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -729,7 +729,7 @@ struct AST_Stmt_Break
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -744,7 +744,7 @@ struct AST_Stmt_Case
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -759,7 +759,7 @@ struct AST_Stmt_Continue
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -774,7 +774,7 @@ struct AST_Stmt_Decl
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -789,7 +789,7 @@ struct AST_Stmt_Do
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -804,7 +804,7 @@ struct AST_Stmt_Expr
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -819,7 +819,7 @@ struct AST_Stmt_Else
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -834,7 +834,7 @@ struct AST_Stmt_If
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -849,7 +849,7 @@ struct AST_Stmt_For
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -864,7 +864,7 @@ struct AST_Stmt_Goto
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -879,7 +879,7 @@ struct AST_Stmt_Label
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -894,7 +894,7 @@ struct AST_Stmt_Switch
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -909,7 +909,7 @@ struct AST_Stmt_While
}; };
CodeExpr Prev; CodeExpr Prev;
CodeExpr Next; CodeExpr Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -935,7 +935,7 @@ struct AST_Struct
}; };
CodeTypename Prev; CodeTypename Prev;
CodeTypename Next; CodeTypename Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -958,7 +958,7 @@ struct AST_Template
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -987,7 +987,7 @@ struct AST_Type
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -1014,7 +1014,7 @@ struct AST_Typename
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -1037,7 +1037,7 @@ struct AST_Typedef
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -1061,7 +1061,7 @@ struct AST_Union
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -1085,7 +1085,7 @@ struct AST_Using
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;
@ -1111,7 +1111,7 @@ struct AST_Var
}; };
Code Prev; Code Prev;
Code Next; Code Next;
parser::Token* Tok; Token* Tok;
Code Parent; Code Parent;
StringCached Name; StringCached Name;
CodeType Type; CodeType Type;

View File

@ -9,7 +9,7 @@ String to_string(CodeAttributes attributes) {
String to_string(CodeBody body) String to_string(CodeBody body)
{ {
GEN_ASSERT(body.ast != nullptr); GEN_ASSERT_NOT_NULL(body.ast);
String result = string_make_reserve( GlobalAllocator, 128 ); String result = string_make_reserve( GlobalAllocator, 128 );
switch ( body.ast->Type ) switch ( body.ast->Type )
{ {
@ -350,6 +350,8 @@ void to_string_fwd(CodeEnum self, String* result )
if ( self->UnderlyingType ) if ( self->UnderlyingType )
string_append_fmt( result, "enum %SC : %S", self->Name, to_string(self->UnderlyingType) ); string_append_fmt( result, "enum %SC : %S", self->Name, to_string(self->UnderlyingType) );
else if (self->UnderlyingTypeMacro)
string_append_fmt( result, "enum %SC : %S", self->Name, to_string(self->UnderlyingTypeMacro) );
else else
string_append_fmt( result, "enum %SC", self->Name ); string_append_fmt( result, "enum %SC", self->Name );
@ -1171,11 +1173,19 @@ void to_string(CodeTypename self, String* result )
String to_string(CodeUnion self) String to_string(CodeUnion self)
{ {
String result = string_make_reserve( GlobalAllocator, 512 ); String result = string_make_reserve( GlobalAllocator, 512 );
to_string( self, & result ); switch ( self->Type )
{
case CT_Union:
to_string_def( self, & result );
break;
case CT_Union_Fwd:
to_string_fwd( self, & result );
break;
}
return result; return result;
} }
void to_string(CodeUnion self, String* result ) void to_string_def(CodeUnion self, String* result )
{ {
if ( bitfield_is_equal( u32, self->ModuleFlags, ModuleFlag_Export )) if ( bitfield_is_equal( u32, self->ModuleFlags, ModuleFlag_Export ))
string_append_strc( result, txt("export ") ); string_append_strc( result, txt("export ") );
@ -1204,6 +1214,25 @@ void to_string(CodeUnion self, String* result )
string_append_strc( result, txt(";\n")); string_append_strc( result, txt(";\n"));
} }
void to_string_fwd(CodeUnion self, String* result )
{
if ( bitfield_is_equal( u32, self->ModuleFlags, ModuleFlag_Export ))
string_append_strc( result, txt("export ") );
string_append_strc( result, txt("union ") );
if ( self->Attributes )
string_append_fmt( result, "%S ", to_string(self->Attributes) );
if ( self->Name )
{
string_append_fmt( result, "%SC", self->Name);
}
if ( self->Parent.ast == nullptr || ( self->Parent->Type != CT_Typedef && self->Parent->Type != CT_Variable ) )
string_append_strc( result, txt(";\n"));
}
String to_string(CodeUsing self) String to_string(CodeUsing self)
{ {
String result = string_make_reserve( GlobalAllocator, 128 ); String result = string_make_reserve( GlobalAllocator, 128 );

View File

@ -110,7 +110,8 @@ String to_string(CodeTypedef self);
void to_string(CodeTypedef self, String* result); void to_string(CodeTypedef self, String* result);
String to_string(CodeUnion self); String to_string(CodeUnion self);
void to_string(CodeUnion self, String* result); void to_string_def(CodeUnion self, String* result);
void to_string_fwd(CodeUnion self, String* result);
String to_string (CodeUsing op_cast ); String to_string (CodeUsing op_cast );
void to_string (CodeUsing op_cast, String* result ); void to_string (CodeUsing op_cast, String* result );

View File

@ -63,6 +63,7 @@ enum CodeType_Def : u32
CT_Typedef, CT_Typedef,
CT_Typename, CT_Typename,
CT_Union, CT_Union,
CT_Union_Fwd,
CT_Union_Body, CT_Union_Body,
CT_Using, CT_Using,
CT_Using_Namespace, CT_Using_Namespace,
@ -130,6 +131,7 @@ inline StrC to_str( CodeType type )
{ sizeof( "Typedef" ), "Typedef" }, { sizeof( "Typedef" ), "Typedef" },
{ sizeof( "Typename" ), "Typename" }, { sizeof( "Typename" ), "Typename" },
{ sizeof( "Union" ), "Union" }, { sizeof( "Union" ), "Union" },
{ sizeof( "Union_Fwd" ), "Union_Fwd" },
{ sizeof( "Union_Body" ), "Union_Body" }, { sizeof( "Union_Body" ), "Union_Body" },
{ sizeof( "Using" ), "Using" }, { sizeof( "Using" ), "Using" },
{ sizeof( "Using_Namespace" ), "Using_Namespace" }, { sizeof( "Using_Namespace" ), "Using_Namespace" },

View File

@ -7,6 +7,12 @@
Public Address: Public Address:
https://github.com/Ed94/gencpp https://github.com/Ed94/gencpp
! ----------------------------------------------------------------------- VERSION: v0.20-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) #if ! defined(GEN_DONT_ENFORCE_GEN_TIME_GUARD) && ! defined(GEN_TIME)
# error Gen.hpp : GEN_TIME not defined # error Gen.hpp : GEN_TIME not defined

View File

@ -122,7 +122,7 @@ void define_constants()
fmt_newline = make_code(); fmt_newline = make_code();
fmt_newline->Type = CT_NewLine; fmt_newline->Type = CT_NewLine;
set_global(fmt_newline); set_global(fmt_newline);
pragma_once = (CodePragma) make_code(); pragma_once = (CodePragma) make_code();
pragma_once->Type = CT_Preprocess_Pragma; pragma_once->Type = CT_Preprocess_Pragma;
pragma_once->Name = get_cached_string( txt("once") ); pragma_once->Name = get_cached_string( txt("once") );
@ -227,7 +227,7 @@ void define_constants()
# pragma pop_macro("neverinline") # pragma pop_macro("neverinline")
# pragma push_macro("enum_underlying") # pragma push_macro("enum_underlying")
array_append(PreprocessorDefines, txt("enum_underlying("));
# pragma pop_macro("enum_underlying") # pragma pop_macro("enum_underlying")
# undef def_constant_spec # undef def_constant_spec

View File

@ -215,7 +215,7 @@ internal Code parse_operator_function_or_variable( bool expects_fu
internal CodePragma parse_pragma (); internal CodePragma parse_pragma ();
internal CodeParam parse_params ( bool use_template_capture = false ); internal CodeParam parse_params ( bool use_template_capture = false );
internal CodePreprocessCond parse_preprocess_cond (); internal CodePreprocessCond parse_preprocess_cond ();
internal Code parse_simple_preprocess ( TokType which ); internal Code parse_simple_preprocess ( TokType which, bool dont_consume_braces = false );
internal Code parse_static_assert (); internal Code parse_static_assert ();
internal void parse_template_args ( Token& token ); internal void parse_template_args ( Token& token );
internal CodeVar parse_variable_after_name ( ModuleFlag mflags, CodeAttributes attributes, CodeSpecifiers specifiers, CodeTypename type, StrC name ); internal CodeVar parse_variable_after_name ( ModuleFlag mflags, CodeAttributes attributes, CodeSpecifiers specifiers, CodeTypename type, StrC name );
@ -240,7 +240,8 @@ internal CodeTypedef parse_typedef ();
internal CodeUnion parse_union ( bool inplace_def = false ); internal CodeUnion parse_union ( bool inplace_def = false );
internal CodeUsing parse_using (); internal CodeUsing parse_using ();
constexpr bool inplace_def = true; constexpr bool inplace_def = true;
constexpr bool dont_consume_braces = true;
// Internal parsing functions // Internal parsing functions
@ -2933,8 +2934,8 @@ CodePreprocessCond parse_preprocess_cond()
return cond; return cond;
} }
internal inline internal
Code parse_simple_preprocess( TokType which ) Code parse_simple_preprocess( TokType which, bool dont_consume_braces )
{ {
// TODO(Ed): We can handle a macro a bit better than this. It's AST can be made more robust.. // TODO(Ed): We can handle a macro a bit better than this. It's AST can be made more robust..
// Make an AST_Macro, it should have an Name be the macro itself, with the function body being an optional function body node. // Make an AST_Macro, it should have an Name be the macro itself, with the function body being an optional function body node.
@ -2945,7 +2946,7 @@ Code parse_simple_preprocess( TokType which )
eat( which ); eat( which );
// <Macro> // <Macro>
if ( peektok.Type == Tok_BraceCurly_Open ) if ( ! dont_consume_braces && peektok.Type == Tok_BraceCurly_Open )
{ {
// Eat the block scope right after the macro. Were assuming the macro defines a function definition's signature // Eat the block scope right after the macro. Were assuming the macro defines a function definition's signature
eat( Tok_BraceCurly_Open ); eat( Tok_BraceCurly_Open );
@ -2985,7 +2986,11 @@ Code parse_simple_preprocess( TokType which )
} }
else else
{ {
if ( str_compare_len( Context.Scope->Prev->ProcName.Ptr, "parse_typedef", Context.Scope->Prev->ProcName.Len ) != 0 ) if (strc_contains(Context.Scope->Prev->ProcName, txt("parse_enum")))
{
// Do nothing
}
else if (strc_contains(Context.Scope->Prev->ProcName, txt("parse_typedef")))
{ {
if ( peektok.Type == Tok_Statement_End ) if ( peektok.Type == Tok_Statement_End )
{ {
@ -3614,15 +3619,14 @@ CodeEnum parse_enum( bool inplace_def )
} }
// enum <class> <Attributes> <Name> : <UnderlyingType> // enum <class> <Attributes> <Name> : <UnderlyingType>
} }
else if ( currtok.Type == Tok_Preprocess_Define ) else if ( currtok.Type == Tok_Preprocess_Macro )
{ {
// We'll support the enum_underlying macro // We'll support the enum_underlying macro
StrC sig = txt("enum_underlying"); StrC sig = txt("enum_underlying(");
if ( strc_contains(to_str(currtok), sig) )
if (currtok.Length >= sig.Len && str_compare_len(currtok.Text, sig.Ptr, sig.Len) == 0 )
{ {
use_macro_underlying = true; use_macro_underlying = true;
underlying_macro = parse_simple_preprocess( Tok_Preprocess_Macro); underlying_macro = parse_simple_preprocess( Tok_Preprocess_Macro, dont_consume_braces );
} }
} }
@ -3793,14 +3797,8 @@ CodeEnum parse_enum( bool inplace_def )
if ( attributes ) if ( attributes )
result->Attributes = attributes; result->Attributes = attributes;
if ( type ) result->UnderlyingTypeMacro = underlying_macro;
{ result->UnderlyingType = type;
result->EnumUnderlyingMacro = use_macro_underlying;
if ( use_macro_underlying )
result->UnderlyingTypeMacro = underlying_macro;
else
result->UnderlyingType = type;
}
if ( inline_cmt ) if ( inline_cmt )
result->InlineCmt = inline_cmt; result->InlineCmt = inline_cmt;
@ -5164,95 +5162,98 @@ CodeUnion parse_union( bool inplace_def )
eat( Tok_Identifier ); eat( Tok_Identifier );
} }
// <ModuleFlags> union <Attributes> <Name> // <ModuleFlags> union <Attributes> <Name>
CodeBody body = { nullptr }; CodeBody body = { nullptr };
eat( Tok_BraceCurly_Open ); if ( ! inplace_def || ! check(Tok_Identifier) )
// <ModuleFlags> union <Attributes> <Name> {
body = make_code();
body->Type = CT_Union_Body;
while ( ! check_noskip( Tok_BraceCurly_Close ) )
{ {
if ( currtok_noskip.Type == Tok_Preprocess_Hash ) eat( Tok_BraceCurly_Open );
eat( Tok_Preprocess_Hash ); // <ModuleFlags> union <Attributes> <Name> {
Code member = { nullptr }; body = make_code();
switch ( currtok_noskip.Type ) body->Type = CT_Union_Body;
while ( ! check_noskip( Tok_BraceCurly_Close ) )
{ {
case Tok_NewLine: if ( currtok_noskip.Type == Tok_Preprocess_Hash )
member = fmt_newline; eat( Tok_Preprocess_Hash );
eat( Tok_NewLine );
break;
case Tok_Comment: Code member = { nullptr };
member = parse_comment(); switch ( currtok_noskip.Type )
break; {
case Tok_NewLine:
member = fmt_newline;
eat( Tok_NewLine );
break;
// TODO(Ed) : Unions can have constructors and destructors case Tok_Comment:
member = parse_comment();
break;
case Tok_Decl_Class: // TODO(Ed) : Unions can have constructors and destructors
member = parse_complicated_definition( Tok_Decl_Class );
break;
case Tok_Decl_Enum: case Tok_Decl_Class:
member = parse_complicated_definition( Tok_Decl_Enum ); member = parse_complicated_definition( Tok_Decl_Class );
break; break;
case Tok_Decl_Struct: case Tok_Decl_Enum:
member = parse_complicated_definition( Tok_Decl_Struct ); member = parse_complicated_definition( Tok_Decl_Enum );
break; break;
case Tok_Decl_Union: case Tok_Decl_Struct:
member = parse_complicated_definition( Tok_Decl_Union ); member = parse_complicated_definition( Tok_Decl_Struct );
break; break;
case Tok_Preprocess_Define: case Tok_Decl_Union:
member = parse_define(); member = parse_complicated_definition( Tok_Decl_Union );
break; break;
case Tok_Preprocess_If: case Tok_Preprocess_Define:
case Tok_Preprocess_IfDef: member = parse_define();
case Tok_Preprocess_IfNotDef: break;
case Tok_Preprocess_ElIf:
member = parse_preprocess_cond();
break;
case Tok_Preprocess_Else: case Tok_Preprocess_If:
member = preprocess_else; case Tok_Preprocess_IfDef:
eat( Tok_Preprocess_Else ); case Tok_Preprocess_IfNotDef:
break; case Tok_Preprocess_ElIf:
member = parse_preprocess_cond();
break;
case Tok_Preprocess_EndIf: case Tok_Preprocess_Else:
member = preprocess_endif; member = preprocess_else;
eat( Tok_Preprocess_EndIf ); eat( Tok_Preprocess_Else );
break; break;
case Tok_Preprocess_Macro: case Tok_Preprocess_EndIf:
member = parse_simple_preprocess( Tok_Preprocess_Macro ); member = preprocess_endif;
break; eat( Tok_Preprocess_EndIf );
break;
case Tok_Preprocess_Pragma: case Tok_Preprocess_Macro:
member = parse_pragma(); member = parse_simple_preprocess( Tok_Preprocess_Macro );
break; break;
case Tok_Preprocess_Unsupported: case Tok_Preprocess_Pragma:
member = parse_simple_preprocess( Tok_Preprocess_Unsupported ); member = parse_pragma();
break; break;
default: case Tok_Preprocess_Unsupported:
member = parse_variable(); member = parse_simple_preprocess( Tok_Preprocess_Unsupported );
break; break;
default:
member = parse_variable();
break;
}
if ( member )
append(body, member );
} }
// <ModuleFlags> union <Attributes> <Name> { <Body>
if ( member )
append(body, member ); eat( Tok_BraceCurly_Close );
// <ModuleFlags> union <Attributes> <Name> { <Body> }
} }
// <ModuleFlags> union <Attributes> <Name> { <Body>
eat( Tok_BraceCurly_Close );
// <ModuleFlags> union <Attributes> <Name> { <Body> }
if ( ! inplace_def ) if ( ! inplace_def )
eat( Tok_Statement_End ); eat( Tok_Statement_End );
@ -5260,17 +5261,14 @@ CodeUnion parse_union( bool inplace_def )
CodeUnion CodeUnion
result = (CodeUnion) make_code(); result = (CodeUnion) make_code();
result->Type = CT_Union; result->Type = body ? CT_Union : CT_Union_Fwd;
result->ModuleFlags = mflags; result->ModuleFlags = mflags;
if ( name ) if ( name )
result->Name = get_cached_string( name ); result->Name = get_cached_string( name );
if ( body ) result->Body = body;
result->Body = body; result->Attributes = attributes;
if ( attributes )
result->Attributes = attributes;
pop(& Context); pop(& Context);
return result; return result;

View File

@ -133,6 +133,7 @@ Array<Type> array_init(AllocatorInfo allocator) {
template<class Type> inline template<class Type> inline
Array<Type> array_init_reserve(AllocatorInfo allocator, ssize capacity) Array<Type> array_init_reserve(AllocatorInfo allocator, ssize capacity)
{ {
GEN_ASSERT(capacity > 0);
ArrayHeader* header = rcast(ArrayHeader*, alloc(allocator, sizeof(ArrayHeader) + sizeof(Type) * capacity)); ArrayHeader* header = rcast(ArrayHeader*, alloc(allocator, sizeof(ArrayHeader) + sizeof(Type) * capacity));
if (header == nullptr) if (header == nullptr)
@ -157,6 +158,8 @@ bool array_append_array(Array<Type>* array, Array<Type> other) {
template<class Type> inline template<class Type> inline
bool array_append(Array<Type>* array, Type value) bool array_append(Array<Type>* array, Type value)
{ {
GEN_ASSERT( array != nullptr);
GEN_ASSERT(* array != nullptr);
ArrayHeader* header = array_get_header(* array); ArrayHeader* header = array_get_header(* array);
if (header->Num == header->Capacity) if (header->Num == header->Capacity)
@ -175,6 +178,10 @@ bool array_append(Array<Type>* array, Type value)
template<class Type> inline template<class Type> inline
bool array_append_items(Array<Type>* array, Type* items, usize item_num) 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); ArrayHeader* header = array_get_header(array);
if (header->Num + item_num > header->Capacity) if (header->Num + item_num > header->Capacity)
@ -193,6 +200,8 @@ bool array_append_items(Array<Type>* array, Type* items, usize item_num)
template<class Type> inline template<class Type> inline
bool array_append_at(Array<Type>* array, Type item, usize idx) 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); ArrayHeader* header = array_get_header(* array);
ssize slot = idx; ssize slot = idx;
@ -215,19 +224,19 @@ bool array_append_at(Array<Type>* array, Type item, usize idx)
mem_move(target + 1, target, (header->Num - slot) * sizeof(Type)); mem_move(target + 1, target, (header->Num - slot) * sizeof(Type));
header->Num++; header->Num++;
header = array_get_header(* array);
return true; return true;
} }
template<class Type> inline template<class Type> inline
bool array_append_items_at(Array<Type>* array, Type* items, usize item_num, usize idx) 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); ArrayHeader* header = get_header(array);
if (idx >= header->Num) if (idx >= header->Num)
{ {
return append(array, items, item_num); return array_append_items(array, items, item_num);
} }
if (item_num > header->Capacity) if (item_num > header->Capacity)
@ -262,6 +271,7 @@ Type* array_back(Array<Type> array)
template<class Type> inline template<class Type> inline
void array_clear(Array<Type> array) { void array_clear(Array<Type> array) {
GEN_ASSERT(array != nullptr);
ArrayHeader* header = array_get_header(array); ArrayHeader* header = array_get_header(array);
header->Num = 0; header->Num = 0;
} }
@ -269,6 +279,8 @@ void array_clear(Array<Type> array) {
template<class Type> inline template<class Type> inline
bool array_fill(Array<Type> array, usize begin, usize end, Type value) 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); ArrayHeader* header = array_get_header(array);
if (begin < 0 || end > header->Num) if (begin < 0 || end > header->Num)
@ -282,9 +294,10 @@ bool array_fill(Array<Type> array, usize begin, usize end, Type value)
return true; return true;
} }
template<class Type> inline template<class Type> forceinline
void array_free(Array<Type>* array) { void array_free(Array<Type>* array) {
GEN_ASSERT(array != nullptr); GEN_ASSERT( array != nullptr);
GEN_ASSERT(* array != nullptr);
ArrayHeader* header = array_get_header(* array); ArrayHeader* header = array_get_header(* array);
allocator_free(header->Allocator, header); allocator_free(header->Allocator, header);
Type** Data = (Type**)array; Type** Data = (Type**)array;
@ -293,14 +306,18 @@ void array_free(Array<Type>* array) {
template<class Type> forceinline template<class Type> forceinline
ArrayHeader* array_get_header(Array<Type> array) { ArrayHeader* array_get_header(Array<Type> array) {
GEN_ASSERT(array != nullptr);
Type* Data = array; Type* Data = array;
using NonConstType = TRemoveConst<Type>; using NonConstType = TRemoveConst<Type>;
return rcast(ArrayHeader*, const_cast<NonConstType*>(Data)) - 1; return rcast(ArrayHeader*, const_cast<NonConstType*>(Data)) - 1;
} }
template<class Type> inline template<class Type> forceinline
bool array_grow(Array<Type>* array, usize min_capacity) 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); ArrayHeader* header = array_get_header(* array);
usize new_capacity = array_grow_formula(header->Capacity); usize new_capacity = array_grow_formula(header->Capacity);
@ -310,13 +327,15 @@ bool array_grow(Array<Type>* array, usize min_capacity)
return array_set_capacity(array, new_capacity); return array_set_capacity(array, new_capacity);
} }
template<class Type> inline template<class Type> forceinline
usize array_num(Array<Type> array) { usize array_num(Array<Type> array) {
GEN_ASSERT(array != nullptr);
return array_get_header(array)->Num; return array_get_header(array)->Num;
} }
template<class Type> inline template<class Type> forceinline
void array_pop(Array<Type> array) { void array_pop(Array<Type> array) {
GEN_ASSERT(array != nullptr);
ArrayHeader* header = array_get_header(array); ArrayHeader* header = array_get_header(array);
GEN_ASSERT(header->Num > 0); GEN_ASSERT(header->Num > 0);
header->Num--; header->Num--;
@ -325,6 +344,7 @@ void array_pop(Array<Type> array) {
template<class Type> inline template<class Type> inline
void array_remove_at(Array<Type> array, usize idx) void array_remove_at(Array<Type> array, usize idx)
{ {
GEN_ASSERT(array != nullptr);
ArrayHeader* header = array_get_header(array); ArrayHeader* header = array_get_header(array);
GEN_ASSERT(idx < header->Num); GEN_ASSERT(idx < header->Num);
@ -335,6 +355,9 @@ void array_remove_at(Array<Type> array, usize idx)
template<class Type> inline template<class Type> inline
bool array_reserve(Array<Type>* array, usize new_capacity) bool array_reserve(Array<Type>* array, usize new_capacity)
{ {
GEN_ASSERT( array != nullptr);
GEN_ASSERT(* array != nullptr);
GEN_ASSERT(num > 0)
ArrayHeader* header = array_get_header(array); ArrayHeader* header = array_get_header(array);
if (header->Capacity < new_capacity) if (header->Capacity < new_capacity)
@ -346,6 +369,8 @@ bool array_reserve(Array<Type>* array, usize new_capacity)
template<class Type> inline template<class Type> inline
bool array_resize(Array<Type>* array, usize num) bool array_resize(Array<Type>* array, usize num)
{ {
GEN_ASSERT( array != nullptr);
GEN_ASSERT(* array != nullptr);
ArrayHeader* header = array_get_header(* array); ArrayHeader* header = array_get_header(* array);
if (header->Capacity < num) { if (header->Capacity < num) {
@ -361,10 +386,12 @@ bool array_resize(Array<Type>* array, usize num)
template<class Type> inline template<class Type> inline
bool array_set_capacity(Array<Type>* array, usize new_capacity) bool array_set_capacity(Array<Type>* array, usize new_capacity)
{ {
GEN_ASSERT( array != nullptr);
GEN_ASSERT(* array != nullptr);
ArrayHeader* header = array_get_header(* array); ArrayHeader* header = array_get_header(* array);
if (new_capacity == header->Capacity) if (new_capacity == header->Capacity)
return true; return true;
if (new_capacity < header->Num) if (new_capacity < header->Num)
{ {
@ -454,12 +481,13 @@ template<class Type> void hashtable_remove (HashTable<Type
template<class Type> void hashtable_remove_entry(HashTable<Type> table, ssize idx); 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> void hashtable_set (HashTable<Type>* table, u64 key, Type value);
template<class Type> ssize hashtable_slot (HashTable<Type> table, u64 key); template<class Type> ssize hashtable_slot (HashTable<Type> table, u64 key);
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);
template<class Type> void hashtable_map (HashTable<Type> table, void (*map_proc)(u64 key, Type value)); 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> 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; static constexpr f32 HashTable_CriticalLoadScale = 0.7f;
template<typename Type> template<typename Type>
@ -513,37 +541,45 @@ HashTable<Type> hashtable_init_reserve(AllocatorInfo allocator, usize num)
result.Hashes = array_init_reserve<ssize>(allocator, num); result.Hashes = array_init_reserve<ssize>(allocator, num);
array_get_header(result.Hashes)->Num = num; array_get_header(result.Hashes)->Num = num;
array_resize(& result.Hashes, num); array_resize(& result.Hashes, num);
array_fill<ssize>(result.Hashes, 0, num, -1); array_fill(result.Hashes, 0, num, (ssize)-1);
result.Entries = array_init_reserve<HashTableEntry<Type>>(allocator, num); result.Entries = array_init_reserve<HashTableEntry<Type>>(allocator, num);
return result; return result;
} }
template<typename Type> inline template<typename Type> forceinline
void hashtable_clear(HashTable<Type> table) { void hashtable_clear(HashTable<Type> table) {
GEN_ASSERT_NOT_NULL(table.Hashes);
GEN_ASSERT_NOT_NULL(table.Entries);
array_clear(table.Entries); array_clear(table.Entries);
array_fill(table.Hashes, 0, array_num(table.Hashes), (ssize)-1); array_fill(table.Hashes, 0, array_num(table.Hashes), (ssize)-1);
} }
template<typename Type> inline template<typename Type> forceinline
void hashtable_destroy(HashTable<Type>* table) { 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) { if (table->Hashes && array_get_header(table->Hashes)->Capacity) {
array_free(table->Hashes); array_free(table->Hashes);
array_free(table->Entries); array_free(table->Entries);
} }
} }
template<typename Type> inline template<typename Type> forceinline
Type* hashtable_get(HashTable<Type> table, u64 key) { Type* hashtable_get(HashTable<Type> table, u64 key) {
ssize idx = hashtable_find(table, key).EntryIndex; GEN_ASSERT_NOT_NULL(table.Hashes);
GEN_ASSERT_NOT_NULL(table.Entries);
ssize idx = hashtable__find(table, key).EntryIndex;
if (idx >= 0) if (idx >= 0)
return & table.Entries[idx].Value; return & table.Entries[idx].Value;
return nullptr; return nullptr;
} }
template<typename Type> inline template<typename Type> forceinline
void hashtable_map(HashTable<Type> table, void (*map_proc)(u64 key, Type value)) { 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); GEN_ASSERT_NOT_NULL(map_proc);
for (ssize idx = 0; idx < ssize(num(table.Entries)); ++idx) { for (ssize idx = 0; idx < ssize(num(table.Entries)); ++idx) {
@ -551,8 +587,10 @@ void hashtable_map(HashTable<Type> table, void (*map_proc)(u64 key, Type value))
} }
} }
template<typename Type> inline template<typename Type> forceinline
void hashtable_map_mut(HashTable<Type> table, void (*map_proc)(u64 key, Type* value)) { 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); GEN_ASSERT_NOT_NULL(map_proc);
for (ssize idx = 0; idx < ssize(num(table.Entries)); ++idx) { for (ssize idx = 0; idx < ssize(num(table.Entries)); ++idx) {
@ -560,8 +598,11 @@ void hashtable_map_mut(HashTable<Type> table, void (*map_proc)(u64 key, Type* va
} }
} }
template<typename Type> inline template<typename Type> forceinline
void hashtable_grow(HashTable<Type>* table) { 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)); ssize new_num = array_grow_formula( array_num(table->Entries));
hashtable_rehash(table, new_num); hashtable_rehash(table, new_num);
} }
@ -569,6 +610,9 @@ void hashtable_grow(HashTable<Type>* table) {
template<typename Type> inline template<typename Type> inline
void hashtable_rehash(HashTable<Type>* table, ssize new_num) 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; ssize last_added_index;
HashTable<Type> new_ht = hashtable_init_reserve<Type>( array_get_header(table->Hashes)->Allocator, new_num); HashTable<Type> new_ht = hashtable_init_reserve<Type>( array_get_header(table->Hashes)->Allocator, new_num);
@ -577,8 +621,8 @@ void hashtable_rehash(HashTable<Type>* table, ssize new_num)
HashTableFindResult find_result; HashTableFindResult find_result;
HashTableEntry<Type>& entry = table->Entries[idx]; HashTableEntry<Type>& entry = table->Entries[idx];
find_result = hashtable_find(new_ht, entry.Key); find_result = hashtable__find(new_ht, entry.Key);
last_added_index = hashtable_add_entry(& new_ht, entry.Key); last_added_index = hashtable__add_entry(& new_ht, entry.Key);
if (find_result.PrevIndex < 0) if (find_result.PrevIndex < 0)
new_ht.Hashes[find_result.HashIndex] = last_added_index; new_ht.Hashes[find_result.HashIndex] = last_added_index;
@ -596,6 +640,8 @@ void hashtable_rehash(HashTable<Type>* table, ssize new_num)
template<typename Type> inline template<typename Type> inline
void hashtable_rehash_fast(HashTable<Type> table) void hashtable_rehash_fast(HashTable<Type> table)
{ {
GEN_ASSERT_NOT_NULL(table.Hashes);
GEN_ASSERT_NOT_NULL(table.Entries);
ssize idx; ssize idx;
for (idx = 0; idx < ssize(num(table.Entries)); idx++) for (idx = 0; idx < ssize(num(table.Entries)); idx++)
@ -619,8 +665,10 @@ void hashtable_rehash_fast(HashTable<Type> table)
} }
} }
template<typename Type> inline template<typename Type> forceinline
void hashtable_remove(HashTable<Type> table, u64 key) { 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); HashTableFindResult find_result = find(table, key);
if (find_result.EntryIndex >= 0) { if (find_result.EntryIndex >= 0) {
@ -629,27 +677,32 @@ void hashtable_remove(HashTable<Type> table, u64 key) {
} }
} }
template<typename Type> inline template<typename Type> forceinline
void hashtable_remove_entry(HashTable<Type> table, ssize idx) { 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); remove_at(table.Entries, idx);
} }
template<typename Type> inline template<typename Type> inline
void hashtable_set(HashTable<Type>* table, u64 key, Type value) 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; ssize idx;
HashTableFindResult find_result; HashTableFindResult find_result;
if (hashtable_full(* table)) if (hashtable_full(* table))
hashtable_grow(table); hashtable_grow(table);
find_result = hashtable_find(* table, key); find_result = hashtable__find(* table, key);
if (find_result.EntryIndex >= 0) { if (find_result.EntryIndex >= 0) {
idx = find_result.EntryIndex; idx = find_result.EntryIndex;
} }
else else
{ {
idx = hashtable_add_entry(table, key); idx = hashtable__add_entry(table, key);
if (find_result.PrevIndex >= 0) { if (find_result.PrevIndex >= 0) {
table->Entries[find_result.PrevIndex].Next = idx; table->Entries[find_result.PrevIndex].Next = idx;
@ -665,8 +718,10 @@ void hashtable_set(HashTable<Type>* table, u64 key, Type value)
hashtable_grow(table); hashtable_grow(table);
} }
template<typename Type> inline template<typename Type> forceinline
ssize hashtable_slot(HashTable<Type> table, u64 key) { 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) for (ssize idx = 0; idx < ssize(num(table.Hashes)); ++idx)
if (table.Hashes[idx] == key) if (table.Hashes[idx] == key)
return idx; return idx;
@ -674,8 +729,11 @@ ssize hashtable_slot(HashTable<Type> table, u64 key) {
return -1; return -1;
} }
template<typename Type> inline template<typename Type> forceinline
ssize hashtable_add_entry(HashTable<Type>* table, u64 key) { 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; ssize idx;
HashTableEntry<Type> entry = { key, -1 }; HashTableEntry<Type> entry = { key, -1 };
@ -685,8 +743,10 @@ ssize hashtable_add_entry(HashTable<Type>* table, u64 key) {
} }
template<typename Type> inline template<typename Type> inline
HashTableFindResult hashtable_find(HashTable<Type> table, u64 key) 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 }; HashTableFindResult result = { -1, -1, -1 };
if (array_num(table.Hashes) > 0) if (array_num(table.Hashes) > 0)
@ -707,8 +767,10 @@ HashTableFindResult hashtable_find(HashTable<Type> table, u64 key)
return result; return result;
} }
template<typename Type> inline template<typename Type> forceinline
bool hashtable_full(HashTable<Type> table) { bool 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))); usize critical_load = usize(HashTable_CriticalLoadScale * f32(array_num(table.Hashes)));
b32 result = array_num(table.Entries) > critical_load; b32 result = array_num(table.Entries) > critical_load;
return result; return result;
@ -726,12 +788,13 @@ bool hashtable_full(HashTable<Type> table) {
#define hashtable_remove_entry(table, idx) hashtable_remove_entry< get_hashtable_underlying_type(table) >(table, idx) #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_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_slot(table, key) hashtable_slot < get_hashtable_underlying_type(table) >(table, key)
#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)
#define hashtable_map(table, map_proc) hashtable_map < get_hashtable_underlying_type(table) >(table, map_proc) #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_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 HashTable
#pragma endregion Containers #pragma endregion Containers

View File

@ -194,6 +194,7 @@ b32 file_read_at( FileInfo* file, void* buffer, ssize size, s64 offset );
*/ */
b32 file_read_at_check( FileInfo* file, void* buffer, ssize size, s64 offset, ssize* bytes_read ); b32 file_read_at_check( FileInfo* file, void* buffer, ssize size, s64 offset, ssize* bytes_read );
typedef struct FileContents FileContents;
struct FileContents struct FileContents
{ {
AllocatorInfo allocator; AllocatorInfo allocator;
@ -201,8 +202,8 @@ struct FileContents
ssize size; ssize size;
}; };
constexpr b32 zero_terminate = true; constexpr b32 file_zero_terminate = true;
constexpr b32 no_zero_terminate = false; constexpr b32 file_no_zero_terminate = false;
/** /**
* Reads the whole file contents * Reads the whole file contents

View File

@ -187,6 +187,17 @@
# endif # endif
#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 #if GEN_COMPILER_CPP
// Already Defined // Already Defined
#elif GEN_COMPILER_C && __STDC_VERSION__ >= 201112L #elif GEN_COMPILER_C && __STDC_VERSION__ >= 201112L
@ -269,13 +280,16 @@
#define struct_init(type, value) {value} #define struct_init(type, value) {value}
#endif #endif
// ------------------------ _Generic function overloading -----------------------------------------
#if GEN_COMPILER_C #if GEN_COMPILER_C
// ------------------------ _Generic function overloading -----------------------------------------
// This implemnents macros for utilizing "The Naive Extendible _Generic Macro" explained in: // This implemnents macros for utilizing "The Naive Extendible _Generic Macro" explained in:
// https://github.com/JacksonAllan/CC/blob/main/articles/Better_C_Generics_Part_1_The_Extendible_Generic.md // https://github.com/JacksonAllan/CC/blob/main/articles/Better_C_Generics_Part_1_The_Extendible_Generic.md
// Since gencpp is used to generate the c-library, it was choosen over the more novel implementations to keep the macros as easy to understand and unopaque as possible. // Since gencpp is used to generate the c-library, it was choosen over the more novel implementations to keep the macros as easy to understand and unopaque as possible.
// Extensive effort was put in below to make this as easy as possible to understand what is going on with this mess of a preoprocessor. // Extensive effort was put in below to make this as easy as possible to understand what is going on with this mess of a preoprocessor.
// Where the signature would be defined using:
#define GEN_TYPE_TO_EXP(type) (* (type*)NULL)
#define GEN_COMMA_OPERATOR , // The comma operator is used by preprocessor macros to delimit arguments, so we have to represent it via a macro to prevent parsing incorrectly. #define GEN_COMMA_OPERATOR , // The comma operator is used by preprocessor macros to delimit arguments, so we have to represent it via a macro to prevent parsing incorrectly.
// Helper macros for argument selection // Helper macros for argument selection
@ -299,19 +313,19 @@
// It takes advantage of the fact that if the macro is defined, then the expanded text will contain a comma. // It takes advantage of the fact that if the macro is defined, then the expanded text will contain a comma.
// Expands to ',' if it can find (type): (function) <comma_operator: ',' > // Expands to ',' if it can find (type): (function) <comma_operator: ',' >
// Where GEN_GENERIC_SEL_ENTRY_COMMA_DELIMITER is specifically looking for that <comma> , // Where GEN_GENERIC_SEL_ENTRY_COMMA_DELIMITER is specifically looking for that <comma> ,
#define GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( slot_exp ) GEN_SELECT_ARG_3( slot_exp, GEN_SELECT_ARG_1( slot_exp, ): GEN_SELECT_ARG_2( slot_exp, ) GEN_COMMA_OPERATOR, , ) #define GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( slot_exp ) GEN_GENERIC_SEL_ENTRY_COMMA_DELIMITER( slot_exp, GEN_GENERIC_SEL_ENTRY_TYPE( slot_exp, ): GEN_GENERIC_SEL_ENTRY_FUNCTION( slot_exp, ) GEN_COMMA_OPERATOR, , )
// ^Selects the comma ^ is the type ^ is the function ^ comma delimiter to select ^ Insert a comma // ^ Selects the comma ^ is the type ^ is the function ^ Insert a comma
// The slot won't exist if that comma is not found. // The slot won't exist if that comma is not found. |
// | // |
// This is the same as above but it does not insert a comma V no comma here. // This is the same as above but it does not insert a comma V no comma here.
#define GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT_LAST( slot_exp ) GEN_GENERIC_SEL_ENTRY_COMMA_DELIMITER( slot_exp, GEN_GENERIC_SEL_ENTRY_TYPE( slot_exp, ): GEN_GENERIC_SEL_ENTRY_FUNCTION( slot_exp, ), , ) #define GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT_LAST( slot_exp ) GEN_GENERIC_SEL_ENTRY_COMMA_DELIMITER( slot_exp, GEN_GENERIC_SEL_ENTRY_TYPE( slot_exp, ): GEN_GENERIC_SEL_ENTRY_FUNCTION( slot_exp, ), , )
// Needed for the last slot as they don't allow trailing commas. // Needed for the last slot as they don't allow trailing commas.
// ---------------------------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------------------------
// Below are generated on demand for a generated function // Below are generated on demand for an overlaod depdendent on a type:
// ---------------------------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------------------------
#define GEN_FUNCTION_GENERIC_EXAMPLE( function_arguments ) _Generic( \ #define GEN_FUNCTION_GENERIC_EXAMPLE( selector_arg ) _Generic( \
(function_arguments), /* Select Via Expression*/ \ (selector_arg), /* Select Via Expression*/ \
/* Extendibility slots: */ \ /* Extendibility slots: */ \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \ GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \ GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \
@ -320,8 +334,8 @@
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \ GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \ GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \ GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT_LAST FunctionID__ARGS_SIG_1 ) \ GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT_LAST(FunctionID__ARGS_SIG_1 ) \
) GEN_RESOLVED_FUNCTION_CALL( function_arguments ) ) GEN_RESOLVED_FUNCTION_CALL( selector_arg )
// ---------------------------------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------------------------------
// Then each definiton of a function has an associated define: // Then each definiton of a function has an associated define:
@ -332,16 +346,14 @@
// <etc> <return_type> <function_id> ( <arguments> ) { <implementation> } // <etc> <return_type> <function_id> ( <arguments> ) { <implementation> }
// Concrete example: // Concrete example:
#define ENABLE_GENERIC_EXAMPLE 0
#if ENABLE_GENERIC_EXAMPLE
// To add support for long: // To add support for long:
#define HASH__ARGS_SIG_1 GEN_GENERIC_FUNCTION_ARG_SIGNATURE( hash__P_long, long long ) #define GEN_EXAMPLE_HASH__ARGS_SIG_1 GEN_GENERIC_FUNCTION_ARG_SIGNATURE( hash__P_long, long long )
size_t hash__P_long ( long val ) { return val * 2654435761ull; } size_t gen_example_hash__P_long( long val ) { return val * 2654435761ull; }
// To add support for long long: // To add support for long long:
#define HASH__ARGS_SIG_2 GEN_GENERIC_FUNCTION_ARG_SIGNATURE( hash__P_long_long, long long ) #define GEN_EXAMPLE_HASH__ARGS_SIG_2 GEN_GENERIC_FUNCTION_ARG_SIGNATURE( hash__P_long_long, long long )
size_t hash__P_long_long( long long val ) { return val * 2654435761ull; } size_t gen_example_hash__P_long_long( long long val ) { return val * 2654435761ull; }
// If using an Editor with support for syntax hightlighting macros: HASH__ARGS_SIG_1 and HASH_ARGS_SIG_2 should show color highlighting indicating the slot is enabled, // If using an Editor with support for syntax hightlighting macros: HASH__ARGS_SIG_1 and HASH_ARGS_SIG_2 should show color highlighting indicating the slot is enabled,
// or, "defined" for usage during the compilation pass that handles the _Generic instrinsic. // or, "defined" for usage during the compilation pass that handles the _Generic instrinsic.
@ -358,8 +370,28 @@ size_t hash__P_long_long( long long val ) { return val * 2654435761ull; }
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT_LAST( HASH__ARGS_SIG_8 ) \ GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT_LAST( HASH__ARGS_SIG_8 ) \
) GEN_RESOLVED_FUNCTION_CALL( function_arguments ) ) GEN_RESOLVED_FUNCTION_CALL( function_arguments )
#endif // ENABLE_GENERIC_EXAMPLE // Additional Variations:
// If the function takes more than one argument the following is used:
#define GEN_FUNCTION_GENERIC_EXAMPLE_VARADIC( selector_arg, ... ) _Generic( \
(selector_arg), \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_2 ) \
... \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT_LAST(FunctionID__ARGS_SIG_N ) \
) GEN_RESOLVED_FUNCTION_CALL( selector_arg, __VA_ARG__ )
// If the function does not take the arugment as a parameter:
#define GEN_FUNCTION_GENERIC_EXAMPLE_DIRECT_TYPE( selector_arg ) _Generic( \
( GEN_TYPE_TO_EXP(selector_arg) ), \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_1 ) \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT( FunctionID__ARGS_SIG_2 ) \
/* ... */ \
GEN_IF_MACRO_DEFINED_INCLUDE_THIS_SLOT_LAST(FunctionID__ARGS_SIG_N ) \
) GEN_RESOLVED_FUNCTION_CALL()
// typedef void* GEN_GenericExampleType;
// GEN_FUNCTION_GENERIC_EXAMPLE_DIRECT_TYPE( GEN_GenericExampleType );
// END OF ------------------------ _Generic function overloading ----------------------------------------- END OF // END OF ------------------------ _Generic function overloading ----------------------------------------- END OF
#endif #endif

View File

@ -123,7 +123,7 @@
#endif #endif
#if GEN_COMPILER_C #if GEN_COMPILER_C
#pragma message("Detected C") #pragma message("GENCPP: Detected C")
#endif #endif
#pragma endregion Platform Detection #pragma endregion Platform Detection

View File

@ -54,6 +54,7 @@ Template
Typedef Typedef
Typename Typename
Union Union
Union_Fwd
Union_Body Union_Body
Using Using
Using_Namespace Using_Namespace

1 Invalid
54 Typedef
55 Typename
56 Union
57 Union_Fwd
58 Union_Body
59 Using
60 Using_Namespace

View File

@ -13,7 +13,7 @@ CodeBody gen_ecode( char const* path )
char scratch_mem[kilobytes(1)]; char scratch_mem[kilobytes(1)];
Arena scratch = arena_init_from_memory( scratch_mem, sizeof(scratch_mem) ); Arena scratch = arena_init_from_memory( scratch_mem, sizeof(scratch_mem) );
file_read_contents( arena_allocator_info( & scratch), zero_terminate, path ); file_read_contents( arena_allocator_info( & scratch), file_zero_terminate, path );
CSV_Object csv_nodes; CSV_Object csv_nodes;
csv_parse( &csv_nodes, scratch_mem, GlobalAllocator, false ); csv_parse( &csv_nodes, scratch_mem, GlobalAllocator, false );
@ -63,7 +63,7 @@ CodeBody gen_eoperator( char const* path )
char scratch_mem[kilobytes(4)]; char scratch_mem[kilobytes(4)];
Arena scratch = arena_init_from_memory( scratch_mem, sizeof(scratch_mem) ); Arena scratch = arena_init_from_memory( scratch_mem, sizeof(scratch_mem) );
file_read_contents( arena_allocator_info(& scratch), zero_terminate, path ); file_read_contents( arena_allocator_info(& scratch), file_zero_terminate, path );
CSV_Object csv_nodes; CSV_Object csv_nodes;
csv_parse( &csv_nodes, scratch_mem, GlobalAllocator, false ); csv_parse( &csv_nodes, scratch_mem, GlobalAllocator, false );
@ -119,7 +119,7 @@ CodeBody gen_especifier( char const* path )
char scratch_mem[kilobytes(4)]; char scratch_mem[kilobytes(4)];
Arena scratch = arena_init_from_memory( scratch_mem, sizeof(scratch_mem) ); Arena scratch = arena_init_from_memory( scratch_mem, sizeof(scratch_mem) );
file_read_contents( arena_allocator_info(& scratch), zero_terminate, path ); file_read_contents( arena_allocator_info(& scratch), file_zero_terminate, path );
CSV_Object csv_nodes; CSV_Object csv_nodes;
csv_parse( &csv_nodes, scratch_mem, GlobalAllocator, false ); csv_parse( &csv_nodes, scratch_mem, GlobalAllocator, false );
@ -226,12 +226,12 @@ CodeBody gen_etoktype( char const* etok_path, char const* attr_path )
AllocatorInfo scratch_info = arena_allocator_info(& scratch); AllocatorInfo scratch_info = arena_allocator_info(& scratch);
FileContents enum_content = file_read_contents( scratch_info, zero_terminate, etok_path ); FileContents enum_content = file_read_contents( scratch_info, file_zero_terminate, etok_path );
CSV_Object csv_enum_nodes; CSV_Object csv_enum_nodes;
csv_parse( &csv_enum_nodes, rcast(char*, enum_content.data), GlobalAllocator, false ); csv_parse( &csv_enum_nodes, rcast(char*, enum_content.data), GlobalAllocator, false );
FileContents attrib_content = file_read_contents( scratch_info, zero_terminate, attr_path ); FileContents attrib_content = file_read_contents( scratch_info, file_zero_terminate, attr_path );
CSV_Object csv_attr_nodes; CSV_Object csv_attr_nodes;
csv_parse( &csv_attr_nodes, rcast(char*, attrib_content.data), GlobalAllocator, false ); csv_parse( &csv_attr_nodes, rcast(char*, attrib_content.data), GlobalAllocator, false );

View File

@ -31,8 +31,9 @@
#undef hashtable_remove_entry #undef hashtable_remove_entry
#undef hashtable_set #undef hashtable_set
#undef hashtable_slot #undef hashtable_slot
#undef hashtable_add_entry
#undef hashtable_find
#undef hashtable_full
#undef hashtable_map #undef hashtable_map
#undef hashtable_map_mut #undef hashtable_map_mut
//#undef hashtable_add_entry
//#undef hashtable_find
//#undef hashtable_full

View File

@ -31,8 +31,9 @@
#define hashtable_remove_entry(table, idx) hashtable_remove_entry< get_hashtable_underlying_type(table) >(table, idx) #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_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_slot(table, key) hashtable_slot < get_hashtable_underlying_type(table) >(table, key)
#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)
#define hashtable_map(table, map_proc) hashtable_map < get_hashtable_underlying_type(table) >(table, map_proc) #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_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)

View File

@ -8,6 +8,7 @@
# pragma clang diagnostic ignored "-Wvarargs" # pragma clang diagnostic ignored "-Wvarargs"
# pragma clang diagnostic ignored "-Wunused-function" # pragma clang diagnostic ignored "-Wunused-function"
# pragma clang diagnostic ignored "-Wbraced-scalar-init" # pragma clang diagnostic ignored "-Wbraced-scalar-init"
# pragma clang diagnostic ignored "-W#pragma-messages"
#endif #endif
#ifdef __GNUC__ #ifdef __GNUC__

View File

@ -137,7 +137,7 @@ if ( $bootstrap )
$unit = join-path $path_project "bootstrap.cpp" $unit = join-path $path_project "bootstrap.cpp"
$executable = join-path $path_build "bootstrap.exe" $executable = join-path $path_build "bootstrap.exe"
build-simple $path_build $includes $compiler_args $linker_args $unit $executable $result = build-simple $path_build $includes $compiler_args $linker_args $unit $executable
Push-Location $path_project Push-Location $path_project
if ( Test-Path( $executable ) ) { if ( Test-Path( $executable ) ) {
@ -175,7 +175,7 @@ if ( $singleheader )
$flag_link_win_subsystem_console $flag_link_win_subsystem_console
) )
build-simple $path_build $includes $compiler_args $linker_args $unit $executable $result = build-simple $path_build $includes $compiler_args $linker_args $unit $executable
Push-Location $path_singleheader Push-Location $path_singleheader
if ( Test-Path( $executable ) ) { if ( Test-Path( $executable ) ) {
@ -213,7 +213,7 @@ if ( $c_library )
$flag_link_win_subsystem_console $flag_link_win_subsystem_console
) )
build-simple $path_build $includes $compiler_args $linker_args $unit $executable $result = build-simple $path_build $includes $compiler_args $linker_args $unit $executable
Push-Location $path_c_library Push-Location $path_c_library
if ( Test-Path( $executable ) ) { if ( Test-Path( $executable ) ) {
@ -240,7 +240,7 @@ if ( $c_library )
$compiler_args += "/std:c11" $compiler_args += "/std:c11"
} }
build-simple $path_build $includes $compiler_args $linker_args $unit $executable $result = build-simple $path_build $includes $compiler_args $linker_args $unit $executable
Push-Location $path_c_library Push-Location $path_c_library
if ( Test-Path( $executable ) ) { if ( Test-Path( $executable ) ) {
@ -278,7 +278,7 @@ if ( $unreal )
$flag_link_win_subsystem_console $flag_link_win_subsystem_console
) )
build-simple $path_build $includes $compiler_args $linker_args $unit $executable $result = build-simple $path_build $includes $compiler_args $linker_args $unit $executable
Push-Location $path_unreal Push-Location $path_unreal
if ( Test-Path( $executable ) ) { if ( Test-Path( $executable ) ) {
@ -340,7 +340,7 @@ if ( $test )
$flag_link_win_subsystem_console $flag_link_win_subsystem_console
) )
build-simple $path_build $includes $compiler_args $linker_args $unit $executable $result = build-simple $path_build $includes $compiler_args $linker_args $unit $executable
Push-Location $path_test Push-Location $path_test
Write-Host $path_test Write-Host $path_test