idetools.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. ================================
  2. Nim IDE Integration Guide
  3. ================================
  4. :Author: Britney Spears
  5. :Version: |nimversion|
  6. .. contents::
  7. .. raw:: html
  8. <blockquote><p>
  9. "yes, I'm the creator" -- Araq, 2013-07-26 19:28:32.
  10. </p></blockquote>
  11. Nim differs from many other compilers in that it is really fast,
  12. and being so fast makes it suited to provide external queries for
  13. text editors about the source code being written. Through the
  14. ``idetools`` command of `the compiler <nimc.html>`_, any IDE
  15. can query a ``.nim`` source file and obtain useful information like
  16. definition of symbols or suggestions for completion.
  17. This document will guide you through the available options. If you
  18. want to look at practical examples of idetools support you can look
  19. at the test files found in the `Test suite`_ or `various editor
  20. integrations <https://github.com/Araq/Nim/wiki/Editor-Support>`_
  21. already available.
  22. Idetools invocation
  23. ===================
  24. Specifying the location of the query
  25. ------------------------------------
  26. All of the available idetools commands require you to specify a
  27. query location through the ``--track`` or ``--trackDirty`` switches.
  28. The general idetools invocations are::
  29. nim idetools --track:FILE,LINE,COL <switches> proj.nim
  30. Or::
  31. nim idetools --trackDirty:DIRTY_FILE,FILE,LINE,COL <switches> proj.nim
  32. ``proj.nim``
  33. This is the main *project* filename. Most of the time you will
  34. pass in the same as **FILE**, but for bigger projects this is
  35. the file which is used as main entry point for the program, the
  36. one which users compile to generate a final binary.
  37. ``<switches>``
  38. This would be any of the other idetools available options, like
  39. ``--def`` or ``--suggest`` explained in the following sections.
  40. ``COL``
  41. An integer with the column you are going to query. For the
  42. compiler columns start at zero, so the first column will be
  43. **0** and the last in an 80 column terminal will be **79**.
  44. ``LINE``
  45. An integer with the line you are going to query. For the compiler
  46. lines start at **1**.
  47. ``FILE``
  48. The file you want to perform the query on. Usually you will
  49. pass in the same value as **proj.nim**.
  50. ``DIRTY_FILE``
  51. The **FILE** paramater is enough for static analysis, but IDEs
  52. tend to have *unsaved buffers* where the user may still be in
  53. the middle of typing a line. In such situations the IDE can
  54. save the current contents to a temporary file and then use the
  55. ``--trackDirty`` switch.
  56. Dirty files are likely to contain errors and they are usually
  57. compiled partially only to the point needed to service the
  58. idetool request. The compiler discriminates them to ensure that
  59. **a)** they won't be cached and **b)** they won't invalidate
  60. the cached contents of the original module.
  61. The other reason is that the dirty file can appear anywhere on
  62. disk (e.g. in tmpfs), but it must be treated as having a path
  63. matching the original module when it comes to usage of relative
  64. paths, etc. Queries, however, will refer to the dirty module
  65. name in their answers instead of the normal filename.
  66. Definitions
  67. -----------
  68. The ``--def`` idetools switch performs a query about the definition
  69. of a specific symbol. If available, idetools will answer with the
  70. type, source file, line/column information and other accessory data
  71. if available like a docstring. With this information an IDE can
  72. provide the typical *Jump to definition* where a user puts the
  73. cursor on a symbol or uses the mouse to select it and is redirected
  74. to the place where the symbol is located.
  75. Since Nim is implemented in Nim, one of the nice things of
  76. this feature is that any user with an IDE supporting it can quickly
  77. jump around the standard library implementation and see exactly
  78. what a proc does, learning about the language and seeing real life
  79. examples of how to write/implement specific features.
  80. Idetools will always answer with a single definition or none if it
  81. can't find any valid symbol matching the position of the query.
  82. Suggestions
  83. -----------
  84. The ``--suggest`` idetools switch performs a query about possible
  85. completion symbols at some point in the file. IDEs can easily provide
  86. an autocompletion feature where the IDE scans the current file (and
  87. related ones, if it knows about the language being edited and follows
  88. includes/imports) and when the user starts typing something a
  89. completion box with different options appears.
  90. However such features are not context sensitive and work simply on
  91. string matching, which can be problematic in Nim especially due
  92. to the case insensitiveness of the language (plus underscores as
  93. separators!).
  94. The typical usage scenario for this option is to call it after the
  95. user has typed the dot character for `the object oriented call
  96. syntax <tut2.html#method-call-syntax>`_. Idetools will try to return
  97. the suggestions sorted first by scope (from innermost to outermost)
  98. and then by item name.
  99. Invocation context
  100. ------------------
  101. The ``--context`` idetools switch is very similar to the suggestions
  102. switch, but instead of being used after the user has typed a dot
  103. character, this one is meant to be used after the user has typed
  104. an opening brace to start typing parameters.
  105. Symbol usages
  106. -------------
  107. The ``--usages`` idetools switch lists all usages of the symbol at
  108. a position. IDEs can use this to find all the places in the file
  109. where the symbol is used and offer the user to rename it in all
  110. places at the same time. Again, a pure string based search and
  111. replace may catch symbols out of the scope of a function/loop.
  112. For this kind of query the IDE will most likely ignore all the
  113. type/signature info provided by idetools and concentrate on the
  114. filename, line and column position of the multiple returned answers.
  115. Expression evaluation
  116. ---------------------
  117. This feature is still under development. In the future it will allow
  118. an IDE to evaluate an expression in the context of the currently
  119. running/debugged user project.
  120. Compiler as a service (CAAS)
  121. ============================
  122. The occasional use of idetools is acceptable for things like
  123. definitions, where the user puts the cursor on a symbol or double
  124. clicks it and after a second or two the IDE displays where that
  125. symbol is defined. Such latencies would be terrible for features
  126. like symbol suggestion, plus why wait at all if we can avoid it?
  127. The idetools command can be run as a compiler service (CAAS),
  128. where you first launch the compiler and it will stay online as a
  129. server, accepting queries in a telnet like fashion. The advantage
  130. of staying on is that for many queries the compiler can cache the
  131. results of the compilation, and subsequent queries should be fast
  132. in the millisecond range, thus being responsive enough for IDEs.
  133. If you want to start the server using stdin/stdout as communication
  134. you need to type::
  135. nim serve --server.type:stdin proj.nim
  136. If you want to start the server using tcp and a port, you need to type::
  137. nim serve --server.type:tcp --server.port:6000 \
  138. --server.address:hostname proj.nim
  139. In both cases the server will start up and await further commands.
  140. The syntax of the commands you can now send to the server is
  141. practically the same as running the nim compiler on the commandline,
  142. you only need to remove the name of the compiler since you are
  143. already talking to it. The server will answer with as many lines
  144. of text it thinks necessary plus an empty line to indicate the end
  145. of the answer.
  146. You can find examples of client/server communication in the idetools
  147. tests found in the `Test suite`_.
  148. Parsing idetools output
  149. =======================
  150. Idetools outputs is always returned on single lines separated by
  151. tab characters (``\t``). The values of each column are:
  152. 1. Three characters indicating the type of returned answer (e.g.
  153. def for definition, ``sug`` for suggestion, etc).
  154. 2. Type of the symbol. This can be ``skProc``, ``skLet``, and just
  155. about any of the enums defined in the module ``compiler/ast.nim``.
  156. 3. Full qualitifed path of the symbol. If you are querying a symbol
  157. defined in the ``proj.nim`` file, this would have the form
  158. ``proj.symbolName``.
  159. 4. Type/signature. For variables and enums this will contain the
  160. type of the symbol, for procs, methods and templates this will
  161. contain the full unique signature (e.g. ``proc (File)``).
  162. 5. Full path to the file containing the symbol.
  163. 6. Line where the symbol is located in the file. Lines start to
  164. count at **1**.
  165. 7. Column where the symbol is located in the file. Columns start
  166. to count at **0**.
  167. 8. Docstring for the symbol if available or the empty string. To
  168. differentiate the docstring from end of answer in server mode,
  169. the docstring is always provided enclosed in double quotes, and
  170. if the docstring spans multiple lines, all following lines of the
  171. docstring will start with a blank space to align visually with
  172. the starting quote.
  173. Also, you won't find raw ``\n`` characters breaking the one
  174. answer per line format. Instead you will need to parse sequences
  175. in the form ``\xHH``, where *HH* is a hexadecimal value (e.g.
  176. newlines generate the sequence ``\x0A``).
  177. The following sections define the expected output for each kind of
  178. symbol for which idetools returns valid output.
  179. skConst
  180. -------
  181. | **Third column**: module + [n scope nesting] + const name.
  182. | **Fourth column**: the type of the const value.
  183. | **Docstring**: always the empty string.
  184. .. code-block:: nim
  185. const SOME_SEQUENCE = @[1, 2]
  186. --> col 2: $MODULE.SOME_SEQUENCE
  187. col 3: seq[int]
  188. col 7: ""
  189. skEnumField
  190. -----------
  191. | **Third column**: module + [n scope nesting] + enum type + enum field name.
  192. | **Fourth column**: enum type grouping other enum fields.
  193. | **Docstring**: always the empty string.
  194. .. code-block:: nim
  195. Open(filename, fmWrite)
  196. --> col 2: system.FileMode.fmWrite
  197. col 3: FileMode
  198. col 7: ""
  199. skForVar
  200. --------
  201. | **Third column**: module + [n scope nesting] + var name.
  202. | **Fourth column**: type of the var.
  203. | **Docstring**: always the empty string.
  204. .. code-block:: nim
  205. proc looper(filename = "tests.nim") =
  206. for letter in filename:
  207. echo letter
  208. --> col 2: $MODULE.looper.letter
  209. col 3: char
  210. col 7: ""
  211. skIterator, skClosureIterator
  212. -----------------------------
  213. The fourth column will be the empty string if the iterator is being
  214. defined, since at that point in the file the parser hasn't processed
  215. the full line yet. The signature will be returned complete in
  216. posterior instances of the iterator.
  217. | **Third column**: module + [n scope nesting] + iterator name.
  218. | **Fourth column**: signature of the iterator including return type.
  219. | **Docstring**: docstring if available.
  220. .. code-block:: nim
  221. let
  222. text = "some text"
  223. letters = toSeq(runes(text))
  224. --> col 2: unicode.runes
  225. col 3: iterator (string): Rune
  226. col 7: "iterates over any unicode character of the string `s`."
  227. skLabel
  228. -------
  229. | **Third column**: module + [n scope nesting] + name.
  230. | **Fourth column**: always the empty string.
  231. | **Docstring**: always the empty string.
  232. .. code-block:: nim
  233. proc test(text: string) =
  234. var found = -1
  235. block loops:
  236. --> col 2: $MODULE.test.loops
  237. col 3: ""
  238. col 7: ""
  239. skLet
  240. -----
  241. | **Third column**: module + [n scope nesting] + let name.
  242. | **Fourth column**: the type of the let variable.
  243. | **Docstring**: always the empty string.
  244. .. code-block:: nim
  245. let
  246. text = "some text"
  247. --> col 2: $MODULE.text
  248. col 3: TaintedString
  249. col 7: ""
  250. skMacro
  251. -------
  252. The fourth column will be the empty string if the macro is being
  253. defined, since at that point in the file the parser hasn't processed
  254. the full line yet. The signature will be returned complete in
  255. posterior instances of the macro.
  256. | **Third column**: module + [n scope nesting] + macro name.
  257. | **Fourth column**: signature of the macro including return type.
  258. | **Docstring**: docstring if available.
  259. .. code-block:: nim
  260. proc testMacro() =
  261. expect(EArithmetic):
  262. --> col 2: idetools_api.expect
  263. col 3: proc (varargs[expr], stmt): stmt
  264. col 7: ""
  265. skMethod
  266. --------
  267. The fourth column will be the empty string if the method is being
  268. defined, since at that point in the file the parser hasn't processed
  269. the full line yet. The signature will be returned complete in
  270. posterior instances of the method.
  271. Methods imply `dynamic dispatch <tut2.html#dynamic-dispatch>`_ and
  272. idetools performs a static analysis on the code. For this reason
  273. idetools may not return the definition of the correct method you
  274. are querying because it may be impossible to know until the code
  275. is executed. It will try to return the method which covers the most
  276. possible cases (i.e. for variations of different classes in a
  277. hierarchy it will prefer methods using the base class).
  278. While at the language level a method is differentiated from others
  279. by the parameters and return value, the signature of the method
  280. returned by idetools returns also the pragmas for the method.
  281. Note that at the moment the word ``proc`` is returned for the
  282. signature of the found method instead of the expected ``method``.
  283. This may change in the future.
  284. | **Third column**: module + [n scope nesting] + method name.
  285. | **Fourth column**: signature of the method including return type.
  286. | **Docstring**: docstring if available.
  287. .. code-block:: nim
  288. method eval(e: PExpr): int = quit "to override!"
  289. method eval(e: PLiteral): int = e.x
  290. method eval(e: PPlusExpr): int = eval(e.a) + eval(e.b)
  291. echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4)))
  292. --> col 2: $MODULE.eval
  293. col 3: proc (PPlusExpr): int
  294. col 7: ""
  295. skParam
  296. -------
  297. | **Third column**: module + [n scope nesting] + param name.
  298. | **Fourth column**: the type of the parameter.
  299. | **Docstring**: always the empty string.
  300. .. code-block:: nim
  301. proc reader(filename = "tests.nim") =
  302. let text = readFile(filename)
  303. --> col 2: $MODULE.reader.filename
  304. col 3: string
  305. col 7: ""
  306. skProc
  307. ------
  308. The fourth column will be the empty string if the proc is being
  309. defined, since at that point in the file the parser hasn't processed
  310. the full line yet. The signature will be returned complete in
  311. posterior instances of the proc.
  312. While at the language level a proc is differentiated from others
  313. by the parameters and return value, the signature of the proc
  314. returned by idetools returns also the pragmas for the proc.
  315. | **Third column**: module + [n scope nesting] + proc name.
  316. | **Fourth column**: signature of the proc including return type.
  317. | **Docstring**: docstring if available.
  318. .. code-block:: nim
  319. open(filename, fmWrite)
  320. --> col 2: system.Open
  321. col 3: proc (var File, string, FileMode, int): bool
  322. col 7:
  323. "Opens a file named `filename` with given `mode`.
  324. Default mode is readonly. Returns true iff the file could be opened.
  325. This throws no exception if the file could not be opened."
  326. skResult
  327. --------
  328. | **Third column**: module + [n scope nesting] + result.
  329. | **Fourth column**: the type of the result.
  330. | **Docstring**: always the empty string.
  331. .. code-block:: nim
  332. proc getRandomValue() : int =
  333. return 4
  334. --> col 2: $MODULE.getRandomValue.result
  335. col 3: int
  336. col 7: ""
  337. skTemplate
  338. ----------
  339. The fourth column will be the empty string if the template is being
  340. defined, since at that point in the file the parser hasn't processed
  341. the full line yet. The signature will be returned complete in
  342. posterior instances of the template.
  343. | **Third column**: module + [n scope nesting] + template name.
  344. | **Fourth column**: signature of the template including return type.
  345. | **Docstring**: docstring if available.
  346. .. code-block:: nim
  347. let
  348. text = "some text"
  349. letters = toSeq(runes(text))
  350. --> col 2: sequtils.toSeq
  351. col 3: proc (expr): expr
  352. col 7:
  353. "Transforms any iterator into a sequence.
  354. Example:
  355. .. code-block:: nim
  356. let
  357. numeric = @[1, 2, 3, 4, 5, 6, 7, 8, 9]
  358. odd_numbers = toSeq(filter(numeric) do (x: int) -> bool:
  359. if x mod 2 == 1:
  360. result = true)
  361. assert odd_numbers == @[1, 3, 5, 7, 9]"
  362. skType
  363. ------
  364. | **Third column**: module + [n scope nesting] + type name.
  365. | **Fourth column**: the type.
  366. | **Docstring**: always the empty string.
  367. .. code-block:: nim
  368. proc writeTempFile() =
  369. var output: File
  370. --> col 2: system.File
  371. col 3: File
  372. col 7: ""
  373. skVar
  374. -----
  375. | **Third column**: module + [n scope nesting] + var name.
  376. | **Fourth column**: the type of the var.
  377. | **Docstring**: always the empty string.
  378. .. code-block:: nim
  379. proc writeTempFile() =
  380. var output: File
  381. output.open("/tmp/somefile", fmWrite)
  382. output.write("test")
  383. --> col 2: $MODULE.writeTempFile.output
  384. col 3: File
  385. col 7: ""
  386. Test suite
  387. ==========
  388. To verify that idetools is working properly there are files in the
  389. ``tests/caas/`` directory which provide unit testing. If you find
  390. odd idetools behaviour and are able to reproduce it, you are welcome
  391. to report it as a bug and add a test to the suite to avoid future
  392. regressions.
  393. Running the test suite
  394. ----------------------
  395. At the moment idetools support is still in development so the test
  396. suite is not integrated with the main test suite and you have to
  397. run it manually. First you have to compile the tester::
  398. $ cd my/nim/checkout/tests
  399. $ nim c testament/caasdriver.nim
  400. Running the ``caasdriver`` without parameters will attempt to process
  401. all the test cases in all three operation modes. If a test succeeds
  402. nothing will be printed and the process will exit with zero. If any
  403. test fails, the specific line of the test preceding the failure
  404. and the failure itself will be dumped to stdout, along with a final
  405. indicator of the success state and operation mode. You can pass the
  406. parameter ``verbose`` to force all output even on successful tests.
  407. The normal operation mode is called ``ProcRun`` and it involves
  408. starting a process for each command or query, similar to running
  409. manually the Nim compiler from the commandline. The ``CaasRun``
  410. mode starts a server process to answer all queries. The ``SymbolProcRun``
  411. mode is used by compiler developers. This means that running all
  412. tests involves processing all ``*.txt`` files three times, which
  413. can be quite time consuming.
  414. If you don't want to run all the test case files you can pass any
  415. substring as a parameter to ``caasdriver``. Only files matching the
  416. passed substring will be run. The filtering doesn't use any globbing
  417. metacharacters, it's a plain match. For example, to run only
  418. ``*-compile*.txt`` tests in verbose mode::
  419. ./caasdriver verbose -compile
  420. Test case file format
  421. ---------------------
  422. All the ``tests/caas/*.txt`` files encode a session with the compiler:
  423. * The first line indicates the main project file.
  424. * Lines starting with ``>`` indicate a command to be sent to the
  425. compiler and the lines following a command include checks for
  426. expected or forbidden output (``!`` for forbidden).
  427. * If a line starts with ``#`` it will be ignored completely, so you
  428. can use that for comments.
  429. * Since some cases are specific to either ``ProcRun`` or ``CaasRun``
  430. modes, you can prefix a line with the mode and the line will be
  431. processed only in that mode.
  432. * The rest of the line is treated as a `regular expression <re.html>`_,
  433. so be careful escaping metacharacters like parenthesis.
  434. Before the line is processed as a regular expression, some basic
  435. variables are searched for and replaced in the tests. The variables
  436. which will be replaced are:
  437. * **$TESTNIM**: filename specified in the first line of the script.
  438. * **$MODULE**: like $TESTNIM but without extension, useful for
  439. expected output.
  440. When adding a test case to the suite it is a good idea to write a
  441. few comments about what the test is meant to verify.