How to write Delphi compile-time functions

Delphi - I can write my own compile-time functions for const and var declarations, executed at compile time.

Delphi standard libraries contain routines such as Ord (), Chr (), Trunc (), Round (), High (), etc., used for constant initialization.

Can I write my own, execute the procedure at compile time, and use the result as a constant?

+5
source share
2 answers

You cannot write your own built-in functions. Because it requires the magic of a compiler.
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

Delphi Preprocessor http://sourceforge.net/p/dpp32/wiki/Home/history

Andreas Hausladen has just opened his own work in this regard.
This is not a preprocessor, but a language expander.
https://github.com/ahausladen/DLangExtensions

The problem with preprocessors is that it kills the connection between the source code (before preprocessing) and the source code that Delphi compiles.
This means that you will not have debug information for your source.
(if you do not overwrite the map file).

Embedding
Depending on what you want to do, you can use inlining to achieve almost the same efficiency as the internal function. See: fooobar.com/questions/1078348 / ...

Build your claims with built-in functions
If you have a block of code consisting of instrinsic functions, the full result will be evaluated at compile time, making the overall construct work as if it were an internal function.

Pay attention to 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; 

Since it is built-in and uses only built-in functions (and compiler directives), the function will be allowed in compiletime to a constant and will not generate any code.

+7
source

Can I write my own, execute the procedure at compile time, and use the result as a constant?

No, you can’t. These functions are built into the compiler, and if there is no extension mechanism allowing third parties to create built-in functions.

+3
source

All Articles