suggest.nim 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  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, nkSinkAsgn} 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 getTokenLenFromSource(conf: ConfigRef; ident: string; info: TLineInfo): int =
  73. let
  74. line = sourceLine(conf, info)
  75. column = toColumn(info)
  76. proc isOpeningBacktick(col: int): bool =
  77. if col >= 0 and col < line.len:
  78. if line[col] == '`':
  79. not isOpeningBacktick(col - 1)
  80. else:
  81. isOpeningBacktick(col - 1)
  82. else:
  83. false
  84. if column > line.len:
  85. result = 0
  86. elif column > 0 and line[column - 1] == '`' and isOpeningBacktick(column - 1):
  87. result = skipUntil(line, '`', column)
  88. if cmpIgnoreStyle(line[column..column + result - 1], ident) != 0:
  89. result = 0
  90. elif ident[0] in linter.Letters and ident[^1] != '=':
  91. result = identLen(line, column)
  92. if cmpIgnoreStyle(line[column..column + result - 1], ident) != 0:
  93. result = 0
  94. else:
  95. var sourceIdent: string
  96. result = parseWhile(line, sourceIdent,
  97. OpChars + {'[', '(', '{', ']', ')', '}'}, column)
  98. if ident[^1] == '=' and ident[0] in linter.Letters:
  99. if sourceIdent != "=":
  100. result = 0
  101. elif sourceIdent.len > ident.len and sourceIdent[0..ident.high] == ident:
  102. result = ident.len
  103. elif sourceIdent != ident:
  104. result = 0
  105. proc symToSuggest*(g: ModuleGraph; s: PSym, isLocal: bool, section: IdeCmd, info: TLineInfo;
  106. quality: range[0..100]; prefix: PrefixMatch;
  107. inTypeContext: bool; scope: int;
  108. useSuppliedInfo = false): Suggest =
  109. new(result)
  110. result.section = section
  111. result.quality = quality
  112. result.isGlobal = sfGlobal in s.flags
  113. result.prefix = prefix
  114. result.contextFits = inTypeContext == (s.kind in {skType, skGenericParam})
  115. result.scope = scope
  116. result.name = addr s.name.s
  117. when defined(nimsuggest):
  118. result.globalUsages = s.allUsages.len
  119. var c = 0
  120. for u in s.allUsages:
  121. if u.fileIndex == info.fileIndex: inc c
  122. result.localUsages = c
  123. result.symkind = byte s.kind
  124. if optIdeTerse notin g.config.globalOptions:
  125. result.qualifiedPath = @[]
  126. if not isLocal and s.kind != skModule:
  127. let ow = s.owner
  128. if ow != nil and ow.kind != skModule and ow.owner != nil:
  129. let ow2 = ow.owner
  130. result.qualifiedPath.add(ow2.origModuleName)
  131. if ow != nil:
  132. result.qualifiedPath.add(ow.origModuleName)
  133. if s.name.s[0] in OpChars + {'[', '{', '('} or
  134. s.name.id in ord(wAddr)..ord(wYield):
  135. result.qualifiedPath.add('`' & s.name.s & '`')
  136. else:
  137. result.qualifiedPath.add(s.name.s)
  138. if s.typ != nil:
  139. result.forth = typeToString(s.typ)
  140. else:
  141. result.forth = ""
  142. when defined(nimsuggest) and not defined(noDocgen) and not defined(leanCompiler):
  143. result.doc = extractDocComment(g, s)
  144. if s.kind == skModule and s.ast.len != 0 and section != ideHighlight:
  145. result.filePath = toFullPath(g.config, s.ast[0].info)
  146. result.line = 1
  147. result.column = 0
  148. result.tokenLen = 0
  149. else:
  150. let infox =
  151. if useSuppliedInfo or section in {ideUse, ideHighlight, ideOutline, ideDeclaration}:
  152. info
  153. else:
  154. s.info
  155. result.filePath = toFullPath(g.config, infox)
  156. result.line = toLinenumber(infox)
  157. result.column = toColumn(infox)
  158. result.tokenLen = if section != ideHighlight:
  159. s.name.s.len
  160. else:
  161. getTokenLenFromSource(g.config, s.name.s, infox)
  162. result.version = g.config.suggestVersion
  163. proc `$`*(suggest: Suggest): string =
  164. result = $suggest.section
  165. result.add(sep)
  166. if suggest.section == ideHighlight:
  167. if suggest.symkind.TSymKind == skVar and suggest.isGlobal:
  168. result.add("skGlobalVar")
  169. elif suggest.symkind.TSymKind == skLet and suggest.isGlobal:
  170. result.add("skGlobalLet")
  171. else:
  172. result.add($suggest.symkind.TSymKind)
  173. result.add(sep)
  174. result.add($suggest.line)
  175. result.add(sep)
  176. result.add($suggest.column)
  177. result.add(sep)
  178. result.add($suggest.tokenLen)
  179. else:
  180. result.add($suggest.symkind.TSymKind)
  181. result.add(sep)
  182. if suggest.qualifiedPath.len != 0:
  183. result.add(suggest.qualifiedPath.join("."))
  184. result.add(sep)
  185. result.add(suggest.forth)
  186. result.add(sep)
  187. result.add(suggest.filePath)
  188. result.add(sep)
  189. result.add($suggest.line)
  190. result.add(sep)
  191. result.add($suggest.column)
  192. result.add(sep)
  193. when defined(nimsuggest) and not defined(noDocgen) and not defined(leanCompiler):
  194. result.add(suggest.doc.escape)
  195. if suggest.version in {0, 3}:
  196. result.add(sep)
  197. result.add($suggest.quality)
  198. if suggest.section == ideSug:
  199. result.add(sep)
  200. result.add($suggest.prefix)
  201. proc suggestResult*(conf: ConfigRef; s: Suggest) =
  202. if not isNil(conf.suggestionResultHook):
  203. conf.suggestionResultHook(s)
  204. else:
  205. conf.suggestWriteln($s)
  206. proc produceOutput(a: var Suggestions; conf: ConfigRef) =
  207. if conf.ideCmd in {ideSug, ideCon}:
  208. a.sort cmpSuggestions
  209. when defined(debug):
  210. # debug code
  211. writeStackTrace()
  212. if a.len > conf.suggestMaxResults: a.setLen(conf.suggestMaxResults)
  213. if not isNil(conf.suggestionResultHook):
  214. for s in a:
  215. conf.suggestionResultHook(s)
  216. else:
  217. for s in a:
  218. conf.suggestWriteln($s)
  219. proc filterSym(s: PSym; prefix: PNode; res: var PrefixMatch): bool {.inline.} =
  220. proc prefixMatch(s: PSym; n: PNode): PrefixMatch =
  221. case n.kind
  222. of nkIdent: result = n.ident.s.prefixMatch(s.name.s)
  223. of nkSym: result = n.sym.name.s.prefixMatch(s.name.s)
  224. of nkOpenSymChoice, nkClosedSymChoice, nkAccQuoted:
  225. if n.len > 0:
  226. result = prefixMatch(s, n[0])
  227. else: discard
  228. if s.kind != skModule:
  229. if prefix != nil:
  230. res = prefixMatch(s, prefix)
  231. result = res != PrefixMatch.None
  232. else:
  233. result = true
  234. proc filterSymNoOpr(s: PSym; prefix: PNode; res: var PrefixMatch): bool {.inline.} =
  235. result = filterSym(s, prefix, res) and s.name.s[0] in lexer.SymChars and
  236. not isKeyword(s.name)
  237. proc fieldVisible*(c: PContext, f: PSym): bool {.inline.} =
  238. let fmoduleId = getModule(f).id
  239. result = sfExported in f.flags or fmoduleId == c.module.id
  240. if not result:
  241. for module in c.friendModules:
  242. if fmoduleId == module.id: return true
  243. if f.kind == skField:
  244. var symObj = f.owner
  245. if symObj.typ.skipTypes({tyGenericBody, tyGenericInst, tyGenericInvocation, tyAlias}).kind in {tyRef, tyPtr}:
  246. symObj = symObj.typ.toObjectFromRefPtrGeneric.sym
  247. for scope in allScopes(c.currentScope):
  248. for sym in scope.allowPrivateAccess:
  249. if symObj.id == sym.id: return true
  250. proc getQuality(s: PSym): range[0..100] =
  251. result = 100
  252. if s.typ != nil and s.typ.len > 1:
  253. var exp = s.typ[1].skipTypes({tyGenericInst, tyVar, tyLent, tyAlias, tySink})
  254. if exp.kind == tyVarargs: exp = elemType(exp)
  255. if exp.kind in {tyUntyped, tyTyped, tyGenericParam, tyAnything}: result = 50
  256. # penalize deprecated symbols
  257. if sfDeprecated in s.flags:
  258. result = result - 5
  259. proc suggestField(c: PContext, s: PSym; f: PNode; info: TLineInfo; outputs: var Suggestions) =
  260. var pm: PrefixMatch
  261. if filterSym(s, f, pm) and fieldVisible(c, s):
  262. outputs.add(symToSuggest(c.graph, s, isLocal=true, ideSug, info,
  263. s.getQuality, pm, c.inTypeContext > 0, 0))
  264. template wholeSymTab(cond, section: untyped) {.dirty.} =
  265. for (item, scopeN, isLocal) in uniqueSyms(c):
  266. let it = item
  267. var pm: PrefixMatch
  268. if cond:
  269. outputs.add(symToSuggest(c.graph, it, isLocal = isLocal, section, info, getQuality(it),
  270. pm, c.inTypeContext > 0, scopeN))
  271. proc suggestSymList(c: PContext, list, f: PNode; info: TLineInfo, outputs: var Suggestions) =
  272. for i in 0..<list.len:
  273. if list[i].kind == nkSym:
  274. suggestField(c, list[i].sym, f, info, outputs)
  275. #else: InternalError(list.info, "getSymFromList")
  276. proc suggestObject(c: PContext, n, f: PNode; info: TLineInfo, outputs: var Suggestions) =
  277. case n.kind
  278. of nkRecList:
  279. for i in 0..<n.len: suggestObject(c, n[i], f, info, outputs)
  280. of nkRecCase:
  281. if n.len > 0:
  282. suggestObject(c, n[0], f, info, outputs)
  283. for i in 1..<n.len: suggestObject(c, lastSon(n[i]), f, info, outputs)
  284. of nkSym: suggestField(c, n.sym, f, info, outputs)
  285. else: discard
  286. proc nameFits(c: PContext, s: PSym, n: PNode): bool =
  287. var op = if n.kind in nkCallKinds: n[0] else: n
  288. if op.kind in {nkOpenSymChoice, nkClosedSymChoice}: op = op[0]
  289. if op.kind == nkDotExpr: op = op[1]
  290. var opr: PIdent
  291. case op.kind
  292. of nkSym: opr = op.sym.name
  293. of nkIdent: opr = op.ident
  294. else: return false
  295. result = opr.id == s.name.id
  296. proc argsFit(c: PContext, candidate: PSym, n, nOrig: PNode): bool =
  297. case candidate.kind
  298. of OverloadableSyms:
  299. var m = newCandidate(c, candidate, nil)
  300. sigmatch.partialMatch(c, n, nOrig, m)
  301. result = m.state != csNoMatch
  302. else:
  303. result = false
  304. proc suggestCall(c: PContext, n, nOrig: PNode, outputs: var Suggestions) =
  305. let info = n.info
  306. wholeSymTab(filterSym(it, nil, pm) and nameFits(c, it, n) and argsFit(c, it, n, nOrig),
  307. ideCon)
  308. proc suggestVar(c: PContext, n: PNode, outputs: var Suggestions) =
  309. let info = n.info
  310. wholeSymTab(nameFits(c, it, n), ideCon)
  311. proc typeFits(c: PContext, s: PSym, firstArg: PType): bool {.inline.} =
  312. if s.typ != nil and s.typ.len > 1 and s.typ[1] != nil:
  313. # special rule: if system and some weird generic match via 'tyUntyped'
  314. # or 'tyGenericParam' we won't list it either to reduce the noise (nobody
  315. # wants 'system.`-|` as suggestion
  316. let m = s.getModule()
  317. if m != nil and sfSystemModule in m.flags:
  318. if s.kind == skType: return
  319. var exp = s.typ[1].skipTypes({tyGenericInst, tyVar, tyLent, tyAlias, tySink})
  320. if exp.kind == tyVarargs: exp = elemType(exp)
  321. if exp.kind in {tyUntyped, tyTyped, tyGenericParam, tyAnything}: return
  322. result = sigmatch.argtypeMatches(c, s.typ[1], firstArg)
  323. proc suggestOperations(c: PContext, n, f: PNode, typ: PType, outputs: var Suggestions) =
  324. assert typ != nil
  325. let info = n.info
  326. wholeSymTab(filterSymNoOpr(it, f, pm) and typeFits(c, it, typ), ideSug)
  327. proc suggestEverything(c: PContext, n, f: PNode, outputs: var Suggestions) =
  328. # do not produce too many symbols:
  329. for (it, scopeN, isLocal) in uniqueSyms(c):
  330. var pm: PrefixMatch
  331. if filterSym(it, f, pm):
  332. outputs.add(symToSuggest(c.graph, it, isLocal = isLocal, ideSug, n.info,
  333. it.getQuality, pm, c.inTypeContext > 0, scopeN))
  334. proc suggestFieldAccess(c: PContext, n, field: PNode, outputs: var Suggestions) =
  335. # special code that deals with ``myObj.``. `n` is NOT the nkDotExpr-node, but
  336. # ``myObj``.
  337. var typ = n.typ
  338. var pm: PrefixMatch
  339. when defined(nimsuggest):
  340. if n.kind == nkSym and n.sym.kind == skError and c.config.suggestVersion == 0:
  341. # consider 'foo.|' where 'foo' is some not imported module.
  342. let fullPath = findModule(c.config, n.sym.name.s, toFullPath(c.config, n.info))
  343. if fullPath.isEmpty:
  344. # error: no known module name:
  345. typ = nil
  346. else:
  347. let m = c.graph.importModuleCallback(c.graph, c.module, fileInfoIdx(c.config, fullPath))
  348. if m == nil: typ = nil
  349. else:
  350. for it in allSyms(c.graph, n.sym):
  351. if filterSym(it, field, pm):
  352. outputs.add(symToSuggest(c.graph, it, isLocal=false, ideSug,
  353. n.info, it.getQuality, pm,
  354. c.inTypeContext > 0, -100))
  355. outputs.add(symToSuggest(c.graph, m, isLocal=false, ideMod, n.info,
  356. 100, PrefixMatch.None, c.inTypeContext > 0,
  357. -99))
  358. if typ == nil:
  359. # a module symbol has no type for example:
  360. if n.kind == nkSym and n.sym.kind == skModule:
  361. if n.sym == c.module:
  362. # all symbols accessible, because we are in the current module:
  363. for it in items(c.topLevelScope.symbols):
  364. if filterSym(it, field, pm):
  365. outputs.add(symToSuggest(c.graph, it, isLocal=false, ideSug,
  366. n.info, it.getQuality, pm,
  367. c.inTypeContext > 0, -99))
  368. else:
  369. for it in allSyms(c.graph, n.sym):
  370. if filterSym(it, field, pm):
  371. outputs.add(symToSuggest(c.graph, it, isLocal=false, ideSug,
  372. n.info, it.getQuality, pm,
  373. c.inTypeContext > 0, -99))
  374. else:
  375. # fallback:
  376. suggestEverything(c, n, field, outputs)
  377. else:
  378. let orig = typ
  379. typ = skipTypes(orig, {tyTypeDesc, tyGenericInst, tyVar, tyLent, tyPtr, tyRef, tyAlias, tySink, tyOwned})
  380. if typ.kind == tyEnum and n.kind == nkSym and n.sym.kind == skType:
  381. # look up if the identifier belongs to the enum:
  382. var t = typ
  383. while t != nil:
  384. suggestSymList(c, t.n, field, n.info, outputs)
  385. t = t[0]
  386. elif typ.kind == tyObject:
  387. var t = typ
  388. while true:
  389. suggestObject(c, t.n, field, n.info, outputs)
  390. if t[0] == nil: break
  391. t = skipTypes(t[0], skipPtrs)
  392. elif typ.kind == tyTuple and typ.n != nil:
  393. suggestSymList(c, typ.n, field, n.info, outputs)
  394. suggestOperations(c, n, field, orig, outputs)
  395. if typ != orig:
  396. suggestOperations(c, n, field, typ, outputs)
  397. type
  398. TCheckPointResult* = enum
  399. cpNone, cpFuzzy, cpExact
  400. proc inCheckpoint*(current, trackPos: TLineInfo): TCheckPointResult =
  401. if current.fileIndex == trackPos.fileIndex:
  402. if current.line == trackPos.line and
  403. abs(current.col-trackPos.col) < 4:
  404. return cpExact
  405. if current.line >= trackPos.line:
  406. return cpFuzzy
  407. proc isTracked*(current, trackPos: TLineInfo, tokenLen: int): bool =
  408. if current.fileIndex==trackPos.fileIndex and current.line==trackPos.line:
  409. let col = trackPos.col
  410. if col >= current.col and col <= current.col+tokenLen-1:
  411. return true
  412. when defined(nimsuggest):
  413. # Since TLineInfo defined a == operator that doesn't include the column,
  414. # we map TLineInfo to a unique int here for this lookup table:
  415. proc infoToInt(info: TLineInfo): int64 =
  416. info.fileIndex.int64 + info.line.int64 shl 32 + info.col.int64 shl 48
  417. proc addNoDup(s: PSym; info: TLineInfo) =
  418. # ensure nothing gets too slow:
  419. if s.allUsages.len > 500: return
  420. let infoAsInt = info.infoToInt
  421. for infoB in s.allUsages:
  422. if infoB.infoToInt == infoAsInt: return
  423. s.allUsages.add(info)
  424. proc findUsages(g: ModuleGraph; info: TLineInfo; s: PSym; usageSym: var PSym) =
  425. if g.config.suggestVersion == 1:
  426. if usageSym == nil and isTracked(info, g.config.m.trackPos, s.name.s.len):
  427. usageSym = s
  428. suggestResult(g.config, symToSuggest(g, s, isLocal=false, ideUse, info, 100, PrefixMatch.None, false, 0))
  429. elif s == usageSym:
  430. if g.config.lastLineInfo != info:
  431. suggestResult(g.config, symToSuggest(g, s, isLocal=false, ideUse, info, 100, PrefixMatch.None, false, 0))
  432. g.config.lastLineInfo = info
  433. when defined(nimsuggest):
  434. proc listUsages*(g: ModuleGraph; s: PSym) =
  435. #echo "usages ", s.allUsages.len
  436. for info in s.allUsages:
  437. let x = if info == s.info and info.col == s.info.col: ideDef else: ideUse
  438. suggestResult(g.config, symToSuggest(g, s, isLocal=false, x, info, 100, PrefixMatch.None, false, 0))
  439. proc findDefinition(g: ModuleGraph; info: TLineInfo; s: PSym; usageSym: var PSym) =
  440. if s.isNil: return
  441. if isTracked(info, g.config.m.trackPos, s.name.s.len) or (s == usageSym and sfForward notin s.flags):
  442. suggestResult(g.config, symToSuggest(g, s, isLocal=false, ideDef, info, 100, PrefixMatch.None, false, 0, useSuppliedInfo = s == usageSym))
  443. if sfForward notin s.flags and g.config.suggestVersion != 3:
  444. suggestQuit()
  445. else:
  446. usageSym = s
  447. proc ensureIdx[T](x: var T, y: int) =
  448. if x.len <= y: x.setLen(y+1)
  449. proc ensureSeq[T](x: var seq[T]) =
  450. if x == nil: newSeq(x, 0)
  451. proc suggestSym*(g: ModuleGraph; info: TLineInfo; s: PSym; usageSym: var PSym; isDecl=true) {.inline.} =
  452. ## misnamed: should be 'symDeclared'
  453. let conf = g.config
  454. when defined(nimsuggest):
  455. g.suggestSymbols.mgetOrPut(info.fileIndex, @[]).add SymInfoPair(sym: s, info: info)
  456. if conf.suggestVersion == 0:
  457. if s.allUsages.len == 0:
  458. s.allUsages = @[info]
  459. else:
  460. s.addNoDup(info)
  461. if conf.ideCmd == ideUse:
  462. findUsages(g, info, s, usageSym)
  463. elif conf.ideCmd == ideDef:
  464. findDefinition(g, info, s, usageSym)
  465. elif conf.ideCmd == ideDus and s != nil:
  466. if isTracked(info, conf.m.trackPos, s.name.s.len):
  467. suggestResult(conf, symToSuggest(g, s, isLocal=false, ideDef, info, 100, PrefixMatch.None, false, 0))
  468. findUsages(g, info, s, usageSym)
  469. elif conf.ideCmd == ideHighlight and info.fileIndex == conf.m.trackPos.fileIndex:
  470. suggestResult(conf, symToSuggest(g, s, isLocal=false, ideHighlight, info, 100, PrefixMatch.None, false, 0))
  471. elif conf.ideCmd == ideOutline and isDecl:
  472. # if a module is included then the info we have is inside the include and
  473. # we need to walk up the owners until we find the outer most module,
  474. # which will be the last skModule prior to an skPackage.
  475. var
  476. parentFileIndex = info.fileIndex # assume we're in the correct module
  477. parentModule = s.owner
  478. while parentModule != nil and parentModule.kind == skModule:
  479. parentFileIndex = parentModule.info.fileIndex
  480. parentModule = parentModule.owner
  481. if parentFileIndex == conf.m.trackPos.fileIndex:
  482. suggestResult(conf, symToSuggest(g, s, isLocal=false, ideOutline, info, 100, PrefixMatch.None, false, 0))
  483. proc warnAboutDeprecated(conf: ConfigRef; info: TLineInfo; s: PSym) =
  484. var pragmaNode: PNode
  485. pragmaNode = if s.kind == skEnumField: extractPragma(s.owner) else: extractPragma(s)
  486. let name =
  487. if s.kind == skEnumField and sfDeprecated notin s.flags: "enum '" & s.owner.name.s & "' which contains field '" & s.name.s & "'"
  488. else: s.name.s
  489. if pragmaNode != nil:
  490. for it in pragmaNode:
  491. if whichPragma(it) == wDeprecated and it.safeLen == 2 and
  492. it[1].kind in {nkStrLit..nkTripleStrLit}:
  493. message(conf, info, warnDeprecated, it[1].strVal & "; " & name & " is deprecated")
  494. return
  495. message(conf, info, warnDeprecated, name & " is deprecated")
  496. proc userError(conf: ConfigRef; info: TLineInfo; s: PSym) =
  497. let pragmaNode = extractPragma(s)
  498. template bail(prefix: string) =
  499. localError(conf, info, "$1usage of '$2' is an {.error.} defined at $3" %
  500. [prefix, s.name.s, toFileLineCol(conf, s.ast.info)])
  501. if pragmaNode != nil:
  502. for it in pragmaNode:
  503. if whichPragma(it) == wError and it.safeLen == 2 and
  504. it[1].kind in {nkStrLit..nkTripleStrLit}:
  505. bail(it[1].strVal & "; ")
  506. return
  507. bail("")
  508. proc markOwnerModuleAsUsed(c: PContext; s: PSym) =
  509. var module = s
  510. while module != nil and module.kind != skModule:
  511. module = module.owner
  512. if module != nil and module != c.module:
  513. var i = 0
  514. while i <= high(c.unusedImports):
  515. let candidate = c.unusedImports[i][0]
  516. if candidate == module or c.importModuleMap.getOrDefault(candidate.id, int.low) == module.id or
  517. c.exportIndirections.contains((candidate.id, s.id)):
  518. # mark it as used:
  519. c.unusedImports.del(i)
  520. else:
  521. inc i
  522. proc markUsed(c: PContext; info: TLineInfo; s: PSym) =
  523. let conf = c.config
  524. incl(s.flags, sfUsed)
  525. if s.kind == skEnumField and s.owner != nil:
  526. incl(s.owner.flags, sfUsed)
  527. if sfDeprecated in s.owner.flags:
  528. warnAboutDeprecated(conf, info, s)
  529. if {sfDeprecated, sfError} * s.flags != {}:
  530. if sfDeprecated in s.flags:
  531. if not (c.lastTLineInfo.line == info.line and
  532. c.lastTLineInfo.col == info.col):
  533. warnAboutDeprecated(conf, info, s)
  534. c.lastTLineInfo = info
  535. if sfError in s.flags: userError(conf, info, s)
  536. when defined(nimsuggest):
  537. suggestSym(c.graph, info, s, c.graph.usageSym, false)
  538. styleCheckUse(c, info, s)
  539. markOwnerModuleAsUsed(c, s)
  540. proc safeSemExpr*(c: PContext, n: PNode): PNode =
  541. # use only for idetools support!
  542. try:
  543. result = c.semExpr(c, n)
  544. except ERecoverableError:
  545. result = c.graph.emptyNode
  546. proc sugExpr(c: PContext, n: PNode, outputs: var Suggestions) =
  547. if n.kind == nkDotExpr:
  548. var obj = safeSemExpr(c, n[0])
  549. # it can happen that errnously we have collected the fieldname
  550. # of the next line, so we check the 'field' is actually on the same
  551. # line as the object to prevent this from happening:
  552. let prefix = if n.len == 2 and n[1].info.line == n[0].info.line and
  553. not c.config.m.trackPosAttached: n[1] else: nil
  554. suggestFieldAccess(c, obj, prefix, outputs)
  555. #if optIdeDebug in gGlobalOptions:
  556. # echo "expression ", renderTree(obj), " has type ", typeToString(obj.typ)
  557. #writeStackTrace()
  558. elif n.kind == nkIdent:
  559. let
  560. prefix = if c.config.m.trackPosAttached: nil else: n
  561. info = n.info
  562. wholeSymTab(filterSym(it, prefix, pm), ideSug)
  563. else:
  564. let prefix = if c.config.m.trackPosAttached: nil else: n
  565. suggestEverything(c, n, prefix, outputs)
  566. proc suggestExprNoCheck*(c: PContext, n: PNode) =
  567. # This keeps semExpr() from coming here recursively:
  568. if c.compilesContextId > 0: return
  569. inc(c.compilesContextId)
  570. var outputs: Suggestions = @[]
  571. if c.config.ideCmd == ideSug:
  572. sugExpr(c, n, outputs)
  573. elif c.config.ideCmd == ideCon:
  574. if n.kind in nkCallKinds:
  575. var a = copyNode(n)
  576. var x = safeSemExpr(c, n[0])
  577. if x.kind == nkEmpty or x.typ == nil: x = n[0]
  578. a.add x
  579. for i in 1..<n.len:
  580. # use as many typed arguments as possible:
  581. var x = safeSemExpr(c, n[i])
  582. if x.kind == nkEmpty or x.typ == nil: break
  583. a.add x
  584. suggestCall(c, a, n, outputs)
  585. elif n.kind in nkIdentKinds:
  586. var x = safeSemExpr(c, n)
  587. if x.kind == nkEmpty or x.typ == nil: x = n
  588. suggestVar(c, x, outputs)
  589. dec(c.compilesContextId)
  590. if outputs.len > 0 and c.config.ideCmd in {ideSug, ideCon, ideDef}:
  591. produceOutput(outputs, c.config)
  592. suggestQuit()
  593. proc suggestExpr*(c: PContext, n: PNode) =
  594. if exactEquals(c.config.m.trackPos, n.info): suggestExprNoCheck(c, n)
  595. proc suggestDecl*(c: PContext, n: PNode; s: PSym) =
  596. let attached = c.config.m.trackPosAttached
  597. if attached: inc(c.inTypeContext)
  598. defer:
  599. if attached: dec(c.inTypeContext)
  600. suggestExpr(c, n)
  601. proc suggestStmt*(c: PContext, n: PNode) =
  602. suggestExpr(c, n)
  603. proc suggestEnum*(c: PContext; n: PNode; t: PType) =
  604. var outputs: Suggestions = @[]
  605. suggestSymList(c, t.n, nil, n.info, outputs)
  606. produceOutput(outputs, c.config)
  607. if outputs.len > 0: suggestQuit()
  608. proc suggestSentinel*(c: PContext) =
  609. if c.config.ideCmd != ideSug or c.module.position != c.config.m.trackPos.fileIndex.int32: return
  610. if c.compilesContextId > 0: return
  611. inc(c.compilesContextId)
  612. var outputs: Suggestions = @[]
  613. # suggest everything:
  614. for (it, scopeN, isLocal) in uniqueSyms(c):
  615. var pm: PrefixMatch
  616. if filterSymNoOpr(it, nil, pm):
  617. outputs.add(symToSuggest(c.graph, it, isLocal = isLocal, ideSug,
  618. newLineInfo(c.config.m.trackPos.fileIndex, 0, -1), it.getQuality,
  619. PrefixMatch.None, false, scopeN))
  620. dec(c.compilesContextId)
  621. produceOutput(outputs, c.config)
  622. when defined(nimsuggest):
  623. proc onDef(graph: ModuleGraph, s: PSym, info: TLineInfo) =
  624. if graph.config.suggestVersion == 3 and info.exactEquals(s.info):
  625. suggestSym(graph, info, s, graph.usageSym)
  626. template getPContext(): untyped =
  627. when c is PContext: c
  628. else: c.c
  629. template onDef*(info: TLineInfo; s: PSym) =
  630. let c = getPContext()
  631. onDef(c.graph, s, info)