Delphi - can I write my own compile-time functions
for const and var declarations, executable at compiler time.
Standard Delphi lib contain routines like Ord(), Chr(), Trunc(), Round(), High() etc, used for constant initialization.
Can I write my own, to execute routine at compile-time and use the result as constant?
You cannot write your own intrinsic functions. Because that requires compiler magic.
However there may be other options to achieve your goal.
Preprocessor
The only way is to use a preprocessor.
There are several: http://wiki.delphi-jedi.org/wiki/JEDI_Pre_Processor
The Delphi preprocessor http://sourceforge.net/p/dpp32/wiki/Home/history
Andreas Hausladen has just open sourced his own work in this respect.
It's not really a preprocessor, but a language extender.
https://github.com/ahausladen/DLangExtensions
The problem with preprocessors is that it kills the link between the original (prior to pre-processing) source code and the source code that Delphi compiles.
This means that you will not have debug info for your original source.
(unless you rewrite the map file).
Inlining
Depending on what you want to do you can use inlining to achieve almost the same efficiency as an intrinsic function.
See: https://stackoverflow.com/a/6401833/650492
Construct your statements using intrinsic functions
If you have a code block consisting of instrinsic functions, the complete result will be evaluated at compile time, making the total construct work as if it was a intrinsic function.
Note the following (silly) example:
function FitsInRegister<T>: Boolean; inline;
begin
if GetTypeKind(T) in [tkString, tkUString] then result:= false
else
{$IFDEF CPU32BITS}
Result:= SizeOf(T) <= 4;
{$ELSEIF CPU64BITS}
Result:= SizeOf(T) <= 8;
{$ENDIF}
end;
Because it is inline and it only uses intrinsic functions (and compiler directives), the function will be resolved at compiletime to a constant and not generate any code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With