suggest.nim 24 KB

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