suggest.nim 27 KB

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