pragmas.txt 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. Pragmas
  2. =======
  3. Pragmas are Nim's method to give the compiler additional information /
  4. commands without introducing a massive number of new keywords. Pragmas are
  5. processed on the fly during semantic checking. Pragmas are enclosed in the
  6. special ``{.`` and ``.}`` curly brackets. Pragmas are also often used as a
  7. first implementation to play with a language feature before a nicer syntax
  8. to access the feature becomes available.
  9. deprecated pragma
  10. -----------------
  11. The deprecated pragma is used to mark a symbol as deprecated:
  12. .. code-block:: nim
  13. proc p() {.deprecated.}
  14. var x {.deprecated.}: char
  15. It can also be used as a statement, in that case it takes a list of *renamings*.
  16. .. code-block:: nim
  17. type
  18. File = object
  19. Stream = ref object
  20. {.deprecated: [TFile: File, PStream: Stream].}
  21. noSideEffect pragma
  22. -------------------
  23. The ``noSideEffect`` pragma is used to mark a proc/iterator to have no side
  24. effects. This means that the proc/iterator only changes locations that are
  25. reachable from its parameters and the return value only depends on the
  26. arguments. If none of its parameters have the type ``var T``
  27. or ``ref T`` or ``ptr T`` this means no locations are modified. It is a static
  28. error to mark a proc/iterator to have no side effect if the compiler cannot
  29. verify this.
  30. As a special semantic rule, the built-in `debugEcho <system.html#debugEcho>`_
  31. pretends to be free of side effects, so that it can be used for debugging
  32. routines marked as ``noSideEffect``.
  33. **Future directions**: ``func`` may become a keyword and syntactic sugar for a
  34. proc with no side effects:
  35. .. code-block:: nim
  36. func `+` (x, y: int): int
  37. destructor pragma
  38. -----------------
  39. The ``destructor`` pragma is used to mark a proc to act as a type destructor.
  40. Its usage is deprecated, see `type bound operations`_ instead.
  41. override pragma
  42. ---------------
  43. See `type bound operations`_ instead.
  44. procvar pragma
  45. --------------
  46. The ``procvar`` pragma is used to mark a proc that it can be passed to a
  47. procedural variable.
  48. compileTime pragma
  49. ------------------
  50. The ``compileTime`` pragma is used to mark a proc or variable to be used at
  51. compile time only. No code will be generated for it. Compile time procs are
  52. useful as helpers for macros. Since version 0.12.0 of the language, a proc
  53. that uses ``system.NimNode`` within its parameter types is implictly declared
  54. ``compileTime``:
  55. .. code-block:: nim
  56. proc astHelper(n: NimNode): NimNode =
  57. result = n
  58. Is the same as:
  59. .. code-block:: nim
  60. proc astHelper(n: NimNode): NimNode {.compileTime.} =
  61. result = n
  62. noReturn pragma
  63. ---------------
  64. The ``noreturn`` pragma is used to mark a proc that never returns.
  65. acyclic pragma
  66. --------------
  67. The ``acyclic`` pragma can be used for object types to mark them as acyclic
  68. even though they seem to be cyclic. This is an **optimization** for the garbage
  69. collector to not consider objects of this type as part of a cycle:
  70. .. code-block:: nim
  71. type
  72. Node = ref NodeObj
  73. NodeObj {.acyclic, final.} = object
  74. left, right: Node
  75. data: string
  76. In the example a tree structure is declared with the ``Node`` type. Note that
  77. the type definition is recursive and the GC has to assume that objects of
  78. this type may form a cyclic graph. The ``acyclic`` pragma passes the
  79. information that this cannot happen to the GC. If the programmer uses the
  80. ``acyclic`` pragma for data types that are in reality cyclic, the GC may leak
  81. memory, but nothing worse happens.
  82. **Future directions**: The ``acyclic`` pragma may become a property of a
  83. ``ref`` type:
  84. .. code-block:: nim
  85. type
  86. Node = acyclic ref NodeObj
  87. NodeObj = object
  88. left, right: Node
  89. data: string
  90. final pragma
  91. ------------
  92. The ``final`` pragma can be used for an object type to specify that it
  93. cannot be inherited from.
  94. shallow pragma
  95. --------------
  96. The ``shallow`` pragma affects the semantics of a type: The compiler is
  97. allowed to make a shallow copy. This can cause serious semantic issues and
  98. break memory safety! However, it can speed up assignments considerably,
  99. because the semantics of Nim require deep copying of sequences and strings.
  100. This can be expensive, especially if sequences are used to build a tree
  101. structure:
  102. .. code-block:: nim
  103. type
  104. NodeKind = enum nkLeaf, nkInner
  105. Node {.final, shallow.} = object
  106. case kind: NodeKind
  107. of nkLeaf:
  108. strVal: string
  109. of nkInner:
  110. children: seq[Node]
  111. pure pragma
  112. -----------
  113. An object type can be marked with the ``pure`` pragma so that its type
  114. field which is used for runtime type identification is omitted. This used to be
  115. necessary for binary compatibility with other compiled languages.
  116. An enum type can be marked as ``pure``. Then access of its fields always
  117. requires full qualification.
  118. asmNoStackFrame pragma
  119. ----------------------
  120. A proc can be marked with the ``asmNoStackFrame`` pragma to tell the compiler
  121. it should not generate a stack frame for the proc. There are also no exit
  122. statements like ``return result;`` generated and the generated C function is
  123. declared as ``__declspec(naked)`` or ``__attribute__((naked))`` (depending on
  124. the used C compiler).
  125. **Note**: This pragma should only be used by procs which consist solely of
  126. assembler statements.
  127. error pragma
  128. ------------
  129. The ``error`` pragma is used to make the compiler output an error message
  130. with the given content. Compilation does not necessarily abort after an error
  131. though.
  132. The ``error`` pragma can also be used to
  133. annotate a symbol (like an iterator or proc). The *usage* of the symbol then
  134. triggers a compile-time error. This is especially useful to rule out that some
  135. operation is valid due to overloading and type conversions:
  136. .. code-block:: nim
  137. ## check that underlying int values are compared and not the pointers:
  138. proc `==`(x, y: ptr int): bool {.error.}
  139. fatal pragma
  140. ------------
  141. The ``fatal`` pragma is used to make the compiler output an error message
  142. with the given content. In contrast to the ``error`` pragma, compilation
  143. is guaranteed to be aborted by this pragma. Example:
  144. .. code-block:: nim
  145. when not defined(objc):
  146. {.fatal: "Compile this program with the objc command!".}
  147. warning pragma
  148. --------------
  149. The ``warning`` pragma is used to make the compiler output a warning message
  150. with the given content. Compilation continues after the warning.
  151. hint pragma
  152. -----------
  153. The ``hint`` pragma is used to make the compiler output a hint message with
  154. the given content. Compilation continues after the hint.
  155. line pragma
  156. -----------
  157. The ``line`` pragma can be used to affect line information of the annotated
  158. statement as seen in stack backtraces:
  159. .. code-block:: nim
  160. template myassert*(cond: untyped, msg = "") =
  161. if not cond:
  162. # change run-time line information of the 'raise' statement:
  163. {.line: InstantiationInfo().}:
  164. raise newException(EAssertionFailed, msg)
  165. If the ``line`` pragma is used with a parameter, the parameter needs be a
  166. ``tuple[filename: string, line: int]``. If it is used without a parameter,
  167. ``system.InstantiationInfo()`` is used.
  168. linearScanEnd pragma
  169. --------------------
  170. The ``linearScanEnd`` pragma can be used to tell the compiler how to
  171. compile a Nim `case`:idx: statement. Syntactically it has to be used as a
  172. statement:
  173. .. code-block:: nim
  174. case myInt
  175. of 0:
  176. echo "most common case"
  177. of 1:
  178. {.linearScanEnd.}
  179. echo "second most common case"
  180. of 2: echo "unlikely: use branch table"
  181. else: echo "unlikely too: use branch table for ", myInt
  182. In the example, the case branches ``0`` and ``1`` are much more common than
  183. the other cases. Therefore the generated assembler code should test for these
  184. values first, so that the CPU's branch predictor has a good chance to succeed
  185. (avoiding an expensive CPU pipeline stall). The other cases might be put into a
  186. jump table for O(1) overhead, but at the cost of a (very likely) pipeline
  187. stall.
  188. The ``linearScanEnd`` pragma should be put into the last branch that should be
  189. tested against via linear scanning. If put into the last branch of the
  190. whole ``case`` statement, the whole ``case`` statement uses linear scanning.
  191. computedGoto pragma
  192. -------------------
  193. The ``computedGoto`` pragma can be used to tell the compiler how to
  194. compile a Nim `case`:idx: in a ``while true`` statement.
  195. Syntactically it has to be used as a statement inside the loop:
  196. .. code-block:: nim
  197. type
  198. MyEnum = enum
  199. enumA, enumB, enumC, enumD, enumE
  200. proc vm() =
  201. var instructions: array [0..100, MyEnum]
  202. instructions[2] = enumC
  203. instructions[3] = enumD
  204. instructions[4] = enumA
  205. instructions[5] = enumD
  206. instructions[6] = enumC
  207. instructions[7] = enumA
  208. instructions[8] = enumB
  209. instructions[12] = enumE
  210. var pc = 0
  211. while true:
  212. {.computedGoto.}
  213. let instr = instructions[pc]
  214. case instr
  215. of enumA:
  216. echo "yeah A"
  217. of enumC, enumD:
  218. echo "yeah CD"
  219. of enumB:
  220. echo "yeah B"
  221. of enumE:
  222. break
  223. inc(pc)
  224. vm()
  225. As the example shows ``computedGoto`` is mostly useful for interpreters. If
  226. the underlying backend (C compiler) does not support the computed goto
  227. extension the pragma is simply ignored.
  228. unroll pragma
  229. -------------
  230. The ``unroll`` pragma can be used to tell the compiler that it should unroll
  231. a `for`:idx: or `while`:idx: loop for runtime efficiency:
  232. .. code-block:: nim
  233. proc searchChar(s: string, c: char): int =
  234. for i in 0 .. s.high:
  235. {.unroll: 4.}
  236. if s[i] == c: return i
  237. result = -1
  238. In the above example, the search loop is unrolled by a factor 4. The unroll
  239. factor can be left out too; the compiler then chooses an appropriate unroll
  240. factor.
  241. **Note**: Currently the compiler recognizes but ignores this pragma.
  242. immediate pragma
  243. ----------------
  244. See `Ordinary vs immediate templates`_.
  245. compilation option pragmas
  246. --------------------------
  247. The listed pragmas here can be used to override the code generation options
  248. for a proc/method/converter.
  249. The implementation currently provides the following possible options (various
  250. others may be added later).
  251. =============== =============== ============================================
  252. pragma allowed values description
  253. =============== =============== ============================================
  254. checks on|off Turns the code generation for all runtime
  255. checks on or off.
  256. boundChecks on|off Turns the code generation for array bound
  257. checks on or off.
  258. overflowChecks on|off Turns the code generation for over- or
  259. underflow checks on or off.
  260. nilChecks on|off Turns the code generation for nil pointer
  261. checks on or off.
  262. assertions on|off Turns the code generation for assertions
  263. on or off.
  264. warnings on|off Turns the warning messages of the compiler
  265. on or off.
  266. hints on|off Turns the hint messages of the compiler
  267. on or off.
  268. optimization none|speed|size Optimize the code for speed or size, or
  269. disable optimization.
  270. patterns on|off Turns the term rewriting templates/macros
  271. on or off.
  272. callconv cdecl|... Specifies the default calling convention for
  273. all procedures (and procedure types) that
  274. follow.
  275. =============== =============== ============================================
  276. Example:
  277. .. code-block:: nim
  278. {.checks: off, optimization: speed.}
  279. # compile without runtime checks and optimize for speed
  280. push and pop pragmas
  281. --------------------
  282. The `push/pop`:idx: pragmas are very similar to the option directive,
  283. but are used to override the settings temporarily. Example:
  284. .. code-block:: nim
  285. {.push checks: off.}
  286. # compile this section without runtime checks as it is
  287. # speed critical
  288. # ... some code ...
  289. {.pop.} # restore old settings
  290. register pragma
  291. ---------------
  292. The ``register`` pragma is for variables only. It declares the variable as
  293. ``register``, giving the compiler a hint that the variable should be placed
  294. in a hardware register for faster access. C compilers usually ignore this
  295. though and for good reasons: Often they do a better job without it anyway.
  296. In highly specific cases (a dispatch loop of a bytecode interpreter for
  297. example) it may provide benefits, though.
  298. global pragma
  299. -------------
  300. The ``global`` pragma can be applied to a variable within a proc to instruct
  301. the compiler to store it in a global location and initialize it once at program
  302. startup.
  303. .. code-block:: nim
  304. proc isHexNumber(s: string): bool =
  305. var pattern {.global.} = re"[0-9a-fA-F]+"
  306. result = s.match(pattern)
  307. When used within a generic proc, a separate unique global variable will be
  308. created for each instantiation of the proc. The order of initialization of
  309. the created global variables within a module is not defined, but all of them
  310. will be initialized after any top-level variables in their originating module
  311. and before any variable in a module that imports it.
  312. deadCodeElim pragma
  313. -------------------
  314. The ``deadCodeElim`` pragma only applies to whole modules: It tells the
  315. compiler to activate (or deactivate) dead code elimination for the module the
  316. pragma appears in.
  317. The ``--deadCodeElim:on`` command line switch has the same effect as marking
  318. every module with ``{.deadCodeElim:on}``. However, for some modules such as
  319. the GTK wrapper it makes sense to *always* turn on dead code elimination -
  320. no matter if it is globally active or not.
  321. Example:
  322. .. code-block:: nim
  323. {.deadCodeElim: on.}
  324. ..
  325. NoForward pragma
  326. ----------------
  327. The ``noforward`` pragma can be used to turn on and off a special compilation
  328. mode that to large extent eliminates the need for forward declarations. In this
  329. mode, the proc definitions may appear out of order and the compiler will postpone
  330. their semantic analysis and compilation until it actually needs to generate code
  331. using the definitions. In this regard, this mode is similar to the modus operandi
  332. of dynamic scripting languages, where the function calls are not resolved until
  333. the code is executed. Here is the detailed algorithm taken by the compiler:
  334. 1. When a callable symbol is first encountered, the compiler will only note the
  335. symbol callable name and it will add it to the appropriate overload set in the
  336. current scope. At this step, it won't try to resolve any of the type expressions
  337. used in the signature of the symbol (so they can refer to other not yet defined
  338. symbols).
  339. 2. When a top level call is encountered (usually at the very end of the module),
  340. the compiler will try to determine the actual types of all of the symbols in the
  341. matching overload set. This is a potentially recursive process as the signatures
  342. of the symbols may include other call expressions, whose types will be resolved
  343. at this point too.
  344. 3. Finally, after the best overload is picked, the compiler will start
  345. compiling the body of the respective symbol. This in turn will lead the
  346. compiler to discover more call expressions that need to be resolved and steps
  347. 2 and 3 will be repeated as necessary.
  348. Please note that if a callable symbol is never used in this scenario, its body
  349. will never be compiled. This is the default behavior leading to best compilation
  350. times, but if exhaustive compilation of all definitions is required, using
  351. ``nim check`` provides this option as well.
  352. Example:
  353. .. code-block:: nim
  354. {.noforward: on.}
  355. proc foo(x: int) =
  356. bar x
  357. proc bar(x: int) =
  358. echo x
  359. foo(10)
  360. pragma pragma
  361. -------------
  362. The ``pragma`` pragma can be used to declare user defined pragmas. This is
  363. useful because Nim's templates and macros do not affect pragmas. User
  364. defined pragmas are in a different module-wide scope than all other symbols.
  365. They cannot be imported from a module.
  366. Example:
  367. .. code-block:: nim
  368. when appType == "lib":
  369. {.pragma: rtl, exportc, dynlib, cdecl.}
  370. else:
  371. {.pragma: rtl, importc, dynlib: "client.dll", cdecl.}
  372. proc p*(a, b: int): int {.rtl.} =
  373. result = a+b
  374. In the example a new pragma named ``rtl`` is introduced that either imports
  375. a symbol from a dynamic library or exports the symbol for dynamic library
  376. generation.
  377. Disabling certain messages
  378. --------------------------
  379. Nim generates some warnings and hints ("line too long") that may annoy the
  380. user. A mechanism for disabling certain messages is provided: Each hint
  381. and warning message contains a symbol in brackets. This is the message's
  382. identifier that can be used to enable or disable it:
  383. .. code-block:: Nim
  384. {.hint[LineTooLong]: off.} # turn off the hint about too long lines
  385. This is often better than disabling all warnings at once.
  386. used pragma
  387. -----------
  388. Nim produces a warning for symbols that are not exported and not used either.
  389. The ``used`` pragma can be attached to a symbol to suppress this warning. This
  390. is particularly useful when the symbol was generated by a macro:
  391. .. code-block:: nim
  392. template implementArithOps(T) =
  393. proc echoAdd(a, b: T) {.used.} =
  394. echo a + b
  395. proc echoSub(a, b: T) {.used.} =
  396. echo a - b
  397. # no warning produced for the unused 'echoSub'
  398. implementArithOps(int)
  399. echoAdd 3, 5
  400. experimental pragma
  401. -------------------
  402. The ``experimental`` pragma enables experimental language features. Depending
  403. on the concrete feature this means that the feature is either considered
  404. too unstable for an otherwise stable release or that the future of the feature
  405. is uncertain (it may be removed any time).
  406. Example:
  407. .. code-block:: nim
  408. {.experimental.}
  409. type
  410. FooId = distinct int
  411. BarId = distinct int
  412. using
  413. foo: FooId
  414. bar: BarId
  415. proc useUsing(bar, foo) =
  416. echo "bar is of type BarId"
  417. echo "foo is of type FooId"
  418. Implementation Specific Pragmas
  419. ===============================
  420. This section describes additional pragmas that the current Nim implementation
  421. supports but which should not be seen as part of the language specification.
  422. Bitsize pragma
  423. --------------
  424. The ``bitsize`` pragma is for object field members. It declares the field as
  425. a bitfield in C/C++.
  426. .. code-block:: Nim
  427. type
  428. mybitfield = object
  429. flag {.bitsize:1.}: cuint
  430. generates:
  431. .. code-block:: C
  432. struct mybitfield {
  433. unsigned int flag:1;
  434. };
  435. Volatile pragma
  436. ---------------
  437. The ``volatile`` pragma is for variables only. It declares the variable as
  438. ``volatile``, whatever that means in C/C++ (its semantics are not well defined
  439. in C/C++).
  440. **Note**: This pragma will not exist for the LLVM backend.
  441. NoDecl pragma
  442. -------------
  443. The ``noDecl`` pragma can be applied to almost any symbol (variable, proc,
  444. type, etc.) and is sometimes useful for interoperability with C:
  445. It tells Nim that it should not generate a declaration for the symbol in
  446. the C code. For example:
  447. .. code-block:: Nim
  448. var
  449. EACCES {.importc, noDecl.}: cint # pretend EACCES was a variable, as
  450. # Nim does not know its value
  451. However, the ``header`` pragma is often the better alternative.
  452. **Note**: This will not work for the LLVM backend.
  453. Header pragma
  454. -------------
  455. The ``header`` pragma is very similar to the ``noDecl`` pragma: It can be
  456. applied to almost any symbol and specifies that it should not be declared
  457. and instead the generated code should contain an ``#include``:
  458. .. code-block:: Nim
  459. type
  460. PFile {.importc: "FILE*", header: "<stdio.h>".} = distinct pointer
  461. # import C's FILE* type; Nim will treat it as a new pointer type
  462. The ``header`` pragma always expects a string constant. The string contant
  463. contains the header file: As usual for C, a system header file is enclosed
  464. in angle brackets: ``<>``. If no angle brackets are given, Nim
  465. encloses the header file in ``""`` in the generated C code.
  466. **Note**: This will not work for the LLVM backend.
  467. IncompleteStruct pragma
  468. -----------------------
  469. The ``incompleteStruct`` pragma tells the compiler to not use the
  470. underlying C ``struct`` in a ``sizeof`` expression:
  471. .. code-block:: Nim
  472. type
  473. DIR* {.importc: "DIR", header: "<dirent.h>",
  474. final, pure, incompleteStruct.} = object
  475. Compile pragma
  476. --------------
  477. The ``compile`` pragma can be used to compile and link a C/C++ source file
  478. with the project:
  479. .. code-block:: Nim
  480. {.compile: "myfile.cpp".}
  481. **Note**: Nim computes a SHA1 checksum and only recompiles the file if it
  482. has changed. You can use the ``-f`` command line option to force recompilation
  483. of the file.
  484. Link pragma
  485. -----------
  486. The ``link`` pragma can be used to link an additional file with the project:
  487. .. code-block:: Nim
  488. {.link: "myfile.o".}
  489. PassC pragma
  490. ------------
  491. The ``passC`` pragma can be used to pass additional parameters to the C
  492. compiler like you would using the commandline switch ``--passC``:
  493. .. code-block:: Nim
  494. {.passC: "-Wall -Werror".}
  495. Note that you can use ``gorge`` from the `system module <system.html>`_ to
  496. embed parameters from an external command at compile time:
  497. .. code-block:: Nim
  498. {.passC: gorge("pkg-config --cflags sdl").}
  499. PassL pragma
  500. ------------
  501. The ``passL`` pragma can be used to pass additional parameters to the linker
  502. like you would using the commandline switch ``--passL``:
  503. .. code-block:: Nim
  504. {.passL: "-lSDLmain -lSDL".}
  505. Note that you can use ``gorge`` from the `system module <system.html>`_ to
  506. embed parameters from an external command at compile time:
  507. .. code-block:: Nim
  508. {.passL: gorge("pkg-config --libs sdl").}
  509. Emit pragma
  510. -----------
  511. The ``emit`` pragma can be used to directly affect the output of the
  512. compiler's code generator. So it makes your code unportable to other code
  513. generators/backends. Its usage is highly discouraged! However, it can be
  514. extremely useful for interfacing with `C++`:idx: or `Objective C`:idx: code.
  515. Example:
  516. .. code-block:: Nim
  517. {.emit: """
  518. static int cvariable = 420;
  519. """.}
  520. {.push stackTrace:off.}
  521. proc embedsC() =
  522. var nimVar = 89
  523. # access Nim symbols within an emit section outside of string literals:
  524. {.emit: ["""fprintf(stdout, "%d\n", cvariable + (int)""", nimVar, ");"].}
  525. {.pop.}
  526. embedsC()
  527. For backwards compatibility, if the argument to the ``emit`` statement
  528. is a single string literal, Nim symbols can be referred to via backticks.
  529. This usage is however deprecated.
  530. For a toplevel emit statement the section where in the generated C/C++ file
  531. the code should be emitted can be influenced via the
  532. prefixes ``/*TYPESECTION*/`` or ``/*VARSECTION*/`` or ``/*INCLUDESECTION*/``:
  533. .. code-block:: Nim
  534. {.emit: """/*TYPESECTION*/
  535. struct Vector3 {
  536. public:
  537. Vector3(): x(5) {}
  538. Vector3(float x_): x(x_) {}
  539. float x;
  540. };
  541. """.}
  542. type Vector3 {.importcpp: "Vector3", nodecl} = object
  543. x: cfloat
  544. proc constructVector3(a: cfloat): Vector3 {.importcpp: "Vector3(@)", nodecl}
  545. ImportCpp pragma
  546. ----------------
  547. **Note**: `c2nim <c2nim.html>`_ can parse a large subset of C++ and knows
  548. about the ``importcpp`` pragma pattern language. It is not necessary
  549. to know all the details described here.
  550. Similar to the `importc pragma for C <manual.html#importc-pragma>`_, the
  551. ``importcpp`` pragma can be used to import `C++`:idx: methods or C++ symbols
  552. in general. The generated code then uses the C++ method calling
  553. syntax: ``obj->method(arg)``. In combination with the ``header`` and ``emit``
  554. pragmas this allows *sloppy* interfacing with libraries written in C++:
  555. .. code-block:: Nim
  556. # Horrible example of how to interface with a C++ engine ... ;-)
  557. {.link: "/usr/lib/libIrrlicht.so".}
  558. {.emit: """
  559. using namespace irr;
  560. using namespace core;
  561. using namespace scene;
  562. using namespace video;
  563. using namespace io;
  564. using namespace gui;
  565. """.}
  566. const
  567. irr = "<irrlicht/irrlicht.h>"
  568. type
  569. IrrlichtDeviceObj {.final, header: irr,
  570. importcpp: "IrrlichtDevice".} = object
  571. IrrlichtDevice = ptr IrrlichtDeviceObj
  572. proc createDevice(): IrrlichtDevice {.
  573. header: irr, importcpp: "createDevice(@)".}
  574. proc run(device: IrrlichtDevice): bool {.
  575. header: irr, importcpp: "#.run(@)".}
  576. The compiler needs to be told to generate C++ (command ``cpp``) for
  577. this to work. The conditional symbol ``cpp`` is defined when the compiler
  578. emits C++ code.
  579. Namespaces
  580. ~~~~~~~~~~
  581. The *sloppy interfacing* example uses ``.emit`` to produce ``using namespace``
  582. declarations. It is usually much better to instead refer to the imported name
  583. via the ``namespace::identifier`` notation:
  584. .. code-block:: nim
  585. type
  586. IrrlichtDeviceObj {.final, header: irr,
  587. importcpp: "irr::IrrlichtDevice".} = object
  588. Importcpp for enums
  589. ~~~~~~~~~~~~~~~~~~~
  590. When ``importcpp`` is applied to an enum type the numerical enum values are
  591. annotated with the C++ enum type, like in this example: ``((TheCppEnum)(3))``.
  592. (This turned out to be the simplest way to implement it.)
  593. Importcpp for procs
  594. ~~~~~~~~~~~~~~~~~~~
  595. Note that the ``importcpp`` variant for procs uses a somewhat cryptic pattern
  596. language for maximum flexibility:
  597. - A hash ``#`` symbol is replaced by the first or next argument.
  598. - A dot following the hash ``#.`` indicates that the call should use C++'s dot
  599. or arrow notation.
  600. - An at symbol ``@`` is replaced by the remaining arguments, separated by
  601. commas.
  602. For example:
  603. .. code-block:: nim
  604. proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "#.CppMethod(@)".}
  605. var x: ptr CppObj
  606. cppMethod(x[], 1, 2, 3)
  607. Produces:
  608. .. code-block:: C
  609. x->CppMethod(1, 2, 3)
  610. As a special rule to keep backwards compatibility with older versions of the
  611. ``importcpp`` pragma, if there is no special pattern
  612. character (any of ``# ' @``) at all, C++'s
  613. dot or arrow notation is assumed, so the above example can also be written as:
  614. .. code-block:: nim
  615. proc cppMethod(this: CppObj, a, b, c: cint) {.importcpp: "CppMethod".}
  616. Note that the pattern language naturally also covers C++'s operator overloading
  617. capabilities:
  618. .. code-block:: nim
  619. proc vectorAddition(a, b: Vec3): Vec3 {.importcpp: "# + #".}
  620. proc dictLookup(a: Dict, k: Key): Value {.importcpp: "#[#]".}
  621. - An apostrophe ``'`` followed by an integer ``i`` in the range 0..9
  622. is replaced by the i'th parameter *type*. The 0th position is the result
  623. type. This can be used to pass types to C++ function templates. Between
  624. the ``'`` and the digit an asterisk can be used to get to the base type
  625. of the type. (So it "takes away a star" from the type; ``T*`` becomes ``T``.)
  626. Two stars can be used to get to the element type of the element type etc.
  627. For example:
  628. .. code-block:: nim
  629. type Input {.importcpp: "System::Input".} = object
  630. proc getSubsystem*[T](): ptr T {.importcpp: "SystemManager::getSubsystem<'*0>()", nodecl.}
  631. let x: ptr Input = getSubsystem[Input]()
  632. Produces:
  633. .. code-block:: C
  634. x = SystemManager::getSubsystem<System::Input>()
  635. - ``#@`` is a special case to support a ``cnew`` operation. It is required so
  636. that the call expression is inlined directly, without going through a
  637. temporary location. This is only required to circumvent a limitation of the
  638. current code generator.
  639. For example C++'s ``new`` operator can be "imported" like this:
  640. .. code-block:: nim
  641. proc cnew*[T](x: T): ptr T {.importcpp: "(new '*0#@)", nodecl.}
  642. # constructor of 'Foo':
  643. proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)".}
  644. let x = cnew constructFoo(3, 4)
  645. Produces:
  646. .. code-block:: C
  647. x = new Foo(3, 4)
  648. However, depending on the use case ``new Foo`` can also be wrapped like this
  649. instead:
  650. .. code-block:: nim
  651. proc newFoo(a, b: cint): ptr Foo {.importcpp: "new Foo(@)".}
  652. let x = newFoo(3, 4)
  653. Wrapping constructors
  654. ~~~~~~~~~~~~~~~~~~~~~
  655. Sometimes a C++ class has a private copy constructor and so code like
  656. ``Class c = Class(1,2);`` must not be generated but instead ``Class c(1,2);``.
  657. For this purpose the Nim proc that wraps a C++ constructor needs to be
  658. annotated with the `constructor`:idx: pragma. This pragma also helps to generate
  659. faster C++ code since construction then doesn't invoke the copy constructor:
  660. .. code-block:: nim
  661. # a better constructor of 'Foo':
  662. proc constructFoo(a, b: cint): Foo {.importcpp: "Foo(@)", constructor.}
  663. Wrapping destructors
  664. ~~~~~~~~~~~~~~~~~~~~
  665. Since Nim generates C++ directly, any destructor is called implicitly by the
  666. C++ compiler at the scope exits. This means that often one can get away with
  667. not wrapping the destructor at all! However when it needs to be invoked
  668. explicitly, it needs to be wrapped. But the pattern language already provides
  669. everything that is required for that:
  670. .. code-block:: nim
  671. proc destroyFoo(this: var Foo) {.importcpp: "#.~Foo()".}
  672. Importcpp for objects
  673. ~~~~~~~~~~~~~~~~~~~~~
  674. Generic ``importcpp``'ed objects are mapped to C++ templates. This means that
  675. you can import C++'s templates rather easily without the need for a pattern
  676. language for object types:
  677. .. code-block:: nim
  678. type
  679. StdMap {.importcpp: "std::map", header: "<map>".} [K, V] = object
  680. proc `[]=`[K, V](this: var StdMap[K, V]; key: K; val: V) {.
  681. importcpp: "#[#] = #", header: "<map>".}
  682. var x: StdMap[cint, cdouble]
  683. x[6] = 91.4
  684. Produces:
  685. .. code-block:: C
  686. std::map<int, double> x;
  687. x[6] = 91.4;
  688. - If more precise control is needed, the apostrophe ``'`` can be used in the
  689. supplied pattern to denote the concrete type parameters of the generic type.
  690. See the usage of the apostrophe operator in proc patterns for more details.
  691. .. code-block:: nim
  692. type
  693. VectorIterator {.importcpp: "std::vector<'0>::iterator".} [T] = object
  694. var x: VectorIterator[cint]
  695. Produces:
  696. .. code-block:: C
  697. std::vector<int>::iterator x;
  698. ImportObjC pragma
  699. -----------------
  700. Similar to the `importc pragma for C <manual.html#importc-pragma>`_, the
  701. ``importobjc`` pragma can be used to import `Objective C`:idx: methods. The
  702. generated code then uses the Objective C method calling syntax: ``[obj method
  703. param1: arg]``. In addition with the ``header`` and ``emit`` pragmas this
  704. allows *sloppy* interfacing with libraries written in Objective C:
  705. .. code-block:: Nim
  706. # horrible example of how to interface with GNUStep ...
  707. {.passL: "-lobjc".}
  708. {.emit: """
  709. #include <objc/Object.h>
  710. @interface Greeter:Object
  711. {
  712. }
  713. - (void)greet:(long)x y:(long)dummy;
  714. @end
  715. #include <stdio.h>
  716. @implementation Greeter
  717. - (void)greet:(long)x y:(long)dummy
  718. {
  719. printf("Hello, World!\n");
  720. }
  721. @end
  722. #include <stdlib.h>
  723. """.}
  724. type
  725. Id {.importc: "id", header: "<objc/Object.h>", final.} = distinct int
  726. proc newGreeter: Id {.importobjc: "Greeter new", nodecl.}
  727. proc greet(self: Id, x, y: int) {.importobjc: "greet", nodecl.}
  728. proc free(self: Id) {.importobjc: "free", nodecl.}
  729. var g = newGreeter()
  730. g.greet(12, 34)
  731. g.free()
  732. The compiler needs to be told to generate Objective C (command ``objc``) for
  733. this to work. The conditional symbol ``objc`` is defined when the compiler
  734. emits Objective C code.
  735. CodegenDecl pragma
  736. ------------------
  737. The ``codegenDecl`` pragma can be used to directly influence Nim's code
  738. generator. It receives a format string that determines how the variable
  739. or proc is declared in the generated code.
  740. For variables $1 in the format string represents the type of the variable
  741. and $2 is the name of the variable.
  742. The following Nim code:
  743. .. code-block:: nim
  744. var
  745. a {.codegenDecl: "$# progmem $#".}: int
  746. will generate this C code:
  747. .. code-block:: c
  748. int progmem a
  749. For procedures $1 is the return type of the procedure, $2 is the name of
  750. the procedure and $3 is the parameter list.
  751. The following nim code:
  752. .. code-block:: nim
  753. proc myinterrupt() {.codegenDecl: "__interrupt $# $#$#".} =
  754. echo "realistic interrupt handler"
  755. will generate this code:
  756. .. code-block:: c
  757. __interrupt void myinterrupt()
  758. InjectStmt pragma
  759. -----------------
  760. The ``injectStmt`` pragma can be used to inject a statement before every
  761. other statement in the current module. It is only supposed to be used for
  762. debugging:
  763. .. code-block:: nim
  764. {.injectStmt: gcInvariants().}
  765. # ... complex code here that produces crashes ...
  766. compile time define pragmas
  767. ---------------------------
  768. The pragmas listed here can be used to optionally accept values from
  769. the -d/--define option at compile time.
  770. The implementation currently provides the following possible options (various
  771. others may be added later).
  772. ================= ============================================
  773. pragma description
  774. ================= ============================================
  775. `intdefine`:idx: Reads in a build-time define as an integer
  776. `strdefine`:idx: Reads in a build-time define as a string
  777. ================= ============================================
  778. .. code-block:: nim
  779. const FooBar {.intdefine.}: int = 5
  780. echo FooBar
  781. .. code-block:: bash
  782. nim c -d:FooBar=42 foobar.c
  783. In the above example, providing the -d flag causes the symbol
  784. ``FooBar`` to be overwritten at compile time, printing out 42. If the
  785. ``-d:FooBar=42`` were to be omitted, the default value of 5 would be
  786. used.