suggest.nim 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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, prefixmatches, lineinfos, pathutils, parseutils
  33. from wordrecg import wDeprecated, wError, wAddr, wYield, specialWords
  34. when defined(nimsuggest):
  35. import passes, tables # 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.sons[0])
  45. if result != nil: return
  46. if n.len > 1:
  47. result = findDocComment(n.sons[1])
  48. elif n.kind in {nkAsgn, nkFastAsgn} and n.len == 2:
  49. result = findDocComment(n.sons[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.sons[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) =
  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 {.inject.} = item
  247. var pm {.inject.}: 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 ..< sonsLen(list):
  253. if list.sons[i].kind == nkSym:
  254. suggestField(c, list.sons[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 ..< sonsLen(n): suggestObject(c, n.sons[i], f, info, outputs)
  260. of nkRecCase:
  261. var L = sonsLen(n)
  262. if L > 0:
  263. suggestObject(c, n.sons[0], f, info, outputs)
  264. for i in 1 ..< L: suggestObject(c, lastSon(n.sons[i]), f, info, outputs)
  265. of nkSym: suggestField(c, n.sym, f, info, outputs)
  266. else: discard
  267. proc nameFits(c: PContext, s: PSym, n: PNode): bool =
  268. var op = n.sons[0]
  269. if op.kind in {nkOpenSymChoice, nkClosedSymChoice}: op = op.sons[0]
  270. var opr: PIdent
  271. case op.kind
  272. of nkSym: opr = op.sym.name
  273. of nkIdent: opr = op.ident
  274. else: return false
  275. result = opr.id == s.name.id
  276. proc argsFit(c: PContext, candidate: PSym, n, nOrig: PNode): bool =
  277. case candidate.kind
  278. of OverloadableSyms:
  279. var m: TCandidate
  280. initCandidate(c, m, candidate, nil)
  281. sigmatch.partialMatch(c, n, nOrig, m)
  282. result = m.state != csNoMatch
  283. else:
  284. result = false
  285. proc suggestCall(c: PContext, n, nOrig: PNode, outputs: var Suggestions) =
  286. let info = n.info
  287. wholeSymTab(filterSym(it, nil, pm) and nameFits(c, it, n) and argsFit(c, it, n, nOrig),
  288. ideCon)
  289. proc typeFits(c: PContext, s: PSym, firstArg: PType): bool {.inline.} =
  290. if s.typ != nil and sonsLen(s.typ) > 1 and s.typ.sons[1] != nil:
  291. # special rule: if system and some weird generic match via 'tyUntyped'
  292. # or 'tyGenericParam' we won't list it either to reduce the noise (nobody
  293. # wants 'system.`-|` as suggestion
  294. let m = s.getModule()
  295. if m != nil and sfSystemModule in m.flags:
  296. if s.kind == skType: return
  297. var exp = s.typ.sons[1].skipTypes({tyGenericInst, tyVar, tyLent, tyAlias, tySink})
  298. if exp.kind == tyVarargs: exp = elemType(exp)
  299. if exp.kind in {tyUntyped, tyTyped, tyGenericParam, tyAnything}: return
  300. result = sigmatch.argtypeMatches(c, s.typ.sons[1], firstArg)
  301. proc suggestOperations(c: PContext, n, f: PNode, typ: PType, outputs: var Suggestions) =
  302. assert typ != nil
  303. let info = n.info
  304. wholeSymTab(filterSymNoOpr(it, f, pm) and typeFits(c, it, typ), ideSug)
  305. proc suggestEverything(c: PContext, n, f: PNode, outputs: var Suggestions) =
  306. # do not produce too many symbols:
  307. var isLocal = true
  308. var scopeN = 0
  309. for scope in walkScopes(c.currentScope):
  310. if scope == c.topLevelScope: isLocal = false
  311. dec scopeN
  312. for it in items(scope.symbols):
  313. var pm: PrefixMatch
  314. if filterSym(it, f, pm):
  315. outputs.add(symToSuggest(c.config, it, isLocal = isLocal, ideSug, n.info, 0, pm,
  316. c.inTypeContext > 0, scopeN))
  317. #if scope == c.topLevelScope and f.isNil: break
  318. proc suggestFieldAccess(c: PContext, n, field: PNode, outputs: var Suggestions) =
  319. # special code that deals with ``myObj.``. `n` is NOT the nkDotExpr-node, but
  320. # ``myObj``.
  321. var typ = n.typ
  322. var pm: PrefixMatch
  323. when defined(nimsuggest):
  324. if n.kind == nkSym and n.sym.kind == skError and c.config.suggestVersion == 0:
  325. # consider 'foo.|' where 'foo' is some not imported module.
  326. let fullPath = findModule(c.config, n.sym.name.s, toFullPath(c.config, n.info))
  327. if fullPath.isEmpty:
  328. # error: no known module name:
  329. typ = nil
  330. else:
  331. let m = c.graph.importModuleCallback(c.graph, c.module, fileInfoIdx(c.config, fullpath))
  332. if m == nil: typ = nil
  333. else:
  334. for it in items(n.sym.tab):
  335. if filterSym(it, field, pm):
  336. outputs.add(symToSuggest(c.config, it, isLocal=false, ideSug, n.info, 100, pm, c.inTypeContext > 0, -100))
  337. outputs.add(symToSuggest(c.config, m, isLocal=false, ideMod, n.info, 100, PrefixMatch.None,
  338. c.inTypeContext > 0, -99))
  339. if typ == nil:
  340. # a module symbol has no type for example:
  341. if n.kind == nkSym and n.sym.kind == skModule:
  342. if n.sym == c.module:
  343. # all symbols accessible, because we are in the current module:
  344. for it in items(c.topLevelScope.symbols):
  345. if filterSym(it, field, pm):
  346. outputs.add(symToSuggest(c.config, it, isLocal=false, ideSug, n.info, 100, pm, c.inTypeContext > 0, -99))
  347. else:
  348. for it in items(n.sym.tab):
  349. if filterSym(it, field, pm):
  350. outputs.add(symToSuggest(c.config, it, isLocal=false, ideSug, n.info, 100, pm, c.inTypeContext > 0, -99))
  351. else:
  352. # fallback:
  353. suggestEverything(c, n, field, outputs)
  354. elif typ.kind == tyEnum and n.kind == nkSym and n.sym.kind == skType:
  355. # look up if the identifier belongs to the enum:
  356. var t = typ
  357. while t != nil:
  358. suggestSymList(c, t.n, field, n.info, outputs)
  359. t = t.sons[0]
  360. suggestOperations(c, n, field, typ, outputs)
  361. else:
  362. let orig = typ # skipTypes(typ, {tyGenericInst, tyAlias, tySink})
  363. typ = skipTypes(typ, {tyGenericInst, tyVar, tyLent, tyPtr, tyRef, tyAlias, tySink, tyOwned})
  364. if typ.kind == tyObject:
  365. var t = typ
  366. while true:
  367. suggestObject(c, t.n, field, n.info, outputs)
  368. if t.sons[0] == nil: break
  369. t = skipTypes(t.sons[0], skipPtrs)
  370. elif typ.kind == tyTuple and typ.n != nil:
  371. suggestSymList(c, typ.n, field, n.info, outputs)
  372. suggestOperations(c, n, field, orig, outputs)
  373. if typ != orig:
  374. suggestOperations(c, n, field, typ, outputs)
  375. type
  376. TCheckPointResult* = enum
  377. cpNone, cpFuzzy, cpExact
  378. proc inCheckpoint*(current, trackPos: TLineInfo): TCheckPointResult =
  379. if current.fileIndex == trackPos.fileIndex:
  380. if current.line == trackPos.line and
  381. abs(current.col-trackPos.col) < 4:
  382. return cpExact
  383. if current.line >= trackPos.line:
  384. return cpFuzzy
  385. proc isTracked*(current, trackPos: TLineInfo, tokenLen: int): bool =
  386. if current.fileIndex==trackPos.fileIndex and current.line==trackPos.line:
  387. let col = trackPos.col
  388. if col >= current.col and col <= current.col+tokenLen-1:
  389. return true
  390. when defined(nimsuggest):
  391. # Since TLineInfo defined a == operator that doesn't include the column,
  392. # we map TLineInfo to a unique int here for this lookup table:
  393. proc infoToInt(info: TLineInfo): int64 =
  394. info.fileIndex.int64 + info.line.int64 shl 32 + info.col.int64 shl 48
  395. proc addNoDup(s: PSym; info: TLineInfo) =
  396. # ensure nothing gets too slow:
  397. if s.allUsages.len > 500: return
  398. let infoAsInt = info.infoToInt
  399. for infoB in s.allUsages:
  400. if infoB.infoToInt == infoAsInt: return
  401. s.allUsages.add(info)
  402. proc findUsages(conf: ConfigRef; info: TLineInfo; s: PSym; usageSym: var PSym) =
  403. if conf.suggestVersion == 1:
  404. if usageSym == nil and isTracked(info, conf.m.trackPos, s.name.s.len):
  405. usageSym = s
  406. suggestResult(conf, symToSuggest(conf, s, isLocal=false, ideUse, info, 100, PrefixMatch.None, false, 0))
  407. elif s == usageSym:
  408. if conf.lastLineInfo != info:
  409. suggestResult(conf, symToSuggest(conf, s, isLocal=false, ideUse, info, 100, PrefixMatch.None, false, 0))
  410. conf.lastLineInfo = info
  411. when defined(nimsuggest):
  412. proc listUsages*(conf: ConfigRef; s: PSym) =
  413. #echo "usages ", len(s.allUsages)
  414. for info in s.allUsages:
  415. let x = if info == s.info and info.col == s.info.col: ideDef else: ideUse
  416. suggestResult(conf, symToSuggest(conf, s, isLocal=false, x, info, 100, PrefixMatch.None, false, 0))
  417. proc findDefinition(conf: ConfigRef; info: TLineInfo; s: PSym) =
  418. if s.isNil: return
  419. if isTracked(info, conf.m.trackPos, s.name.s.len):
  420. suggestResult(conf, symToSuggest(conf, s, isLocal=false, ideDef, info, 100, PrefixMatch.None, false, 0))
  421. suggestQuit()
  422. proc ensureIdx[T](x: var T, y: int) =
  423. if x.len <= y: x.setLen(y+1)
  424. proc ensureSeq[T](x: var seq[T]) =
  425. if x == nil: newSeq(x, 0)
  426. proc suggestSym*(conf: ConfigRef; info: TLineInfo; s: PSym; usageSym: var PSym; isDecl=true) {.inline.} =
  427. ## misnamed: should be 'symDeclared'
  428. when defined(nimsuggest):
  429. if conf.suggestVersion == 0:
  430. if s.allUsages.len == 0:
  431. s.allUsages = @[info]
  432. else:
  433. s.addNoDup(info)
  434. if conf.ideCmd == ideUse:
  435. findUsages(conf, info, s, usageSym)
  436. elif conf.ideCmd == ideDef:
  437. findDefinition(conf, info, s)
  438. elif conf.ideCmd == ideDus and s != nil:
  439. if isTracked(info, conf.m.trackPos, s.name.s.len):
  440. suggestResult(conf, symToSuggest(conf, s, isLocal=false, ideDef, info, 100, PrefixMatch.None, false, 0))
  441. findUsages(conf, info, s, usageSym)
  442. elif conf.ideCmd == ideHighlight and info.fileIndex == conf.m.trackPos.fileIndex:
  443. suggestResult(conf, symToSuggest(conf, s, isLocal=false, ideHighlight, info, 100, PrefixMatch.None, false, 0))
  444. elif conf.ideCmd == ideOutline and info.fileIndex == conf.m.trackPos.fileIndex and
  445. isDecl:
  446. suggestResult(conf, symToSuggest(conf, s, isLocal=false, ideOutline, info, 100, PrefixMatch.None, false, 0))
  447. proc extractPragma(s: PSym): PNode =
  448. if s.kind in routineKinds:
  449. result = s.ast[pragmasPos]
  450. elif s.kind in {skType, skVar, skLet} and s.ast[0].kind == nkPragmaExpr:
  451. # s.ast = nkTypedef / nkPragmaExpr / [nkSym, nkPragma]
  452. result = s.ast[0][1]
  453. doAssert result == nil or result.kind == nkPragma
  454. proc warnAboutDeprecated(conf: ConfigRef; info: TLineInfo; s: PSym) =
  455. var pragmaNode: PNode
  456. if optOldAst in conf.options and s.kind in {skVar, skLet}:
  457. pragmaNode = nil
  458. else:
  459. pragmaNode = if s.kind == skEnumField: extractPragma(s.owner) else: extractPragma(s)
  460. let name =
  461. if s.kind == skEnumField and sfDeprecated notin s.flags: "enum '" & s.owner.name.s & "' which contains field '" & s.name.s & "'"
  462. else: s.name.s
  463. if pragmaNode != nil:
  464. for it in pragmaNode:
  465. if whichPragma(it) == wDeprecated and it.safeLen == 2 and
  466. it[1].kind in {nkStrLit..nkTripleStrLit}:
  467. message(conf, info, warnDeprecated, it[1].strVal & "; " & name & " is deprecated")
  468. return
  469. message(conf, info, warnDeprecated, name & " is deprecated")
  470. proc userError(conf: ConfigRef; info: TLineInfo; s: PSym) =
  471. let pragmaNode = extractPragma(s)
  472. if pragmaNode != nil:
  473. for it in pragmaNode:
  474. if whichPragma(it) == wError and it.safeLen == 2 and
  475. it[1].kind in {nkStrLit..nkTripleStrLit}:
  476. localError(conf, info, it[1].strVal & "; usage of '$1' is a user-defined error" % s.name.s)
  477. return
  478. localError(conf, info, "usage of '$1' is a user-defined error" % s.name.s)
  479. proc markUsed(conf: ConfigRef; info: TLineInfo; s: PSym; usageSym: var PSym) =
  480. incl(s.flags, sfUsed)
  481. if s.kind == skEnumField and s.owner != nil:
  482. incl(s.owner.flags, sfUsed)
  483. if sfDeprecated in s.owner.flags:
  484. warnAboutDeprecated(conf, info, s)
  485. if {sfDeprecated, sfError} * s.flags != {}:
  486. if sfDeprecated in s.flags: warnAboutDeprecated(conf, info, s)
  487. if sfError in s.flags: userError(conf, info, s)
  488. when defined(nimsuggest):
  489. suggestSym(conf, info, s, usageSym, false)
  490. proc safeSemExpr*(c: PContext, n: PNode): PNode =
  491. # use only for idetools support!
  492. try:
  493. result = c.semExpr(c, n)
  494. except ERecoverableError:
  495. result = c.graph.emptyNode
  496. proc sugExpr(c: PContext, n: PNode, outputs: var Suggestions) =
  497. if n.kind == nkDotExpr:
  498. var obj = safeSemExpr(c, n.sons[0])
  499. # it can happen that errnously we have collected the fieldname
  500. # of the next line, so we check the 'field' is actually on the same
  501. # line as the object to prevent this from happening:
  502. let prefix = if n.len == 2 and n[1].info.line == n[0].info.line and
  503. not c.config.m.trackPosAttached: n[1] else: nil
  504. suggestFieldAccess(c, obj, prefix, outputs)
  505. #if optIdeDebug in gGlobalOptions:
  506. # echo "expression ", renderTree(obj), " has type ", typeToString(obj.typ)
  507. #writeStackTrace()
  508. else:
  509. let prefix = if c.config.m.trackPosAttached: nil else: n
  510. suggestEverything(c, n, prefix, outputs)
  511. proc suggestExprNoCheck*(c: PContext, n: PNode) =
  512. # This keeps semExpr() from coming here recursively:
  513. if c.compilesContextId > 0: return
  514. inc(c.compilesContextId)
  515. var outputs: Suggestions = @[]
  516. if c.config.ideCmd == ideSug:
  517. sugExpr(c, n, outputs)
  518. elif c.config.ideCmd == ideCon:
  519. if n.kind in nkCallKinds:
  520. var a = copyNode(n)
  521. var x = safeSemExpr(c, n.sons[0])
  522. if x.kind == nkEmpty or x.typ == nil: x = n.sons[0]
  523. addSon(a, x)
  524. for i in 1..sonsLen(n)-1:
  525. # use as many typed arguments as possible:
  526. var x = safeSemExpr(c, n.sons[i])
  527. if x.kind == nkEmpty or x.typ == nil: break
  528. addSon(a, x)
  529. suggestCall(c, a, n, outputs)
  530. dec(c.compilesContextId)
  531. if outputs.len > 0 and c.config.ideCmd in {ideSug, ideCon, ideDef}:
  532. produceOutput(outputs, c.config)
  533. suggestQuit()
  534. proc suggestExpr*(c: PContext, n: PNode) =
  535. if exactEquals(c.config.m.trackPos, n.info): suggestExprNoCheck(c, n)
  536. proc suggestDecl*(c: PContext, n: PNode; s: PSym) =
  537. let attached = c.config.m.trackPosAttached
  538. if attached: inc(c.inTypeContext)
  539. defer:
  540. if attached: dec(c.inTypeContext)
  541. suggestExpr(c, n)
  542. proc suggestStmt*(c: PContext, n: PNode) =
  543. suggestExpr(c, n)
  544. proc suggestEnum*(c: PContext; n: PNode; t: PType) =
  545. var outputs: Suggestions = @[]
  546. suggestSymList(c, t.n, nil, n.info, outputs)
  547. produceOutput(outputs, c.config)
  548. if outputs.len > 0: suggestQuit()
  549. proc suggestSentinel*(c: PContext) =
  550. if c.config.ideCmd != ideSug or c.module.position != c.config.m.trackPos.fileIndex.int32: return
  551. if c.compilesContextId > 0: return
  552. inc(c.compilesContextId)
  553. var outputs: Suggestions = @[]
  554. # suggest everything:
  555. var isLocal = true
  556. var scopeN = 0
  557. for scope in walkScopes(c.currentScope):
  558. if scope == c.topLevelScope: isLocal = false
  559. dec scopeN
  560. for it in items(scope.symbols):
  561. var pm: PrefixMatch
  562. if filterSymNoOpr(it, nil, pm):
  563. outputs.add(symToSuggest(c.config, it, isLocal = isLocal, ideSug,
  564. newLineInfo(c.config.m.trackPos.fileIndex, -1, -1), 0,
  565. PrefixMatch.None, false, scopeN))
  566. dec(c.compilesContextId)
  567. produceOutput(outputs, c.config)