suggest.nim 25 KB

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