Built-in Compilation Flags
The Cangjie language provides predefined compilation tags that can be used to control the behavior of the Cangjie compiler during compilation.
Source Code Location
Cangjie offers several built-in compilation tags to obtain the location of the source code during compilation.
- After
@sourcePackage()
is expanded, it becomes a literal of theString
type, representing the package name of the source code where the current macro is located. - After
@sourceFile()
is expanded, it becomes a literal of theString
type, representing the file name of the source code where the current macro is located. - After
@sourceLine()
is expanded, it becomes a literal of theInt64
type, representing the code line of the source code where the current macro is located.
These compilation tags can be used in any expressions, as long as they meet the type check rules. An example is provided below:
func test1() {
let s: String = @sourceFile() // The value of `s` is the current source file name
}
func test2(n!: Int64 = @sourceLine()) { /* at line 5 */
// The default value of `n` is the source file line number of the definition of `test2`
println(n) // print 5
}
Conditional Compilation
Conditional compilation uses the @When
tag. It is a technology that selectively compiles different code segments in program code based on specific conditions. The main uses of conditional compilation include:
- Platform adaptation: Enables selective code compilation based on the current compilation environment, facilitating cross-platform compatibility.
- Function selection: Allows selective enabling or disabling of certain features based on different requirements, providing flexible feature configuration. For example, selectively compiling code to include or exclude certain functionalities.
- Debugging support: Supports compiling code in debug mode to improve program performance and security. For example, compiling debug information or logging code in debug mode, while excluding them in release versions.
- Performance optimization: Enables selective compilation based on predefined conditions to improve program performance.
For details about conditional compilation, see Conditional Compilation.
@FastNative
To enhance performance when interoperating with the C
language, Cangjie provides the @FastNative
tag to optimize C
function calls. Note that @FastNative
can be used only for functions declared by foreign
.
An example usage is provided below:
@FastNative
foreign func strlen(str: CPointer<UInt8>): UIntNative
When using @FastNative
to modify the foreign
function, ensure that the corresponding C
function meets the following requirements:
- The overall execution time of the function should not be too long. For example, the function should not contain large loops or produce blocking, such as calling functions like
sleep
andwait
. - The Cangjie method cannot be called in the function.