[Draft Feature] Adding Support for Custom Literal Constants#12
[Draft Feature] Adding Support for Custom Literal Constants#12HenryAWE wants to merge 14 commits into
Conversation
|
Thanks for sharing. I will have a closer look at what you have so far. |
|
@HenryAWE can summarize what you've done so far, and what is still left to do? |
Currently, only parser for literal pattern (e.g. I'm still working on where is the best place to add parsing logic for custom literals within script (e.g. I was employed recently and might no longer have many free time compared to a student in university😂. This PR is expected to take long time to complete. |
Resolved conflict in main.cpp: kept Test_Addon_Autowrapper from master, moved TestCompiler before addon tests so it runs first.
|
Finally, I'm coming back to this PR 😀. Now it can compile & run a simple fixed point number test. I will continue working on it. Here is an example extracted from the test case in test_compiler.cpp. // C++ side: Fixed32 is a fixed-point type (16-bit integer + 16-bit fraction)
class Fixed32
{
public:
int value;
Fixed32(int v) : value(v) {}
static void LiteralConstructDouble(double dblVal, void* mem)
{
int integer = int(dblVal);
int fraction = int((dblVal - integer) * double(1 << 15));
new(mem) Fixed32((integer << 15) + fraction);
}
operator int() const { return value >> 15; }
};
// Register the type and its literal suffix
engine->RegisterObjectType("Fixed32", sizeof(int),
asGetTypeTraits<Fixed32>() | asOBJ_POD | asOBJ_VALUE | asOBJ_APP_CLASS_ALLINTS);
engine->RegisterObjectBehaviour("Fixed32", asBEHAVE_LITERAL_CONSTRUCT,
"void f(double) {'_f32' suffix}",
asFUNCTION(Fixed32::LiteralConstructDouble), asCALL_CDECL_OBJLAST);
// Script side
asIScriptModule* m = engine->GetModule("test", asGM_ALWAYS_CREATE);
m->AddScriptSection("test", "Fixed32 test() { return 3.14_f32; }");
m->Build();
// Execute and verify
asIScriptContext* ctx = engine->CreateContext();
ctx->Prepare(m->GetFunctionByName("test"));
ctx->Execute();
Fixed32 result = *(Fixed32*)ctx->GetAddressOfReturnValue();
assert(static_cast<int>(result) == 3); |
|
@anjo76 Can you approve the workflow for this PR? Previously I was developing on Windows using MSVC, and now I'm developing on arm64 macOS with Apple Clang. The CI can help me find if any code that cannot be compiled by other compilers. |
TL;DR
Once this is implemented, AngelScript will allow user to make their own literals. For example, if you want a fixed point number instead of built-in floating point number for consistent math result across platforms, you can write script like this:
This is moved from gamedev.net to here (original thread link)
This branch is still work-in-progress (only the part of modification to parser is done), so I mark it as draft PR for now.