suggest.nim 27 KB

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