nimsuggest.nim 42 KB

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