nimsuggest.nim 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2017 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. import compiler/renderer
  10. import strformat
  11. import algorithm
  12. import tables
  13. import std/sha1
  14. import times
  15. ## Nimsuggest is a tool that helps to give editors IDE like capabilities.
  16. when not defined(nimcore):
  17. {.error: "nimcore MUST be defined for Nim's core tooling".}
  18. import strutils, os, parseopt, parseutils, sequtils, net, rdstdin, sexp
  19. # Do NOT import suggest. It will lead to weird bugs with
  20. # suggestionResultHook, because suggest.nim is included by sigmatch.
  21. # So we import that one instead.
  22. import compiler / [options, commands, modules, sem,
  23. passes, passaux, msgs,
  24. sigmatch, ast,
  25. idents, modulegraphs, prefixmatches, lineinfos, cmdlinehelper,
  26. pathutils]
  27. when defined(windows):
  28. import winlean
  29. else:
  30. import posix
  31. const DummyEof = "!EOF!"
  32. const Usage = """
  33. Nimsuggest - Tool to give every editor IDE like capabilities for Nim
  34. Usage:
  35. nimsuggest [options] projectfile.nim
  36. Options:
  37. --autobind automatically binds into a free port
  38. --port:PORT port, by default 6000
  39. --address:HOST binds to that address, by default ""
  40. --stdin read commands from stdin and write results to
  41. stdout instead of using sockets
  42. --epc use emacs epc mode
  43. --debug enable debug output
  44. --log enable verbose logging to nimsuggest.log file
  45. --v1 use version 1 of the protocol; for backwards compatibility
  46. --v2 use version 2(default) of the protocol
  47. --v3 use version 3 of the protocol
  48. --refresh perform automatic refreshes to keep the analysis precise
  49. --maxresults:N limit the number of suggestions to N
  50. --tester implies --stdin and outputs a line
  51. '""" & DummyEof & """' for the tester
  52. --find attempts to find the project file of the current project
  53. The server then listens to the connection and takes line-based commands.
  54. If --autobind is used, the binded port number will be printed to stdout.
  55. In addition, all command line options of Nim that do not affect code generation
  56. are supported.
  57. """
  58. type
  59. Mode = enum mstdin, mtcp, mepc, mcmdsug, mcmdcon
  60. CachedMsg = object
  61. info: TLineInfo
  62. msg: string
  63. sev: Severity
  64. CachedMsgs = seq[CachedMsg]
  65. var
  66. gPort = 6000.Port
  67. gAddress = ""
  68. gMode: Mode
  69. gEmitEof: bool # whether we write '!EOF!' dummy lines
  70. gLogging = defined(logging)
  71. gRefresh: bool
  72. gAutoBind = false
  73. requests: Channel[string]
  74. results: Channel[Suggest]
  75. proc executeNoHooksV3(cmd: IdeCmd, file: AbsoluteFile, dirtyfile: AbsoluteFile, line, col: int;
  76. graph: ModuleGraph);
  77. proc writelnToChannel(line: string) =
  78. results.send(Suggest(section: ideMsg, doc: line))
  79. proc sugResultHook(s: Suggest) =
  80. results.send(s)
  81. proc errorHook(conf: ConfigRef; info: TLineInfo; msg: string; sev: Severity) =
  82. results.send(Suggest(section: ideChk, filePath: toFullPath(conf, info),
  83. line: toLinenumber(info), column: toColumn(info), doc: msg,
  84. forth: $sev))
  85. proc myLog(s: string) =
  86. if gLogging: log(s)
  87. const
  88. seps = {':', ';', ' ', '\t'}
  89. Help = "usage: sug|con|def|use|dus|chk|mod|highlight|outline|known|project file.nim[;dirtyfile.nim]:line:col\n" &
  90. "type 'quit' to quit\n" &
  91. "type 'debug' to toggle debug mode on/off\n" &
  92. "type 'terse' to toggle terse mode on/off"
  93. proc parseQuoted(cmd: string; outp: var string; start: int): int =
  94. var i = start
  95. i += skipWhitespace(cmd, i)
  96. if i < cmd.len and cmd[i] == '"':
  97. i += parseUntil(cmd, outp, '"', i+1)+2
  98. else:
  99. i += parseUntil(cmd, outp, seps, i)
  100. result = i
  101. proc sexp(s: IdeCmd|TSymKind|PrefixMatch): SexpNode = sexp($s)
  102. proc sexp(s: Suggest): SexpNode =
  103. # If you change the order here, make sure to change it over in
  104. # nim-mode.el too.
  105. let qp = if s.qualifiedPath.len == 0: @[] else: s.qualifiedPath
  106. result = convertSexp([
  107. s.section,
  108. TSymKind s.symkind,
  109. qp.map(newSString),
  110. s.filePath,
  111. s.forth,
  112. s.line,
  113. s.column,
  114. s.doc,
  115. s.quality
  116. ])
  117. if s.section == ideSug:
  118. result.add convertSexp(s.prefix)
  119. proc sexp(s: seq[Suggest]): SexpNode =
  120. result = newSList()
  121. for sug in s:
  122. result.add(sexp(sug))
  123. proc listEpc(): SexpNode =
  124. # This function is called from Emacs to show available options.
  125. let
  126. argspecs = sexp("file line column dirtyfile".split(" ").map(newSSymbol))
  127. docstring = sexp("line starts at 1, column at 0, dirtyfile is optional")
  128. result = newSList()
  129. for command in ["sug", "con", "def", "use", "dus", "chk", "mod", "globalSymbols", "recompile", "saved", "chkFile", "declaration"]:
  130. let
  131. cmd = sexp(command)
  132. methodDesc = newSList()
  133. methodDesc.add(cmd)
  134. methodDesc.add(argspecs)
  135. methodDesc.add(docstring)
  136. result.add(methodDesc)
  137. proc findNode(n: PNode; trackPos: TLineInfo): PSym =
  138. #echo "checking node ", n.info
  139. if n.kind == nkSym:
  140. if isTracked(n.info, trackPos, n.sym.name.s.len): return n.sym
  141. else:
  142. for i in 0 ..< safeLen(n):
  143. let res = findNode(n[i], trackPos)
  144. if res != nil: return res
  145. proc symFromInfo(graph: ModuleGraph; trackPos: TLineInfo): PSym =
  146. let m = graph.getModule(trackPos.fileIndex)
  147. if m != nil and m.ast != nil:
  148. result = findNode(m.ast, trackPos)
  149. proc executeNoHooks(cmd: IdeCmd, file, dirtyfile: AbsoluteFile, line, col: int;
  150. graph: ModuleGraph) =
  151. let conf = graph.config
  152. if conf.suggestVersion == 3:
  153. executeNoHooksV3(cmd, file, dirtyfile, line, col, graph)
  154. return
  155. myLog("cmd: " & $cmd & ", file: " & file.string &
  156. ", dirtyFile: " & dirtyfile.string &
  157. "[" & $line & ":" & $col & "]")
  158. conf.ideCmd = cmd
  159. if cmd == ideUse and conf.suggestVersion != 0:
  160. graph.resetAllModules()
  161. var isKnownFile = true
  162. let dirtyIdx = fileInfoIdx(conf, file, isKnownFile)
  163. if not dirtyfile.isEmpty: msgs.setDirtyFile(conf, dirtyIdx, dirtyfile)
  164. else: msgs.setDirtyFile(conf, dirtyIdx, AbsoluteFile"")
  165. conf.m.trackPos = newLineInfo(dirtyIdx, line, col)
  166. conf.m.trackPosAttached = false
  167. conf.errorCounter = 0
  168. if conf.suggestVersion == 1:
  169. graph.usageSym = nil
  170. if not isKnownFile:
  171. graph.compileProject(dirtyIdx)
  172. if conf.suggestVersion == 0 and conf.ideCmd in {ideUse, ideDus} and
  173. dirtyfile.isEmpty:
  174. discard "no need to recompile anything"
  175. else:
  176. let modIdx = graph.parentModule(dirtyIdx)
  177. graph.markDirty dirtyIdx
  178. graph.markClientsDirty dirtyIdx
  179. if conf.ideCmd != ideMod:
  180. if isKnownFile:
  181. graph.compileProject(modIdx)
  182. if conf.ideCmd in {ideUse, ideDus}:
  183. let u = if conf.suggestVersion != 1: graph.symFromInfo(conf.m.trackPos) else: graph.usageSym
  184. if u != nil:
  185. listUsages(graph, u)
  186. else:
  187. localError(conf, conf.m.trackPos, "found no symbol at this position " & (conf $ conf.m.trackPos))
  188. proc execute(cmd: IdeCmd, file, dirtyfile: AbsoluteFile, line, col: int;
  189. graph: ModuleGraph) =
  190. if cmd == ideChk:
  191. graph.config.structuredErrorHook = errorHook
  192. graph.config.writelnHook = myLog
  193. else:
  194. graph.config.structuredErrorHook = nil
  195. graph.config.writelnHook = myLog
  196. executeNoHooks(cmd, file, dirtyfile, line, col, graph)
  197. proc executeEpc(cmd: IdeCmd, args: SexpNode;
  198. graph: ModuleGraph) =
  199. let
  200. file = AbsoluteFile args[0].getStr
  201. line = args[1].getNum
  202. column = args[2].getNum
  203. var dirtyfile = AbsoluteFile""
  204. if len(args) > 3:
  205. dirtyfile = AbsoluteFile args[3].getStr("")
  206. execute(cmd, file, dirtyfile, int(line), int(column), graph)
  207. proc returnEpc(socket: Socket, uid: BiggestInt, s: SexpNode|string,
  208. returnSymbol = "return") =
  209. let response = $convertSexp([newSSymbol(returnSymbol), uid, s])
  210. socket.send(toHex(len(response), 6))
  211. socket.send(response)
  212. template checkSanity(client, sizeHex, size, messageBuffer: typed) =
  213. if client.recv(sizeHex, 6) != 6:
  214. raise newException(ValueError, "didn't get all the hexbytes")
  215. if parseHex(sizeHex, size) == 0:
  216. raise newException(ValueError, "invalid size hex: " & $sizeHex)
  217. if client.recv(messageBuffer, size) != size:
  218. raise newException(ValueError, "didn't get all the bytes")
  219. proc toStdout() {.gcsafe.} =
  220. while true:
  221. let res = results.recv()
  222. case res.section
  223. of ideNone: break
  224. of ideMsg: echo res.doc
  225. of ideKnown: echo res.quality == 1
  226. of ideProject: echo res.filePath
  227. else: echo res
  228. proc toSocket(stdoutSocket: Socket) {.gcsafe.} =
  229. while true:
  230. let res = results.recv()
  231. case res.section
  232. of ideNone: break
  233. of ideMsg: stdoutSocket.send(res.doc & "\c\L")
  234. of ideKnown: stdoutSocket.send($(res.quality == 1) & "\c\L")
  235. of ideProject: stdoutSocket.send(res.filePath & "\c\L")
  236. else: stdoutSocket.send($res & "\c\L")
  237. proc toEpc(client: Socket; uid: BiggestInt) {.gcsafe.} =
  238. var list = newSList()
  239. while true:
  240. let res = results.recv()
  241. case res.section
  242. of ideNone: break
  243. of ideMsg:
  244. list.add sexp(res.doc)
  245. of ideKnown:
  246. list.add sexp(res.quality == 1)
  247. of ideProject:
  248. list.add sexp(res.filePath)
  249. else:
  250. list.add sexp(res)
  251. returnEpc(client, uid, list)
  252. template setVerbosity(level: typed) =
  253. gVerbosity = level
  254. conf.notes = NotesVerbosity[gVerbosity]
  255. proc connectToNextFreePort(server: Socket, host: string): Port =
  256. server.bindAddr(Port(0), host)
  257. let (_, port) = server.getLocalAddr
  258. result = port
  259. type
  260. ThreadParams = tuple[port: Port; address: string]
  261. proc replStdinSingleCmd(line: string) =
  262. requests.send line
  263. toStdout()
  264. echo ""
  265. flushFile(stdout)
  266. proc replStdin(x: ThreadParams) {.thread.} =
  267. if gEmitEof:
  268. echo DummyEof
  269. while true:
  270. let line = readLine(stdin)
  271. requests.send line
  272. if line == "quit": break
  273. toStdout()
  274. echo DummyEof
  275. flushFile(stdout)
  276. else:
  277. echo Help
  278. var line = ""
  279. while readLineFromStdin("> ", line):
  280. replStdinSingleCmd(line)
  281. requests.send "quit"
  282. proc replCmdline(x: ThreadParams) {.thread.} =
  283. replStdinSingleCmd(x.address)
  284. requests.send "quit"
  285. proc replTcp(x: ThreadParams) {.thread.} =
  286. var server = newSocket()
  287. if gAutoBind:
  288. let port = server.connectToNextFreePort(x.address)
  289. server.listen()
  290. echo port
  291. stdout.flushFile()
  292. else:
  293. server.bindAddr(x.port, x.address)
  294. server.listen()
  295. var inp = ""
  296. var stdoutSocket: Socket
  297. while true:
  298. accept(server, stdoutSocket)
  299. stdoutSocket.readLine(inp)
  300. requests.send inp
  301. toSocket(stdoutSocket)
  302. stdoutSocket.send("\c\L")
  303. stdoutSocket.close()
  304. proc argsToStr(x: SexpNode): string =
  305. if x.kind != SList: return x.getStr
  306. doAssert x.kind == SList
  307. doAssert x.len >= 4
  308. let file = x[0].getStr
  309. let line = x[1].getNum
  310. let col = x[2].getNum
  311. let dirty = x[3].getStr
  312. result = x[0].getStr.escape
  313. if dirty.len > 0:
  314. result.add ';'
  315. result.add dirty.escape
  316. result.add ':'
  317. result.addInt line
  318. result.add ':'
  319. result.addInt col
  320. proc replEpc(x: ThreadParams) {.thread.} =
  321. var server = newSocket()
  322. let port = connectToNextFreePort(server, "localhost")
  323. server.listen()
  324. echo port
  325. stdout.flushFile()
  326. var client: Socket
  327. # Wait for connection
  328. accept(server, client)
  329. while true:
  330. var
  331. sizeHex = ""
  332. size = 0
  333. messageBuffer = ""
  334. checkSanity(client, sizeHex, size, messageBuffer)
  335. let
  336. message = parseSexp($messageBuffer)
  337. epcApi = message[0].getSymbol
  338. case epcApi
  339. of "call":
  340. let
  341. uid = message[1].getNum
  342. cmd = message[2].getSymbol
  343. args = message[3]
  344. when false:
  345. x.ideCmd[] = parseIdeCmd(message[2].getSymbol)
  346. case x.ideCmd[]
  347. of ideSug, ideCon, ideDef, ideUse, ideDus, ideOutline, ideHighlight:
  348. setVerbosity(0)
  349. else: discard
  350. let fullCmd = cmd & " " & args.argsToStr
  351. myLog "MSG CMD: " & fullCmd
  352. requests.send(fullCmd)
  353. toEpc(client, uid)
  354. of "methods":
  355. returnEpc(client, message[1].getNum, listEpc())
  356. of "epc-error":
  357. # an unhandled exception forces down the whole process anyway, so we
  358. # use 'quit' here instead of 'raise'
  359. quit("received epc error: " & $messageBuffer)
  360. else:
  361. let errMessage = case epcApi
  362. of "return", "return-error":
  363. "no return expected"
  364. else:
  365. "unexpected call: " & epcApi
  366. quit errMessage
  367. proc execCmd(cmd: string; graph: ModuleGraph; cachedMsgs: CachedMsgs) =
  368. let conf = graph.config
  369. template sentinel() =
  370. # send sentinel for the input reading thread:
  371. results.send(Suggest(section: ideNone))
  372. template toggle(sw) =
  373. if sw in conf.globalOptions:
  374. excl(conf.globalOptions, sw)
  375. else:
  376. incl(conf.globalOptions, sw)
  377. sentinel()
  378. return
  379. template err() =
  380. echo Help
  381. sentinel()
  382. return
  383. var opc = ""
  384. var i = parseIdent(cmd, opc, 0)
  385. case opc.normalize
  386. of "sug": conf.ideCmd = ideSug
  387. of "con": conf.ideCmd = ideCon
  388. of "def": conf.ideCmd = ideDef
  389. of "use": conf.ideCmd = ideUse
  390. of "dus": conf.ideCmd = ideDus
  391. of "mod": conf.ideCmd = ideMod
  392. of "chk": conf.ideCmd = ideChk
  393. of "highlight": conf.ideCmd = ideHighlight
  394. of "outline": conf.ideCmd = ideOutline
  395. of "quit":
  396. sentinel()
  397. quit()
  398. of "debug": toggle optIdeDebug
  399. of "terse": toggle optIdeTerse
  400. of "known": conf.ideCmd = ideKnown
  401. of "project": conf.ideCmd = ideProject
  402. of "changed": conf.ideCmd = ideChanged
  403. of "globalsymbols": conf.ideCmd = ideGlobalSymbols
  404. of "declaration": conf.ideCmd = ideDeclaration
  405. of "chkfile": conf.ideCmd = ideChkFile
  406. of "recompile": conf.ideCmd = ideRecompile
  407. of "type": conf.ideCmd = ideType
  408. else: err()
  409. var dirtyfile = ""
  410. var orig = ""
  411. i += skipWhitespace(cmd, i)
  412. if i < cmd.len and cmd[i] in {'0'..'9'}:
  413. orig = string conf.projectFull
  414. else:
  415. i = parseQuoted(cmd, orig, i)
  416. if i < cmd.len and cmd[i] == ';':
  417. i = parseQuoted(cmd, dirtyfile, i+1)
  418. i += skipWhile(cmd, seps, i)
  419. var line = 0
  420. var col = -1
  421. i += parseInt(cmd, line, i)
  422. i += skipWhile(cmd, seps, i)
  423. i += parseInt(cmd, col, i)
  424. if conf.ideCmd == ideKnown:
  425. results.send(Suggest(section: ideKnown, quality: ord(fileInfoKnown(conf, AbsoluteFile orig))))
  426. elif conf.ideCmd == ideProject:
  427. results.send(Suggest(section: ideProject, filePath: string conf.projectFull))
  428. else:
  429. if conf.ideCmd == ideChk:
  430. for cm in cachedMsgs: errorHook(conf, cm.info, cm.msg, cm.sev)
  431. execute(conf.ideCmd, AbsoluteFile orig, AbsoluteFile dirtyfile, line, col, graph)
  432. sentinel()
  433. template benchmark(benchmarkName: string, code: untyped) =
  434. block:
  435. myLog "Started [" & benchmarkName & "]..."
  436. let t0 = epochTime()
  437. code
  438. let elapsed = epochTime() - t0
  439. let elapsedStr = elapsed.formatFloat(format = ffDecimal, precision = 3)
  440. myLog "CPU Time [" & benchmarkName & "] " & elapsedStr & "s"
  441. proc recompileFullProject(graph: ModuleGraph) =
  442. benchmark "Recompilation(clean)":
  443. graph.resetForBackend()
  444. graph.resetSystemArtifacts()
  445. graph.vm = nil
  446. graph.resetAllModules()
  447. GC_fullCollect()
  448. graph.compileProject()
  449. proc mainThread(graph: ModuleGraph) =
  450. let conf = graph.config
  451. if gLogging:
  452. for it in conf.searchPaths:
  453. log(it.string)
  454. proc wrHook(line: string) {.closure.} =
  455. if gMode == mepc:
  456. if gLogging: log(line)
  457. else:
  458. writelnToChannel(line)
  459. conf.writelnHook = wrHook
  460. conf.suggestionResultHook = sugResultHook
  461. graph.doStopCompile = proc (): bool = requests.peek() > 0
  462. var idle = 0
  463. var cachedMsgs: CachedMsgs = @[]
  464. while true:
  465. let (hasData, req) = requests.tryRecv()
  466. if hasData:
  467. conf.writelnHook = wrHook
  468. conf.suggestionResultHook = sugResultHook
  469. execCmd(req, graph, cachedMsgs)
  470. idle = 0
  471. else:
  472. os.sleep 250
  473. idle += 1
  474. if idle == 20 and gRefresh and conf.suggestVersion != 3:
  475. # we use some nimsuggest activity to enable a lazy recompile:
  476. conf.ideCmd = ideChk
  477. conf.writelnHook = proc (s: string) = discard
  478. cachedMsgs.setLen 0
  479. conf.structuredErrorHook = proc (conf: ConfigRef; info: TLineInfo; msg: string; sev: Severity) =
  480. cachedMsgs.add(CachedMsg(info: info, msg: msg, sev: sev))
  481. conf.suggestionResultHook = proc (s: Suggest) = discard
  482. recompileFullProject(graph)
  483. var
  484. inputThread: Thread[ThreadParams]
  485. proc mainCommand(graph: ModuleGraph) =
  486. let conf = graph.config
  487. clearPasses(graph)
  488. registerPass graph, verbosePass
  489. registerPass graph, semPass
  490. conf.setCmd cmdIdeTools
  491. wantMainModule(conf)
  492. if not fileExists(conf.projectFull):
  493. quit "cannot find file: " & conf.projectFull.string
  494. add(conf.searchPaths, conf.libpath)
  495. conf.setErrorMaxHighMaybe # honor --errorMax even if it may not make sense here
  496. # do not print errors, but log them
  497. conf.writelnHook = proc (msg: string) = discard
  498. if graph.config.suggestVersion == 3:
  499. graph.config.structuredErrorHook = proc (conf: ConfigRef; info: TLineInfo; msg: string; sev: Severity) =
  500. let suggest = Suggest(section: ideChk, filePath: toFullPath(conf, info),
  501. line: toLinenumber(info), column: toColumn(info), doc: msg, forth: $sev)
  502. graph.suggestErrors.mgetOrPut(info.fileIndex, @[]).add suggest
  503. # compile the project before showing any input so that we already
  504. # can answer questions right away:
  505. benchmark "Initial compilation":
  506. compileProject(graph)
  507. open(requests)
  508. open(results)
  509. case gMode
  510. of mstdin: createThread(inputThread, replStdin, (gPort, gAddress))
  511. of mtcp: createThread(inputThread, replTcp, (gPort, gAddress))
  512. of mepc: createThread(inputThread, replEpc, (gPort, gAddress))
  513. of mcmdsug: createThread(inputThread, replCmdline,
  514. (gPort, "sug \"" & conf.projectFull.string & "\":" & gAddress))
  515. of mcmdcon: createThread(inputThread, replCmdline,
  516. (gPort, "con \"" & conf.projectFull.string & "\":" & gAddress))
  517. mainThread(graph)
  518. joinThread(inputThread)
  519. close(requests)
  520. close(results)
  521. proc processCmdLine*(pass: TCmdLinePass, cmd: string; conf: ConfigRef) =
  522. var p = parseopt.initOptParser(cmd)
  523. var findProject = false
  524. while true:
  525. parseopt.next(p)
  526. case p.kind
  527. of cmdEnd: break
  528. of cmdLongOption, cmdShortOption:
  529. case p.key.normalize
  530. of "help", "h":
  531. stdout.writeLine(Usage)
  532. quit()
  533. of "autobind":
  534. gMode = mtcp
  535. gAutoBind = true
  536. of "port":
  537. gPort = parseInt(p.val).Port
  538. gMode = mtcp
  539. of "address":
  540. gAddress = p.val
  541. gMode = mtcp
  542. of "stdin": gMode = mstdin
  543. of "cmdsug":
  544. gMode = mcmdsug
  545. gAddress = p.val
  546. incl(conf.globalOptions, optIdeDebug)
  547. of "cmdcon":
  548. gMode = mcmdcon
  549. gAddress = p.val
  550. incl(conf.globalOptions, optIdeDebug)
  551. of "epc":
  552. gMode = mepc
  553. conf.verbosity = 0 # Port number gotta be first.
  554. of "debug": incl(conf.globalOptions, optIdeDebug)
  555. of "v1": conf.suggestVersion = 1
  556. of "v2": conf.suggestVersion = 0
  557. of "v3": conf.suggestVersion = 3
  558. of "tester":
  559. gMode = mstdin
  560. gEmitEof = true
  561. gRefresh = false
  562. of "log": gLogging = true
  563. of "refresh":
  564. if p.val.len > 0:
  565. gRefresh = parseBool(p.val)
  566. else:
  567. gRefresh = true
  568. of "maxresults":
  569. conf.suggestMaxResults = parseInt(p.val)
  570. of "find":
  571. findProject = true
  572. else: processSwitch(pass, p, conf)
  573. of cmdArgument:
  574. let a = unixToNativePath(p.key)
  575. if dirExists(a) and not fileExists(a.addFileExt("nim")):
  576. conf.projectName = findProjectNimFile(conf, a)
  577. # don't make it worse, report the error the old way:
  578. if conf.projectName.len == 0: conf.projectName = a
  579. else:
  580. if findProject:
  581. conf.projectName = findProjectNimFile(conf, a.parentDir())
  582. if conf.projectName.len == 0:
  583. conf.projectName = a
  584. else:
  585. conf.projectName = a
  586. # if processArgument(pass, p, argsCount): break
  587. proc handleCmdLine(cache: IdentCache; conf: ConfigRef) =
  588. let self = NimProg(
  589. suggestMode: true,
  590. processCmdLine: processCmdLine
  591. )
  592. self.initDefinesProg(conf, "nimsuggest")
  593. if paramCount() == 0:
  594. stdout.writeLine(Usage)
  595. return
  596. self.processCmdLineAndProjectPath(conf)
  597. if gMode != mstdin:
  598. conf.writelnHook = proc (msg: string) = discard
  599. # Find Nim's prefix dir.
  600. let binaryPath = findExe("nim")
  601. if binaryPath == "":
  602. raise newException(IOError,
  603. "Cannot find Nim standard library: Nim compiler not in PATH")
  604. conf.prefixDir = AbsoluteDir binaryPath.splitPath().head.parentDir()
  605. if not dirExists(conf.prefixDir / RelativeDir"lib"):
  606. conf.prefixDir = AbsoluteDir""
  607. #msgs.writelnHook = proc (line: string) = log(line)
  608. myLog("START " & conf.projectFull.string)
  609. var graph = newModuleGraph(cache, conf)
  610. if self.loadConfigsAndProcessCmdLine(cache, conf, graph):
  611. mainCommand(graph)
  612. # v3 start
  613. proc recompilePartially(graph: ModuleGraph, projectFileIdx = InvalidFileIdx) =
  614. if projectFileIdx == InvalidFileIdx:
  615. myLog "Recompiling partially from root"
  616. else:
  617. myLog fmt "Recompiling partially starting from {graph.getModule(projectFileIdx)}"
  618. # inst caches are breaking incremental compilation when the cache caches stuff
  619. # from dirty buffer
  620. # TODO: investigate more efficient way to achieve the same
  621. # graph.typeInstCache.clear()
  622. # graph.procInstCache.clear()
  623. GC_fullCollect()
  624. try:
  625. benchmark "Recompilation":
  626. graph.compileProject(projectFileIdx)
  627. except Exception as e:
  628. myLog fmt "Failed to recompile partially with the following error:\n {e.msg} \n\n {e.getStackTrace()}"
  629. try:
  630. graph.recompileFullProject()
  631. except Exception as e:
  632. myLog fmt "Failed clean recompilation:\n {e.msg} \n\n {e.getStackTrace()}"
  633. func deduplicateSymInfoPair[SymInfoPair](xs: seq[SymInfoPair]): seq[SymInfoPair] =
  634. # xs contains duplicate items and we want to filter them by range because the
  635. # sym may not match. This can happen when xs contains the same definition but
  636. # with different signature becase suggestSym might be called multiple times
  637. # for the same symbol (e. g. including/excluding the pragma)
  638. result = @[]
  639. for itm in xs.reversed:
  640. var found = false
  641. for res in result:
  642. if res.info.exactEquals(itm.info):
  643. found = true
  644. break
  645. if not found:
  646. result.add(itm)
  647. result.reverse()
  648. proc findSymData(graph: ModuleGraph, file: AbsoluteFile; line, col: int):
  649. ref SymInfoPair =
  650. let
  651. fileIdx = fileInfoIdx(graph.config, file)
  652. trackPos = newLineInfo(fileIdx, line, col)
  653. for s in graph.fileSymbols(fileIdx).deduplicateSymInfoPair:
  654. if isTracked(s.info, trackPos, s.sym.name.s.len):
  655. new(result)
  656. result[] = s
  657. break
  658. proc markDirtyIfNeeded(graph: ModuleGraph, file: string, originalFileIdx: FileIndex) =
  659. let sha = $sha1.secureHashFile(file)
  660. if graph.config.m.fileInfos[originalFileIdx.int32].hash != sha or graph.config.ideCmd == ideSug:
  661. myLog fmt "{file} changed compared to last compilation"
  662. graph.markDirty originalFileIdx
  663. graph.markClientsDirty originalFileIdx
  664. else:
  665. myLog fmt "No changes in file {file} compared to last compilation"
  666. proc suggestResult(graph: ModuleGraph, sym: PSym, info: TLineInfo, defaultSection = ideNone) =
  667. let section = if defaultSection != ideNone:
  668. defaultSection
  669. elif sym.info.exactEquals(info):
  670. ideDef
  671. else:
  672. ideUse
  673. let suggest = symToSuggest(graph, sym, isLocal=false, section,
  674. info, 100, PrefixMatch.None, false, 0)
  675. suggestResult(graph.config, suggest)
  676. const
  677. # kinds for ideOutline and ideGlobalSymbols
  678. searchableSymKinds = {skField, skEnumField, skIterator, skMethod, skFunc, skProc, skConverter, skTemplate}
  679. proc symbolEqual(left, right: PSym): bool =
  680. # More relaxed symbol comparison
  681. return left.info.exactEquals(right.info) and left.name == right.name
  682. proc executeNoHooksV3(cmd: IdeCmd, file: AbsoluteFile, dirtyfile: AbsoluteFile, line, col: int;
  683. graph: ModuleGraph) =
  684. let conf = graph.config
  685. conf.writelnHook = proc (s: string) = discard
  686. conf.structuredErrorHook = proc (conf: ConfigRef; info: TLineInfo;
  687. msg: string; sev: Severity) =
  688. let suggest = Suggest(section: ideChk, filePath: toFullPath(conf, info),
  689. line: toLinenumber(info), column: toColumn(info), doc: msg, forth: $sev)
  690. graph.suggestErrors.mgetOrPut(info.fileIndex, @[]).add suggest
  691. conf.ideCmd = cmd
  692. myLog fmt "cmd: {cmd}, file: {file}[{line}:{col}], dirtyFile: {dirtyfile}"
  693. var fileIndex: FileIndex
  694. if not (cmd in {ideRecompile, ideGlobalSymbols}):
  695. if not fileInfoKnown(conf, file):
  696. myLog fmt "{file} is unknown, returning no results"
  697. return
  698. fileIndex = fileInfoIdx(conf, file)
  699. msgs.setDirtyFile(
  700. conf,
  701. fileIndex,
  702. if dirtyfile.isEmpty: AbsoluteFile"" else: dirtyfile)
  703. if not dirtyfile.isEmpty:
  704. graph.markDirtyIfNeeded(dirtyFile.string, fileInfoIdx(conf, file))
  705. # these commands require fully compiled project
  706. if cmd in {ideUse, ideDus, ideGlobalSymbols, ideChk} and graph.needsCompilation():
  707. graph.recompilePartially()
  708. # when doing incremental build for the project root we should make sure that
  709. # everything is unmarked as no longer beeing dirty in case there is no
  710. # longer reference to a particular module. E. g. A depends on B, B is marked
  711. # as dirty and A loses B import.
  712. graph.unmarkAllDirty()
  713. # these commands require partially compiled project
  714. elif cmd in {ideSug, ideOutline, ideHighlight, ideDef, ideChkFile, ideType, ideDeclaration} and
  715. (graph.needsCompilation(fileIndex) or cmd == ideSug):
  716. # for ideSug use v2 implementation
  717. if cmd == ideSug:
  718. conf.m.trackPos = newLineInfo(fileIndex, line, col)
  719. conf.m.trackPosAttached = false
  720. else:
  721. conf.m.trackPos = default(TLineInfo)
  722. graph.recompilePartially(fileIndex)
  723. case cmd
  724. of ideDef:
  725. let s = graph.findSymData(file, line, col)
  726. if not s.isNil:
  727. graph.suggestResult(s.sym, s.sym.info)
  728. of ideType:
  729. let s = graph.findSymData(file, line, col)
  730. if not s.isNil:
  731. let typeSym = s.sym.typ.sym
  732. if typeSym != nil:
  733. graph.suggestResult(typeSym, typeSym.info, ideType)
  734. elif s.sym.typ.len != 0:
  735. let genericType = s.sym.typ[0].sym
  736. graph.suggestResult(genericType, genericType.info, ideType)
  737. of ideUse, ideDus:
  738. let symbol = graph.findSymData(file, line, col)
  739. if not symbol.isNil:
  740. var res: seq[SymInfoPair] = @[]
  741. for s in graph.suggestSymbolsIter:
  742. if s.sym.symbolEqual(symbol.sym):
  743. res.add(s)
  744. for s in res.deduplicateSymInfoPair():
  745. graph.suggestResult(s.sym, s.info)
  746. of ideHighlight:
  747. let sym = graph.findSymData(file, line, col)
  748. if not sym.isNil:
  749. let usages = graph.fileSymbols(fileIndex).filterIt(it.sym == sym.sym)
  750. myLog fmt "Found {usages.len} usages in {file.string}"
  751. for s in usages:
  752. graph.suggestResult(s.sym, s.info)
  753. of ideRecompile:
  754. graph.recompileFullProject()
  755. of ideChanged:
  756. graph.markDirtyIfNeeded(file.string, fileIndex)
  757. of ideSug:
  758. # ideSug performs partial build of the file, thus mark it dirty for the
  759. # future calls.
  760. graph.markDirtyIfNeeded(file.string, fileIndex)
  761. of ideOutline:
  762. let
  763. module = graph.getModule fileIndex
  764. symbols = graph.fileSymbols(fileIndex)
  765. .deduplicateSymInfoPair
  766. .filterIt(it.sym.info.exactEquals(it.info) and
  767. (it.sym.owner == module or
  768. it.sym.kind in searchableSymKinds))
  769. for s in symbols:
  770. graph.suggestResult(s.sym, s.info, ideOutline)
  771. of ideChk:
  772. myLog fmt "Reporting errors for {graph.suggestErrors.len} file(s)"
  773. for sug in graph.suggestErrorsIter:
  774. suggestResult(graph.config, sug)
  775. of ideChkFile:
  776. let errors = graph.suggestErrors.getOrDefault(fileIndex, @[])
  777. myLog fmt "Reporting {errors.len} error(s) for {file.string}"
  778. for error in errors:
  779. suggestResult(graph.config, error)
  780. of ideGlobalSymbols:
  781. var
  782. counter = 0
  783. res: seq[SymInfoPair] = @[]
  784. for s in graph.suggestSymbolsIter:
  785. if (sfGlobal in s.sym.flags or s.sym.kind in searchableSymKinds) and
  786. s.sym.info == s.info:
  787. if contains(s.sym.name.s, file.string):
  788. inc counter
  789. res = res.filterIt(not it.info.exactEquals(s.info))
  790. res.add s
  791. # stop after first 1000 matches...
  792. if counter > 1000:
  793. break
  794. # ... then sort them by weight ...
  795. res.sort() do (left, right: SymInfoPair) -> int:
  796. let
  797. leftString = left.sym.name.s
  798. rightString = right.sym.name.s
  799. leftIndex = leftString.find(file.string)
  800. rightIndex = rightString.find(file.string)
  801. if leftIndex == rightIndex:
  802. result = cmp(toLowerAscii(leftString),
  803. toLowerAscii(rightString))
  804. else:
  805. result = cmp(leftIndex, rightIndex)
  806. # ... and send first 100 results
  807. if res.len > 0:
  808. for i in 0 .. min(100, res.len - 1):
  809. let s = res[i]
  810. graph.suggestResult(s.sym, s.info)
  811. of ideDeclaration:
  812. let s = graph.findSymData(file, line, col)
  813. if not s.isNil:
  814. # find first mention of the symbol in the file containing the definition.
  815. # It is either the definition or the declaration.
  816. var first: SymInfoPair
  817. for symbol in graph.fileSymbols(s.sym.info.fileIndex).deduplicateSymInfoPair:
  818. if s.sym.symbolEqual(symbol.sym):
  819. first = symbol
  820. break
  821. if s.info.exactEquals(first.info):
  822. # we are on declaration, go to definition
  823. graph.suggestResult(first.sym, first.sym.info, ideDeclaration)
  824. else:
  825. # we are on definition or usage, look for declaration
  826. graph.suggestResult(first.sym, first.info, ideDeclaration)
  827. else:
  828. myLog fmt "Discarding {cmd}"
  829. # v3 end
  830. when isMainModule:
  831. handleCmdLine(newIdentCache(), newConfigRef())
  832. else:
  833. export Suggest
  834. export IdeCmd
  835. export AbsoluteFile
  836. type NimSuggest* = ref object
  837. graph: ModuleGraph
  838. idle: int
  839. cachedMsgs: CachedMsgs
  840. proc initNimSuggest*(project: string, nimPath: string = ""): NimSuggest =
  841. var retval: ModuleGraph
  842. proc mockCommand(graph: ModuleGraph) =
  843. retval = graph
  844. let conf = graph.config
  845. clearPasses(graph)
  846. registerPass graph, verbosePass
  847. registerPass graph, semPass
  848. conf.setCmd cmdIdeTools
  849. wantMainModule(conf)
  850. if not fileExists(conf.projectFull):
  851. quit "cannot find file: " & conf.projectFull.string
  852. add(conf.searchPaths, conf.libpath)
  853. conf.setErrorMaxHighMaybe
  854. # do not print errors, but log them
  855. conf.writelnHook = myLog
  856. conf.structuredErrorHook = nil
  857. # compile the project before showing any input so that we already
  858. # can answer questions right away:
  859. compileProject(graph)
  860. proc mockCmdLine(pass: TCmdLinePass, cmd: string; conf: ConfigRef) =
  861. conf.suggestVersion = 0
  862. let a = unixToNativePath(project)
  863. if dirExists(a) and not fileExists(a.addFileExt("nim")):
  864. conf.projectName = findProjectNimFile(conf, a)
  865. # don't make it worse, report the error the old way:
  866. if conf.projectName.len == 0: conf.projectName = a
  867. else:
  868. conf.projectName = a
  869. # if processArgument(pass, p, argsCount): break
  870. let
  871. cache = newIdentCache()
  872. conf = newConfigRef()
  873. self = NimProg(
  874. suggestMode: true,
  875. processCmdLine: mockCmdLine
  876. )
  877. self.initDefinesProg(conf, "nimsuggest")
  878. self.processCmdLineAndProjectPath(conf)
  879. if gMode != mstdin:
  880. conf.writelnHook = proc (msg: string) = discard
  881. # Find Nim's prefix dir.
  882. if nimPath == "":
  883. let binaryPath = findExe("nim")
  884. if binaryPath == "":
  885. raise newException(IOError,
  886. "Cannot find Nim standard library: Nim compiler not in PATH")
  887. conf.prefixDir = AbsoluteDir binaryPath.splitPath().head.parentDir()
  888. if not dirExists(conf.prefixDir / RelativeDir"lib"):
  889. conf.prefixDir = AbsoluteDir""
  890. else:
  891. conf.prefixDir = AbsoluteDir nimPath
  892. #msgs.writelnHook = proc (line: string) = log(line)
  893. myLog("START " & conf.projectFull.string)
  894. var graph = newModuleGraph(cache, conf)
  895. if self.loadConfigsAndProcessCmdLine(cache, conf, graph):
  896. mockCommand(graph)
  897. if gLogging:
  898. log("Search paths:")
  899. for it in conf.searchPaths:
  900. log(" " & it.string)
  901. retval.doStopCompile = proc (): bool = false
  902. return NimSuggest(graph: retval, idle: 0, cachedMsgs: @[])
  903. proc runCmd*(nimsuggest: NimSuggest, cmd: IdeCmd, file, dirtyfile: AbsoluteFile, line, col: int): seq[Suggest] =
  904. var retval: seq[Suggest] = @[]
  905. let conf = nimsuggest.graph.config
  906. conf.ideCmd = cmd
  907. conf.writelnHook = proc (line: string) =
  908. retval.add(Suggest(section: ideMsg, doc: line))
  909. conf.suggestionResultHook = proc (s: Suggest) =
  910. retval.add(s)
  911. conf.writelnHook = proc (s: string) =
  912. stderr.write s & "\n"
  913. if conf.ideCmd == ideKnown:
  914. retval.add(Suggest(section: ideKnown, quality: ord(fileInfoKnown(conf, file))))
  915. elif conf.ideCmd == ideProject:
  916. retval.add(Suggest(section: ideProject, filePath: string conf.projectFull))
  917. else:
  918. if conf.ideCmd == ideChk:
  919. for cm in nimsuggest.cachedMsgs: errorHook(conf, cm.info, cm.msg, cm.sev)
  920. if conf.ideCmd == ideChk:
  921. conf.structuredErrorHook = proc (conf: ConfigRef; info: TLineInfo; msg: string; sev: Severity) =
  922. retval.add(Suggest(section: ideChk, filePath: toFullPath(conf, info),
  923. line: toLinenumber(info), column: toColumn(info), doc: msg,
  924. forth: $sev))
  925. else:
  926. conf.structuredErrorHook = nil
  927. executeNoHooks(conf.ideCmd, file, dirtyfile, line, col, nimsuggest.graph)
  928. return retval