suggest.nim 24 KB

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