nimsuggest.nim 34 KB

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