suggest.nim 31 KB

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