sempass2.nim 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  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. import
  10. ast, astalgo, msgs, renderer, magicsys, types, idents, trees,
  11. wordrecg, options, guards, lineinfos, semfold, semdata,
  12. modulegraphs, varpartitions, typeallowed, nilcheck, errorhandling,
  13. semstrictfuncs, suggestsymdb
  14. import std/[tables, intsets, strutils, sequtils]
  15. when defined(nimPreviewSlimSystem):
  16. import std/assertions
  17. when defined(useDfa):
  18. import dfa
  19. import liftdestructors
  20. include sinkparameter_inference
  21. #[ Second semantic checking pass over the AST. Necessary because the old
  22. way had some inherent problems. Performs:
  23. * effect+exception tracking
  24. * "usage before definition" checking
  25. * also now calls the "lift destructor logic" at strategic positions, this
  26. is about to be put into the spec:
  27. We treat assignment and sinks and destruction as identical.
  28. In the construct let/var x = expr() x's type is marked.
  29. In x = y the type of x is marked.
  30. For every sink parameter of type T T is marked.
  31. For every call f() the return type of f() is marked.
  32. ]#
  33. # ------------------------ exception and tag tracking -------------------------
  34. discard """
  35. exception tracking:
  36. a() # raises 'x', 'e'
  37. try:
  38. b() # raises 'e'
  39. except e:
  40. # must not undo 'e' here; hrm
  41. c()
  42. --> we need a stack of scopes for this analysis
  43. # XXX enhance the algorithm to care about 'dirty' expressions:
  44. lock a[i].L:
  45. inc i # mark 'i' dirty
  46. lock a[j].L:
  47. access a[i], a[j] # --> reject a[i]
  48. """
  49. type
  50. CaughtExceptionsStack = object
  51. nodes: seq[seq[PType]]
  52. TEffects = object
  53. exc: PNode # stack of exceptions
  54. when defined(nimsuggest):
  55. caughtExceptions: CaughtExceptionsStack
  56. tags: PNode # list of tags
  57. forbids: PNode # list of tags
  58. bottom, inTryStmt, inExceptOrFinallyStmt, leftPartOfAsgn, inIfStmt, currentBlock: int
  59. owner: PSym
  60. ownerModule: PSym
  61. init: seq[int] # list of initialized variables
  62. scopes: Table[int, int] # maps var-id to its scope (see also `currentBlock`).
  63. guards: TModel # nested guards
  64. locked: seq[PNode] # locked locations
  65. gcUnsafe, isRecursive, isTopLevel, hasSideEffect, inEnforcedGcSafe: bool
  66. isInnerProc: bool
  67. inEnforcedNoSideEffects: bool
  68. currOptions: TOptions
  69. config: ConfigRef
  70. graph: ModuleGraph
  71. c: PContext
  72. escapingParams: IntSet
  73. PEffects = var TEffects
  74. const
  75. errXCannotBeAssignedTo = "'$1' cannot be assigned to"
  76. errLetNeedsInit = "'let' symbol requires an initialization"
  77. proc getObjDepth(t: PType): (int, ItemId) =
  78. var x = t
  79. result = (-1, default(ItemId))
  80. var stack = newSeq[ItemId]()
  81. while x != nil:
  82. x = skipTypes(x, skipPtrs)
  83. if x.kind != tyObject:
  84. return (-3, default(ItemId))
  85. stack.add x.itemId
  86. x = x.baseClass
  87. inc(result[0])
  88. result[1] = stack[^2]
  89. proc collectObjectTree(graph: ModuleGraph, n: PNode) =
  90. for section in n:
  91. if section.kind == nkTypeDef and section[^1].kind in {nkObjectTy, nkRefTy, nkPtrTy} and section[^1].typ != nil:
  92. let typ = section[^1].typ.skipTypes(skipPtrs)
  93. if typ.kind == tyObject and typ.baseClass != nil:
  94. let (depthLevel, root) = getObjDepth(typ)
  95. if depthLevel != -3:
  96. if depthLevel == 1:
  97. graph.objectTree[root] = @[]
  98. else:
  99. if root notin graph.objectTree:
  100. graph.objectTree[root] = @[(depthLevel, typ)]
  101. else:
  102. graph.objectTree[root].add (depthLevel, typ)
  103. proc createTypeBoundOps(tracked: PEffects, typ: PType; info: TLineInfo) =
  104. if typ == nil or sfGeneratedOp in tracked.owner.flags:
  105. # don't create type bound ops for anything in a function with a `nodestroy` pragma
  106. # bug #21987
  107. return
  108. when false:
  109. let realType = typ.skipTypes(abstractInst)
  110. if realType.kind == tyRef and
  111. optSeqDestructors in tracked.config.globalOptions:
  112. createTypeBoundOps(tracked.graph, tracked.c, realType.lastSon, info)
  113. createTypeBoundOps(tracked.graph, tracked.c, typ, info, tracked.c.idgen)
  114. if tracked.config.selectedGC == gcRefc or
  115. optSeqDestructors in tracked.config.globalOptions or
  116. tfHasAsgn in typ.flags:
  117. tracked.owner.flags.incl sfInjectDestructors
  118. proc isLocalSym(a: PEffects, s: PSym): bool =
  119. s.typ != nil and (s.kind in {skLet, skVar, skResult} or (s.kind == skParam and isOutParam(s.typ))) and
  120. sfGlobal notin s.flags and s.owner == a.owner
  121. proc lockLocations(a: PEffects; pragma: PNode) =
  122. if pragma.kind != nkExprColonExpr:
  123. localError(a.config, pragma.info, "locks pragma without argument")
  124. return
  125. for x in pragma[1]:
  126. a.locked.add x
  127. proc guardGlobal(a: PEffects; n: PNode; guard: PSym) =
  128. # check whether the corresponding lock is held:
  129. for L in a.locked:
  130. if L.kind == nkSym and L.sym == guard: return
  131. # we allow accesses nevertheless in top level statements for
  132. # easier initialization:
  133. #if a.isTopLevel:
  134. # message(a.config, n.info, warnUnguardedAccess, renderTree(n))
  135. #else:
  136. if not a.isTopLevel:
  137. localError(a.config, n.info, "unguarded access: " & renderTree(n))
  138. # 'guard*' are checks which are concerned with 'guard' annotations
  139. # (var x{.guard: y.}: int)
  140. proc guardDotAccess(a: PEffects; n: PNode) =
  141. let ri = n[1]
  142. if ri.kind != nkSym or ri.sym.kind != skField: return
  143. var g = ri.sym.guard
  144. if g.isNil or a.isTopLevel: return
  145. # fixup guard:
  146. if g.kind == skUnknown:
  147. var field: PSym = nil
  148. var ty = n[0].typ.skipTypes(abstractPtrs)
  149. if ty.kind == tyTuple and not ty.n.isNil:
  150. field = lookupInRecord(ty.n, g.name)
  151. else:
  152. while ty != nil and ty.kind == tyObject:
  153. field = lookupInRecord(ty.n, g.name)
  154. if field != nil: break
  155. ty = ty[0]
  156. if ty == nil: break
  157. ty = ty.skipTypes(skipPtrs)
  158. if field == nil:
  159. localError(a.config, n.info, "invalid guard field: " & g.name.s)
  160. return
  161. g = field
  162. #ri.sym.guard = field
  163. # XXX unfortunately this is not correct for generic instantiations!
  164. if g.kind == skField:
  165. let dot = newNodeI(nkDotExpr, n.info, 2)
  166. dot[0] = n[0]
  167. dot[1] = newSymNode(g)
  168. dot.typ = g.typ
  169. for L in a.locked:
  170. #if a.guards.sameSubexprs(dot, L): return
  171. if guards.sameTree(dot, L): return
  172. localError(a.config, n.info, "unguarded access: " & renderTree(n))
  173. else:
  174. guardGlobal(a, n, g)
  175. proc makeVolatile(a: PEffects; s: PSym) {.inline.} =
  176. if a.inTryStmt > 0 and a.config.exc == excSetjmp:
  177. incl(s.flags, sfVolatile)
  178. proc varDecl(a: PEffects; n: PNode) {.inline.} =
  179. if n.kind == nkSym:
  180. a.scopes[n.sym.id] = a.currentBlock
  181. proc skipHiddenDeref(n: PNode): PNode {.inline.} =
  182. result = if n.kind == nkHiddenDeref: n[0] else: n
  183. proc initVar(a: PEffects, n: PNode; volatileCheck: bool) =
  184. let n = skipHiddenDeref(n)
  185. if n.kind != nkSym: return
  186. let s = n.sym
  187. if isLocalSym(a, s):
  188. if volatileCheck: makeVolatile(a, s)
  189. for x in a.init:
  190. if x == s.id:
  191. if strictDefs in a.c.features and s.kind == skLet:
  192. localError(a.config, n.info, errXCannotBeAssignedTo %
  193. renderTree(n, {renderNoComments}
  194. ))
  195. return
  196. a.init.add s.id
  197. if a.scopes.getOrDefault(s.id) == a.currentBlock:
  198. #[ Consider this case:
  199. var x: T
  200. while true:
  201. if cond:
  202. x = T() #1
  203. else:
  204. x = T() #2
  205. use x
  206. Even though both #1 and #2 are first writes we must use the `=copy`
  207. here so that the old value is destroyed because `x`'s destructor is
  208. run outside of the while loop. This is why we need the check here that
  209. the assignment is done in the same logical block as `x` was declared in.
  210. ]#
  211. n.flags.incl nfFirstWrite
  212. proc initVarViaNew(a: PEffects, n: PNode) =
  213. let n = skipHiddenDeref(n)
  214. if n.kind != nkSym: return
  215. let s = n.sym
  216. if {tfRequiresInit, tfNotNil} * s.typ.flags <= {tfNotNil}:
  217. # 'x' is not nil, but that doesn't mean its "not nil" children
  218. # are initialized:
  219. initVar(a, n, volatileCheck=true)
  220. elif isLocalSym(a, s):
  221. makeVolatile(a, s)
  222. proc warnAboutGcUnsafe(n: PNode; conf: ConfigRef) =
  223. #assert false
  224. message(conf, n.info, warnGcUnsafe, renderTree(n))
  225. proc markGcUnsafe(a: PEffects; reason: PSym) =
  226. if not a.inEnforcedGcSafe:
  227. a.gcUnsafe = true
  228. if a.owner.kind in routineKinds: a.owner.gcUnsafetyReason = reason
  229. proc markGcUnsafe(a: PEffects; reason: PNode) =
  230. if not a.inEnforcedGcSafe:
  231. a.gcUnsafe = true
  232. if a.owner.kind in routineKinds:
  233. if reason.kind == nkSym:
  234. a.owner.gcUnsafetyReason = reason.sym
  235. else:
  236. a.owner.gcUnsafetyReason = newSym(skUnknown, a.owner.name, a.c.idgen,
  237. a.owner, reason.info, {})
  238. proc markSideEffect(a: PEffects; reason: PNode | PSym; useLoc: TLineInfo) =
  239. if not a.inEnforcedNoSideEffects:
  240. a.hasSideEffect = true
  241. if a.owner.kind in routineKinds:
  242. var sym: PSym
  243. when reason is PNode:
  244. if reason.kind == nkSym:
  245. sym = reason.sym
  246. else:
  247. let kind = if reason.kind == nkHiddenDeref: skParam else: skUnknown
  248. sym = newSym(kind, a.owner.name, a.c.idgen, a.owner, reason.info, {})
  249. else:
  250. sym = reason
  251. a.c.sideEffects.mgetOrPut(a.owner.id, @[]).add (useLoc, sym)
  252. when false: markGcUnsafe(a, reason)
  253. proc listGcUnsafety(s: PSym; onlyWarning: bool; cycleCheck: var IntSet; conf: ConfigRef) =
  254. let u = s.gcUnsafetyReason
  255. if u != nil and not cycleCheck.containsOrIncl(u.id):
  256. let msgKind = if onlyWarning: warnGcUnsafe2 else: errGenerated
  257. case u.kind
  258. of skLet, skVar:
  259. if u.typ.skipTypes(abstractInst).kind == tyProc:
  260. message(conf, s.info, msgKind,
  261. "'$#' is not GC-safe as it calls '$#'" %
  262. [s.name.s, u.name.s])
  263. else:
  264. message(conf, s.info, msgKind,
  265. ("'$#' is not GC-safe as it accesses '$#'" &
  266. " which is a global using GC'ed memory") % [s.name.s, u.name.s])
  267. of routineKinds:
  268. # recursive call *always* produces only a warning so the full error
  269. # message is printed:
  270. if u.kind == skMethod and {sfBase, sfThread} * u.flags == {sfBase}:
  271. message(conf, u.info, msgKind,
  272. "Base method '$#' requires explicit '{.gcsafe.}' to be GC-safe" %
  273. [u.name.s])
  274. else:
  275. listGcUnsafety(u, true, cycleCheck, conf)
  276. message(conf, s.info, msgKind,
  277. "'$#' is not GC-safe as it calls '$#'" %
  278. [s.name.s, u.name.s])
  279. of skParam, skForVar:
  280. message(conf, s.info, msgKind,
  281. "'$#' is not GC-safe as it performs an indirect call via '$#'" %
  282. [s.name.s, u.name.s])
  283. else:
  284. message(conf, u.info, msgKind,
  285. "'$#' is not GC-safe as it performs an indirect call here" % s.name.s)
  286. proc listGcUnsafety(s: PSym; onlyWarning: bool; conf: ConfigRef) =
  287. var cycleCheck = initIntSet()
  288. listGcUnsafety(s, onlyWarning, cycleCheck, conf)
  289. proc listSideEffects(result: var string; s: PSym; cycleCheck: var IntSet;
  290. conf: ConfigRef; context: PContext; indentLevel: int) =
  291. template addHint(msg; lineInfo; sym; level = indentLevel) =
  292. result.addf("$# $# Hint: '$#' $#\n", repeat(">", level), conf $ lineInfo, sym, msg)
  293. if context.sideEffects.hasKey(s.id):
  294. for (useLineInfo, u) in context.sideEffects[s.id]:
  295. if u != nil and not cycleCheck.containsOrIncl(u.id):
  296. case u.kind
  297. of skLet, skVar:
  298. addHint("accesses global state '$#'" % u.name.s, useLineInfo, s.name.s)
  299. addHint("accessed by '$#'" % s.name.s, u.info, u.name.s, indentLevel + 1)
  300. of routineKinds:
  301. addHint("calls `.sideEffect` '$#'" % u.name.s, useLineInfo, s.name.s)
  302. addHint("called by '$#'" % s.name.s, u.info, u.name.s, indentLevel + 1)
  303. listSideEffects(result, u, cycleCheck, conf, context, indentLevel + 2)
  304. of skParam, skForVar:
  305. addHint("calls routine via hidden pointer indirection", useLineInfo, s.name.s)
  306. else:
  307. addHint("calls routine via pointer indirection", useLineInfo, s.name.s)
  308. proc listSideEffects(result: var string; s: PSym; conf: ConfigRef; context: PContext) =
  309. var cycleCheck = initIntSet()
  310. result.addf("'$#' can have side effects\n", s.name.s)
  311. listSideEffects(result, s, cycleCheck, conf, context, 1)
  312. proc useVarNoInitCheck(a: PEffects; n: PNode; s: PSym) =
  313. if {sfGlobal, sfThread} * s.flags != {} and s.kind in {skVar, skLet} and
  314. s.magic != mNimvm:
  315. if s.guard != nil: guardGlobal(a, n, s.guard)
  316. if {sfGlobal, sfThread} * s.flags == {sfGlobal} and
  317. (tfHasGCedMem in s.typ.flags or s.typ.isGCedMem):
  318. #if a.config.hasWarn(warnGcUnsafe): warnAboutGcUnsafe(n)
  319. markGcUnsafe(a, s)
  320. markSideEffect(a, s, n.info)
  321. if s.owner != a.owner and s.kind in {skVar, skLet, skForVar, skResult, skParam} and
  322. {sfGlobal, sfThread} * s.flags == {}:
  323. a.isInnerProc = true
  324. proc useVar(a: PEffects, n: PNode) =
  325. let s = n.sym
  326. if a.inExceptOrFinallyStmt > 0:
  327. incl s.flags, sfUsedInFinallyOrExcept
  328. if isLocalSym(a, s):
  329. if sfNoInit in s.flags:
  330. # If the variable is explicitly marked as .noinit. do not emit any error
  331. a.init.add s.id
  332. elif s.id notin a.init:
  333. if s.typ.requiresInit:
  334. message(a.config, n.info, warnProveInit, s.name.s)
  335. elif a.leftPartOfAsgn <= 0:
  336. if strictDefs in a.c.features:
  337. if s.kind == skLet:
  338. localError(a.config, n.info, errLetNeedsInit)
  339. else:
  340. message(a.config, n.info, warnUninit, s.name.s)
  341. # prevent superfluous warnings about the same variable:
  342. a.init.add s.id
  343. useVarNoInitCheck(a, n, s)
  344. type
  345. BreakState = enum
  346. bsNone
  347. bsBreakOrReturn
  348. bsNoReturn
  349. type
  350. TIntersection = seq[tuple[id, count: int]] # a simple count table
  351. proc addToIntersection(inter: var TIntersection, s: int, state: BreakState) =
  352. for j in 0..<inter.len:
  353. if s == inter[j].id:
  354. if state == bsNone:
  355. inc inter[j].count
  356. return
  357. if state == bsNone:
  358. inter.add((id: s, count: 1))
  359. else:
  360. inter.add((id: s, count: 0))
  361. proc throws(tracked, n, orig: PNode) =
  362. if n.typ == nil or n.typ.kind != tyError:
  363. if orig != nil:
  364. let x = copyTree(orig)
  365. x.typ = n.typ
  366. tracked.add x
  367. else:
  368. tracked.add n
  369. proc getEbase*(g: ModuleGraph; info: TLineInfo): PType =
  370. result = g.sysTypeFromName(info, "Exception")
  371. proc excType(g: ModuleGraph; n: PNode): PType =
  372. # reraise is like raising E_Base:
  373. let t = if n.kind == nkEmpty or n.typ.isNil: getEbase(g, n.info) else: n.typ
  374. result = skipTypes(t, skipPtrs)
  375. proc createRaise(g: ModuleGraph; n: PNode): PNode =
  376. result = newNode(nkType)
  377. result.typ = getEbase(g, n.info)
  378. if not n.isNil: result.info = n.info
  379. proc createTag(g: ModuleGraph; n: PNode): PNode =
  380. result = newNode(nkType)
  381. result.typ = g.sysTypeFromName(n.info, "RootEffect")
  382. if not n.isNil: result.info = n.info
  383. proc addRaiseEffect(a: PEffects, e, comesFrom: PNode) =
  384. #assert e.kind != nkRaiseStmt
  385. var aa = a.exc
  386. for i in a.bottom..<aa.len:
  387. # we only track the first node that can have the effect E in order
  388. # to safe space and time.
  389. if sameType(a.graph.excType(aa[i]), a.graph.excType(e)): return
  390. if e.typ != nil:
  391. if not isDefectException(e.typ):
  392. throws(a.exc, e, comesFrom)
  393. proc addTag(a: PEffects, e, comesFrom: PNode) =
  394. var aa = a.tags
  395. for i in 0..<aa.len:
  396. # we only track the first node that can have the effect E in order
  397. # to safe space and time.
  398. if sameType(aa[i].typ.skipTypes(skipPtrs), e.typ.skipTypes(skipPtrs)): return
  399. throws(a.tags, e, comesFrom)
  400. proc addNotTag(a: PEffects, e, comesFrom: PNode) =
  401. var aa = a.forbids
  402. for i in 0..<aa.len:
  403. if sameType(aa[i].typ.skipTypes(skipPtrs), e.typ.skipTypes(skipPtrs)): return
  404. throws(a.forbids, e, comesFrom)
  405. proc mergeRaises(a: PEffects, b, comesFrom: PNode) =
  406. if b.isNil:
  407. addRaiseEffect(a, createRaise(a.graph, comesFrom), comesFrom)
  408. else:
  409. for effect in items(b): addRaiseEffect(a, effect, comesFrom)
  410. proc mergeTags(a: PEffects, b, comesFrom: PNode) =
  411. if b.isNil:
  412. addTag(a, createTag(a.graph, comesFrom), comesFrom)
  413. else:
  414. for effect in items(b): addTag(a, effect, comesFrom)
  415. proc listEffects(a: PEffects) =
  416. for e in items(a.exc): message(a.config, e.info, hintUser, typeToString(e.typ))
  417. for e in items(a.tags): message(a.config, e.info, hintUser, typeToString(e.typ))
  418. for e in items(a.forbids): message(a.config, e.info, hintUser, typeToString(e.typ))
  419. proc catches(tracked: PEffects, e: PType) =
  420. let e = skipTypes(e, skipPtrs)
  421. var L = tracked.exc.len
  422. var i = tracked.bottom
  423. while i < L:
  424. # r supertype of e?
  425. if safeInheritanceDiff(tracked.graph.excType(tracked.exc[i]), e) <= 0:
  426. tracked.exc[i] = tracked.exc[L-1]
  427. dec L
  428. else:
  429. inc i
  430. if tracked.exc.len > 0:
  431. setLen(tracked.exc.sons, L)
  432. else:
  433. assert L == 0
  434. proc catchesAll(tracked: PEffects) =
  435. if tracked.exc.len > 0:
  436. setLen(tracked.exc.sons, tracked.bottom)
  437. proc push(s: var CaughtExceptionsStack) =
  438. s.nodes.add(@[])
  439. proc pop(s: var CaughtExceptionsStack) =
  440. s.nodes.del(high(s.nodes))
  441. proc addCatch(s: var CaughtExceptionsStack, e: PType) =
  442. s.nodes[high(s.nodes)].add(e)
  443. proc addCatchAll(s: var CaughtExceptionsStack) =
  444. s.nodes[high(s.nodes)].add(nil)
  445. proc track(tracked: PEffects, n: PNode)
  446. proc trackTryStmt(tracked: PEffects, n: PNode) =
  447. let oldBottom = tracked.bottom
  448. tracked.bottom = tracked.exc.len
  449. let oldState = tracked.init.len
  450. var inter: TIntersection = @[]
  451. when defined(nimsuggest):
  452. tracked.caughtExceptions.push
  453. for i in 1..<n.len:
  454. let b = n[i]
  455. if b.kind == nkExceptBranch:
  456. if b.len == 1:
  457. tracked.caughtExceptions.addCatchAll
  458. else:
  459. for j in 0..<b.len - 1:
  460. if b[j].isInfixAs():
  461. assert(b[j][1].kind == nkType)
  462. tracked.caughtExceptions.addCatch(b[j][1].typ)
  463. else:
  464. assert(b[j].kind == nkType)
  465. tracked.caughtExceptions.addCatch(b[j].typ)
  466. else:
  467. assert b.kind == nkFinally
  468. inc tracked.inTryStmt
  469. track(tracked, n[0])
  470. dec tracked.inTryStmt
  471. for i in oldState..<tracked.init.len:
  472. addToIntersection(inter, tracked.init[i], bsNone)
  473. when defined(nimsuggest):
  474. tracked.caughtExceptions.pop
  475. var branches = 1
  476. var hasFinally = false
  477. inc tracked.inExceptOrFinallyStmt
  478. # Collect the exceptions caught by the except branches
  479. for i in 1..<n.len:
  480. let b = n[i]
  481. if b.kind == nkExceptBranch:
  482. inc branches
  483. if b.len == 1:
  484. catchesAll(tracked)
  485. else:
  486. for j in 0..<b.len - 1:
  487. if b[j].isInfixAs():
  488. assert(b[j][1].kind == nkType)
  489. catches(tracked, b[j][1].typ)
  490. createTypeBoundOps(tracked, b[j][2].typ, b[j][2].info)
  491. else:
  492. assert(b[j].kind == nkType)
  493. catches(tracked, b[j].typ)
  494. else:
  495. assert b.kind == nkFinally
  496. # Add any other exception raised in the except bodies
  497. for i in 1..<n.len:
  498. let b = n[i]
  499. if b.kind == nkExceptBranch:
  500. setLen(tracked.init, oldState)
  501. for j in 0..<b.len - 1:
  502. if b[j].isInfixAs(): # skips initialization checks
  503. assert(b[j][2].kind == nkSym)
  504. tracked.init.add b[j][2].sym.id
  505. track(tracked, b[^1])
  506. for i in oldState..<tracked.init.len:
  507. addToIntersection(inter, tracked.init[i], bsNone)
  508. else:
  509. setLen(tracked.init, oldState)
  510. track(tracked, b[^1])
  511. hasFinally = true
  512. tracked.bottom = oldBottom
  513. dec tracked.inExceptOrFinallyStmt
  514. if not hasFinally:
  515. setLen(tracked.init, oldState)
  516. for id, count in items(inter):
  517. if count == branches: tracked.init.add id
  518. proc isIndirectCall(tracked: PEffects; n: PNode): bool =
  519. # we don't count f(...) as an indirect call if 'f' is an parameter.
  520. # Instead we track expressions of type tyProc too. See the manual for
  521. # details:
  522. if n.kind != nkSym:
  523. result = true
  524. elif n.sym.kind == skParam:
  525. if laxEffects notin tracked.c.config.legacyFeatures:
  526. if tracked.owner == n.sym.owner and sfEffectsDelayed in n.sym.flags:
  527. result = false # it is not a harmful call
  528. else:
  529. result = true
  530. else:
  531. result = tracked.owner != n.sym.owner or tracked.owner == nil
  532. elif n.sym.kind notin routineKinds:
  533. result = true
  534. else:
  535. result = false
  536. proc isForwardedProc(n: PNode): bool =
  537. result = n.kind == nkSym and sfForward in n.sym.flags
  538. proc trackPragmaStmt(tracked: PEffects, n: PNode) =
  539. for i in 0..<n.len:
  540. var it = n[i]
  541. let pragma = whichPragma(it)
  542. if pragma == wEffects:
  543. # list the computed effects up to here:
  544. listEffects(tracked)
  545. template notGcSafe(t): untyped = {tfGcSafe, tfNoSideEffect} * t.flags == {}
  546. proc importedFromC(n: PNode): bool =
  547. # when imported from C, we assume GC-safety.
  548. result = n.kind == nkSym and sfImportc in n.sym.flags
  549. proc propagateEffects(tracked: PEffects, n: PNode, s: PSym) =
  550. let pragma = s.ast[pragmasPos]
  551. let spec = effectSpec(pragma, wRaises)
  552. mergeRaises(tracked, spec, n)
  553. let tagSpec = effectSpec(pragma, wTags)
  554. mergeTags(tracked, tagSpec, n)
  555. if notGcSafe(s.typ) and sfImportc notin s.flags:
  556. if tracked.config.hasWarn(warnGcUnsafe): warnAboutGcUnsafe(n, tracked.config)
  557. markGcUnsafe(tracked, s)
  558. if tfNoSideEffect notin s.typ.flags:
  559. markSideEffect(tracked, s, n.info)
  560. proc procVarCheck(n: PNode; conf: ConfigRef) =
  561. if n.kind in nkSymChoices:
  562. for x in n: procVarCheck(x, conf)
  563. elif n.kind == nkSym and n.sym.magic != mNone and n.sym.kind in routineKinds:
  564. localError(conf, n.info, ("'$1' is a built-in and cannot be used as " &
  565. "a first-class procedure") % n.sym.name.s)
  566. proc notNilCheck(tracked: PEffects, n: PNode, paramType: PType) =
  567. let n = n.skipConv
  568. if paramType.isNil or paramType.kind != tyTypeDesc:
  569. procVarCheck skipConvCastAndClosure(n), tracked.config
  570. #elif n.kind in nkSymChoices:
  571. # echo "came here"
  572. let paramType = paramType.skipTypesOrNil(abstractInst)
  573. if paramType != nil and tfNotNil in paramType.flags and n.typ != nil:
  574. let ntyp = n.typ.skipTypesOrNil({tyVar, tyLent, tySink})
  575. if ntyp != nil and tfNotNil notin ntyp.flags:
  576. if n.kind in {nkAddr, nkHiddenAddr}:
  577. # addr(x[]) can't be proven, but addr(x) can:
  578. if not containsNode(n, {nkDerefExpr, nkHiddenDeref}): return
  579. elif (n.kind == nkSym and n.sym.kind in routineKinds) or
  580. (n.kind in procDefs+{nkObjConstr, nkBracket, nkClosure, nkStrLit..nkTripleStrLit}) or
  581. (n.kind in nkCallKinds and n[0].kind == nkSym and n[0].sym.magic == mArrToSeq) or
  582. n.typ.kind == tyTypeDesc:
  583. # 'p' is not nil obviously:
  584. return
  585. case impliesNotNil(tracked.guards, n)
  586. of impUnknown:
  587. message(tracked.config, n.info, errGenerated,
  588. "cannot prove '$1' is not nil" % n.renderTree)
  589. of impNo:
  590. message(tracked.config, n.info, errGenerated,
  591. "'$1' is provably nil" % n.renderTree)
  592. of impYes: discard
  593. proc assumeTheWorst(tracked: PEffects; n: PNode; op: PType) =
  594. addRaiseEffect(tracked, createRaise(tracked.graph, n), nil)
  595. addTag(tracked, createTag(tracked.graph, n), nil)
  596. proc isOwnedProcVar(tracked: PEffects; n: PNode): bool =
  597. # XXX prove the soundness of this effect system rule
  598. result = n.kind == nkSym and n.sym.kind == skParam and
  599. tracked.owner == n.sym.owner
  600. #if result and sfPolymorphic notin n.sym.flags:
  601. # echo tracked.config $ n.info, " different here!"
  602. if laxEffects notin tracked.c.config.legacyFeatures:
  603. result = result and sfEffectsDelayed in n.sym.flags
  604. proc isNoEffectList(n: PNode): bool {.inline.} =
  605. assert n.kind == nkEffectList
  606. n.len == 0 or (n[tagEffects] == nil and n[exceptionEffects] == nil and n[forbiddenEffects] == nil)
  607. proc isTrival(caller: PNode): bool {.inline.} =
  608. result = caller.kind == nkSym and caller.sym.magic in {mEqProc, mIsNil, mMove, mWasMoved, mSwap}
  609. proc trackOperandForIndirectCall(tracked: PEffects, n: PNode, formals: PType; argIndex: int; caller: PNode) =
  610. let a = skipConvCastAndClosure(n)
  611. let op = a.typ
  612. let param = if formals != nil and formals.n != nil and argIndex < formals.n.len: formals.n[argIndex].sym else: nil
  613. # assume indirect calls are taken here:
  614. if op != nil and op.kind == tyProc and n.skipConv.kind != nkNilLit and
  615. not isTrival(caller) and
  616. ((param != nil and sfEffectsDelayed in param.flags) or laxEffects in tracked.c.config.legacyFeatures):
  617. internalAssert tracked.config, op.n[0].kind == nkEffectList
  618. var effectList = op.n[0]
  619. var s = n.skipConv
  620. if s.kind == nkCast and s[1].typ.kind == tyProc:
  621. s = s[1]
  622. if s.kind == nkSym and s.sym.kind in routineKinds and isNoEffectList(effectList):
  623. propagateEffects(tracked, n, s.sym)
  624. elif isNoEffectList(effectList):
  625. if isForwardedProc(n):
  626. # we have no explicit effects but it's a forward declaration and so it's
  627. # stated there are no additional effects, so simply propagate them:
  628. propagateEffects(tracked, n, n.sym)
  629. elif not isOwnedProcVar(tracked, a):
  630. # we have no explicit effects so assume the worst:
  631. assumeTheWorst(tracked, n, op)
  632. # assume GcUnsafe unless in its type; 'forward' does not matter:
  633. if notGcSafe(op) and not isOwnedProcVar(tracked, a):
  634. if tracked.config.hasWarn(warnGcUnsafe): warnAboutGcUnsafe(n, tracked.config)
  635. markGcUnsafe(tracked, a)
  636. elif tfNoSideEffect notin op.flags and not isOwnedProcVar(tracked, a):
  637. markSideEffect(tracked, a, n.info)
  638. else:
  639. mergeRaises(tracked, effectList[exceptionEffects], n)
  640. mergeTags(tracked, effectList[tagEffects], n)
  641. if notGcSafe(op):
  642. if tracked.config.hasWarn(warnGcUnsafe): warnAboutGcUnsafe(n, tracked.config)
  643. markGcUnsafe(tracked, a)
  644. elif tfNoSideEffect notin op.flags:
  645. markSideEffect(tracked, a, n.info)
  646. let paramType = if formals != nil and argIndex < formals.signatureLen: formals[argIndex] else: nil
  647. if paramType != nil and paramType.kind in {tyVar}:
  648. invalidateFacts(tracked.guards, n)
  649. if n.kind == nkSym and isLocalSym(tracked, n.sym):
  650. makeVolatile(tracked, n.sym)
  651. if paramType != nil and paramType.kind == tyProc and tfGcSafe in paramType.flags:
  652. let argtype = skipTypes(a.typ, abstractInst)
  653. # XXX figure out why this can be a non tyProc here. See httpclient.nim for an
  654. # example that triggers it.
  655. if argtype.kind == tyProc and notGcSafe(argtype) and not tracked.inEnforcedGcSafe:
  656. localError(tracked.config, n.info, $n & " is not GC safe")
  657. notNilCheck(tracked, n, paramType)
  658. proc breaksBlock(n: PNode): BreakState =
  659. # semantic check doesn't allow statements after raise, break, return or
  660. # call to noreturn proc, so it is safe to check just the last statements
  661. var it = n
  662. while it.kind in {nkStmtList, nkStmtListExpr} and it.len > 0:
  663. it = it.lastSon
  664. case it.kind
  665. of nkBreakStmt, nkReturnStmt:
  666. result = bsBreakOrReturn
  667. of nkRaiseStmt:
  668. result = bsNoReturn
  669. of nkCallKinds:
  670. if it[0].kind == nkSym and sfNoReturn in it[0].sym.flags:
  671. result = bsNoReturn
  672. else:
  673. result = bsNone
  674. else:
  675. result = bsNone
  676. proc addIdToIntersection(tracked: PEffects, inter: var TIntersection, resCounter: var int,
  677. hasBreaksBlock: BreakState, oldState: int, resSym: PSym, hasResult: bool) =
  678. if hasResult:
  679. var alreadySatisfy = false
  680. if hasBreaksBlock == bsNoReturn:
  681. alreadySatisfy = true
  682. inc resCounter
  683. for i in oldState..<tracked.init.len:
  684. if tracked.init[i] == resSym.id:
  685. if not alreadySatisfy:
  686. inc resCounter
  687. alreadySatisfy = true
  688. else:
  689. addToIntersection(inter, tracked.init[i], hasBreaksBlock)
  690. else:
  691. for i in oldState..<tracked.init.len:
  692. addToIntersection(inter, tracked.init[i], hasBreaksBlock)
  693. template hasResultSym(s: PSym): bool =
  694. s != nil and s.kind in {skProc, skFunc, skConverter, skMethod} and
  695. not isEmptyType(s.typ.returnType)
  696. proc trackCase(tracked: PEffects, n: PNode) =
  697. track(tracked, n[0])
  698. inc tracked.inIfStmt
  699. let oldState = tracked.init.len
  700. let oldFacts = tracked.guards.s.len
  701. let stringCase = n[0].typ != nil and skipTypes(n[0].typ,
  702. abstractVarRange-{tyTypeDesc}).kind in {tyFloat..tyFloat128, tyString, tyCstring}
  703. let interesting = not stringCase and interestingCaseExpr(n[0]) and
  704. (tracked.config.hasWarn(warnProveField) or strictCaseObjects in tracked.c.features)
  705. var inter: TIntersection = @[]
  706. var toCover = 0
  707. let hasResult = hasResultSym(tracked.owner)
  708. let resSym = if hasResult: tracked.owner.ast[resultPos].sym else: nil
  709. var resCounter = 0
  710. for i in 1..<n.len:
  711. let branch = n[i]
  712. setLen(tracked.init, oldState)
  713. if interesting:
  714. setLen(tracked.guards.s, oldFacts)
  715. addCaseBranchFacts(tracked.guards, n, i)
  716. for i in 0..<branch.len:
  717. track(tracked, branch[i])
  718. let hasBreaksBlock = breaksBlock(branch.lastSon)
  719. if hasBreaksBlock == bsNone:
  720. inc toCover
  721. addIdToIntersection(tracked, inter, resCounter, hasBreaksBlock, oldState, resSym, hasResult)
  722. setLen(tracked.init, oldState)
  723. if not stringCase or lastSon(n).kind == nkElse:
  724. if hasResult and resCounter == n.len-1:
  725. tracked.init.add resSym.id
  726. for id, count in items(inter):
  727. if count >= toCover: tracked.init.add id
  728. # else we can't merge
  729. setLen(tracked.guards.s, oldFacts)
  730. dec tracked.inIfStmt
  731. proc trackIf(tracked: PEffects, n: PNode) =
  732. track(tracked, n[0][0])
  733. inc tracked.inIfStmt
  734. let oldFacts = tracked.guards.s.len
  735. addFact(tracked.guards, n[0][0])
  736. let oldState = tracked.init.len
  737. let hasResult = hasResultSym(tracked.owner)
  738. let resSym = if hasResult: tracked.owner.ast[resultPos].sym else: nil
  739. var resCounter = 0
  740. var inter: TIntersection = @[]
  741. var toCover = 0
  742. track(tracked, n[0][1])
  743. let hasBreaksBlock = breaksBlock(n[0][1])
  744. if hasBreaksBlock == bsNone:
  745. inc toCover
  746. addIdToIntersection(tracked, inter, resCounter, hasBreaksBlock, oldState, resSym, hasResult)
  747. for i in 1..<n.len:
  748. let branch = n[i]
  749. setLen(tracked.guards.s, oldFacts)
  750. for j in 0..i-1:
  751. addFactNeg(tracked.guards, n[j][0])
  752. if branch.len > 1:
  753. addFact(tracked.guards, branch[0])
  754. setLen(tracked.init, oldState)
  755. for i in 0..<branch.len:
  756. track(tracked, branch[i])
  757. let hasBreaksBlock = breaksBlock(branch.lastSon)
  758. if hasBreaksBlock == bsNone:
  759. inc toCover
  760. addIdToIntersection(tracked, inter, resCounter, hasBreaksBlock, oldState, resSym, hasResult)
  761. setLen(tracked.init, oldState)
  762. if lastSon(n).len == 1:
  763. if hasResult and resCounter == n.len:
  764. tracked.init.add resSym.id
  765. for id, count in items(inter):
  766. if count >= toCover: tracked.init.add id
  767. # else we can't merge as it is not exhaustive
  768. setLen(tracked.guards.s, oldFacts)
  769. dec tracked.inIfStmt
  770. proc trackBlock(tracked: PEffects, n: PNode) =
  771. if n.kind in {nkStmtList, nkStmtListExpr}:
  772. var oldState = -1
  773. for i in 0..<n.len:
  774. if hasSubnodeWith(n[i], nkBreakStmt):
  775. # block:
  776. # x = def
  777. # if ...: ... break # some nested break
  778. # y = def
  779. # --> 'y' not defined after block!
  780. if oldState < 0: oldState = tracked.init.len
  781. track(tracked, n[i])
  782. if oldState > 0: setLen(tracked.init, oldState)
  783. else:
  784. track(tracked, n)
  785. proc cstringCheck(tracked: PEffects; n: PNode) =
  786. if n[0].typ.kind == tyCstring and (let a = skipConv(n[1]);
  787. a.typ.kind == tyString and a.kind notin {nkStrLit..nkTripleStrLit}):
  788. message(tracked.config, n.info, warnUnsafeCode, renderTree(n))
  789. proc patchResult(c: PEffects; n: PNode) =
  790. if n.kind == nkSym and n.sym.kind == skResult:
  791. let fn = c.owner
  792. if fn != nil and fn.kind in routineKinds and fn.ast != nil and resultPos < fn.ast.len:
  793. n.sym = fn.ast[resultPos].sym
  794. else:
  795. localError(c.config, n.info, "routine has no return type, but .requires contains 'result'")
  796. else:
  797. for i in 0..<safeLen(n):
  798. patchResult(c, n[i])
  799. proc checkLe(c: PEffects; a, b: PNode) =
  800. case proveLe(c.guards, a, b)
  801. of impUnknown:
  802. #for g in c.guards.s:
  803. # if g != nil: echo "I Know ", g
  804. message(c.config, a.info, warnStaticIndexCheck,
  805. "cannot prove: " & $a & " <= " & $b)
  806. of impYes:
  807. discard
  808. of impNo:
  809. message(c.config, a.info, warnStaticIndexCheck,
  810. "can prove: " & $a & " > " & $b)
  811. proc checkBounds(c: PEffects; arr, idx: PNode) =
  812. checkLe(c, lowBound(c.config, arr), idx)
  813. checkLe(c, idx, highBound(c.config, arr, c.guards.g.operators))
  814. proc checkRange(c: PEffects; value: PNode; typ: PType) =
  815. let t = typ.skipTypes(abstractInst - {tyRange})
  816. if t.kind == tyRange:
  817. let lowBound = copyTree(t.n[0])
  818. lowBound.info = value.info
  819. let highBound = copyTree(t.n[1])
  820. highBound.info = value.info
  821. checkLe(c, lowBound, value)
  822. checkLe(c, value, highBound)
  823. #[
  824. proc passedToEffectsDelayedParam(tracked: PEffects; n: PNode) =
  825. let t = n.typ.skipTypes(abstractInst)
  826. if t.kind == tyProc:
  827. if n.kind == nkSym and tracked.owner == n.sym.owner and sfEffectsDelayed in n.sym.flags:
  828. discard "the arg is itself a delayed parameter, so do nothing"
  829. else:
  830. var effectList = t.n[0]
  831. if effectList.len == effectListLen:
  832. mergeRaises(tracked, effectList[exceptionEffects], n)
  833. mergeTags(tracked, effectList[tagEffects], n)
  834. if not importedFromC(n):
  835. if notGcSafe(t):
  836. if tracked.config.hasWarn(warnGcUnsafe): warnAboutGcUnsafe(n, tracked.config)
  837. markGcUnsafe(tracked, n)
  838. if tfNoSideEffect notin t.flags:
  839. markSideEffect(tracked, n, n.info)
  840. ]#
  841. proc checkForSink(tracked: PEffects; n: PNode) =
  842. if tracked.inIfStmt == 0 and optSinkInference in tracked.config.options:
  843. checkForSink(tracked.config, tracked.c.idgen, tracked.owner, n)
  844. proc markCaughtExceptions(tracked: PEffects; g: ModuleGraph; info: TLineInfo; s: PSym; usageSym: var PSym) =
  845. when defined(nimsuggest):
  846. proc internalMarkCaughtExceptions(tracked: PEffects; q: var SuggestFileSymbolDatabase; info: TLineInfo) =
  847. var si = q.findSymInfoIndex(info)
  848. if si != -1:
  849. q.caughtExceptionsSet[si] = true
  850. for w1 in tracked.caughtExceptions.nodes:
  851. for w2 in w1:
  852. q.caughtExceptions[si].add(w2)
  853. if optIdeExceptionInlayHints in tracked.config.globalOptions:
  854. internalMarkCaughtExceptions(tracked, g.suggestSymbols.mgetOrPut(info.fileIndex, newSuggestFileSymbolDatabase(info.fileIndex, true)), info)
  855. proc trackCall(tracked: PEffects; n: PNode) =
  856. template gcsafeAndSideeffectCheck() =
  857. if notGcSafe(op) and not importedFromC(a):
  858. # and it's not a recursive call:
  859. if not (a.kind == nkSym and a.sym == tracked.owner):
  860. if tracked.config.hasWarn(warnGcUnsafe): warnAboutGcUnsafe(n, tracked.config)
  861. markGcUnsafe(tracked, a)
  862. if tfNoSideEffect notin op.flags and not importedFromC(a):
  863. # and it's not a recursive call:
  864. if not (a.kind == nkSym and a.sym == tracked.owner):
  865. markSideEffect(tracked, a, n.info)
  866. # p's effects are ours too:
  867. var a = n[0]
  868. #if canRaise(a):
  869. # echo "this can raise ", tracked.config $ n.info
  870. let op = a.typ
  871. if n.typ != nil:
  872. if tracked.owner.kind != skMacro and n.typ.skipTypes(abstractVar).kind != tyOpenArray:
  873. createTypeBoundOps(tracked, n.typ, n.info)
  874. when defined(nimsuggest):
  875. var actualLoc = a.info
  876. if n.kind == nkHiddenCallConv:
  877. actualLoc = n.info
  878. if a.kind == nkSym:
  879. markCaughtExceptions(tracked, tracked.graph, actualLoc, a.sym, tracked.graph.usageSym)
  880. let notConstExpr = getConstExpr(tracked.ownerModule, n, tracked.c.idgen, tracked.graph) == nil
  881. if notConstExpr:
  882. if a.kind == nkCast and a[1].typ.kind == tyProc:
  883. a = a[1]
  884. # XXX: in rare situations, templates and macros will reach here after
  885. # calling getAst(templateOrMacro()). Currently, templates and macros
  886. # are indistinguishable from normal procs (both have tyProc type) and
  887. # we can detect them only by checking for attached nkEffectList.
  888. if op != nil and op.kind == tyProc and op.n[0].kind == nkEffectList:
  889. if a.kind == nkSym:
  890. if a.sym == tracked.owner: tracked.isRecursive = true
  891. # even for recursive calls we need to check the lock levels (!):
  892. if sfSideEffect in a.sym.flags: markSideEffect(tracked, a, n.info)
  893. else:
  894. discard
  895. var effectList = op.n[0]
  896. if a.kind == nkSym and a.sym.kind == skMethod:
  897. if {sfBase, sfThread} * a.sym.flags == {sfBase}:
  898. if tracked.config.hasWarn(warnGcUnsafe): warnAboutGcUnsafe(n, tracked.config)
  899. markGcUnsafe(tracked, a)
  900. propagateEffects(tracked, n, a.sym)
  901. elif isNoEffectList(effectList):
  902. if isForwardedProc(a):
  903. propagateEffects(tracked, n, a.sym)
  904. elif isIndirectCall(tracked, a):
  905. assumeTheWorst(tracked, n, op)
  906. gcsafeAndSideeffectCheck()
  907. else:
  908. if laxEffects notin tracked.c.config.legacyFeatures and a.kind == nkSym and
  909. a.sym.kind in routineKinds:
  910. propagateEffects(tracked, n, a.sym)
  911. else:
  912. mergeRaises(tracked, effectList[exceptionEffects], n)
  913. mergeTags(tracked, effectList[tagEffects], n)
  914. gcsafeAndSideeffectCheck()
  915. if a.kind != nkSym or a.sym.magic notin {mNBindSym, mFinished, mExpandToAst, mQuoteAst}:
  916. for i in 1..<n.len:
  917. trackOperandForIndirectCall(tracked, n[i], op, i, a)
  918. if a.kind == nkSym and a.sym.magic in {mNew, mNewFinalize, mNewSeq}:
  919. # may not look like an assignment, but it is:
  920. let arg = n[1]
  921. initVarViaNew(tracked, arg)
  922. if arg.typ.hasElementType and {tfRequiresInit} * arg.typ.elementType.flags != {}:
  923. if a.sym.magic == mNewSeq and n[2].kind in {nkCharLit..nkUInt64Lit} and
  924. n[2].intVal == 0:
  925. # var s: seq[notnil]; newSeq(s, 0) is a special case!
  926. discard
  927. else:
  928. message(tracked.config, arg.info, warnProveInit, $arg)
  929. # check required for 'nim check':
  930. if n[1].typ.hasElementType:
  931. createTypeBoundOps(tracked, n[1].typ.elementType, n.info)
  932. createTypeBoundOps(tracked, n[1].typ, n.info)
  933. # new(x, finalizer): Problem: how to move finalizer into 'createTypeBoundOps'?
  934. elif a.kind == nkSym and a.sym.magic in {mArrGet, mArrPut} and
  935. optStaticBoundsCheck in tracked.currOptions:
  936. checkBounds(tracked, n[1], n[2])
  937. if a.kind == nkSym and a.sym.name.s.len > 0 and a.sym.name.s[0] == '=' and
  938. tracked.owner.kind != skMacro:
  939. var opKind = find(AttachedOpToStr, a.sym.name.s.normalize)
  940. if a.sym.name.s == "=": opKind = attachedAsgn.int
  941. if opKind != -1:
  942. # rebind type bounds operations after createTypeBoundOps call
  943. let t = n[1].typ.skipTypes({tyAlias, tyVar})
  944. if a.sym != getAttachedOp(tracked.graph, t, TTypeAttachedOp(opKind)):
  945. createTypeBoundOps(tracked, t, n.info)
  946. let op = getAttachedOp(tracked.graph, t, TTypeAttachedOp(opKind))
  947. if op != nil:
  948. n[0].sym = op
  949. if op != nil and op.kind == tyProc:
  950. for i in 1..<min(n.safeLen, op.signatureLen):
  951. let paramType = op[i]
  952. case paramType.kind
  953. of tySink:
  954. createTypeBoundOps(tracked, paramType.elementType, n.info)
  955. checkForSink(tracked, n[i])
  956. of tyVar:
  957. if isOutParam(paramType):
  958. # consider this case: p(out x, x); we want to remark that 'x' is not
  959. # initialized until after the call. Since we do this after we analysed the
  960. # call, this is fine.
  961. initVar(tracked, n[i].skipHiddenAddr, false)
  962. if strictFuncs in tracked.c.features and not tracked.inEnforcedNoSideEffects and
  963. isDangerousLocation(n[i].skipHiddenAddr, tracked.owner):
  964. if sfNoSideEffect in tracked.owner.flags:
  965. localError(tracked.config, n[i].info,
  966. "cannot pass $1 to `var T` parameter within a strict func" % renderTree(n[i]))
  967. tracked.hasSideEffect = true
  968. else: discard
  969. if notConstExpr and (a.kind != nkSym or
  970. a.sym.magic notin {mRunnableExamples, mNBindSym, mExpandToAst, mQuoteAst}
  971. ):
  972. # tracked after out analysis
  973. for i in 0..<n.safeLen:
  974. track(tracked, n[i])
  975. type
  976. PragmaBlockContext = object
  977. oldLocked: int
  978. enforcedGcSafety, enforceNoSideEffects: bool
  979. oldExc, oldTags, oldForbids: int
  980. exc, tags, forbids: PNode
  981. proc createBlockContext(tracked: PEffects): PragmaBlockContext =
  982. var oldForbidsLen = 0
  983. if tracked.forbids != nil: oldForbidsLen = tracked.forbids.len
  984. result = PragmaBlockContext(oldLocked: tracked.locked.len,
  985. enforcedGcSafety: false, enforceNoSideEffects: false,
  986. oldExc: tracked.exc.len, oldTags: tracked.tags.len,
  987. oldForbids: oldForbidsLen)
  988. proc applyBlockContext(tracked: PEffects, bc: PragmaBlockContext) =
  989. if bc.enforcedGcSafety: tracked.inEnforcedGcSafe = true
  990. if bc.enforceNoSideEffects: tracked.inEnforcedNoSideEffects = true
  991. proc unapplyBlockContext(tracked: PEffects; bc: PragmaBlockContext) =
  992. if bc.enforcedGcSafety: tracked.inEnforcedGcSafe = false
  993. if bc.enforceNoSideEffects: tracked.inEnforcedNoSideEffects = false
  994. setLen(tracked.locked, bc.oldLocked)
  995. if bc.exc != nil:
  996. # beware that 'raises: []' is very different from not saying
  997. # anything about 'raises' in the 'cast' at all. Same applies for 'tags'.
  998. setLen(tracked.exc.sons, bc.oldExc)
  999. for e in bc.exc:
  1000. addRaiseEffect(tracked, e, e)
  1001. if bc.tags != nil:
  1002. setLen(tracked.tags.sons, bc.oldTags)
  1003. for t in bc.tags:
  1004. addTag(tracked, t, t)
  1005. if bc.forbids != nil:
  1006. setLen(tracked.forbids.sons, bc.oldForbids)
  1007. for t in bc.forbids:
  1008. addNotTag(tracked, t, t)
  1009. proc castBlock(tracked: PEffects, pragma: PNode, bc: var PragmaBlockContext) =
  1010. case whichPragma(pragma)
  1011. of wGcSafe:
  1012. bc.enforcedGcSafety = true
  1013. of wNoSideEffect:
  1014. bc.enforceNoSideEffects = true
  1015. of wTags:
  1016. let n = pragma[1]
  1017. if n.kind in {nkCurly, nkBracket}:
  1018. bc.tags = n
  1019. else:
  1020. bc.tags = newNodeI(nkArgList, pragma.info)
  1021. bc.tags.add n
  1022. of wForbids:
  1023. let n = pragma[1]
  1024. if n.kind in {nkCurly, nkBracket}:
  1025. bc.forbids = n
  1026. else:
  1027. bc.forbids = newNodeI(nkArgList, pragma.info)
  1028. bc.forbids.add n
  1029. of wRaises:
  1030. let n = pragma[1]
  1031. if n.kind in {nkCurly, nkBracket}:
  1032. bc.exc = n
  1033. else:
  1034. bc.exc = newNodeI(nkArgList, pragma.info)
  1035. bc.exc.add n
  1036. of wUncheckedAssign:
  1037. discard "handled in sempass1"
  1038. else:
  1039. localError(tracked.config, pragma.info,
  1040. "invalid pragma block: " & $pragma)
  1041. proc trackInnerProc(tracked: PEffects, n: PNode) =
  1042. case n.kind
  1043. of nkSym:
  1044. let s = n.sym
  1045. if s.kind == skParam and s.owner == tracked.owner:
  1046. tracked.escapingParams.incl s.id
  1047. of nkNone..pred(nkSym), succ(nkSym)..nkNilLit:
  1048. discard
  1049. of nkProcDef, nkConverterDef, nkMethodDef, nkIteratorDef, nkLambda, nkFuncDef, nkDo:
  1050. if n[0].kind == nkSym and n[0].sym.ast != nil:
  1051. trackInnerProc(tracked, getBody(tracked.graph, n[0].sym))
  1052. of nkTypeSection, nkMacroDef, nkTemplateDef, nkError,
  1053. nkConstSection, nkConstDef, nkIncludeStmt, nkImportStmt,
  1054. nkExportStmt, nkPragma, nkCommentStmt, nkBreakState,
  1055. nkTypeOfExpr, nkMixinStmt, nkBindStmt:
  1056. discard
  1057. else:
  1058. for ch in n: trackInnerProc(tracked, ch)
  1059. proc allowCStringConv(n: PNode): bool =
  1060. case n.kind
  1061. of nkStrLit..nkTripleStrLit: result = true
  1062. of nkSym: result = n.sym.kind in {skConst, skParam}
  1063. of nkAddr: result = isCharArrayPtr(n.typ, true)
  1064. of nkCallKinds:
  1065. result = isCharArrayPtr(n.typ, n[0].kind == nkSym and n[0].sym.magic == mAddr)
  1066. else: result = isCharArrayPtr(n.typ, false)
  1067. proc track(tracked: PEffects, n: PNode) =
  1068. case n.kind
  1069. of nkSym:
  1070. useVar(tracked, n)
  1071. if n.sym.typ != nil and tfHasAsgn in n.sym.typ.flags:
  1072. tracked.owner.flags.incl sfInjectDestructors
  1073. # bug #15038: ensure consistency
  1074. if not hasDestructor(n.typ) and sameType(n.typ, n.sym.typ): n.typ = n.sym.typ
  1075. of nkHiddenAddr, nkAddr:
  1076. if n[0].kind == nkSym and isLocalSym(tracked, n[0].sym) and
  1077. n.typ.kind notin {tyVar, tyLent}:
  1078. useVarNoInitCheck(tracked, n[0], n[0].sym)
  1079. else:
  1080. track(tracked, n[0])
  1081. of nkRaiseStmt:
  1082. if n[0].kind != nkEmpty:
  1083. n[0].info = n.info
  1084. #throws(tracked.exc, n[0])
  1085. addRaiseEffect(tracked, n[0], n)
  1086. for i in 0..<n.safeLen:
  1087. track(tracked, n[i])
  1088. createTypeBoundOps(tracked, n[0].typ, n.info)
  1089. else:
  1090. # A `raise` with no arguments means we're going to re-raise the exception
  1091. # being handled or, if outside of an `except` block, a `ReraiseDefect`.
  1092. # Here we add a `Exception` tag in order to cover both the cases.
  1093. addRaiseEffect(tracked, createRaise(tracked.graph, n), nil)
  1094. of nkCallKinds:
  1095. trackCall(tracked, n)
  1096. of nkDotExpr:
  1097. guardDotAccess(tracked, n)
  1098. let oldLeftPartOfAsgn = tracked.leftPartOfAsgn
  1099. tracked.leftPartOfAsgn = 0
  1100. for i in 0..<n.len: track(tracked, n[i])
  1101. tracked.leftPartOfAsgn = oldLeftPartOfAsgn
  1102. of nkCheckedFieldExpr:
  1103. track(tracked, n[0])
  1104. if tracked.config.hasWarn(warnProveField) or strictCaseObjects in tracked.c.features:
  1105. checkFieldAccess(tracked.guards, n, tracked.config, strictCaseObjects in tracked.c.features)
  1106. of nkTryStmt: trackTryStmt(tracked, n)
  1107. of nkPragma: trackPragmaStmt(tracked, n)
  1108. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  1109. track(tracked, n[1])
  1110. initVar(tracked, n[0], volatileCheck=true)
  1111. invalidateFacts(tracked.guards, n[0])
  1112. inc tracked.leftPartOfAsgn
  1113. track(tracked, n[0])
  1114. dec tracked.leftPartOfAsgn
  1115. addAsgnFact(tracked.guards, n[0], n[1])
  1116. notNilCheck(tracked, n[1], n[0].typ)
  1117. when false: cstringCheck(tracked, n)
  1118. if tracked.owner.kind != skMacro and n[0].typ.kind notin {tyOpenArray, tyVarargs}:
  1119. createTypeBoundOps(tracked, n[0].typ, n.info)
  1120. if n[0].kind != nkSym or not isLocalSym(tracked, n[0].sym):
  1121. checkForSink(tracked, n[1])
  1122. if strictFuncs in tracked.c.features and not tracked.inEnforcedNoSideEffects and
  1123. isDangerousLocation(n[0], tracked.owner):
  1124. tracked.hasSideEffect = true
  1125. if sfNoSideEffect in tracked.owner.flags:
  1126. localError(tracked.config, n[0].info,
  1127. "cannot mutate location $1 within a strict func" % renderTree(n[0]))
  1128. of nkVarSection, nkLetSection:
  1129. for child in n:
  1130. let last = lastSon(child)
  1131. if last.kind != nkEmpty: track(tracked, last)
  1132. if tracked.owner.kind != skMacro:
  1133. if child.kind == nkVarTuple:
  1134. createTypeBoundOps(tracked, child[^1].typ, child.info)
  1135. for i in 0..<child.len-2:
  1136. createTypeBoundOps(tracked, child[i].typ, child.info)
  1137. else:
  1138. createTypeBoundOps(tracked, skipPragmaExpr(child[0]).typ, child.info)
  1139. if child.kind == nkIdentDefs:
  1140. for i in 0..<child.len-2:
  1141. let a = skipPragmaExpr(child[i])
  1142. varDecl(tracked, a)
  1143. if last.kind != nkEmpty:
  1144. initVar(tracked, a, volatileCheck=false)
  1145. addAsgnFact(tracked.guards, a, last)
  1146. notNilCheck(tracked, last, a.typ)
  1147. elif child.kind == nkVarTuple:
  1148. for i in 0..<child.len-1:
  1149. if child[i].kind == nkEmpty or
  1150. child[i].kind == nkSym and child[i].sym.name.id == ord(wUnderscore):
  1151. continue
  1152. varDecl(tracked, child[i])
  1153. if last.kind != nkEmpty:
  1154. initVar(tracked, child[i], volatileCheck=false)
  1155. if last.kind in {nkPar, nkTupleConstr}:
  1156. addAsgnFact(tracked.guards, child[i], last[i])
  1157. notNilCheck(tracked, last[i], child[i].typ)
  1158. # since 'var (a, b): T = ()' is not even allowed, there is always type
  1159. # inference for (a, b) and thus no nil checking is necessary.
  1160. of nkConstSection:
  1161. for child in n:
  1162. let last = lastSon(child)
  1163. track(tracked, last)
  1164. of nkCaseStmt: trackCase(tracked, n)
  1165. of nkWhen, nkIfStmt, nkIfExpr: trackIf(tracked, n)
  1166. of nkBlockStmt, nkBlockExpr: trackBlock(tracked, n[1])
  1167. of nkWhileStmt:
  1168. # 'while true' loop?
  1169. inc tracked.currentBlock
  1170. if isTrue(n[0]):
  1171. trackBlock(tracked, n[1])
  1172. else:
  1173. # loop may never execute:
  1174. let oldState = tracked.init.len
  1175. let oldFacts = tracked.guards.s.len
  1176. addFact(tracked.guards, n[0])
  1177. track(tracked, n[0])
  1178. track(tracked, n[1])
  1179. setLen(tracked.init, oldState)
  1180. setLen(tracked.guards.s, oldFacts)
  1181. dec tracked.currentBlock
  1182. of nkForStmt, nkParForStmt:
  1183. # we are very conservative here and assume the loop is never executed:
  1184. inc tracked.currentBlock
  1185. let oldState = tracked.init.len
  1186. let oldFacts = tracked.guards.s.len
  1187. let iterCall = n[n.len-2]
  1188. if optStaticBoundsCheck in tracked.currOptions and iterCall.kind in nkCallKinds:
  1189. let op = iterCall[0]
  1190. if op.kind == nkSym and fromSystem(op.sym):
  1191. let iterVar = n[0]
  1192. case op.sym.name.s
  1193. of "..", "countup", "countdown":
  1194. let lower = iterCall[1]
  1195. let upper = iterCall[2]
  1196. # for i in 0..n means 0 <= i and i <= n. Countdown is
  1197. # the same since only the iteration direction changes.
  1198. addFactLe(tracked.guards, lower, iterVar)
  1199. addFactLe(tracked.guards, iterVar, upper)
  1200. of "..<":
  1201. let lower = iterCall[1]
  1202. let upper = iterCall[2]
  1203. addFactLe(tracked.guards, lower, iterVar)
  1204. addFactLt(tracked.guards, iterVar, upper)
  1205. else: discard
  1206. for i in 0..<n.len-2:
  1207. let it = n[i]
  1208. track(tracked, it)
  1209. if tracked.owner.kind != skMacro:
  1210. if it.kind == nkVarTuple:
  1211. for x in it:
  1212. createTypeBoundOps(tracked, x.typ, x.info)
  1213. else:
  1214. createTypeBoundOps(tracked, it.typ, it.info)
  1215. let loopBody = n[^1]
  1216. if tracked.owner.kind != skMacro and iterCall.safeLen > 1:
  1217. # XXX this is a bit hacky:
  1218. if iterCall[1].typ != nil and iterCall[1].typ.skipTypes(abstractVar).kind notin {tyVarargs, tyOpenArray}:
  1219. createTypeBoundOps(tracked, iterCall[1].typ, iterCall[1].info)
  1220. track(tracked, iterCall)
  1221. track(tracked, loopBody)
  1222. setLen(tracked.init, oldState)
  1223. setLen(tracked.guards.s, oldFacts)
  1224. dec tracked.currentBlock
  1225. of nkObjConstr:
  1226. when false: track(tracked, n[0])
  1227. let oldFacts = tracked.guards.s.len
  1228. for i in 1..<n.len:
  1229. let x = n[i]
  1230. track(tracked, x)
  1231. if x[0].kind == nkSym and sfDiscriminant in x[0].sym.flags:
  1232. addDiscriminantFact(tracked.guards, x)
  1233. if tracked.owner.kind != skMacro:
  1234. createTypeBoundOps(tracked, x[1].typ, n.info)
  1235. if x.kind == nkExprColonExpr:
  1236. if x[0].kind == nkSym:
  1237. notNilCheck(tracked, x[1], x[0].sym.typ)
  1238. checkForSink(tracked, x[1])
  1239. else:
  1240. checkForSink(tracked, x)
  1241. setLen(tracked.guards.s, oldFacts)
  1242. if tracked.owner.kind != skMacro:
  1243. # XXX n.typ can be nil in runnableExamples, we need to do something about it.
  1244. if n.typ != nil and n.typ.skipTypes(abstractInst).kind == tyRef:
  1245. createTypeBoundOps(tracked, n.typ.elementType, n.info)
  1246. createTypeBoundOps(tracked, n.typ, n.info)
  1247. of nkTupleConstr:
  1248. for i in 0..<n.len:
  1249. track(tracked, n[i])
  1250. notNilCheck(tracked, n[i].skipColon, n[i].typ)
  1251. if tracked.owner.kind != skMacro:
  1252. if n[i].kind == nkExprColonExpr:
  1253. createTypeBoundOps(tracked, n[i][0].typ, n.info)
  1254. else:
  1255. createTypeBoundOps(tracked, n[i].typ, n.info)
  1256. checkForSink(tracked, n[i])
  1257. of nkPragmaBlock:
  1258. let pragmaList = n[0]
  1259. var bc = createBlockContext(tracked)
  1260. for i in 0..<pragmaList.len:
  1261. let pragma = whichPragma(pragmaList[i])
  1262. case pragma
  1263. of wLocks:
  1264. lockLocations(tracked, pragmaList[i])
  1265. of wGcSafe:
  1266. bc.enforcedGcSafety = true
  1267. of wNoSideEffect:
  1268. bc.enforceNoSideEffects = true
  1269. of wCast:
  1270. castBlock(tracked, pragmaList[i][1], bc)
  1271. else:
  1272. discard
  1273. applyBlockContext(tracked, bc)
  1274. track(tracked, n.lastSon)
  1275. unapplyBlockContext(tracked, bc)
  1276. of nkProcDef, nkConverterDef, nkMethodDef, nkIteratorDef, nkLambda, nkFuncDef, nkDo:
  1277. if n[0].kind == nkSym and n[0].sym.ast != nil:
  1278. trackInnerProc(tracked, getBody(tracked.graph, n[0].sym))
  1279. of nkMacroDef, nkTemplateDef:
  1280. discard
  1281. of nkTypeSection:
  1282. if tracked.isTopLevel:
  1283. collectObjectTree(tracked.graph, n)
  1284. of nkCast:
  1285. if n.len == 2:
  1286. track(tracked, n[1])
  1287. if tracked.owner.kind != skMacro:
  1288. createTypeBoundOps(tracked, n.typ, n.info)
  1289. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  1290. if n.kind in {nkHiddenStdConv, nkHiddenSubConv} and
  1291. n.typ.skipTypes(abstractInst).kind == tyCstring and
  1292. not allowCStringConv(n[1]):
  1293. message(tracked.config, n.info, warnCstringConv,
  1294. "implicit conversion to 'cstring' from a non-const location: $1; this will become a compile time error in the future" %
  1295. $n[1])
  1296. if n.typ.skipTypes(abstractInst).kind == tyCstring and
  1297. isCharArrayPtr(n[1].typ, true):
  1298. message(tracked.config, n.info, warnPtrToCstringConv,
  1299. $n[1].typ)
  1300. let t = n.typ.skipTypes(abstractInst)
  1301. if t.kind == tyEnum:
  1302. if tfEnumHasHoles in t.flags:
  1303. message(tracked.config, n.info, warnHoleEnumConv, "conversion to enum with holes is unsafe: $1" % $n)
  1304. else:
  1305. message(tracked.config, n.info, warnAnyEnumConv, "enum conversion: $1" % $n)
  1306. if n.len == 2:
  1307. track(tracked, n[1])
  1308. if tracked.owner.kind != skMacro:
  1309. createTypeBoundOps(tracked, n.typ, n.info)
  1310. # This is a hacky solution in order to fix bug #13110. Hopefully
  1311. # a better solution will come up eventually.
  1312. if n[1].typ.kind != tyString:
  1313. createTypeBoundOps(tracked, n[1].typ, n[1].info)
  1314. if optStaticBoundsCheck in tracked.currOptions:
  1315. checkRange(tracked, n[1], n.typ)
  1316. of nkObjUpConv, nkObjDownConv, nkChckRange, nkChckRangeF, nkChckRange64:
  1317. if n.len == 1:
  1318. track(tracked, n[0])
  1319. if tracked.owner.kind != skMacro:
  1320. createTypeBoundOps(tracked, n.typ, n.info)
  1321. createTypeBoundOps(tracked, n[0].typ, n[0].info)
  1322. if optStaticBoundsCheck in tracked.currOptions:
  1323. checkRange(tracked, n[0], n.typ)
  1324. of nkBracket:
  1325. for i in 0..<n.safeLen:
  1326. track(tracked, n[i])
  1327. checkForSink(tracked, n[i])
  1328. if tracked.owner.kind != skMacro:
  1329. createTypeBoundOps(tracked, n.typ, n.info)
  1330. of nkBracketExpr:
  1331. if optStaticBoundsCheck in tracked.currOptions and n.len == 2:
  1332. if n[0].typ != nil and skipTypes(n[0].typ, abstractVar).kind != tyTuple:
  1333. checkBounds(tracked, n[0], n[1])
  1334. track(tracked, n[0])
  1335. dec tracked.leftPartOfAsgn
  1336. for i in 1 ..< n.len: track(tracked, n[i])
  1337. inc tracked.leftPartOfAsgn
  1338. of nkError:
  1339. localError(tracked.config, n.info, errorToString(tracked.config, n))
  1340. else:
  1341. for i in 0..<n.safeLen: track(tracked, n[i])
  1342. proc subtypeRelation(g: ModuleGraph; spec, real: PNode): bool =
  1343. if spec.typ.kind == tyOr:
  1344. result = false
  1345. for t in spec.typ.kids:
  1346. if safeInheritanceDiff(g.excType(real), t) <= 0:
  1347. return true
  1348. else:
  1349. return safeInheritanceDiff(g.excType(real), spec.typ) <= 0
  1350. proc checkRaisesSpec(g: ModuleGraph; emitWarnings: bool; spec, real: PNode, msg: string, hints: bool;
  1351. effectPredicate: proc (g: ModuleGraph; a, b: PNode): bool {.nimcall.};
  1352. hintsArg: PNode = nil; isForbids: bool = false) =
  1353. # check that any real exception is listed in 'spec'; mark those as used;
  1354. # report any unused exception
  1355. var used = initIntSet()
  1356. for r in items(real):
  1357. block search:
  1358. for s in 0..<spec.len:
  1359. if effectPredicate(g, spec[s], r):
  1360. if isForbids: break
  1361. used.incl(s)
  1362. break search
  1363. if isForbids:
  1364. break search
  1365. # XXX call graph analysis would be nice here!
  1366. pushInfoContext(g.config, spec.info)
  1367. var rr = if r.kind == nkRaiseStmt: r[0] else: r
  1368. while rr.kind in {nkStmtList, nkStmtListExpr} and rr.len > 0: rr = rr.lastSon
  1369. message(g.config, r.info, if emitWarnings: warnEffect else: errGenerated,
  1370. renderTree(rr) & " " & msg & typeToString(r.typ))
  1371. popInfoContext(g.config)
  1372. # hint about unnecessarily listed exception types:
  1373. if hints:
  1374. for s in 0..<spec.len:
  1375. if not used.contains(s):
  1376. message(g.config, spec[s].info, hintXCannotRaiseY,
  1377. "'$1' cannot raise '$2'" % [renderTree(hintsArg), renderTree(spec[s])])
  1378. proc checkMethodEffects*(g: ModuleGraph; disp, branch: PSym) =
  1379. ## checks for consistent effects for multi methods.
  1380. let actual = branch.typ.n[0]
  1381. if actual.len != effectListLen: return
  1382. let p = disp.ast[pragmasPos]
  1383. let raisesSpec = effectSpec(p, wRaises)
  1384. if not isNil(raisesSpec):
  1385. checkRaisesSpec(g, false, raisesSpec, actual[exceptionEffects],
  1386. "can raise an unlisted exception: ", hints=off, subtypeRelation)
  1387. let tagsSpec = effectSpec(p, wTags)
  1388. if not isNil(tagsSpec):
  1389. checkRaisesSpec(g, false, tagsSpec, actual[tagEffects],
  1390. "can have an unlisted effect: ", hints=off, subtypeRelation)
  1391. let forbidsSpec = effectSpec(p, wForbids)
  1392. if not isNil(forbidsSpec):
  1393. checkRaisesSpec(g, false, forbidsSpec, actual[tagEffects],
  1394. "has an illegal effect: ", hints=off, subtypeRelation, isForbids=true)
  1395. if sfThread in disp.flags and notGcSafe(branch.typ):
  1396. localError(g.config, branch.info, "base method is GC-safe, but '$1' is not" %
  1397. branch.name.s)
  1398. when defined(drnim):
  1399. if not g.compatibleProps(g, disp.typ, branch.typ):
  1400. localError(g.config, branch.info, "for method '" & branch.name.s &
  1401. "' the `.requires` or `.ensures` properties are incompatible.")
  1402. proc setEffectsForProcType*(g: ModuleGraph; t: PType, n: PNode; s: PSym = nil) =
  1403. var effects = t.n[0]
  1404. if t.kind != tyProc or effects.kind != nkEffectList: return
  1405. if n.kind != nkEmpty:
  1406. internalAssert g.config, effects.len == 0
  1407. newSeq(effects.sons, effectListLen)
  1408. let raisesSpec = effectSpec(n, wRaises)
  1409. if not isNil(raisesSpec):
  1410. effects[exceptionEffects] = raisesSpec
  1411. elif s != nil and (s.magic != mNone or {sfImportc, sfExportc} * s.flags == {sfImportc}):
  1412. effects[exceptionEffects] = newNodeI(nkArgList, effects.info)
  1413. let tagsSpec = effectSpec(n, wTags)
  1414. if not isNil(tagsSpec):
  1415. effects[tagEffects] = tagsSpec
  1416. elif s != nil and (s.magic != mNone or {sfImportc, sfExportc} * s.flags == {sfImportc}):
  1417. effects[tagEffects] = newNodeI(nkArgList, effects.info)
  1418. let forbidsSpec = effectSpec(n, wForbids)
  1419. if not isNil(forbidsSpec):
  1420. effects[forbiddenEffects] = forbidsSpec
  1421. elif s != nil and (s.magic != mNone or {sfImportc, sfExportc} * s.flags == {sfImportc}):
  1422. effects[forbiddenEffects] = newNodeI(nkArgList, effects.info)
  1423. let requiresSpec = propSpec(n, wRequires)
  1424. if not isNil(requiresSpec):
  1425. effects[requiresEffects] = requiresSpec
  1426. let ensuresSpec = propSpec(n, wEnsures)
  1427. if not isNil(ensuresSpec):
  1428. effects[ensuresEffects] = ensuresSpec
  1429. effects[pragmasEffects] = n
  1430. if s != nil and s.magic != mNone:
  1431. if s.magic != mEcho:
  1432. t.flags.incl tfNoSideEffect
  1433. proc rawInitEffects(g: ModuleGraph; effects: PNode) =
  1434. newSeq(effects.sons, effectListLen)
  1435. effects[exceptionEffects] = newNodeI(nkArgList, effects.info)
  1436. effects[tagEffects] = newNodeI(nkArgList, effects.info)
  1437. effects[forbiddenEffects] = newNodeI(nkArgList, effects.info)
  1438. effects[requiresEffects] = g.emptyNode
  1439. effects[ensuresEffects] = g.emptyNode
  1440. effects[pragmasEffects] = g.emptyNode
  1441. proc initEffects(g: ModuleGraph; effects: PNode; s: PSym; c: PContext): TEffects =
  1442. rawInitEffects(g, effects)
  1443. result = TEffects(exc: effects[exceptionEffects], tags: effects[tagEffects],
  1444. forbids: effects[forbiddenEffects], owner: s, ownerModule: s.getModule,
  1445. init: @[], locked: @[], graph: g, config: g.config, c: c,
  1446. currentBlock: 1
  1447. )
  1448. result.guards.s = @[]
  1449. result.guards.g = g
  1450. when defined(drnim):
  1451. result.currOptions = g.config.options + s.options - {optStaticBoundsCheck}
  1452. else:
  1453. result.currOptions = g.config.options + s.options
  1454. result.guards.beSmart = optStaticBoundsCheck in result.currOptions
  1455. proc hasRealBody(s: PSym): bool =
  1456. ## also handles importc procs with runnableExamples, which requires `=`,
  1457. ## which is not a real implementation, refs #14314
  1458. result = {sfForward, sfImportc} * s.flags == {}
  1459. proc trackProc*(c: PContext; s: PSym, body: PNode) =
  1460. let g = c.graph
  1461. when defined(nimsuggest):
  1462. if g.config.expandDone():
  1463. return
  1464. var effects = s.typ.n[0]
  1465. if effects.kind != nkEffectList: return
  1466. # effects already computed?
  1467. if not s.hasRealBody: return
  1468. let emitWarnings = tfEffectSystemWorkaround in s.typ.flags
  1469. if effects.len == effectListLen and not emitWarnings: return
  1470. var inferredEffects = newNodeI(nkEffectList, s.info)
  1471. var t: TEffects = initEffects(g, inferredEffects, s, c)
  1472. rawInitEffects g, effects
  1473. if not isEmptyType(s.typ.returnType) and
  1474. s.kind in {skProc, skFunc, skConverter, skMethod}:
  1475. var res = s.ast[resultPos].sym # get result symbol
  1476. t.scopes[res.id] = t.currentBlock
  1477. track(t, body)
  1478. if s.kind != skMacro:
  1479. let params = s.typ.n
  1480. for i in 1..<params.len:
  1481. let param = params[i].sym
  1482. let typ = param.typ
  1483. if isSinkTypeForParam(typ) or
  1484. (t.config.selectedGC in {gcArc, gcOrc, gcAtomicArc} and
  1485. (isClosure(typ.skipTypes(abstractInst)) or param.id in t.escapingParams)):
  1486. createTypeBoundOps(t, typ, param.info)
  1487. if isOutParam(typ) and param.id notin t.init:
  1488. message(g.config, param.info, warnProveInit, param.name.s)
  1489. if not isEmptyType(s.typ.returnType) and
  1490. (s.typ.returnType.requiresInit or s.typ.returnType.skipTypes(abstractInst).kind == tyVar or
  1491. strictDefs in c.features) and
  1492. s.kind in {skProc, skFunc, skConverter, skMethod} and s.magic == mNone:
  1493. var res = s.ast[resultPos].sym # get result symbol
  1494. if res.id notin t.init and breaksBlock(body) != bsNoReturn:
  1495. if tfRequiresInit in s.typ.returnType.flags:
  1496. localError(g.config, body.info, "'$1' requires explicit initialization" % "result")
  1497. else:
  1498. message(g.config, body.info, warnProveInit, "result")
  1499. let p = s.ast[pragmasPos]
  1500. let raisesSpec = effectSpec(p, wRaises)
  1501. if not isNil(raisesSpec):
  1502. let useWarning = s.name.s == "=destroy"
  1503. checkRaisesSpec(g, useWarning, raisesSpec, t.exc, "can raise an unlisted exception: ",
  1504. hints=on, subtypeRelation, hintsArg=s.ast[0])
  1505. # after the check, use the formal spec:
  1506. effects[exceptionEffects] = raisesSpec
  1507. else:
  1508. effects[exceptionEffects] = t.exc
  1509. let tagsSpec = effectSpec(p, wTags)
  1510. if not isNil(tagsSpec):
  1511. checkRaisesSpec(g, false, tagsSpec, t.tags, "can have an unlisted effect: ",
  1512. hints=off, subtypeRelation)
  1513. # after the check, use the formal spec:
  1514. effects[tagEffects] = tagsSpec
  1515. else:
  1516. effects[tagEffects] = t.tags
  1517. let forbidsSpec = effectSpec(p, wForbids)
  1518. if not isNil(forbidsSpec):
  1519. checkRaisesSpec(g, false, forbidsSpec, t.tags, "has an illegal effect: ",
  1520. hints=off, subtypeRelation, isForbids=true)
  1521. # after the check, use the formal spec:
  1522. effects[forbiddenEffects] = forbidsSpec
  1523. else:
  1524. effects[forbiddenEffects] = t.forbids
  1525. let requiresSpec = propSpec(p, wRequires)
  1526. if not isNil(requiresSpec):
  1527. effects[requiresEffects] = requiresSpec
  1528. let ensuresSpec = propSpec(p, wEnsures)
  1529. if not isNil(ensuresSpec):
  1530. patchResult(t, ensuresSpec)
  1531. effects[ensuresEffects] = ensuresSpec
  1532. var mutationInfo = MutationInfo()
  1533. if views in c.features:
  1534. var partitions = computeGraphPartitions(s, body, g, {borrowChecking})
  1535. checkBorrowedLocations(partitions, body, g.config)
  1536. if sfThread in s.flags and t.gcUnsafe:
  1537. if optThreads in g.config.globalOptions and optThreadAnalysis in g.config.globalOptions:
  1538. #localError(s.info, "'$1' is not GC-safe" % s.name.s)
  1539. listGcUnsafety(s, onlyWarning=false, g.config)
  1540. else:
  1541. listGcUnsafety(s, onlyWarning=true, g.config)
  1542. #localError(s.info, warnGcUnsafe2, s.name.s)
  1543. if sfNoSideEffect in s.flags and t.hasSideEffect:
  1544. when false:
  1545. listGcUnsafety(s, onlyWarning=false, g.config)
  1546. else:
  1547. if c.compilesContextId == 0: # don't render extended diagnostic messages in `system.compiles` context
  1548. var msg = ""
  1549. listSideEffects(msg, s, g.config, t.c)
  1550. message(g.config, s.info, errGenerated, msg)
  1551. else:
  1552. localError(g.config, s.info, "") # simple error for `system.compiles` context
  1553. if not t.gcUnsafe:
  1554. s.typ.flags.incl tfGcSafe
  1555. if not t.hasSideEffect and sfSideEffect notin s.flags:
  1556. s.typ.flags.incl tfNoSideEffect
  1557. when defined(drnim):
  1558. if c.graph.strongSemCheck != nil: c.graph.strongSemCheck(c.graph, s, body)
  1559. when defined(useDfa):
  1560. if s.name.s == "testp":
  1561. dataflowAnalysis(s, body)
  1562. when false: trackWrites(s, body)
  1563. if strictNotNil in c.features and s.kind in {skProc, skFunc, skMethod, skConverter}:
  1564. checkNil(s, body, g.config, c.idgen)
  1565. proc trackStmt*(c: PContext; module: PSym; n: PNode, isTopLevel: bool) =
  1566. case n.kind
  1567. of {nkPragma, nkMacroDef, nkTemplateDef, nkProcDef, nkFuncDef,
  1568. nkConverterDef, nkMethodDef, nkIteratorDef}:
  1569. discard
  1570. of nkTypeSection:
  1571. if isTopLevel:
  1572. collectObjectTree(c.graph, n)
  1573. else:
  1574. let g = c.graph
  1575. var effects = newNodeI(nkEffectList, n.info)
  1576. var t: TEffects = initEffects(g, effects, module, c)
  1577. t.isTopLevel = isTopLevel
  1578. track(t, n)
  1579. when defined(drnim):
  1580. if c.graph.strongSemCheck != nil: c.graph.strongSemCheck(c.graph, module, n)