16 Commits

Author SHA1 Message Date
Ed_
b1de5b1ac7 Fixed swap fn 2023-07-21 01:40:45 -04:00
Ed_
a37c3f63c2 Update to readme, update CodePool_NumBlocks to 64k 2023-07-21 01:12:38 -04:00
Ed_
efd7af9f96 Added ability for a CodeBody to append another 2023-07-20 23:51:56 -04:00
Ed_
8bb0db8145 Moved the indentation for the library over
The entire project uses the namespace and it felt redundant.

There is a fix for array append_at. Finally got csv parsing working with it.
2023-07-19 23:42:28 -04:00
Ed_
d1c061769c GlobalAllocator fixes
- Made a gen script (does full build and test) build just builds gencpp now.
2023-07-19 00:49:54 -04:00
Ed_
1488aeb188 update todo 2023-07-19 00:24:00 -04:00
Ed_
db584d8fe6 Removed GEN_FEATURE_PARSING macro, fixes to readme
Parsing constructors are too ergonomic to be a "optional" feature.
2023-07-19 00:14:15 -04:00
Ed_
4d2f6a6315 Refactor Test gen_time to GEN_TIME 2023-07-19 00:13:12 -04:00
Ed_
231ae5f5d6 Some refactors (see description)
- Renamed macro gen_time to GEN_TIME
- Moved scanner and editor to their own headers, I'm going to consider them extensions.
- I'm preparing to setup the library to build on multiple compiler platforms: clang, gcc, msvc.
2023-07-18 23:33:00 -04:00
Ed_
e501941c5c Fix for sanity test... 2023-07-17 23:40:28 -04:00
Ed_
9a784fe92f Preparing to implement ADT for csv functions.
I'm rewritting it the way I'd like to learn it.
- I want to use csv parsing heavily with the library so I'm just going to add it to the scanner.

- Globaly memory allocator moved to regular gen header/source as its something really just made for the library.
- Some small refactors to macros
- The parser was updated to support tokenizing preprocessor directives.
  - The purpose is based off intuition that it will be required for the scanner.
2023-07-17 20:17:19 -04:00
Ed_
2a319ed6db Additions and fixes based off genc repo
Typedef parses enum namespaced types properly (C typedefs of enums to expose to global scope).
2023-07-16 23:18:00 -04:00
Ed_
41dc0e3fbb Bad ifdef for benchmark in gen_dep. 2023-07-16 18:06:43 -04:00
Ed_
98b776d66e Small correction to test comment. 2023-07-16 18:01:22 -04:00
Ed_
7634aeb34c Fixes to memory mangment, library is much faster now. 2023-07-16 18:00:07 -04:00
Ed_
b544f24015 Moved dependencies back to their own files (gen_dep.hpp/cpp)
Its easier to manage, I'm sticking with generating the single header so it wont matter, its easy to refactor back if desired.
2023-07-16 12:08:57 -04:00
42 changed files with 14317 additions and 11573 deletions

View File

@ -9,7 +9,7 @@
"_DEBUG",
"UNICODE",
"_UNICODE",
"gen_time"
"GEN_TIME"
],
"windowsSdkVersion": "10.0.19041.0",
"compilerPath": "C:/Users/Ed/scoop/apps/llvm/current/bin/clang++.exe",

View File

@ -23,5 +23,6 @@
"C_Cpp.intelliSenseEngineFallback": "disabled",
"mesonbuild.configureOnOpen": true,
"C_Cpp.errorSquiggles": "enabled",
"godot_tools.scene_file_config": ""
}
"godot_tools.scene_file_config": "",
"C_Cpp.default.compilerPath": "cl.exe"
}

115
Readme.md
View File

@ -2,7 +2,7 @@
An attempt at simple staged metaprogramming for c/c++.
The library API is a compositon of code element constructors.
The library API is a composition of code element constructors.
These build up a code AST to then serialize with a file builder.
### TOC
@ -18,6 +18,7 @@ These build up a code AST to then serialize with a file builder.
* [On multithreading](#on-multi-threading)
* [Extending the library](#extending-the-library)
* [TODO](#todo)
* [Thoughts](#thoughts)
## Notes
@ -44,7 +45,7 @@ A C variant is hosted [here](https://github.com/Ed94/genc); I haven't gotten hea
## Usage
A metaprogram is built to generate files before the main program is built. We'll term runtime for this program as `gen_time`. The metaprogram's core implementation are within `gen.hpp` and `gen.cpp` in the project directory.
A metaprogram is built to generate files before the main program is built. We'll term runtime for this program as `GEN_TIME`. The metaprogram's core implementation are within `gen.hpp` and `gen.cpp` in the project directory.
`gen.cpp` \`s `main()` is defined as `gen_main()` which the user will have to define once for their program. There they will dictate everything that should be generated.
@ -53,10 +54,9 @@ In order to keep the locality of this code within the same files the following p
Within `program.cpp` :
```cpp
#ifdef GEN_TIME
#include "gen.hpp"
#ifdef gen_time
...
u32 gen_main()
@ -65,8 +65,7 @@ u32 gen_main()
}
#endif
#ifndef gen_time
#ifndef GEN_TIME
#include "program.gen.cpp"
// Regular runtime dependent on the generated code here.
@ -125,7 +124,7 @@ Code header = untyped_str( code(
));
```
`name` is a helper macro for providing a string literal with its size, intended for the name paraemter of functions.
`name` is a helper macro for providing a string literal with its size, intended for the name parameter of functions.
`code` is a helper macro for providing a string literal with its size, but intended for code string parameters.
`args` is a helper macro for providing the number of arguments to varadic constructors.
@ -149,7 +148,7 @@ An example of building is provided in the test directory.
There are two meson build files the one within test is the program's build specification.
The other one in the gen directory within test is the metaprogram's build specification.
Both of them build the same source file: `test.cpp`. The only differences are that gen needs a different relative path to the include directories and defines the macro definition: `gen_time`.
Both of them build the same source file: `test.cpp`. The only differences are that gen needs a different relative path to the include directories and defines the macro definition: `GEN_TIME`.
This method is setup where all the metaprogram's code are the within the same files as the regular program's code.
@ -184,7 +183,7 @@ Especially when the priority is to keep this library small and easy to grasp for
When it comes to templates:
Only trivial template support is provided. the intention is for only simple, non-recursive subsitution.
Only trivial template support is provided. the intention is for only simple, non-recursive substitution.
The parameters of the template are treated like regular parameter AST entries.
This means that the typename entry for the parameter AST would be either:
@ -195,7 +194,7 @@ This means that the typename entry for the parameter AST would be either:
Anything beyond this usage is not supported by parse_template for arguments (at least not intentionally).
Use at your own mental peril...
*Concepts and Constraints are not supported, its usage is non-tirival substiution.*
*Concepts and Constraints are not supported, its usage is non-trivial substitution.*
### The Data & Interface
@ -277,27 +276,34 @@ Data Notes:
* The allocator definitions used are exposed to the user incase they want to dictate memory usage
* You'll find the memory handling in `init`, `gen_string_allocator`, `get_cached_string`, `make_code`.
* ASTs are wrapped for the user in a Code struct which is a warpper for a AST* type.
* ASTs are wrapped for the user in a Code struct which is a wrapper for a AST* type.
* Both AST and Code have member symbols but their data layout is enforced to be POD types.
* This library treats memory failures as fatal.
* Strings are stored in their own set of arenas. AST constructors use cached strings for names, and content.
* Cached Strings are stored in their own set of arenas. AST constructors use cached strings for names, and content.
* `StringArenas`, `StringCache`, `Allocator_StringArena`, and `Allocator_StringTable` are the associated containers or allocators.
* Strings used for seralization and file buffers are not contained by those used for cached strings.
* They are currently using `Memory::GlobalAllocator`, which are tracked array of arenas that grows as needed (adds buckets when one runs out).
* Memory within the buckets is not resused, so its inherently wasteful (most likely will give non-cached strings their own tailored allocator later)
* Strings used for serialization and file buffers are not contained by those used for cached strings.
* They are currently using `GlobalAllocator`, which are tracked array of arenas that grows as needed (adds buckets when one runs out).
* Memory within the buckets is not reused, so its inherently wasteful.
* I will be augmenting the single arena with a simple slag allocator.
* Linked lists used children nodes on bodies, and parameters.
* Its intended to generate the AST in one go and serialize after. The contructors and serializer are designed to be a "one pass, front to back" setup.
* Its intended to generate the AST in one go and serialize after. The constructors and serializer are designed to be a "one pass, front to back" setup.
* When benchmarking, the three most significant var to tune are:
* `Global_BlockSize` (found gen_dep.hpp) : Used by the GlobalAllocator for the size of each global arena.
* `SizePer_StringArena` (found in gen.hpp under the constants region) : Used by the string cache to store strings.
* `CodePool_NumBlocks` (found in gen.hpp under constants region) : Used by code pool to store ASTs.
* The default values can handled generating for a string up to a size of ~650 kbs (bottleneck is serialization).
* Increasing the values can generate files upwards of over a million lines without issue (the formatter will most likely run slower than it)
Two generic templated containers are used throughout the library:
* `template< class Type> struct Array`
* `template< class Type> struct HashTable`
Both Code and AST definitions have a `template< class Type> Code/AST cast()`. Its just an alternative way to explictly cast to each other.
Both Code and AST definitions have a `template< class Type> Code/AST cast()`. Its just an alternative way to explicitly cast to each other.
Otherwise the library is free of any templates.
The following CodeTypes are used which the user may optionally use strong typeing with if they enable: `GEN_ENFORCE_STRONG_CODE_TYPES`
The following CodeTypes are used which the user may optionally use strong typing with if they enable: `GEN_ENFORCE_STRONG_CODE_TYPES`
* CodeBody : Has support for `for-range` iterating across Code objects.
* CodeAttributes
@ -313,7 +319,7 @@ The following CodeTypes are used which the user may optionally use strong typein
* CodeNamespace
* CodeOperator
* CodeOpCast
* CodeParam : Has suppor for `for-range` iterating across parameters.
* CodeParam : Has support for `for-range` iterating across parameters.
* CodeSpecifier : Has support for `for-range` iterating across specifiers.
* CodeStruct
* CodeTemplate
@ -324,9 +330,9 @@ The following CodeTypes are used which the user may optionally use strong typein
* CodeUsingNamespace
* CodeVar
Each Code boy has an assoicated "filtered AST" with the naming convention: `AST_<CodeName>`
Unrelated fields of the AST for that node type are omitted and only necesary padding members are defined otherwise.
Retreiving a raw version of the ast can be done using the `raw()` function defined in each AST.
Each Code boy has an associated "filtered AST" with the naming convention: `AST_<CodeName>`
Unrelated fields of the AST for that node type are omitted and only necessary padding members are defined otherwise.
Retrieving a raw version of the ast can be done using the `raw()` function defined in each AST.
## There are three sets of interfaces for Code AST generation the library provides
@ -342,7 +348,7 @@ The construction will fail and return Code::Invalid otherwise.
Interface :``
* def_attributes
* *This is preappened right before the function symbol, or placed after the class or struct keyword for any flavor of attributes used.*
* *This is pre-appended right before the function symbol, or placed after the class or struct keyword for any flavor of attributes used.*
* *Its up to the user to use the desired attribute formatting: `[[]]` (standard), `__declspec` (Microsoft), or `__attribute__` (GNU).*
* def_comment
* def_class
@ -442,7 +448,7 @@ The lexing and parsing takes shortcuts from whats expected in the standard.
* Assumed to *come before specifiers* (`const`, `constexpr`, `extern`, `static`, etc) for a function
* Or in the usual spot for class, structs, (*right after the declaration keyword*)
* typedefs have attributes with the type (`parse_type`)
* As a general rule; if its not available from the upfront contructors, its not available in the parsing constructors.
* As a general rule; if its not available from the upfront constructors, its not available in the parsing constructors.
* *Upfront constructors are not necessarily used in the parsing constructors, this is just a good metric to know what can be parsed.*
Usage:
@ -485,9 +491,18 @@ These restrictions help prevent abuse of untyped code to some extent.
Usage Conventions:
```cpp
Code <name> = def_varaible( <type>, <name>, untyped_<function name>(
Code <name> = def_variable( <type>, <name>, untyped_<function name>(
<string with code>
));
Code <name> = untyped_str( code(
<some code without "" quotes>
));
```
Optionally, `code_str`, and `code_fmt` macros can be used so that the code macro doesn't have to be used:
```cpp
Code <name> = code_str( <some code without "" quotes > )
```
Template metaprogramming in the traditional sense becomes possible with the use of `token_fmt` and parse constructors:
@ -583,9 +598,9 @@ Editor and Scanner are disabled by default, use `GEN_FEATURE_EDITOR` and `GEN_FE
### Builder is a similar object to the jai language's string_builder
* The purpose of it is to generate a file.
* A file is specified and opened for writting using the open( file_path) ) function.
* The code is provided via print( code ) function will be seralized to its buffer.
* When all seralization is finished, use the write() command to write the buffer to the file.
* A file is specified and opened for writing using the open( file_path) ) function.
* The code is provided via print( code ) function will be serialized to its buffer.
* When all serialization is finished, use the write() command to write the buffer to the file.
### Editor is for editing a series of files based on a set of requests provided to it
@ -618,7 +633,7 @@ It will on call add a request to the queue to run the refactor script on the fil
* The purpose is to grab definitions to generate metadata or generate new code from these definitions.
* Requests are populated using the add( SymbolInfo, Policy ) function. The symbol info is the same as the one used for the editor. So is the case with Policy.
The file will only be read from, no writting supported.
The file will only be read from, no writing supported.
One great use case is for example: generating the single-header library for gencpp!
@ -636,10 +651,10 @@ Request queue in both Editor and Scanner are cleared once process_requests compl
Currently unsupported. The following changes would have to be made:
* Setup static data accesss with fences if more than one thread will generate ASTs ( or keep a different set for each thread)
* Make sure local peristent data of functions are also thread local.
* Setup static data access with fences if more than one thread will generate ASTs ( or keep a different set for each thread)
* Make sure local persistent data of functions are also thread local.
* The builder should be done on a per-thread basis.
* Due to the design of the editor and scanner, it will most likely be best to make each file a job to process request entries on. Receipts should have an an array to store per thread. They can be combined to the final reciepts array when all files have been processed.
* Due to the design of the editor and scanner, it will most likely be best to make each file a job to process request entries on. Receipts should have an an array to store per thread. They can be combined to the final receipts array when all files have been processed.
## Extending the library
@ -660,21 +675,39 @@ The convention you'll see used throughout the API of the library is as follows:
1. Check name or parameters to make sure they are valid for the construction requested
2. Create a code object using `make_code`.
3. Populate immediate fields (Name, Type, ModuleFlags, etc)
4. Populate sub-entires using `add_entry`. If using the default seralization function `to_string`, follow the order at which entires are expected to appear (there is a strong ordering expected).
4. Populate sub-entires using `add_entry`. If using the default serialization function `to_string`, follow the order at which entires are expected to appear (there is a strong ordering expected).
Names or Content fields are interned strings and thus showed be cached using `get_cached_string` if its desired to preserve that behavior.
`def_operator` is the most sophisitacated constructor as it has multiple permutations of definitions that could be created that are not trivial to determine if valid.
`def_operator` is the most sophisticated constructor as it has multiple permutations of definitions that could be created that are not trivial to determine if valid.
# TODO
* Implement a context stack for the parsing, allows for accurate scope validation for the AST types.
* Make a more robust test suite.
* Generate a single-header library.
* Improve the allocation strategy for strings in `Builder`, `AST::to_string`, `Parser::lex`, all three can use some form of slab allocation strategy...
* Can most likely use a simple slag allocator.
* May be in need of a better name, I found a few repos with this same one...
* Support defining & parsing full definitions inside a typedef. (For C patterns)
* Support module and attribute parsing (Marked with TODOs for now..)
* Suffix specifiers for functions (const, override, final)
* Implement a context stack for the parsing, allows for accurate scope validation for the AST types.
* Trailing specifiers ( postfix ) for functions (const, override, final)
* Make a more robust test suite.
* Generate a single-header library
* Componetize the library, make a metaprogram using gencpp to bootstrap itself.
* Implement the Scanner
* Implement the Editor
* Should the builder be an "extension" header?
* Technically the library doesn't require it and the user can use their own filesystem library.
* It would allow me to remove the filesystem dependencies and related functions outside of gen base headers. ( At least 1k loc reduced )
* ADT and the CSV parser depend on it as well. The `str_fmt_file` related functions do as well but they can be ommited.
* Scanner and editor will also depend on it so they would need to include w/e the depency header for all three file-interacting interfaces.
* `gen.dep.files.hpp`
* Convert GlobalAllocator to a slab allocator:
```md
Slab classes (for 10 mb arena)
1KB slab: 5MB ( 5MB / 1KB ~ 5,000 blocks )
4KB slab: 10MB ( 10MB / 4KB ~ 2,500 blocks )
16KB slab: 15MB ( 15MB / 16KB ~ 960 blocks )
64KB slab: 15MB ( 15MB / 64KB ~ 240 blocks )
256KB slab: 20MB ( 20MB / 256KB ~ 80 blocks )
512KB slab: 20MB ( 20MB / 512KB ~ 40 blocks )
1MB slab: 15MB ( 15MB / 1MB ~ 15 blocks )
```

View File

@ -79,7 +79,7 @@
<NMakeBuildCommandLine>powershell.exe -ExecutionPolicy Unrestricted -File "$(ProjectDir)scripts\build.ps1"</NMakeBuildCommandLine>
<NMakeReBuildCommandLine>powershell.exe -ExecutionPolicy Unrestricted -File "$(ProjectDir)scripts\build.ps1"</NMakeReBuildCommandLine>
<NMakeCleanCommandLine>powershell.exe -ExecutionPolicy Unrestricted -File "$(ProjectDir)scripts\clean.ps1"</NMakeCleanCommandLine>
<NMakePreprocessorDefinitions>gen_time;$(NMakePreprocessorDefinitions)</NMakePreprocessorDefinitions>
<NMakePreprocessorDefinitions>GEN_TIME;$(NMakePreprocessorDefinitions)</NMakePreprocessorDefinitions>
<IncludePath>$(ProjectDir)thirdparty;$(ProjectDir)project;$(ProjectDir)test;$(IncludePath)</IncludePath>
<SourcePath>$(ProjectDir)project;$(ProjectDir)test;$(SourcePath)</SourcePath>
</PropertyGroup>
@ -87,7 +87,7 @@
<NMakeBuildCommandLine>powershell.exe -ExecutionPolicy Unrestricted -File "$(ProjectDir)scripts\build.ps1"</NMakeBuildCommandLine>
<NMakeReBuildCommandLine>powershell.exe -ExecutionPolicy Unrestricted -File "$(ProjectDir)scripts\build.ps1"</NMakeReBuildCommandLine>
<NMakeCleanCommandLine>powershell.exe -ExecutionPolicy Unrestricted -File "$(ProjectDir)scripts\clean.ps1"</NMakeCleanCommandLine>
<NMakePreprocessorDefinitions>gen_time;$(NMakePreprocessorDefinitions)</NMakePreprocessorDefinitions>
<NMakePreprocessorDefinitions>GEN_TIME;$(NMakePreprocessorDefinitions)</NMakePreprocessorDefinitions>
<IncludePath>$(ProjectDir)thirdparty;$(ProjectDir)project;$(ProjectDir)test;$(IncludePath)</IncludePath>
<SourcePath>$(ProjectDir)project;$(ProjectDir)test;$(SourcePath)</SourcePath>
</PropertyGroup>

View File

@ -1,22 +1,24 @@
# Documentation
All the library code is contained in two files: `gen.hpp` and `gen.cpp`
The core library is contained within `gen.hpp` and `gen.cpp`.
Things related to the editor and scanner are in their own respective files. (Ex: `gen.scanner.<hpp/cpp>` )
## gen.hpp
Feature Macros:
* `GEN_DONT_ENFORCE_GEN_TIME_GUARD` : By default, the library ( gen.hpp/ gen.cpp ) expects the macro `GEN_TIME` to be defined, this disables that.
* `GEN_ROLL_OWN_DEPENDENCIES` : Optional override so that user may define the dependencies themselves.
* `GEN_DEFINE_LIBRARY_CORE_CONSTANTS` : Optional typename codes as they are non-standard to C/C++ and not necessary to library usage
* `GEN_ENFORCE_STRONG_CODE_TYPES` : Enforces casts to filtered code types.
* `GEN_FEATURE_PARSING` : Defines the parse constructors
* `GEN_FEATURE_EDITOR` : Defines the file editing features for changing definitions based on ASTs
* `GEN_FEATURE_SCANNER` : Defines the file scanning features for generating ASTs
`GEN_USE_RECURSIVE_AST_DUPLICATION` is available but its not well tested and should not need to be used.
If constructing ASTs properly. There should be no modification of ASTs, and thus this would never become an issue.
`GEN_USE_RECURSIVE_AST_DUPLICATION` is available but its not well tested and should not need to be used.
If constructing ASTs properly. There should be no modification of ASTs, and thus this would never become an issue.
(I will probably remove down the line...)
Due to the design of `gen.hpp` to support being written alongside runtime intended code (in the same file), all the code is wrapped in a `gen_time` `#ifdef` and then wrapped further in a `gen` namespace to avoid pollution of the global scope.
Due to the design of `gen.hpp` to support being written alongside runtime intended code (in the same file), all the code is wrapped in a `GEN_TIME` `#ifdef` and then wrapped further in a `gen` namespace to avoid pollution of the global scope.
*Note: Its possible with the scanner feature to support parsing runtime files that use "generic" macros or identifiers with certain patterns.
This can be used to auto-queue generation of dependent definitions for the symbols used.*
@ -30,27 +32,27 @@ log_failure definition : based on whether to always use fatal on all errors
Major enum definitions and their associated functions used with the AST data
* `ECode` : Used to tag ASTs by their type
* `EOperator` : Used to tag operator overloads with thier op type
* `EOperator` : Used to tag operator overloads with their op type
* `ESpecifier` : Used with specifier ASTs for all specifiers the user may tag an associated
AST with.
* `AccessSpec` : Used with class and struct ASTs to denote the public, protected, or private fields.
* `EnumT` : Used with def_enum to determine if constructing a regular enum or an enum class.
* `ModuleFlag` : Used with any valid definition that can have export or import related keywords assoicated with it.
* `ModuleFlag` : Used with any valid definition that can have export or import related keywords associated with it.
#### Data Structures
`StringCache` : Hash table for cached strings. (`StringCached` typedef used to denote strings managed by it)
`Code` : Wrapper for `AST` with functionality for handling it appropriately.
`AST` : The node data strucuture for the code.
`AST` : The node data structure for the code.
`Code Types` : Codes with typed ASTs. Body, Param, and Specifier have unique implementation, the rest use `Define_CodeType`
`AST Types` : Filtered AST definitions.
#### Gen Interface
First set of fowards are either backend functions used for various aspects of AST generation or configurating allocators used for different containers.
First set of forwards are either backend functions used for various aspects of AST generation or configurations allocators used for different containers.
Interface fowards defined in order of: Upfront, Parsing, Untyped.
Interface forwards defined in order of: Upfront, Parsing, Untyped.
From there forwards for the File handlers are defined: Builder, Editor, Scanner.

File diff suppressed because it is too large Load Diff

3269
project/gen.dep.cpp Normal file

File diff suppressed because it is too large Load Diff

2923
project/gen.dep.hpp Normal file

File diff suppressed because it is too large Load Diff

73
project/gen.editor.hpp Normal file
View File

@ -0,0 +1,73 @@
#pragma once
#include "gen.scanner.hpp"
namespace gen {
struct Policy
{
// Nothing for now.
};
enum class SymbolType : u32
{
Code,
Line,
Marker
};
struct Editor
{
enum RequestType : u32
{
Add,
Replace,
Remove
};
struct SymbolData
{
Policy Policy;
SymbolInfo Info;
};
struct RequestEntry
{
union {
SymbolData Symbol;
String Specification;
};
RequestType Type;
};
struct Receipt
{
StringCached File;
Code Found;
Code Written;
bool Result;
};
static AllocatorInfo Allocator;
static void set_allocator( AllocatorInfo allocator );
Array<FileInfo> Files;
String Buffer;
Array<RequestEntry> Requests;
void add_files( s32 num, char const** files );
void add ( SymbolInfo definition, Policy policy, Code to_inject );
void remove ( SymbolInfo definition, Policy policy );
void replace( SymbolInfo definition, Policy policy, Code to_replace);
# ifdef GEN_FEATURE_EDITOR_REFACTOR
void refactor( char const* file_path, char const* specification_path );
# endif
bool process_requests( Array<Receipt> out_receipts );
};
// namespace gen
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,7 @@
#if __clang__
# pragma clang diagnostic pop
#endif
#if __GNUC__
# pragma GCC diagnostic pop
#endif

View File

@ -0,0 +1,17 @@
#if __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wunused-const-variable"
# pragma clang diagnostic ignored "-Wswitch"
# pragma clang diagnostic ignored "-Wunused-variable"
# pragma clang diagnostic ignored "-Wunknown-pragmas"
# pragma clang diagnostic ignored "-Wvarargs"
# pragma clang diagnostic ignored "-Wunused-function"
#endif
#if __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunknown-pragmas"
# pragma GCC diagnostic ignored "-Wcomment"
# pragma GCC diagnostic ignored "-Wswitch"
# pragma GCC diagnostic ignored "-Wunused-variable"
#endif

44
project/gen.scanner.hpp Normal file
View File

@ -0,0 +1,44 @@
#pragma once
#include "gen.hpp"
namespace gen {
struct SymbolInfo
{
StringCached File;
char const* Marker;
Code Signature;
};
struct Scanner
{
struct RequestEntry
{
SymbolInfo Info;
};
struct Receipt
{
StringCached File;
Code Defintion;
bool Result;
};
AllocatorInfo MemAlloc;
static void set_allocator( AllocatorInfo allocator );
Array<FileInfo> Files;
String Buffer;
Array<RequestEntry> Requests;
void add_files( s32 num, char const** files );
void add( SymbolInfo signature, Policy policy );
bool process_requests( Array<Receipt> out_receipts );
};
// namespace gen
}

View File

@ -1,4 +1,4 @@
#if gen_time
#if GEN_TIME
// This undefines the macros used by the gen library but are not necessary for the user.
#undef GEN_ARCH_64_BIT
@ -66,11 +66,15 @@
#undef stringize_va
#undef txt_StrC
#undef __
#undef args
#undef GEN_TIME
#undef gen_main
#undef gen_time
#undef __
#undef name
#undef code
#undef args
#undef code_str
#undef code_fmt
#undef token_fmt
// gen_time
// GEN_TIME
#endif

View File

@ -1,6 +1,6 @@
# Scripts
Build and cleanup scripts for the test deirectory are found here along with `natvis` and `natstepfilter` files for debugging.
Build and cleanup scripts for the test directory are found here along with `natvis` and `natstepfilter` files for debugging.
The build works as follows:
@ -9,4 +9,4 @@ The build works as follows:
* Build a program that uses some the generated definitions. (Have not done yet)
The `test/gen` directory has the meson.build config for the meta-program
The `test` directory has the one for the depdendent-program.
The `test` directory has the one for the dependent-program.

View File

@ -43,53 +43,3 @@ Push-Location $path_root
& ninja $args_ninja
Pop-Location
Push-location $path_gen
# Run meta-program
$gencpp = Join-Path $path_gen_build gencpp.exe
Write-Host `nGenerating files -- Parsed...
& $gencpp
# Format generated files
Write-Host `nBeginning format...
$formatParams = @(
'-i' # In-place
'-style=file' # Search for a .clang-format file in the parent directory of the source file.
'-verbose'
)
$include = @('*.gen.hpp', '*.gen.cpp')
$exclude = $null
$targetFiles = @(Get-ChildItem -Recurse -Path $path_gen -Include $include -Exclude $exclude | Select-Object -ExpandProperty FullName)
clang-format $formatParams $targetFiles
Write-Host "`nFormatting complete"
Pop-Location
# Build the program depending on generated files.
if ( -not( Test-Path $path_test_build ) )
{
Push-Location $path_test
$args_meson = @()
$args_meson += "setup"
$args_meson += $path_test_build
# & meson $args_meson
Pop-Location
}
Push-Location $path_root
$args_ninja = @()
$args_ninja += "-C"
$args_ninja += $path_test_build
# ninja $args_ninja
Pop-Location
Push-Location $path_test
$testcpp = Join-Path $path_test_build testcpp.exe
# & $testcpp
Pop-Location

95
scripts/gen.ps1 Normal file
View File

@ -0,0 +1,95 @@
[string] $type = $null
[string] $test = $false
foreach ( $arg in $args )
{
if ( $arg -eq "test" )
{
$test = $true
}
else
{
$type = $arg
}
}
$path_root = git rev-parse --show-toplevel
$path_build = Join-Path $path_root build
$path_scripts = Join-Path $path_root scripts
$path_test = Join-Path $path_root test
$path_gen = Join-Path $path_test gen
$path_test_build = Join-Path $path_test build
$path_gen_build = Join-Path $path_gen build
write-host "`n`nBuilding Test`n"
if ( -not( Test-Path $path_gen_build ) )
{
# Generate build files for meta-program
Push-Location $path_gen
$args_meson = @()
$args_meson += "setup"
$args_meson += $path_gen_build
& meson $args_meson
Pop-Location
}
# Compile meta-program
Push-Location $path_root
$args_ninja = @()
$args_ninja += "-C"
$args_ninja += $path_gen_build
& ninja $args_ninja
Pop-Location
Push-location $path_gen
# Run meta-program
$gencpp = Join-Path $path_gen_build gencpp.exe
Write-Host `nRunning tests...
& $gencpp
# Format generated files
Write-Host `nBeginning format...
$formatParams = @(
'-i' # In-place
'-style=file' # Search for a .clang-format file in the parent directory of the source file.
'-verbose'
)
$include = @('*.gen.hpp', '*.gen.cpp')
$exclude = $null
$targetFiles = @(Get-ChildItem -Recurse -Path $path_gen -Include $include -Exclude $exclude | Select-Object -ExpandProperty FullName)
clang-format $formatParams $targetFiles
Write-Host "`nFormatting complete"
Pop-Location
# Build the program depending on generated files.
if ( -not( Test-Path $path_test_build ) )
{
Push-Location $path_test
$args_meson = @()
$args_meson += "setup"
$args_meson += $path_test_build
# & meson $args_meson
Pop-Location
}
Push-Location $path_root
$args_ninja = @()
$args_ninja += "-C"
$args_ninja += $path_test_build
# ninja $args_ninja
Pop-Location
Push-Location $path_test
$testcpp = Join-Path $path_test_build testcpp.exe
# & $testcpp
Pop-Location

View File

@ -24,4 +24,7 @@
<Name>gen::Code.*::to_string</Name>
<Action>NoStepInto</Action>
</Function>
<Function>
<Name>gen::String::operator .*</Name>
</Function>
</StepFilter>

View File

@ -5,6 +5,18 @@
<DisplayString>Data:{Data} Proc:{Proc}</DisplayString>
</Type>
<Type Name="gen::Pool">
<DisplayString>NumBlocks: {NumBlocks} TotalSize: {TotalSize}</DisplayString>
<Expand>
<LinkedListItems>
<Size>NumBlocks</Size>
<HeadPointer>FreeList</HeadPointer>
<NextPointer>FreeList</NextPointer>
<ValueNode>PhysicalStart</ValueNode>
</LinkedListItems>
</Expand>
</Type>
<Type Name="gen::Array&lt;*&gt;">
<DisplayString>Num:{((Header*)((char*)Data - sizeof(Header)))->Num},
Capacity:{((Header*)((char*)Data - sizeof(Header)))->Capacity}</DisplayString>
@ -70,7 +82,8 @@
<Item Name="Content">ast->Content</Item>
<Item Name="Body">ast->Body</Item>
<Item Name="Parent">ast->Parent</Item>
<Item Name="ModuleFlags" Condition="ast->ModuleFlags != ModuleFlag::Invalid">ast->ModuleFlags</Item>
<Item Name="ModuleFlags" Condition="ast->ModuleFlags != ModuleFlag::Invalid">
ast->ModuleFlags</Item>
<Item Name="ArrSpecs" Condition="ast->ArrSpecs[0] &lt; 18">ast->ArrSpecs</Item>
<Item Name="Prev">ast->Prev</Item>
<Item Name="Next">ast->Next</Item>
@ -665,4 +678,4 @@
<DisplayString>Current[ { Arr[Idx] } ] Idx:{ Idx }</DisplayString>
</Type>
</AutoVisualizer>
</AutoVisualizer>

View File

@ -352,7 +352,7 @@
// gencpp macros
// word gen_main new_name
// word gen_time new_name
// word GEN_TIME new_name
// word __ new_name
// word code new_name

View File

@ -1 +0,0 @@
// Only for gen testing.

View File

@ -1,9 +1,11 @@
#pragma once
#if gen_time
#if GEN_TIME
#define GEN_FEATURE_PARSING
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
#define GEN_ENFORCE_STRONG_CODE_TYPES
#define GEN_EXPOSE_BACKEND
#define GEN_BENCHMARK
#include "gen.hpp"
using namespace gen;

View File

@ -1,9 +1,11 @@
#pragma once
#if gen_time
#if GEN_TIME
#define GEN_FEATURE_PARSING
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
#define GEN_ENFORCE_STRONG_CODE_TYPES
#define GEN_EXPOSE_BACKEND
#define GEN_BENCHMARK
#include "gen.hpp"
using namespace gen;
@ -201,4 +203,4 @@ u32 gen_buffer_file()
return 0;
}
#endif // gen_time
#endif // GEN_TIME

View File

@ -1,9 +1,11 @@
#pragma once
#if gen_time
#if GEN_TIME
#define GEN_FEATURE_PARSING
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
#define GEN_ENFORCE_STRONG_CODE_TYPES
#define GEN_EXPOSE_BACKEND
#define GEN_BENCHMARK
#include "gen.hpp"
#include "Array.Parsed.hpp"
@ -355,4 +357,4 @@ u32 gen_hashtable_file()
return 0;
}
#endif // gen_time
#endif // GEN_TIME

View File

@ -1,9 +1,11 @@
#pragma once
#if gen_time
#if GEN_TIME
#define GEN_FEATURE_PARSING
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
#define GEN_ENFORCE_STRONG_CODE_TYPES
#define GEN_EXPOSE_BACKEND
#define GEN_BENCHMARK
#include "gen.hpp"
#include "Buffer.Parsed.hpp"
@ -171,4 +173,4 @@ u32 gen_ring_file()
return 0;
}
#endif // gen_time
#endif // GEN_TIME

View File

@ -1,8 +1,10 @@
#pragma once
#ifdef gen_time
#ifdef GEN_TIME
#define GEN_FEATURE_PARSING
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
#define GEN_ENFORCE_STRONG_CODE_TYPES
#define GEN_EXPOSE_BACKEND
#define GEN_BENCHMARK
#include "gen.hpp"
using namespace gen;
@ -289,7 +291,7 @@ u32 gen_sanity()
));
CodeUsingNamespace npspace_using = (CodeUsingNamespace) parse_using( code(
CodeUsing npspace_using = parse_using( code(
using namespace TestNamespace;
));

View File

@ -2,10 +2,10 @@
The following tests focus on attempting to generate some math, containers, and the memory module of zpl.
Not all the files are written how I would practically use the librarry, the containers for example would
Not all the files are written how I would practically use the library, the containers for example would
be better on in c++ as templates, since the templates they generate are trivial symbols to inspect or debug.
An exmaple of a non-trival generation is a container for elements with SOA or AOS policy for layout.
An example of a non-trivial generation is a container for elements with SOA or AOS policy for layout.
(If a unified element syntax is desired)
The test is divided between two major sets of tests: Parsed and Upfront.

View File

@ -1,9 +1,9 @@
#pragma once
#ifdef gen_time
#if GEN_TIME
#define GEN_FEATURE_PARSING
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
#define GEN_ENFORCE_STRONG_CODE_TYPES
#define GEN_EXPOSE_BACKEND
#define GEN_BENCHMARK
#include "gen.hpp"
using namespace gen;
@ -91,7 +91,7 @@ Code gen_SOA( CodeStruct struct_def, s32 num_entries = 0 )
}
));
String content = String::make( Memory::GlobalAllocator, "return\n{\n" );
String content = String::make( GlobalAllocator, "return\n{\n" );
for ( CodeVar member : vars )
{
@ -114,4 +114,33 @@ Code gen_SOA( CodeStruct struct_def, s32 num_entries = 0 )
return soa;
}
void check_SOA()
{
log_fmt("\ncheck_SOA:");
gen::init();
Builder soa_test; soa_test.open( "SOA.gen.hpp" );
soa_test.print( parse_using( code(
using u16 = unsigned short;
)));
soa_test.print( def_include( txt_StrC("gen.hpp")));
soa_test.print( def_using_namespace( name(gen) ) );
soa_test.print( gen_SOA(
parse_struct( code(
struct TestStruct
{
u8 A;
u16 B;
u32 C;
u64 D;
};
))
));
soa_test.write();
gen::deinit();
log_fmt(" passed!\n");
}
#endif

View File

@ -1,6 +1,6 @@
#pragma once
#if gen_time
#if GEN_TIME
#include "gen.hpp"
using namespace gen;

View File

@ -1,6 +1,6 @@
#pragma once
#if gen_time
#if GEN_TIME
#include "gen.hpp"
using namespace gen;
@ -271,4 +271,4 @@ u32 gen_buffer_file()
return 0;
}
#endif // gen_time
#endif // GEN_TIME

View File

@ -1,6 +1,6 @@
#pragma once
#if gen_time
#if GEN_TIME
#include "gen.hpp"
#include "Array.Upfront.hpp"
@ -483,4 +483,4 @@ u32 gen_hashtable_file()
return 0;
}
#endif // gen_time
#endif // GEN_TIME

View File

@ -1,6 +1,6 @@
#pragma once
#if gen_time
#if GEN_TIME
#include "gen.hpp"
#include "Buffer.Upfront.hpp"
@ -225,4 +225,4 @@ u32 gen_ring_file()
return 0;
}
#endif // gen_time
#endif // GEN_TIME

View File

@ -1,4 +1,4 @@
#ifdef gen_time
#ifdef GEN_TIME
#include "gen.hpp"
using namespace gen;

View File

@ -22,6 +22,6 @@ endif
# add_project_arguments('-E', language : ['c', 'cpp'])
# add_global_arguments( '-E', language : ['cpp'])
add_project_arguments('-Dgen_time', language : ['c', 'cpp'])
add_project_arguments('-DGEN_TIME', language : ['c', 'cpp'])
executable( 'gencpp', sources, include_directories : includes )

0
test/parsing.cpp Normal file
View File

0
test/parsing.hpp Normal file
View File

93
test/sanity.cpp Normal file
View File

@ -0,0 +1,93 @@
// Testing to make sure backend of library is operating properly.
#ifdef GEN_TIME
#define GEN_FEATURE_PARSING
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
#define GEN_ENFORCE_STRONG_CODE_TYPES
#define GEN_EXPOSE_BACKEND
#define GEN_BENCHMARK
#include "gen.hpp"
void check_sanity()
{
using namespace gen;
gen::init();
log_fmt("\ncheck_sanity:\n");
// Test string caching:
CodeType t_int_dupe = def_type( name(int) );
if ( t_int_dupe->Name != t_int->Name )
fatal("check_sanity: String caching failed!");
// Purposefully use an excessive amount of memory to make so the the memory backend doesn't break.
// This has been tested with num_iterations set to 15000000 (generates 15 million lines of code), the Global_BlockSize, along with CodePool_NumBlocks, and SizePer_StringArena
// must be adjusted to gigabytes(2), kilobytes(512), and gigabyte(1) for good performance without crashing.
/*
Typical usage (megabytes(10), kilobytes(4), megabytes(1), for 650000 (the limit of 10 meg partition buckets in global arena) )
Memory after builder:
Num Global Arenas : 14 TotalSize: 146800640 !
Num Code Pools : 794 TotalSize: 416284672 !
Num String Cache Arenas : 60 TotalSize: 62914560 !
Num String Cache : 1300007
Memory usage to expect at 15 mil file:
Num Global Arenas : 2 TotalSize: 4294967296 !
Num Code Pools : 144 TotalSize: 9663676416 !
Num String Cache Arenas : 2 TotalSize: 2147483648 !
Num String Cache : 30000025
*/
constexpr
s32 num_iterations = 650000;
Array<CodeTypedef> typedefs = Array<CodeTypedef>::init_reserve( GlobalAllocator, num_iterations * 2 );
s32 idx = num_iterations;
while( --idx )
{
// Stress testing string allocation
String type_name = String::fmt_buf( GlobalAllocator, "type_%ld", idx );
String typedef_name = String::fmt_buf(GlobalAllocator, "typedef_%ld", idx );
CodeTypedef type_as_int = def_typedef( type_name, t_int );
CodeType type = def_type( type_name );
CodeTypedef type_def = def_typedef( typedef_name, type );
typedefs.append( type_as_int );
typedefs.append( type_def );
}
log_fmt("\nMemory before builder:\n");
log_fmt("Num Global Arenas : %llu TotalSize: %llu !\n", Global_AllocatorBuckets.num(), Global_AllocatorBuckets.num() * Global_BucketSize);
log_fmt("Num Code Pools : %llu TotalSize: %llu !\n", CodePools.num(), CodePools.num() * CodePool_NumBlocks * CodePools.back().BlockSize);
log_fmt("Num String Cache Arenas : %llu TotalSize: %llu !\n", StringArenas.num(), StringArenas.num() * SizePer_StringArena);
log_fmt("Num String Cache : %llu\n", StringCache.Entries.num(), StringCache);
Builder builder;
builder.open( "sanity.gen.hpp" );
idx = typedefs.num();
#ifdef GEN_BENCHMARK
u64 time_start = time_rel_ms();
#endif
while( --idx )
{
builder.print( typedefs[idx] );
}
builder.write();
#ifdef GEN_BENCHMARK
log_fmt("\n\nBuilder finished writting. Time taken: %llu ms\n", time_rel_ms() - time_start);
#endif
log_fmt("\nMemory after builder:\n");
log_fmt("Num Global Arenas : %llu TotalSize: %llu !\n", Global_AllocatorBuckets.num(), Global_AllocatorBuckets.num() * Global_BucketSize);
log_fmt("Num Code Pools : %llu TotalSize: %llu !\n", CodePools.num(), CodePools.num() * CodePool_NumBlocks * CodePools.back().BlockSize);
log_fmt("Num String Cache Arenas : %llu TotalSize: %llu !\n", StringArenas.num(), StringArenas.num() * SizePer_StringArena);
log_fmt("Num String Cache : %llu\n", StringCache.Entries.num(), StringCache);
gen::deinit();
log_fmt("\nSanity passed!\n");
}
#endif

View File

@ -1,6 +1,9 @@
#ifdef gen_time
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
#ifdef GEN_TIME
#define GEN_FEATURE_PARSING
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
#define GEN_ENFORCE_STRONG_CODE_TYPES
#define GEN_EXPOSE_BACKEND
#define GEN_BENCHMARK
#include "gen.cpp"
#include "Upfront\Array.Upfront.hpp"
#include "Upfront\Buffer.Upfront.hpp"

View File

@ -1,73 +1,33 @@
#ifdef gen_time
#define GEN_FEATURE_PARSING
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
#define GEN_ENFORCE_STRONG_CODE_TYPES
#include "Parsed\Array.Parsed.hpp"
#include "Parsed\Buffer.Parsed.hpp"
#include "Parsed\HashTable.Parsed.hpp"
#include "Parsed\Ring.Parsed.hpp"
#include "Parsed\Sanity.Parsed.hpp"
#include "SOA.hpp"
#define GEN_EXPOSE_BACKEND
#define GEN_BENCHMARK
#include "gen.cpp"
#include "sanity.cpp"
#include "SOA.cpp"
using namespace gen;
// TODO : Need to make a more robust test suite
#if GEN_TIME
int gen_main()
{
gen::init();
using namespace gen;
log_fmt("\ngen_time:");
gen_sanity();
check_sanity();
gen_array( u8 );
gen_array( sw );
check_SOA();
gen_buffer( u8 );
gen_hashtable( u32 );
gen_ring( s16 );
gen_ring( uw );
gen_array_file();
gen_buffer_file();
gen_hashtable_file();
gen_ring_file();
Builder soa_test; soa_test.open( "SOA.gen.hpp" );
soa_test.print( parse_using( code(
using u16 = unsigned short;
)));
soa_test.print( def_include( txt_StrC("gen.hpp")));
soa_test.print( def_using_namespace( name(gen) ) );
soa_test.print( gen_SOA(
parse_struct( code(
struct TestStruct
{
u8 A;
u16 B;
u32 C;
u64 D;
};
))
));
soa_test.write();
gen::deinit();
return 0;
}
#endif
#ifdef runtime
// This only has to be done if symbol conflicts occur.
#ifndef GEN_TIME
int main()
{
return 0;
}
#endif

75
test/test.parsing.cpp Normal file
View File

@ -0,0 +1,75 @@
#ifdef GEN_TIME
#define GEN_FEATURE_PARSING
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
#define GEN_ENFORCE_STRONG_CODE_TYPES
#define GEN_EXPOSE_BACKEND
#define GEN_BENCHMARK
#include "Parsed\Array.Parsed.hpp"
#include "Parsed\Buffer.Parsed.hpp"
#include "Parsed\HashTable.Parsed.hpp"
#include "Parsed\Ring.Parsed.hpp"
#include "Parsed\Sanity.Parsed.hpp"
#include "SOA.cpp"
#include "gen.cpp"
using namespace gen;
// TODO : Need to make a more robust test suite
int gen_main()
{
gen::init();
gen_sanity();
gen_array( u8 );
gen_array( sw );
gen_buffer( u8 );
gen_hashtable( u32 );
gen_ring( s16 );
gen_ring( uw );
gen_array_file();
gen_buffer_file();
gen_hashtable_file();
gen_ring_file();
Builder soa_test; soa_test.open( "SOA.gen.hpp" );
soa_test.print( parse_using( code(
using u16 = unsigned short;
)));
soa_test.print( def_include( txt_StrC("gen.hpp")));
soa_test.print( def_using_namespace( name(gen) ) );
soa_test.print( gen_SOA(
parse_struct( code(
struct TestStruct
{
u8 A;
u16 B;
u32 C;
u64 D;
};
))
));
soa_test.write();
gen::deinit();
return 0;
}
#endif
#ifdef runtime
int main()
{
return 0;
}
#endif

0
test/upfront.cpp Normal file
View File

21
test/upfront.hpp Normal file
View File

@ -0,0 +1,21 @@
#ifdef GEN_TIME
#define GEN_FEATURE_PARSING
#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS
#define GEN_ENFORCE_STRONG_CODE_TYPES
#define GEN_EXPOSE_BACKEND
#define GEN_BENCHMARK
#include "gen.hpp"
void check_upfront()
{
using namespace gen;
log_fmt("\nupfront: ");
gen::init();
gen::deinit();
log_fmt("Passed!\n");
}
#endif