suggest.nim 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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 in {0, 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. for scope in allScopes(c.currentScope):
  257. for sym in scope.allowPrivateAccess:
  258. if symObj.id == sym.id: return true
  259. proc getQuality(s: PSym): range[0..100] =
  260. result = 100
  261. if s.typ != nil and s.typ.len > 1:
  262. var exp = s.typ[1].skipTypes({tyGenericInst, tyVar, tyLent, tyAlias, tySink})
  263. if exp.kind == tyVarargs: exp = elemType(exp)
  264. if exp.kind in {tyUntyped, tyTyped, tyGenericParam, tyAnything}: result = 50
  265. # penalize deprecated symbols
  266. if sfDeprecated in s.flags:
  267. result = result - 5
  268. proc suggestField(c: PContext, s: PSym; f: PNode; info: TLineInfo; outputs: var Suggestions) =
  269. var pm: PrefixMatch
  270. if filterSym(s, f, pm) and fieldVisible(c, s):
  271. outputs.add(symToSuggest(c.graph, s, isLocal=true, ideSug, info,
  272. s.getQuality, pm, c.inTypeContext > 0, 0))
  273. template wholeSymTab(cond, section: untyped) {.dirty.} =
  274. for (item, scopeN, isLocal) in uniqueSyms(c):
  275. let it = item
  276. var pm: PrefixMatch
  277. if cond:
  278. outputs.add(symToSuggest(c.graph, it, isLocal = isLocal, section, info, getQuality(it),
  279. pm, c.inTypeContext > 0, scopeN))
  280. proc suggestSymList(c: PContext, list, f: PNode; info: TLineInfo, outputs: var Suggestions) =
  281. for i in 0..<list.len:
  282. if list[i].kind == nkSym:
  283. suggestField(c, list[i].sym, f, info, outputs)
  284. #else: InternalError(list.info, "getSymFromList")
  285. proc suggestObject(c: PContext, n, f: PNode; info: TLineInfo, outputs: var Suggestions) =
  286. case n.kind
  287. of nkRecList:
  288. for i in 0..<n.len: suggestObject(c, n[i], f, info, outputs)
  289. of nkRecCase:
  290. if n.len > 0:
  291. suggestObject(c, n[0], f, info, outputs)
  292. for i in 1..<n.len: suggestObject(c, lastSon(n[i]), f, info, outputs)
  293. of nkSym: suggestField(c, n.sym, f, info, outputs)
  294. else: discard
  295. proc nameFits(c: PContext, s: PSym, n: PNode): bool =
  296. var op = if n.kind in nkCallKinds: n[0] else: n
  297. if op.kind in {nkOpenSymChoice, nkClosedSymChoice}: op = op[0]
  298. if op.kind == nkDotExpr: op = op[1]
  299. var opr: PIdent
  300. case op.kind
  301. of nkSym: opr = op.sym.name
  302. of nkIdent: opr = op.ident
  303. else: return false
  304. result = opr.id == s.name.id
  305. proc argsFit(c: PContext, candidate: PSym, n, nOrig: PNode): bool =
  306. case candidate.kind
  307. of OverloadableSyms:
  308. var m = newCandidate(c, candidate, nil)
  309. sigmatch.partialMatch(c, n, nOrig, m)
  310. result = m.state != csNoMatch
  311. else:
  312. result = false
  313. proc suggestCall(c: PContext, n, nOrig: PNode, outputs: var Suggestions) =
  314. let info = n.info
  315. wholeSymTab(filterSym(it, nil, pm) and nameFits(c, it, n) and argsFit(c, it, n, nOrig),
  316. ideCon)
  317. proc suggestVar(c: PContext, n: PNode, outputs: var Suggestions) =
  318. let info = n.info
  319. wholeSymTab(nameFits(c, it, n), ideCon)
  320. proc typeFits(c: PContext, s: PSym, firstArg: PType): bool {.inline.} =
  321. if s.typ != nil and s.typ.len > 1 and s.typ[1] != nil:
  322. # special rule: if system and some weird generic match via 'tyUntyped'
  323. # or 'tyGenericParam' we won't list it either to reduce the noise (nobody
  324. # wants 'system.`-|` as suggestion
  325. let m = s.getModule()
  326. if m != nil and sfSystemModule in m.flags:
  327. if s.kind == skType: return
  328. var exp = s.typ[1].skipTypes({tyGenericInst, tyVar, tyLent, tyAlias, tySink})
  329. if exp.kind == tyVarargs: exp = elemType(exp)
  330. if exp.kind in {tyUntyped, tyTyped, tyGenericParam, tyAnything}: return
  331. result = sigmatch.argtypeMatches(c, s.typ[1], firstArg)
  332. proc suggestOperations(c: PContext, n, f: PNode, typ: PType, outputs: var Suggestions) =
  333. assert typ != nil
  334. let info = n.info
  335. wholeSymTab(filterSymNoOpr(it, f, pm) and typeFits(c, it, typ), ideSug)
  336. proc suggestEverything(c: PContext, n, f: PNode, outputs: var Suggestions) =
  337. # do not produce too many symbols:
  338. for (it, scopeN, isLocal) in uniqueSyms(c):
  339. var pm: PrefixMatch
  340. if filterSym(it, f, pm):
  341. outputs.add(symToSuggest(c.graph, it, isLocal = isLocal, ideSug, n.info,
  342. it.getQuality, pm, c.inTypeContext > 0, scopeN))
  343. proc suggestFieldAccess(c: PContext, n, field: PNode, outputs: var Suggestions) =
  344. # special code that deals with ``myObj.``. `n` is NOT the nkDotExpr-node, but
  345. # ``myObj``.
  346. var typ = n.typ
  347. var pm: PrefixMatch
  348. when defined(nimsuggest):
  349. if n.kind == nkSym and n.sym.kind == skError and c.config.suggestVersion == 0:
  350. # consider 'foo.|' where 'foo' is some not imported module.
  351. let fullPath = findModule(c.config, n.sym.name.s, toFullPath(c.config, n.info))
  352. if fullPath.isEmpty:
  353. # error: no known module name:
  354. typ = nil
  355. else:
  356. let m = c.graph.importModuleCallback(c.graph, c.module, fileInfoIdx(c.config, fullPath))
  357. if m == nil: typ = nil
  358. else:
  359. for it in allSyms(c.graph, n.sym):
  360. if filterSym(it, field, pm):
  361. outputs.add(symToSuggest(c.graph, it, isLocal=false, ideSug,
  362. n.info, it.getQuality, pm,
  363. c.inTypeContext > 0, -100))
  364. outputs.add(symToSuggest(c.graph, m, isLocal=false, ideMod, n.info,
  365. 100, PrefixMatch.None, c.inTypeContext > 0,
  366. -99))
  367. if typ == nil:
  368. # a module symbol has no type for example:
  369. if n.kind == nkSym and n.sym.kind == skModule:
  370. if n.sym == c.module:
  371. # all symbols accessible, because we are in the current module:
  372. for it in items(c.topLevelScope.symbols):
  373. if filterSym(it, field, pm):
  374. outputs.add(symToSuggest(c.graph, it, isLocal=false, ideSug,
  375. n.info, it.getQuality, pm,
  376. c.inTypeContext > 0, -99))
  377. else:
  378. for it in allSyms(c.graph, n.sym):
  379. if filterSym(it, field, pm):
  380. outputs.add(symToSuggest(c.graph, it, isLocal=false, ideSug,
  381. n.info, it.getQuality, pm,
  382. c.inTypeContext > 0, -99))
  383. else:
  384. # fallback:
  385. suggestEverything(c, n, field, outputs)
  386. else:
  387. let orig = typ
  388. typ = skipTypes(orig, {tyTypeDesc, tyGenericInst, tyVar, tyLent, tyPtr, tyRef, tyAlias, tySink, tyOwned})
  389. if typ.kind == tyEnum and n.kind == nkSym and n.sym.kind == skType:
  390. # look up if the identifier belongs to the enum:
  391. var t = typ
  392. while t != nil:
  393. suggestSymList(c, t.n, field, n.info, outputs)
  394. t = t[0]
  395. elif typ.kind == tyObject:
  396. var t = typ
  397. while true:
  398. suggestObject(c, t.n, field, n.info, outputs)
  399. if t[0] == nil: break
  400. t = skipTypes(t[0], skipPtrs)
  401. elif typ.kind == tyTuple and typ.n != nil:
  402. suggestSymList(c, typ.n, field, n.info, outputs)
  403. suggestOperations(c, n, field, orig, outputs)
  404. if typ != orig:
  405. suggestOperations(c, n, field, typ, outputs)
  406. type
  407. TCheckPointResult* = enum
  408. cpNone, cpFuzzy, cpExact
  409. proc inCheckpoint*(current, trackPos: TLineInfo): TCheckPointResult =
  410. if current.fileIndex == trackPos.fileIndex:
  411. if current.line == trackPos.line and
  412. abs(current.col-trackPos.col) < 4:
  413. return cpExact
  414. if current.line >= trackPos.line:
  415. return cpFuzzy
  416. proc isTracked*(current, trackPos: TLineInfo, tokenLen: int): bool =
  417. if current.fileIndex==trackPos.fileIndex and current.line==trackPos.line:
  418. let col = trackPos.col
  419. if col >= current.col and col <= current.col+tokenLen-1:
  420. return true
  421. when defined(nimsuggest):
  422. # Since TLineInfo defined a == operator that doesn't include the column,
  423. # we map TLineInfo to a unique int here for this lookup table:
  424. proc infoToInt(info: TLineInfo): int64 =
  425. info.fileIndex.int64 + info.line.int64 shl 32 + info.col.int64 shl 48
  426. proc addNoDup(s: PSym; info: TLineInfo) =
  427. # ensure nothing gets too slow:
  428. if s.allUsages.len > 500: return
  429. let infoAsInt = info.infoToInt
  430. for infoB in s.allUsages:
  431. if infoB.infoToInt == infoAsInt: return
  432. s.allUsages.add(info)
  433. proc findUsages(g: ModuleGraph; info: TLineInfo; s: PSym; usageSym: var PSym) =
  434. if g.config.suggestVersion == 1:
  435. if usageSym == nil and isTracked(info, g.config.m.trackPos, s.name.s.len):
  436. usageSym = s
  437. suggestResult(g.config, symToSuggest(g, s, isLocal=false, ideUse, info, 100, PrefixMatch.None, false, 0))
  438. elif s == usageSym:
  439. if g.config.lastLineInfo != info:
  440. suggestResult(g.config, symToSuggest(g, s, isLocal=false, ideUse, info, 100, PrefixMatch.None, false, 0))
  441. g.config.lastLineInfo = info
  442. when defined(nimsuggest):
  443. proc listUsages*(g: ModuleGraph; s: PSym) =
  444. #echo "usages ", s.allUsages.len
  445. for info in s.allUsages:
  446. let x = if info == s.info and info.col == s.info.col: ideDef else: ideUse
  447. suggestResult(g.config, symToSuggest(g, s, isLocal=false, x, info, 100, PrefixMatch.None, false, 0))
  448. proc findDefinition(g: ModuleGraph; info: TLineInfo; s: PSym; usageSym: var PSym) =
  449. if s.isNil: return
  450. if isTracked(info, g.config.m.trackPos, s.name.s.len) or (s == usageSym and sfForward notin s.flags):
  451. suggestResult(g.config, symToSuggest(g, s, isLocal=false, ideDef, info, 100, PrefixMatch.None, false, 0, useSuppliedInfo = s == usageSym))
  452. if sfForward notin s.flags and g.config.suggestVersion != 3:
  453. suggestQuit()
  454. else:
  455. usageSym = s
  456. proc ensureIdx[T](x: var T, y: int) =
  457. if x.len <= y: x.setLen(y+1)
  458. proc ensureSeq[T](x: var seq[T]) =
  459. if x == nil: newSeq(x, 0)
  460. proc suggestSym*(g: ModuleGraph; info: TLineInfo; s: PSym; usageSym: var PSym; isDecl=true) {.inline.} =
  461. ## misnamed: should be 'symDeclared'
  462. let conf = g.config
  463. when defined(nimsuggest):
  464. g.suggestSymbols.mgetOrPut(info.fileIndex, @[]).add SymInfoPair(sym: s, info: info)
  465. if conf.suggestVersion == 0:
  466. if s.allUsages.len == 0:
  467. s.allUsages = @[info]
  468. else:
  469. s.addNoDup(info)
  470. if conf.ideCmd == ideUse:
  471. findUsages(g, info, s, usageSym)
  472. elif conf.ideCmd == ideDef:
  473. findDefinition(g, info, s, usageSym)
  474. elif conf.ideCmd == ideDus and s != nil:
  475. if isTracked(info, conf.m.trackPos, s.name.s.len):
  476. suggestResult(conf, symToSuggest(g, s, isLocal=false, ideDef, info, 100, PrefixMatch.None, false, 0))
  477. findUsages(g, info, s, usageSym)
  478. elif conf.ideCmd == ideHighlight and info.fileIndex == conf.m.trackPos.fileIndex:
  479. suggestResult(conf, symToSuggest(g, s, isLocal=false, ideHighlight, info, 100, PrefixMatch.None, false, 0))
  480. elif conf.ideCmd == ideOutline and isDecl:
  481. # if a module is included then the info we have is inside the include and
  482. # we need to walk up the owners until we find the outer most module,
  483. # which will be the last skModule prior to an skPackage.
  484. var
  485. parentFileIndex = info.fileIndex # assume we're in the correct module
  486. parentModule = s.owner
  487. while parentModule != nil and parentModule.kind == skModule:
  488. parentFileIndex = parentModule.info.fileIndex
  489. parentModule = parentModule.owner
  490. if parentFileIndex == conf.m.trackPos.fileIndex:
  491. suggestResult(conf, symToSuggest(g, s, isLocal=false, ideOutline, info, 100, PrefixMatch.None, false, 0))
  492. proc warnAboutDeprecated(conf: ConfigRef; info: TLineInfo; s: PSym) =
  493. var pragmaNode: PNode
  494. pragmaNode = if s.kind == skEnumField: extractPragma(s.owner) else: extractPragma(s)
  495. let name =
  496. if s.kind == skEnumField and sfDeprecated notin s.flags: "enum '" & s.owner.name.s & "' which contains field '" & s.name.s & "'"
  497. else: s.name.s
  498. if pragmaNode != nil:
  499. for it in pragmaNode:
  500. if whichPragma(it) == wDeprecated and it.safeLen == 2 and
  501. it[1].kind in {nkStrLit..nkTripleStrLit}:
  502. message(conf, info, warnDeprecated, it[1].strVal & "; " & name & " is deprecated")
  503. return
  504. message(conf, info, warnDeprecated, name & " is deprecated")
  505. proc userError(conf: ConfigRef; info: TLineInfo; s: PSym) =
  506. let pragmaNode = extractPragma(s)
  507. template bail(prefix: string) =
  508. localError(conf, info, "$1usage of '$2' is an {.error.} defined at $3" %
  509. [prefix, s.name.s, toFileLineCol(conf, s.ast.info)])
  510. if pragmaNode != nil:
  511. for it in pragmaNode:
  512. if whichPragma(it) == wError and it.safeLen == 2 and
  513. it[1].kind in {nkStrLit..nkTripleStrLit}:
  514. bail(it[1].strVal & "; ")
  515. return
  516. bail("")
  517. proc markOwnerModuleAsUsed(c: PContext; s: PSym) =
  518. var module = s
  519. while module != nil and module.kind != skModule:
  520. module = module.owner
  521. if module != nil and module != c.module:
  522. var i = 0
  523. while i <= high(c.unusedImports):
  524. let candidate = c.unusedImports[i][0]
  525. if candidate == module or c.importModuleMap.getOrDefault(candidate.id, int.low) == module.id or
  526. c.exportIndirections.contains((candidate.id, s.id)):
  527. # mark it as used:
  528. c.unusedImports.del(i)
  529. else:
  530. inc i
  531. proc markUsed(c: PContext; info: TLineInfo; s: PSym) =
  532. let conf = c.config
  533. incl(s.flags, sfUsed)
  534. if s.kind == skEnumField and s.owner != nil:
  535. incl(s.owner.flags, sfUsed)
  536. if sfDeprecated in s.owner.flags:
  537. warnAboutDeprecated(conf, info, s)
  538. if {sfDeprecated, sfError} * s.flags != {}:
  539. if sfDeprecated in s.flags:
  540. if not (c.lastTLineInfo.line == info.line and
  541. c.lastTLineInfo.col == info.col):
  542. warnAboutDeprecated(conf, info, s)
  543. c.lastTLineInfo = info
  544. if sfError in s.flags: userError(conf, info, s)
  545. when defined(nimsuggest):
  546. suggestSym(c.graph, info, s, c.graph.usageSym, false)
  547. styleCheckUse(c, info, s)
  548. markOwnerModuleAsUsed(c, s)
  549. proc safeSemExpr*(c: PContext, n: PNode): PNode =
  550. # use only for idetools support!
  551. try:
  552. result = c.semExpr(c, n)
  553. except ERecoverableError:
  554. result = c.graph.emptyNode
  555. proc sugExpr(c: PContext, n: PNode, outputs: var Suggestions) =
  556. if n.kind == nkDotExpr:
  557. var obj = safeSemExpr(c, n[0])
  558. # it can happen that errnously we have collected the fieldname
  559. # of the next line, so we check the 'field' is actually on the same
  560. # line as the object to prevent this from happening:
  561. let prefix = if n.len == 2 and n[1].info.line == n[0].info.line and
  562. not c.config.m.trackPosAttached: n[1] else: nil
  563. suggestFieldAccess(c, obj, prefix, outputs)
  564. #if optIdeDebug in gGlobalOptions:
  565. # echo "expression ", renderTree(obj), " has type ", typeToString(obj.typ)
  566. #writeStackTrace()
  567. elif n.kind == nkIdent:
  568. let
  569. prefix = if c.config.m.trackPosAttached: nil else: n
  570. info = n.info
  571. wholeSymTab(filterSym(it, prefix, pm), ideSug)
  572. else:
  573. let prefix = if c.config.m.trackPosAttached: nil else: n
  574. suggestEverything(c, n, prefix, outputs)
  575. proc suggestExprNoCheck*(c: PContext, n: PNode) =
  576. # This keeps semExpr() from coming here recursively:
  577. if c.compilesContextId > 0: return
  578. inc(c.compilesContextId)
  579. var outputs: Suggestions = @[]
  580. if c.config.ideCmd == ideSug:
  581. sugExpr(c, n, outputs)
  582. elif c.config.ideCmd == ideCon:
  583. if n.kind in nkCallKinds:
  584. var a = copyNode(n)
  585. var x = safeSemExpr(c, n[0])
  586. if x.kind == nkEmpty or x.typ == nil: x = n[0]
  587. a.add x
  588. for i in 1..<n.len:
  589. # use as many typed arguments as possible:
  590. var x = safeSemExpr(c, n[i])
  591. if x.kind == nkEmpty or x.typ == nil: break
  592. a.add x
  593. suggestCall(c, a, n, outputs)
  594. elif n.kind in nkIdentKinds:
  595. var x = safeSemExpr(c, n)
  596. if x.kind == nkEmpty or x.typ == nil: x = n
  597. suggestVar(c, x, outputs)
  598. dec(c.compilesContextId)
  599. if outputs.len > 0 and c.config.ideCmd in {ideSug, ideCon, ideDef}:
  600. produceOutput(outputs, c.config)
  601. suggestQuit()
  602. proc suggestExpr*(c: PContext, n: PNode) =
  603. if exactEquals(c.config.m.trackPos, n.info): suggestExprNoCheck(c, n)
  604. proc suggestDecl*(c: PContext, n: PNode; s: PSym) =
  605. let attached = c.config.m.trackPosAttached
  606. if attached: inc(c.inTypeContext)
  607. defer:
  608. if attached: dec(c.inTypeContext)
  609. suggestExpr(c, n)
  610. proc suggestStmt*(c: PContext, n: PNode) =
  611. suggestExpr(c, n)
  612. proc suggestEnum*(c: PContext; n: PNode; t: PType) =
  613. var outputs: Suggestions = @[]
  614. suggestSymList(c, t.n, nil, n.info, outputs)
  615. produceOutput(outputs, c.config)
  616. if outputs.len > 0: suggestQuit()
  617. proc suggestSentinel*(c: PContext) =
  618. if c.config.ideCmd != ideSug or c.module.position != c.config.m.trackPos.fileIndex.int32: return
  619. if c.compilesContextId > 0: return
  620. inc(c.compilesContextId)
  621. var outputs: Suggestions = @[]
  622. # suggest everything:
  623. for (it, scopeN, isLocal) in uniqueSyms(c):
  624. var pm: PrefixMatch
  625. if filterSymNoOpr(it, nil, pm):
  626. outputs.add(symToSuggest(c.graph, it, isLocal = isLocal, ideSug,
  627. newLineInfo(c.config.m.trackPos.fileIndex, 0, -1), it.getQuality,
  628. PrefixMatch.None, false, scopeN))
  629. dec(c.compilesContextId)
  630. produceOutput(outputs, c.config)
  631. when defined(nimsuggest):
  632. proc onDef(graph: ModuleGraph, s: PSym, info: TLineInfo) =
  633. if graph.config.suggestVersion == 3 and info.exactEquals(s.info):
  634. suggestSym(graph, info, s, graph.usageSym)
  635. template getPContext(): untyped =
  636. when c is PContext: c
  637. else: c.c
  638. template onDef*(info: TLineInfo; s: PSym) =
  639. let c = getPContext()
  640. onDef(c.graph, s, info)