suggest.nim 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This file implements features required for IDE support.
  10. ##
  11. ## Due to Nim's nature and the fact that ``system.nim`` is always imported,
  12. ## there are lots of potential symbols. Furthermore thanks to templates and
  13. ## macros even context based analysis does not help much: In a context like
  14. ## ``let x: |`` where a type has to follow, that type might be constructed from
  15. ## a template like ``extractField(MyObject, fieldName)``. We deal with this
  16. ## problem by smart sorting so that the likely symbols come first. This sorting
  17. ## is done this way:
  18. ##
  19. ## - If there is a prefix (foo|), symbols starting with this prefix come first.
  20. ## - If the prefix is part of the name (but the name doesn't start with it),
  21. ## these symbols come second.
  22. ## - If we have a prefix, only symbols matching this prefix are returned and
  23. ## nothing else.
  24. ## - If we have no prefix, consider the context. We currently distinguish
  25. ## between type and non-type contexts.
  26. ## - Finally, sort matches by relevance. The relevance is determined by the
  27. ## number of usages, so ``strutils.replace`` comes before
  28. ## ``strutils.wordWrap``.
  29. ## - In any case, sorting also considers scoping information. Local variables
  30. ## get high priority.
  31. # included from sigmatch.nim
  32. import algorithm, sets, prefixmatches, parseutils, tables
  33. from wordrecg import wDeprecated, wError, wAddr, wYield
  34. when defined(nimsuggest):
  35. import passes, tables, pathutils # importer
  36. const
  37. sep = '\t'
  38. #template sectionSuggest(): expr = "##begin\n" & getStackTrace() & "##end\n"
  39. template origModuleName(m: PSym): string = m.name.s
  40. proc findDocComment(n: PNode): PNode =
  41. if n == nil: return nil
  42. if n.comment.len > 0: return n
  43. if n.kind in {nkStmtList, nkStmtListExpr, nkObjectTy, nkRecList} and n.len > 0:
  44. result = findDocComment(n[0])
  45. if result != nil: return
  46. if n.len > 1:
  47. result = findDocComment(n[1])
  48. elif n.kind in {nkAsgn, nkFastAsgn} and n.len == 2:
  49. result = findDocComment(n[1])
  50. proc extractDocComment(g: ModuleGraph; s: PSym): string =
  51. var n = findDocComment(s.ast)
  52. if n.isNil and s.kind in routineKinds and s.ast != nil:
  53. n = findDocComment(getBody(g, s))
  54. if not n.isNil:
  55. result = n.comment.replace("\n##", "\n").strip
  56. else:
  57. result = ""
  58. proc cmpSuggestions(a, b: Suggest): int =
  59. template cf(field) {.dirty.} =
  60. result = b.field.int - a.field.int
  61. if result != 0: return result
  62. cf prefix
  63. cf contextFits
  64. cf scope
  65. # when the first type matches, it's better when it's a generic match:
  66. cf quality
  67. cf localUsages
  68. cf globalUsages
  69. # if all is equal, sort alphabetically for deterministic output,
  70. # independent of hashing order:
  71. result = cmp(a.name[], b.name[])
  72. proc scanForTrailingAsterisk(line: string, start: int): int =
  73. result = 0
  74. while start+result < line.len and line[start+result] in {' ', '\t'}:
  75. inc result
  76. if start+result < line.len and line[start+result] == '*':
  77. inc result
  78. else:
  79. result = 0
  80. proc getTokenLenFromSource(conf: ConfigRef; ident: string; info: TLineInfo; skipTrailingAsterisk: bool = false): int =
  81. let
  82. line = sourceLine(conf, info)
  83. column = toColumn(info)
  84. proc isOpeningBacktick(col: int): bool =
  85. if col >= 0 and col < line.len:
  86. if line[col] == '`':
  87. not isOpeningBacktick(col - 1)
  88. else:
  89. isOpeningBacktick(col - 1)
  90. else:
  91. false
  92. if column > line.len:
  93. result = 0
  94. elif column > 0 and line[column - 1] == '`' and isOpeningBacktick(column - 1):
  95. result = skipUntil(line, '`', column)
  96. if cmpIgnoreStyle(line[column..column + result - 1], ident) != 0:
  97. result = 0
  98. elif ident[0] in linter.Letters and ident[^1] != '=':
  99. result = identLen(line, column)
  100. if cmpIgnoreStyle(line[column..column + result - 1], ident[0..min(result-1,len(ident)-1)]) != 0:
  101. result = 0
  102. if skipTrailingAsterisk and result > 0:
  103. result += scanForTrailingAsterisk(line, column + result)
  104. else:
  105. var sourceIdent: string
  106. result = parseWhile(line, sourceIdent,
  107. OpChars + {'[', '(', '{', ']', ')', '}'}, column)
  108. if ident[^1] == '=' and ident[0] in linter.Letters:
  109. if sourceIdent != "=":
  110. result = 0
  111. elif sourceIdent.len > ident.len and sourceIdent[0..ident.high] == ident:
  112. result = ident.len
  113. elif sourceIdent != ident:
  114. result = 0
  115. proc symToSuggest*(g: ModuleGraph; s: PSym, isLocal: bool, section: IdeCmd, info: TLineInfo;
  116. quality: range[0..100]; prefix: PrefixMatch;
  117. inTypeContext: bool; scope: int;
  118. useSuppliedInfo = false,
  119. endLine: uint16 = 0,
  120. endCol = 0): Suggest =
  121. new(result)
  122. result.section = section
  123. result.quality = quality
  124. result.isGlobal = sfGlobal in s.flags
  125. result.prefix = prefix
  126. result.contextFits = inTypeContext == (s.kind in {skType, skGenericParam})
  127. result.scope = scope
  128. result.name = addr s.name.s
  129. when defined(nimsuggest):
  130. result.globalUsages = s.allUsages.len
  131. var c = 0
  132. for u in s.allUsages:
  133. if u.fileIndex == info.fileIndex: inc c
  134. result.localUsages = c
  135. result.symkind = byte s.kind
  136. if optIdeTerse notin g.config.globalOptions:
  137. result.qualifiedPath = @[]
  138. if not isLocal and s.kind != skModule:
  139. let ow = s.owner
  140. if ow != nil and ow.kind != skModule and ow.owner != nil:
  141. let ow2 = ow.owner
  142. result.qualifiedPath.add(ow2.origModuleName)
  143. if ow != nil:
  144. result.qualifiedPath.add(ow.origModuleName)
  145. if s.name.s[0] in OpChars + {'[', '{', '('} or
  146. s.name.id in ord(wAddr)..ord(wYield):
  147. result.qualifiedPath.add('`' & s.name.s & '`')
  148. else:
  149. result.qualifiedPath.add(s.name.s)
  150. if s.typ != nil:
  151. if section == ideInlayHints:
  152. result.forth = typeToString(s.typ, preferInlayHint)
  153. else:
  154. result.forth = typeToString(s.typ, preferInferredEffects)
  155. else:
  156. result.forth = ""
  157. when defined(nimsuggest) and not defined(noDocgen) and not defined(leanCompiler):
  158. result.doc = extractDocComment(g, s)
  159. if s.kind == skModule and s.ast.len != 0 and section != ideHighlight:
  160. result.filePath = toFullPath(g.config, s.ast[0].info)
  161. result.line = 1
  162. result.column = 0
  163. result.tokenLen = 0
  164. else:
  165. let infox =
  166. if useSuppliedInfo or section in {ideUse, ideHighlight, ideOutline, ideDeclaration}:
  167. info
  168. else:
  169. s.info
  170. result.filePath = toFullPath(g.config, infox)
  171. result.line = toLinenumber(infox)
  172. result.column = toColumn(infox)
  173. result.tokenLen = if section notin {ideHighlight, ideInlayHints}:
  174. s.name.s.len
  175. else:
  176. getTokenLenFromSource(g.config, s.name.s, infox, section == ideInlayHints)
  177. result.version = g.config.suggestVersion
  178. result.endLine = endLine
  179. result.endCol = endCol
  180. proc `$`*(suggest: SuggestInlayHint): string =
  181. result = $suggest.kind
  182. result.add(sep)
  183. result.add($suggest.line)
  184. result.add(sep)
  185. result.add($suggest.column)
  186. result.add(sep)
  187. result.add(suggest.label)
  188. result.add(sep)
  189. result.add($suggest.paddingLeft)
  190. result.add(sep)
  191. result.add($suggest.paddingRight)
  192. result.add(sep)
  193. result.add($suggest.allowInsert)
  194. result.add(sep)
  195. result.add(suggest.tooltip)
  196. proc `$`*(suggest: Suggest): string =
  197. if suggest.section == ideInlayHints:
  198. result = $suggest.inlayHintInfo
  199. else:
  200. result = $suggest.section
  201. result.add(sep)
  202. if suggest.section == ideHighlight:
  203. if suggest.symkind.TSymKind == skVar and suggest.isGlobal:
  204. result.add("skGlobalVar")
  205. elif suggest.symkind.TSymKind == skLet and suggest.isGlobal:
  206. result.add("skGlobalLet")
  207. else:
  208. result.add($suggest.symkind.TSymKind)
  209. result.add(sep)
  210. result.add($suggest.line)
  211. result.add(sep)
  212. result.add($suggest.column)
  213. result.add(sep)
  214. result.add($suggest.tokenLen)
  215. else:
  216. result.add($suggest.symkind.TSymKind)
  217. result.add(sep)
  218. if suggest.qualifiedPath.len != 0:
  219. result.add(suggest.qualifiedPath.join("."))
  220. result.add(sep)
  221. result.add(suggest.forth)
  222. result.add(sep)
  223. result.add(suggest.filePath)
  224. result.add(sep)
  225. result.add($suggest.line)
  226. result.add(sep)
  227. result.add($suggest.column)
  228. result.add(sep)
  229. when defined(nimsuggest) and not defined(noDocgen) and not defined(leanCompiler):
  230. result.add(suggest.doc.escape)
  231. if suggest.version in {0, 3}:
  232. result.add(sep)
  233. result.add($suggest.quality)
  234. if suggest.section == ideSug:
  235. result.add(sep)
  236. result.add($suggest.prefix)
  237. if (suggest.version == 3 and suggest.section in {ideOutline, ideExpand}):
  238. result.add(sep)
  239. result.add($suggest.endLine)
  240. result.add(sep)
  241. result.add($suggest.endCol)
  242. proc suggestToSuggestInlayHint*(sug: Suggest): SuggestInlayHint =
  243. SuggestInlayHint(
  244. kind: sihkType,
  245. line: sug.line,
  246. column: sug.column + sug.tokenLen,
  247. label: ": " & sug.forth,
  248. paddingLeft: false,
  249. paddingRight: false,
  250. allowInsert: true,
  251. tooltip: ""
  252. )
  253. proc suggestResult*(conf: ConfigRef; s: Suggest) =
  254. if not isNil(conf.suggestionResultHook):
  255. conf.suggestionResultHook(s)
  256. else:
  257. conf.suggestWriteln($s)
  258. proc produceOutput(a: var Suggestions; conf: ConfigRef) =
  259. if conf.ideCmd in {ideSug, ideCon}:
  260. a.sort cmpSuggestions
  261. when defined(debug):
  262. # debug code
  263. writeStackTrace()
  264. if a.len > conf.suggestMaxResults: a.setLen(conf.suggestMaxResults)
  265. if not isNil(conf.suggestionResultHook):
  266. for s in a:
  267. conf.suggestionResultHook(s)
  268. else:
  269. for s in a:
  270. conf.suggestWriteln($s)
  271. proc filterSym(s: PSym; prefix: PNode; res: var PrefixMatch): bool {.inline.} =
  272. proc prefixMatch(s: PSym; n: PNode): PrefixMatch =
  273. case n.kind
  274. of nkIdent: result = n.ident.s.prefixMatch(s.name.s)
  275. of nkSym: result = n.sym.name.s.prefixMatch(s.name.s)
  276. of nkOpenSymChoice, nkClosedSymChoice, nkAccQuoted:
  277. if n.len > 0:
  278. result = prefixMatch(s, n[0])
  279. else: discard
  280. if s.kind != skModule:
  281. if prefix != nil:
  282. res = prefixMatch(s, prefix)
  283. result = res != PrefixMatch.None
  284. else:
  285. result = true
  286. proc filterSymNoOpr(s: PSym; prefix: PNode; res: var PrefixMatch): bool {.inline.} =
  287. result = filterSym(s, prefix, res) and s.name.s[0] in lexer.SymChars and
  288. not isKeyword(s.name)
  289. proc fieldVisible*(c: PContext, f: PSym): bool {.inline.} =
  290. let fmoduleId = getModule(f).id
  291. result = sfExported in f.flags or fmoduleId == c.module.id
  292. if not result:
  293. for module in c.friendModules:
  294. if fmoduleId == module.id: return true
  295. if f.kind == skField:
  296. var symObj = f.owner
  297. if symObj.typ.kind in {tyRef, tyPtr}:
  298. symObj = symObj.typ[0].sym
  299. for scope in allScopes(c.currentScope):
  300. for sym in scope.allowPrivateAccess:
  301. if symObj.id == sym.id: return true
  302. proc getQuality(s: PSym): range[0..100] =
  303. result = 100
  304. if s.typ != nil and s.typ.len > 1:
  305. var exp = s.typ[1].skipTypes({tyGenericInst, tyVar, tyLent, tyAlias, tySink})
  306. if exp.kind == tyVarargs: exp = elemType(exp)
  307. if exp.kind in {tyUntyped, tyTyped, tyGenericParam, tyAnything}: result = 50
  308. # penalize deprecated symbols
  309. if sfDeprecated in s.flags:
  310. result = result - 5
  311. proc suggestField(c: PContext, s: PSym; f: PNode; info: TLineInfo; outputs: var Suggestions) =
  312. var pm: PrefixMatch
  313. if filterSym(s, f, pm) and fieldVisible(c, s):
  314. outputs.add(symToSuggest(c.graph, s, isLocal=true, ideSug, info,
  315. s.getQuality, pm, c.inTypeContext > 0, 0))
  316. template wholeSymTab(cond, section: untyped) {.dirty.} =
  317. for (item, scopeN, isLocal) in allSyms(c):
  318. let it = item
  319. var pm: PrefixMatch
  320. if cond:
  321. outputs.add(symToSuggest(c.graph, it, isLocal = isLocal, section, info, getQuality(it),
  322. pm, c.inTypeContext > 0, scopeN))
  323. proc suggestSymList(c: PContext, list, f: PNode; info: TLineInfo, outputs: var Suggestions) =
  324. for i in 0..<list.len:
  325. if list[i].kind == nkSym:
  326. suggestField(c, list[i].sym, f, info, outputs)
  327. #else: InternalError(list.info, "getSymFromList")
  328. proc suggestObject(c: PContext, n, f: PNode; info: TLineInfo, outputs: var Suggestions) =
  329. case n.kind
  330. of nkRecList:
  331. for i in 0..<n.len: suggestObject(c, n[i], f, info, outputs)
  332. of nkRecCase:
  333. if n.len > 0:
  334. suggestObject(c, n[0], f, info, outputs)
  335. for i in 1..<n.len: suggestObject(c, lastSon(n[i]), f, info, outputs)
  336. of nkSym: suggestField(c, n.sym, f, info, outputs)
  337. else: discard
  338. proc nameFits(c: PContext, s: PSym, n: PNode): bool =
  339. var op = if n.kind in nkCallKinds: n[0] else: n
  340. if op.kind in {nkOpenSymChoice, nkClosedSymChoice}: op = op[0]
  341. if op.kind == nkDotExpr: op = op[1]
  342. var opr: PIdent
  343. case op.kind
  344. of nkSym: opr = op.sym.name
  345. of nkIdent: opr = op.ident
  346. else: return false
  347. result = opr.id == s.name.id
  348. proc argsFit(c: PContext, candidate: PSym, n, nOrig: PNode): bool =
  349. case candidate.kind
  350. of OverloadableSyms:
  351. var m = newCandidate(c, candidate, nil)
  352. sigmatch.partialMatch(c, n, nOrig, m)
  353. result = m.state != csNoMatch
  354. else:
  355. result = false
  356. proc suggestCall(c: PContext, n, nOrig: PNode, outputs: var Suggestions) =
  357. let info = n.info
  358. wholeSymTab(filterSym(it, nil, pm) and nameFits(c, it, n) and argsFit(c, it, n, nOrig),
  359. ideCon)
  360. proc suggestVar(c: PContext, n: PNode, outputs: var Suggestions) =
  361. let info = n.info
  362. wholeSymTab(nameFits(c, it, n), ideCon)
  363. proc typeFits(c: PContext, s: PSym, firstArg: PType): bool {.inline.} =
  364. if s.typ != nil and s.typ.len > 1 and s.typ[1] != nil:
  365. # special rule: if system and some weird generic match via 'tyUntyped'
  366. # or 'tyGenericParam' we won't list it either to reduce the noise (nobody
  367. # wants 'system.`-|` as suggestion
  368. let m = s.getModule()
  369. if m != nil and sfSystemModule in m.flags:
  370. if s.kind == skType: return
  371. var exp = s.typ[1].skipTypes({tyGenericInst, tyVar, tyLent, tyAlias, tySink})
  372. if exp.kind == tyVarargs: exp = elemType(exp)
  373. if exp.kind in {tyUntyped, tyTyped, tyGenericParam, tyAnything}: return
  374. result = sigmatch.argtypeMatches(c, s.typ[1], firstArg)
  375. proc suggestOperations(c: PContext, n, f: PNode, typ: PType, outputs: var Suggestions) =
  376. assert typ != nil
  377. let info = n.info
  378. wholeSymTab(filterSymNoOpr(it, f, pm) and typeFits(c, it, typ), ideSug)
  379. proc suggestEverything(c: PContext, n, f: PNode, outputs: var Suggestions) =
  380. # do not produce too many symbols:
  381. for (it, scopeN, isLocal) in allSyms(c):
  382. var pm: PrefixMatch
  383. if filterSym(it, f, pm):
  384. outputs.add(symToSuggest(c.graph, it, isLocal = isLocal, ideSug, n.info,
  385. it.getQuality, pm, c.inTypeContext > 0, scopeN))
  386. proc suggestFieldAccess(c: PContext, n, field: PNode, outputs: var Suggestions) =
  387. # special code that deals with ``myObj.``. `n` is NOT the nkDotExpr-node, but
  388. # ``myObj``.
  389. var typ = n.typ
  390. var pm: PrefixMatch
  391. when defined(nimsuggest):
  392. if n.kind == nkSym and n.sym.kind == skError and c.config.suggestVersion == 0:
  393. # consider 'foo.|' where 'foo' is some not imported module.
  394. let fullPath = findModule(c.config, n.sym.name.s, toFullPath(c.config, n.info))
  395. if fullPath.isEmpty:
  396. # error: no known module name:
  397. typ = nil
  398. else:
  399. let m = c.graph.importModuleCallback(c.graph, c.module, fileInfoIdx(c.config, fullPath))
  400. if m == nil: typ = nil
  401. else:
  402. for it in allSyms(c.graph, n.sym):
  403. if filterSym(it, field, pm):
  404. outputs.add(symToSuggest(c.graph, it, isLocal=false, ideSug,
  405. n.info, it.getQuality, pm,
  406. c.inTypeContext > 0, -100))
  407. outputs.add(symToSuggest(c.graph, m, isLocal=false, ideMod, n.info,
  408. 100, PrefixMatch.None, c.inTypeContext > 0,
  409. -99))
  410. if typ == nil:
  411. # a module symbol has no type for example:
  412. if n.kind == nkSym and n.sym.kind == skModule:
  413. if n.sym == c.module:
  414. # all symbols accessible, because we are in the current module:
  415. for it in items(c.topLevelScope.symbols):
  416. if filterSym(it, field, pm):
  417. outputs.add(symToSuggest(c.graph, it, isLocal=false, ideSug,
  418. n.info, it.getQuality, pm,
  419. c.inTypeContext > 0, -99))
  420. else:
  421. for it in allSyms(c.graph, n.sym):
  422. if filterSym(it, field, pm):
  423. outputs.add(symToSuggest(c.graph, it, isLocal=false, ideSug,
  424. n.info, it.getQuality, pm,
  425. c.inTypeContext > 0, -99))
  426. else:
  427. # fallback:
  428. suggestEverything(c, n, field, outputs)
  429. else:
  430. let orig = typ
  431. typ = skipTypes(orig, {tyTypeDesc, tyGenericInst, tyVar, tyLent, tyPtr, tyRef, tyAlias, tySink, tyOwned})
  432. if typ.kind == tyEnum and n.kind == nkSym and n.sym.kind == skType:
  433. # look up if the identifier belongs to the enum:
  434. var t = typ
  435. while t != nil:
  436. suggestSymList(c, t.n, field, n.info, outputs)
  437. t = t[0]
  438. elif typ.kind == tyObject:
  439. var t = typ
  440. while true:
  441. suggestObject(c, t.n, field, n.info, outputs)
  442. if t[0] == nil: break
  443. t = skipTypes(t[0], skipPtrs)
  444. elif typ.kind == tyTuple and typ.n != nil:
  445. # All tuple fields are in scope
  446. # So go through each field and add it to the suggestions (If it passes the filter)
  447. for node in typ.n:
  448. if node.kind == nkSym:
  449. let s = node.sym
  450. var pm: PrefixMatch
  451. if filterSym(s, field, pm):
  452. outputs.add(symToSuggest(c.graph, s, isLocal=true, ideSug, n.info,
  453. s.getQuality, pm, c.inTypeContext > 0, 0))
  454. suggestOperations(c, n, field, orig, outputs)
  455. if typ != orig:
  456. suggestOperations(c, n, field, typ, outputs)
  457. type
  458. TCheckPointResult* = enum
  459. cpNone, cpFuzzy, cpExact
  460. proc inCheckpoint*(current, trackPos: TLineInfo): TCheckPointResult =
  461. if current.fileIndex == trackPos.fileIndex:
  462. if current.line == trackPos.line and
  463. abs(current.col-trackPos.col) < 4:
  464. return cpExact
  465. if current.line >= trackPos.line:
  466. return cpFuzzy
  467. proc isTracked*(current, trackPos: TLineInfo, tokenLen: int): bool =
  468. if current.fileIndex==trackPos.fileIndex and current.line==trackPos.line:
  469. let col = trackPos.col
  470. if col >= current.col and col <= current.col+tokenLen-1:
  471. return true
  472. when defined(nimsuggest):
  473. # Since TLineInfo defined a == operator that doesn't include the column,
  474. # we map TLineInfo to a unique int here for this lookup table:
  475. proc infoToInt(info: TLineInfo): int64 =
  476. info.fileIndex.int64 + info.line.int64 shl 32 + info.col.int64 shl 48
  477. proc addNoDup(s: PSym; info: TLineInfo) =
  478. # ensure nothing gets too slow:
  479. if s.allUsages.len > 500: return
  480. let infoAsInt = info.infoToInt
  481. for infoB in s.allUsages:
  482. if infoB.infoToInt == infoAsInt: return
  483. s.allUsages.add(info)
  484. proc findUsages(g: ModuleGraph; info: TLineInfo; s: PSym; usageSym: var PSym) =
  485. if g.config.suggestVersion == 1:
  486. if usageSym == nil and isTracked(info, g.config.m.trackPos, s.name.s.len):
  487. usageSym = s
  488. suggestResult(g.config, symToSuggest(g, s, isLocal=false, ideUse, info, 100, PrefixMatch.None, false, 0))
  489. elif s == usageSym:
  490. if g.config.lastLineInfo != info:
  491. suggestResult(g.config, symToSuggest(g, s, isLocal=false, ideUse, info, 100, PrefixMatch.None, false, 0))
  492. g.config.lastLineInfo = info
  493. when defined(nimsuggest):
  494. proc listUsages*(g: ModuleGraph; s: PSym) =
  495. #echo "usages ", s.allUsages.len
  496. for info in s.allUsages:
  497. let x = if info == s.info and info.col == s.info.col: ideDef else: ideUse
  498. suggestResult(g.config, symToSuggest(g, s, isLocal=false, x, info, 100, PrefixMatch.None, false, 0))
  499. proc findDefinition(g: ModuleGraph; info: TLineInfo; s: PSym; usageSym: var PSym) =
  500. if s.isNil: return
  501. if isTracked(info, g.config.m.trackPos, s.name.s.len) or (s == usageSym and sfForward notin s.flags):
  502. suggestResult(g.config, symToSuggest(g, s, isLocal=false, ideDef, info, 100, PrefixMatch.None, false, 0, useSuppliedInfo = s == usageSym))
  503. if sfForward notin s.flags and g.config.suggestVersion < 3:
  504. suggestQuit()
  505. else:
  506. usageSym = s
  507. proc ensureIdx[T](x: var T, y: int) =
  508. if x.len <= y: x.setLen(y+1)
  509. proc ensureSeq[T](x: var seq[T]) =
  510. if x == nil: newSeq(x, 0)
  511. proc suggestSym*(g: ModuleGraph; info: TLineInfo; s: PSym; usageSym: var PSym; isDecl=true) {.inline.} =
  512. ## misnamed: should be 'symDeclared'
  513. let conf = g.config
  514. when defined(nimsuggest):
  515. g.suggestSymbols.mgetOrPut(info.fileIndex, @[]).add SymInfoPair(sym: s, info: info, isDecl: isDecl)
  516. if conf.suggestVersion == 0:
  517. if s.allUsages.len == 0:
  518. s.allUsages = @[info]
  519. else:
  520. s.addNoDup(info)
  521. if conf.ideCmd == ideUse:
  522. findUsages(g, info, s, usageSym)
  523. elif conf.ideCmd == ideDef:
  524. findDefinition(g, info, s, usageSym)
  525. elif conf.ideCmd == ideDus and s != nil:
  526. if isTracked(info, conf.m.trackPos, s.name.s.len):
  527. suggestResult(conf, symToSuggest(g, s, isLocal=false, ideDef, info, 100, PrefixMatch.None, false, 0))
  528. findUsages(g, info, s, usageSym)
  529. elif conf.ideCmd == ideHighlight and info.fileIndex == conf.m.trackPos.fileIndex:
  530. suggestResult(conf, symToSuggest(g, s, isLocal=false, ideHighlight, info, 100, PrefixMatch.None, false, 0))
  531. elif conf.ideCmd == ideOutline and isDecl:
  532. # if a module is included then the info we have is inside the include and
  533. # we need to walk up the owners until we find the outer most module,
  534. # which will be the last skModule prior to an skPackage.
  535. var
  536. parentFileIndex = info.fileIndex # assume we're in the correct module
  537. parentModule = s.owner
  538. while parentModule != nil and parentModule.kind == skModule:
  539. parentFileIndex = parentModule.info.fileIndex
  540. parentModule = parentModule.owner
  541. if parentFileIndex == conf.m.trackPos.fileIndex:
  542. suggestResult(conf, symToSuggest(g, s, isLocal=false, ideOutline, info, 100, PrefixMatch.None, false, 0))
  543. proc extractPragma(s: PSym): PNode =
  544. if s.kind in routineKinds:
  545. result = s.ast[pragmasPos]
  546. elif s.kind in {skType, skVar, skLet}:
  547. if s.ast != nil and s.ast.len > 0:
  548. if s.ast[0].kind == nkPragmaExpr and s.ast[0].len > 1:
  549. # s.ast = nkTypedef / nkPragmaExpr / [nkSym, nkPragma]
  550. result = s.ast[0][1]
  551. doAssert result == nil or result.kind == nkPragma
  552. proc warnAboutDeprecated(conf: ConfigRef; info: TLineInfo; s: PSym) =
  553. var pragmaNode: PNode
  554. pragmaNode = if s.kind == skEnumField: extractPragma(s.owner) else: extractPragma(s)
  555. let name =
  556. if s.kind == skEnumField and sfDeprecated notin s.flags: "enum '" & s.owner.name.s & "' which contains field '" & s.name.s & "'"
  557. else: s.name.s
  558. if pragmaNode != nil:
  559. for it in pragmaNode:
  560. if whichPragma(it) == wDeprecated and it.safeLen == 2 and
  561. it[1].kind in {nkStrLit..nkTripleStrLit}:
  562. message(conf, info, warnDeprecated, it[1].strVal & "; " & name & " is deprecated")
  563. return
  564. message(conf, info, warnDeprecated, name & " is deprecated")
  565. proc userError(conf: ConfigRef; info: TLineInfo; s: PSym) =
  566. let pragmaNode = extractPragma(s)
  567. template bail(prefix: string) =
  568. localError(conf, info, "$1usage of '$2' is an {.error.} defined at $3" %
  569. [prefix, s.name.s, toFileLineCol(conf, s.ast.info)])
  570. if pragmaNode != nil:
  571. for it in pragmaNode:
  572. if whichPragma(it) == wError and it.safeLen == 2 and
  573. it[1].kind in {nkStrLit..nkTripleStrLit}:
  574. bail(it[1].strVal & "; ")
  575. return
  576. bail("")
  577. proc markOwnerModuleAsUsed(c: PContext; s: PSym) =
  578. var module = s
  579. while module != nil and module.kind != skModule:
  580. module = module.owner
  581. if module != nil and module != c.module:
  582. var i = 0
  583. while i <= high(c.unusedImports):
  584. let candidate = c.unusedImports[i][0]
  585. if candidate == module or c.importModuleMap.getOrDefault(candidate.id, int.low) == module.id or
  586. c.exportIndirections.contains((candidate.id, s.id)):
  587. # mark it as used:
  588. c.unusedImports.del(i)
  589. else:
  590. inc i
  591. proc markUsed(c: PContext; info: TLineInfo; s: PSym) =
  592. let conf = c.config
  593. incl(s.flags, sfUsed)
  594. if s.kind == skEnumField and s.owner != nil:
  595. incl(s.owner.flags, sfUsed)
  596. if sfDeprecated in s.owner.flags:
  597. warnAboutDeprecated(conf, info, s)
  598. if {sfDeprecated, sfError} * s.flags != {}:
  599. if sfDeprecated in s.flags:
  600. if not (c.lastTLineInfo.line == info.line and
  601. c.lastTLineInfo.col == info.col):
  602. warnAboutDeprecated(conf, info, s)
  603. c.lastTLineInfo = info
  604. if sfError in s.flags: userError(conf, info, s)
  605. when defined(nimsuggest):
  606. suggestSym(c.graph, info, s, c.graph.usageSym, false)
  607. styleCheckUse(c, info, s)
  608. markOwnerModuleAsUsed(c, s)
  609. proc safeSemExpr*(c: PContext, n: PNode): PNode =
  610. # use only for idetools support!
  611. try:
  612. result = c.semExpr(c, n)
  613. except ERecoverableError:
  614. result = c.graph.emptyNode
  615. proc sugExpr(c: PContext, n: PNode, outputs: var Suggestions) =
  616. if n.kind == nkDotExpr:
  617. var obj = safeSemExpr(c, n[0])
  618. # it can happen that errnously we have collected the fieldname
  619. # of the next line, so we check the 'field' is actually on the same
  620. # line as the object to prevent this from happening:
  621. let prefix = if n.len == 2 and n[1].info.line == n[0].info.line and
  622. not c.config.m.trackPosAttached: n[1] else: nil
  623. suggestFieldAccess(c, obj, prefix, outputs)
  624. #if optIdeDebug in gGlobalOptions:
  625. # echo "expression ", renderTree(obj), " has type ", typeToString(obj.typ)
  626. #writeStackTrace()
  627. elif n.kind == nkIdent:
  628. let
  629. prefix = if c.config.m.trackPosAttached: nil else: n
  630. info = n.info
  631. wholeSymTab(filterSym(it, prefix, pm), ideSug)
  632. else:
  633. let prefix = if c.config.m.trackPosAttached: nil else: n
  634. suggestEverything(c, n, prefix, outputs)
  635. proc suggestExprNoCheck*(c: PContext, n: PNode) =
  636. # This keeps semExpr() from coming here recursively:
  637. if c.compilesContextId > 0: return
  638. inc(c.compilesContextId)
  639. var outputs: Suggestions = @[]
  640. if c.config.ideCmd == ideSug:
  641. sugExpr(c, n, outputs)
  642. elif c.config.ideCmd == ideCon:
  643. if n.kind in nkCallKinds:
  644. var a = copyNode(n)
  645. var x = safeSemExpr(c, n[0])
  646. if x.kind == nkEmpty or x.typ == nil: x = n[0]
  647. a.add x
  648. for i in 1..<n.len:
  649. # use as many typed arguments as possible:
  650. var x = safeSemExpr(c, n[i])
  651. if x.kind == nkEmpty or x.typ == nil: break
  652. a.add x
  653. suggestCall(c, a, n, outputs)
  654. elif n.kind in nkIdentKinds:
  655. var x = safeSemExpr(c, n)
  656. if x.kind == nkEmpty or x.typ == nil: x = n
  657. suggestVar(c, x, outputs)
  658. dec(c.compilesContextId)
  659. if outputs.len > 0 and c.config.ideCmd in {ideSug, ideCon, ideDef}:
  660. produceOutput(outputs, c.config)
  661. suggestQuit()
  662. proc suggestExpr*(c: PContext, n: PNode) =
  663. if exactEquals(c.config.m.trackPos, n.info): suggestExprNoCheck(c, n)
  664. proc suggestDecl*(c: PContext, n: PNode; s: PSym) =
  665. let attached = c.config.m.trackPosAttached
  666. if attached: inc(c.inTypeContext)
  667. defer:
  668. if attached: dec(c.inTypeContext)
  669. suggestExpr(c, n)
  670. proc suggestStmt*(c: PContext, n: PNode) =
  671. suggestExpr(c, n)
  672. proc suggestEnum*(c: PContext; n: PNode; t: PType) =
  673. var outputs: Suggestions = @[]
  674. suggestSymList(c, t.n, nil, n.info, outputs)
  675. produceOutput(outputs, c.config)
  676. if outputs.len > 0: suggestQuit()
  677. proc suggestSentinel*(c: PContext) =
  678. if c.config.ideCmd != ideSug or c.module.position != c.config.m.trackPos.fileIndex.int32: return
  679. if c.compilesContextId > 0: return
  680. inc(c.compilesContextId)
  681. var outputs: Suggestions = @[]
  682. # suggest everything:
  683. for (it, scopeN, isLocal) in allSyms(c):
  684. var pm: PrefixMatch
  685. if filterSymNoOpr(it, nil, pm):
  686. outputs.add(symToSuggest(c.graph, it, isLocal = isLocal, ideSug,
  687. newLineInfo(c.config.m.trackPos.fileIndex, 0, -1), it.getQuality,
  688. PrefixMatch.None, false, scopeN))
  689. dec(c.compilesContextId)
  690. produceOutput(outputs, c.config)
  691. when defined(nimsuggest):
  692. proc onDef(graph: ModuleGraph, s: PSym, info: TLineInfo) =
  693. if graph.config.suggestVersion >= 3 and info.exactEquals(s.info):
  694. suggestSym(graph, info, s, graph.usageSym)
  695. template getPContext(): untyped =
  696. when c is PContext: c
  697. else: c.c
  698. template onDef*(info: TLineInfo; s: PSym) =
  699. let c = getPContext()
  700. onDef(c.graph, s, info)