Compile-Time Conditionals (v0.2.1)
Target-dependent branching using @if, @elif, and @else.
Overview
Compile-time conditionals choose code before the program is generated. The inactive branches are not emitted.
They are useful for platform-specific imports, constants, and declarations.
Use @if with target builtins such as isLinux or isWindows when a program needs different code for different targets.
Primary source: syntax/statements/compiletime.md
Syntax Signatures
@if(isLinux()) const PLATFORM: u32 = 1;
@elif(isWindows()) const PLATFORM: u32 = 2;
@else const PLATFORM: u32 = 0;
Behavior and Use
Only the selected branch is kept. Each branch should still be valid for the target where it can be selected.
If many files need the same target decision, put that decision in one small module instead of repeating it everywhere.
Best Practices
- Use compile-time branches when the code really differs by target.
- Keep branch predicates simple and testable.
- Test each target branch so unused code does not go stale.
Selection Time
Compile-time conditionals are evaluated before code generation.
- The selected branch remains in the program for that compilation target.
- Inactive branches are not emitted, which allows target-specific declarations and imports.
- Each branch should still be valid for the target where its predicate can become true.
Predicates
Predicates usually come from target and compiler builtins.
- Use target checks such as isLinux, isWindows, isWasm, and pointerWidth for platform-dependent declarations.
- Keep predicates small. Complex target rules are easier to maintain when moved into named constants or helper modules.
- When a branch imports a platform file, test that branch on the matching target so it does not silently become stale.
Example
@if(isLinux()) const PLATFORM: u32 = 2;
@elif(isWindows()) const PLATFORM: u32 = 1;
@else const PLATFORM: u32 = 3;
fn currentPlatform() u32 @public {
return PLATFORM;
}