idetools.rst 20 KB

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