sempass2.nim 57 KB

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