varpartitions.nim 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2020 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Partition variables into different graphs. Used for
  10. ## Nim's write tracking, borrow checking and also for the
  11. ## cursor inference.
  12. ## The algorithm is a reinvention / variation of Steensgaard's
  13. ## algorithm.
  14. ## The used data structure is "union find" with path compression.
  15. ## We perform two passes over the AST:
  16. ## - Pass one (``computeLiveRanges``): collect livetimes of local
  17. ## variables and whether they are potentially re-assigned.
  18. ## - Pass two (``traverse``): combine local variables to abstract "graphs".
  19. ## Strict func checking: Ensure that graphs that are connected to
  20. ## const parameters are not mutated.
  21. ## Cursor inference: Ensure that potential cursors are not
  22. ## borrowed from locations that are connected to a graph
  23. ## that is mutated during the liveness of the cursor.
  24. ## (We track all possible mutations of a graph.)
  25. ##
  26. ## See https://nim-lang.github.io/Nim/manual_experimental.html#view-types-algorithm
  27. ## for a high-level description of how borrow checking works.
  28. import ast, types, lineinfos, options, msgs, renderer, typeallowed
  29. from trees import getMagic, isNoSideEffectPragma, stupidStmtListExpr
  30. from isolation_check import canAlias
  31. type
  32. AbstractTime = distinct int
  33. const
  34. MaxTime = AbstractTime high(int)
  35. MinTime = AbstractTime(-1)
  36. proc `<=`(a, b: AbstractTime): bool {.borrow.}
  37. proc `<`(a, b: AbstractTime): bool {.borrow.}
  38. proc inc(x: var AbstractTime; diff = 1) {.borrow.}
  39. proc dec(x: var AbstractTime; diff = 1) {.borrow.}
  40. type
  41. SubgraphFlag = enum
  42. isMutated, # graph might be mutated
  43. isMutatedDirectly, # graph is mutated directly by a non-var parameter.
  44. connectsConstParam # graph is connected to a non-var parameter.
  45. VarFlag = enum
  46. ownsData,
  47. preventCursor,
  48. isReassigned,
  49. viewDoesMutate,
  50. viewBorrowsFromConst
  51. VarIndexKind = enum
  52. isEmptyRoot,
  53. dependsOn,
  54. isRootOf
  55. Connection = object
  56. case kind: VarIndexKind
  57. of isEmptyRoot: discard
  58. of dependsOn: parent: int
  59. of isRootOf: graphIndex: int
  60. VarIndex = object
  61. con: Connection
  62. flags: set[VarFlag]
  63. sym: PSym
  64. reassignedTo: int
  65. aliveStart, aliveEnd: AbstractTime # the range for which the variable is alive.
  66. borrowsFrom: seq[int] # indexes into Partitions.s
  67. MutationInfo* = object
  68. param: PSym
  69. mutatedHere, connectedVia: TLineInfo
  70. flags: set[SubgraphFlag]
  71. maxMutation, minConnection: AbstractTime
  72. mutations: seq[AbstractTime]
  73. Goal* = enum
  74. constParameters,
  75. borrowChecking,
  76. cursorInference
  77. Partitions* = object
  78. abstractTime: AbstractTime
  79. s: seq[VarIndex]
  80. graphs: seq[MutationInfo]
  81. goals: set[Goal]
  82. unanalysableMutation: bool
  83. inAsgnSource, inConstructor, inNoSideEffectSection: int
  84. owner: PSym
  85. config: ConfigRef
  86. proc mutationAfterConnection(g: MutationInfo): bool {.inline.} =
  87. #echo g.maxMutation.int, " ", g.minConnection.int, " ", g.param
  88. g.maxMutation > g.minConnection
  89. proc `$`*(config: ConfigRef; g: MutationInfo): string =
  90. result = ""
  91. if g.flags * {isMutated, connectsConstParam} == {isMutated, connectsConstParam}:
  92. result.add "\nan object reachable from '"
  93. result.add g.param.name.s
  94. result.add "' is potentially mutated"
  95. if g.mutatedHere != unknownLineInfo:
  96. result.add "\n"
  97. result.add config $ g.mutatedHere
  98. result.add " the mutation is here"
  99. if g.connectedVia != unknownLineInfo:
  100. result.add "\n"
  101. result.add config $ g.connectedVia
  102. result.add " is the statement that connected the mutation to the parameter"
  103. proc hasSideEffect*(c: var Partitions; info: var MutationInfo): bool =
  104. for g in mitems c.graphs:
  105. if g.flags * {isMutated, connectsConstParam} == {isMutated, connectsConstParam} and
  106. (mutationAfterConnection(g) or isMutatedDirectly in g.flags):
  107. info = g
  108. return true
  109. return false
  110. template isConstParam(a): bool = a.kind == skParam and a.typ.kind != tyVar
  111. proc variableId(c: Partitions; x: PSym): int =
  112. for i in 0 ..< c.s.len:
  113. if c.s[i].sym == x: return i
  114. return -1
  115. proc registerResult(c: var Partitions; n: PNode) =
  116. if n.kind == nkSym:
  117. c.s.add VarIndex(con: Connection(kind: isEmptyRoot), sym: n.sym, reassignedTo: 0,
  118. aliveStart: MaxTime, aliveEnd: c.abstractTime)
  119. proc registerParam(c: var Partitions; n: PNode) =
  120. assert n.kind == nkSym
  121. if isConstParam(n.sym):
  122. c.s.add VarIndex(con: Connection(kind: isRootOf, graphIndex: c.graphs.len),
  123. sym: n.sym, reassignedTo: 0,
  124. aliveStart: c.abstractTime, aliveEnd: c.abstractTime)
  125. c.graphs.add MutationInfo(param: n.sym, mutatedHere: unknownLineInfo,
  126. connectedVia: unknownLineInfo, flags: {connectsConstParam},
  127. maxMutation: MinTime, minConnection: MaxTime,
  128. mutations: @[])
  129. else:
  130. c.s.add VarIndex(con: Connection(kind: isEmptyRoot), sym: n.sym, reassignedTo: 0,
  131. aliveStart: c.abstractTime, aliveEnd: c.abstractTime)
  132. proc registerVariable(c: var Partitions; n: PNode) =
  133. if n.kind == nkSym and variableId(c, n.sym) < 0:
  134. c.s.add VarIndex(con: Connection(kind: isEmptyRoot), sym: n.sym, reassignedTo: 0,
  135. aliveStart: c.abstractTime, aliveEnd: c.abstractTime)
  136. proc root(v: var Partitions; start: int): int =
  137. result = start
  138. var depth = 0
  139. while v.s[result].con.kind == dependsOn:
  140. result = v.s[result].con.parent
  141. inc depth
  142. if depth > 0:
  143. # path compression:
  144. var it = start
  145. while v.s[it].con.kind == dependsOn:
  146. let next = v.s[it].con.parent
  147. v.s[it].con = Connection(kind: dependsOn, parent: result)
  148. it = next
  149. proc potentialMutation(v: var Partitions; s: PSym; info: TLineInfo) =
  150. let id = variableId(v, s)
  151. if id >= 0:
  152. let r = root(v, id)
  153. let flags = if s.kind == skParam and isConstParam(s):
  154. {isMutated, isMutatedDirectly}
  155. else:
  156. {isMutated}
  157. case v.s[r].con.kind
  158. of isEmptyRoot:
  159. v.s[r].con = Connection(kind: isRootOf, graphIndex: v.graphs.len)
  160. v.graphs.add MutationInfo(param: if isConstParam(s): s else: nil, mutatedHere: info,
  161. connectedVia: unknownLineInfo, flags: flags,
  162. maxMutation: v.abstractTime, minConnection: MaxTime,
  163. mutations: @[v.abstractTime])
  164. of isRootOf:
  165. let g = addr v.graphs[v.s[r].con.graphIndex]
  166. if g.param == nil and isConstParam(s):
  167. g.param = s
  168. if v.abstractTime > g.maxMutation:
  169. g.mutatedHere = info
  170. g.maxMutation = v.abstractTime
  171. g.flags.incl flags
  172. g.mutations.add v.abstractTime
  173. else:
  174. assert false, "cannot happen"
  175. else:
  176. v.unanalysableMutation = true
  177. proc connect(v: var Partitions; a, b: PSym; info: TLineInfo) =
  178. let aid = variableId(v, a)
  179. if aid < 0:
  180. return
  181. let bid = variableId(v, b)
  182. if bid < 0:
  183. return
  184. let ra = root(v, aid)
  185. let rb = root(v, bid)
  186. if ra != rb:
  187. var param = PSym(nil)
  188. if isConstParam(a): param = a
  189. elif isConstParam(b): param = b
  190. let paramFlags =
  191. if param != nil:
  192. {connectsConstParam}
  193. else:
  194. {}
  195. # for now we always make 'rb' the slave and 'ra' the master:
  196. var rbFlags: set[SubgraphFlag] = {}
  197. var mutatedHere = unknownLineInfo
  198. var mut = AbstractTime 0
  199. var con = v.abstractTime
  200. var gb: ptr MutationInfo = nil
  201. if v.s[rb].con.kind == isRootOf:
  202. gb = addr v.graphs[v.s[rb].con.graphIndex]
  203. if param == nil: param = gb.param
  204. mutatedHere = gb.mutatedHere
  205. rbFlags = gb.flags
  206. mut = gb.maxMutation
  207. con = min(con, gb.minConnection)
  208. v.s[rb].con = Connection(kind: dependsOn, parent: ra)
  209. case v.s[ra].con.kind
  210. of isEmptyRoot:
  211. v.s[ra].con = Connection(kind: isRootOf, graphIndex: v.graphs.len)
  212. v.graphs.add MutationInfo(param: param, mutatedHere: mutatedHere,
  213. connectedVia: info, flags: paramFlags + rbFlags,
  214. maxMutation: mut, minConnection: con,
  215. mutations: if gb != nil: gb.mutations else: @[])
  216. of isRootOf:
  217. var g = addr v.graphs[v.s[ra].con.graphIndex]
  218. if g.param == nil: g.param = param
  219. if g.mutatedHere == unknownLineInfo: g.mutatedHere = mutatedHere
  220. g.minConnection = min(g.minConnection, con)
  221. g.connectedVia = info
  222. g.flags.incl paramFlags + rbFlags
  223. if gb != nil:
  224. g.mutations.add gb.mutations
  225. else:
  226. assert false, "cannot happen"
  227. proc borrowFromConstExpr(n: PNode): bool =
  228. case n.kind
  229. of nkCharLit..nkNilLit:
  230. result = true
  231. of nkExprEqExpr, nkExprColonExpr, nkHiddenStdConv, nkHiddenSubConv,
  232. nkCast, nkObjUpConv, nkObjDownConv:
  233. result = borrowFromConstExpr(n.lastSon)
  234. of nkCurly, nkBracket, nkPar, nkTupleConstr, nkObjConstr, nkClosure, nkRange:
  235. result = true
  236. for i in ord(n.kind == nkObjConstr)..<n.len:
  237. if not borrowFromConstExpr(n[i]): return false
  238. of nkCallKinds:
  239. if getMagic(n) == mArrToSeq:
  240. result = true
  241. for i in 1..<n.len:
  242. if not borrowFromConstExpr(n[i]): return false
  243. else: discard
  244. proc pathExpr(node: PNode; owner: PSym): PNode =
  245. #[ From the spec:
  246. - ``source`` itself is a path expression.
  247. - Container access like ``e[i]`` is a path expression.
  248. - Tuple access ``e[0]`` is a path expression.
  249. - Object field access ``e.field`` is a path expression.
  250. - ``system.toOpenArray(e, ...)`` is a path expression.
  251. - Pointer dereference ``e[]`` is a path expression.
  252. - An address ``addr e``, ``unsafeAddr e`` is a path expression.
  253. - A type conversion ``T(e)`` is a path expression.
  254. - A cast expression ``cast[T](e)`` is a path expression.
  255. - ``f(e, ...)`` is a path expression if ``f``'s return type is a view type.
  256. Because the view can only have been borrowed from ``e``, we then know
  257. that owner of ``f(e, ...)`` is ``e``.
  258. Returns the owner of the path expression. Returns ``nil``
  259. if it is not a valid path expression.
  260. ]#
  261. var n = node
  262. result = nil
  263. while true:
  264. case n.kind
  265. of nkSym:
  266. case n.sym.kind
  267. of skParam, skTemp, skResult, skForVar:
  268. if n.sym.owner == owner: result = n
  269. of skVar:
  270. if n.sym.owner == owner or sfThread in n.sym.flags: result = n
  271. of skLet, skConst:
  272. if n.sym.owner == owner or {sfThread, sfGlobal} * n.sym.flags != {}:
  273. result = n
  274. else:
  275. discard
  276. break
  277. of nkDotExpr, nkDerefExpr, nkBracketExpr, nkHiddenDeref,
  278. nkCheckedFieldExpr, nkAddr, nkHiddenAddr:
  279. n = n[0]
  280. of nkHiddenStdConv, nkHiddenSubConv, nkConv, nkCast,
  281. nkObjUpConv, nkObjDownConv:
  282. n = n.lastSon
  283. of nkStmtList, nkStmtListExpr:
  284. if n.len > 0 and stupidStmtListExpr(n):
  285. n = n.lastSon
  286. else:
  287. break
  288. of nkCallKinds:
  289. if n.len > 1:
  290. if (n.typ != nil and classifyViewType(n.typ) != noView) or getMagic(n) == mSlice:
  291. n = n[1]
  292. else:
  293. break
  294. else:
  295. break
  296. else:
  297. break
  298. # borrowFromConstExpr(n) is correct here because we need 'node'
  299. # stripped off the path suffixes:
  300. if result == nil and borrowFromConstExpr(n):
  301. result = n
  302. proc allRoots(n: PNode; result: var seq[PSym]; followDotExpr = true) =
  303. case n.kind
  304. of nkSym:
  305. if n.sym.kind in {skParam, skVar, skTemp, skLet, skResult, skForVar}:
  306. result.add(n.sym)
  307. of nkDotExpr, nkDerefExpr, nkBracketExpr, nkHiddenDeref,
  308. nkCheckedFieldExpr, nkAddr, nkHiddenAddr:
  309. if followDotExpr:
  310. allRoots(n[0], result, followDotExpr)
  311. of nkExprEqExpr, nkExprColonExpr, nkHiddenStdConv, nkHiddenSubConv, nkConv,
  312. nkStmtList, nkStmtListExpr, nkBlockStmt, nkBlockExpr, nkCast,
  313. nkObjUpConv, nkObjDownConv:
  314. if n.len > 0:
  315. allRoots(n.lastSon, result, followDotExpr)
  316. of nkCaseStmt, nkObjConstr:
  317. for i in 1..<n.len:
  318. allRoots(n[i].lastSon, result, followDotExpr)
  319. of nkIfStmt, nkIfExpr:
  320. for i in 0..<n.len:
  321. allRoots(n[i].lastSon, result, followDotExpr)
  322. of nkBracket, nkTupleConstr, nkPar:
  323. for i in 0..<n.len:
  324. allRoots(n[i], result, followDotExpr)
  325. of nkCallKinds:
  326. if n.typ != nil and n.typ.kind in {tyVar, tyLent}:
  327. if n.len > 1:
  328. allRoots(n[1], result, followDotExpr)
  329. else:
  330. let m = getMagic(n)
  331. case m
  332. of mNone:
  333. if n[0].typ.isNil: return
  334. var typ = n[0].typ
  335. if typ != nil:
  336. typ = skipTypes(typ, abstractInst)
  337. if typ.kind != tyProc: typ = nil
  338. else: assert(typ.len == typ.n.len)
  339. for i in 1 ..< n.len:
  340. let it = n[i]
  341. if typ != nil and i < typ.len:
  342. assert(typ.n[i].kind == nkSym)
  343. let paramType = typ.n[i].typ
  344. if not paramType.isCompileTimeOnly and not typ.sons[0].isEmptyType and
  345. canAlias(paramType, typ.sons[0]):
  346. allRoots(it, result, followDotExpr)
  347. else:
  348. allRoots(it, result, followDotExpr)
  349. of mSlice:
  350. allRoots(n[1], result, followDotExpr)
  351. else:
  352. discard "harmless operation"
  353. else:
  354. discard "nothing to do"
  355. proc destMightOwn(c: var Partitions; dest: var VarIndex; n: PNode) =
  356. ## Analyse if 'n' is an expression that owns the data, if so mark 'dest'
  357. ## with 'ownsData'.
  358. case n.kind
  359. of nkEmpty, nkCharLit..nkNilLit:
  360. # primitive literals including the empty are harmless:
  361. discard
  362. of nkExprEqExpr, nkExprColonExpr, nkHiddenStdConv, nkHiddenSubConv, nkCast, nkConv:
  363. destMightOwn(c, dest, n[1])
  364. of nkIfStmt, nkIfExpr:
  365. for i in 0..<n.len:
  366. destMightOwn(c, dest, n[i].lastSon)
  367. of nkCaseStmt:
  368. for i in 1..<n.len:
  369. destMightOwn(c, dest, n[i].lastSon)
  370. of nkStmtList, nkStmtListExpr:
  371. if n.len > 0:
  372. destMightOwn(c, dest, n[^1])
  373. of nkClosure:
  374. for i in 1..<n.len:
  375. destMightOwn(c, dest, n[i])
  376. # you must destroy a closure:
  377. dest.flags.incl ownsData
  378. of nkObjConstr:
  379. for i in 1..<n.len:
  380. destMightOwn(c, dest, n[i])
  381. if hasDestructor(n.typ):
  382. # you must destroy a ref object:
  383. dest.flags.incl ownsData
  384. of nkCurly, nkBracket, nkPar, nkTupleConstr:
  385. inc c.inConstructor
  386. for son in n:
  387. destMightOwn(c, dest, son)
  388. dec c.inConstructor
  389. if n.typ.skipTypes(abstractInst).kind == tySequence:
  390. # you must destroy a sequence:
  391. dest.flags.incl ownsData
  392. of nkSym:
  393. if n.sym.kind in {skVar, skResult, skTemp, skLet, skForVar, skParam}:
  394. if n.sym.flags * {sfThread, sfGlobal} != {}:
  395. # aliasing a global is inherently dangerous:
  396. dest.flags.incl ownsData
  397. else:
  398. # otherwise it's just a dependency, nothing to worry about:
  399. connect(c, dest.sym, n.sym, n.info)
  400. # but a construct like ``[symbol]`` is dangerous:
  401. if c.inConstructor > 0: dest.flags.incl ownsData
  402. of nkDotExpr, nkBracketExpr, nkHiddenDeref, nkDerefExpr,
  403. nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr, nkAddr, nkHiddenAddr:
  404. destMightOwn(c, dest, n[0])
  405. of nkCallKinds:
  406. if hasDestructor(n.typ):
  407. # calls do construct, what we construct must be destroyed,
  408. # so dest cannot be a cursor:
  409. dest.flags.incl ownsData
  410. elif n.typ.kind in {tyLent, tyVar}:
  411. # we know the result is derived from the first argument:
  412. var roots: seq[PSym]
  413. allRoots(n[1], roots)
  414. for r in roots:
  415. connect(c, dest.sym, r, n[1].info)
  416. else:
  417. let magic = if n[0].kind == nkSym: n[0].sym.magic else: mNone
  418. # this list is subtle, we try to answer the question if after 'dest = f(src)'
  419. # there is a connection betwen 'src' and 'dest' so that mutations to 'src'
  420. # also reflect 'dest':
  421. if magic in {mNone, mMove, mSlice, mAppendStrCh, mAppendStrStr, mAppendSeqElem, mArrToSeq}:
  422. for i in 1..<n.len:
  423. # we always have to assume a 'select(...)' like mechanism.
  424. # But at least we do filter out simple POD types from the
  425. # list of dependencies via the 'hasDestructor' check for
  426. # the root's symbol.
  427. if hasDestructor(n[i].typ.skipTypes({tyVar, tySink, tyLent, tyGenericInst, tyAlias})):
  428. destMightOwn(c, dest, n[i])
  429. else:
  430. # something we cannot handle:
  431. dest.flags.incl preventCursor
  432. proc noCursor(c: var Partitions, s: PSym) =
  433. let vid = variableId(c, s)
  434. if vid >= 0:
  435. c.s[vid].flags.incl preventCursor
  436. proc pretendOwnsData(c: var Partitions, s: PSym) =
  437. let vid = variableId(c, s)
  438. if vid >= 0:
  439. c.s[vid].flags.incl ownsData
  440. const
  441. explainCursors = false
  442. proc isConstSym(s: PSym): bool =
  443. result = s.kind in {skConst, skLet} or isConstParam(s)
  444. proc borrowFrom(c: var Partitions; dest: PSym; src: PNode) =
  445. const
  446. url = "see https://nim-lang.github.io/Nim/manual_experimental.html#view-types-algorithm-path-expressions for details"
  447. let s = pathExpr(src, c.owner)
  448. if s == nil:
  449. localError(c.config, src.info, "cannot borrow from " & $src & ", it is not a path expression; " & url)
  450. elif s.kind == nkSym:
  451. if dest.kind == skResult:
  452. if s.sym.kind != skParam or s.sym.position != 0:
  453. localError(c.config, src.info, "'result' must borrow from the first parameter")
  454. let vid = variableId(c, dest)
  455. if vid >= 0:
  456. var sourceIdx = variableId(c, s.sym)
  457. if sourceIdx < 0:
  458. sourceIdx = c.s.len
  459. c.s.add VarIndex(con: Connection(kind: isEmptyRoot), sym: s.sym, reassignedTo: 0,
  460. aliveStart: MinTime, aliveEnd: MaxTime)
  461. c.s[vid].borrowsFrom.add sourceIdx
  462. if isConstSym(s.sym):
  463. c.s[vid].flags.incl viewBorrowsFromConst
  464. else:
  465. let vid = variableId(c, dest)
  466. if vid >= 0:
  467. c.s[vid].flags.incl viewBorrowsFromConst
  468. #discard "a valid borrow location that is a deeply constant expression so we have nothing to track"
  469. proc borrowingCall(c: var Partitions; destType: PType; n: PNode; i: int) =
  470. let v = pathExpr(n[i], c.owner)
  471. if v != nil and v.kind == nkSym:
  472. when false:
  473. let isView = directViewType(destType) == immutableView
  474. if n[0].kind == nkSym and n[0].sym.name.s == "[]=":
  475. localError(c.config, n[i].info, "attempt to mutate an immutable view")
  476. for j in i+1..<n.len:
  477. if getMagic(n[j]) == mSlice:
  478. borrowFrom(c, v.sym, n[j])
  479. else:
  480. localError(c.config, n[i].info, "cannot determine the target of the borrow")
  481. proc borrowingAsgn(c: var Partitions; dest, src: PNode) =
  482. if dest.kind == nkSym:
  483. if directViewType(dest.typ) != noView:
  484. borrowFrom(c, dest.sym, src)
  485. elif dest.kind in {nkHiddenDeref, nkDerefExpr, nkBracketExpr}:
  486. case directViewType(dest[0].typ)
  487. of mutableView:
  488. # we do not borrow, but we use the view to mutate the borrowed
  489. # location:
  490. let viewOrigin = pathExpr(dest, c.owner)
  491. if viewOrigin.kind == nkSym:
  492. let vid = variableId(c, viewOrigin.sym)
  493. if vid >= 0:
  494. c.s[vid].flags.incl viewDoesMutate
  495. of immutableView:
  496. localError(c.config, dest.info, "attempt to mutate a borrowed location from an immutable view")
  497. of noView: discard "nothing to do"
  498. proc containsPointer(t: PType): bool =
  499. proc wrap(t: PType): bool {.nimcall.} = t.kind in {tyRef, tyPtr}
  500. result = types.searchTypeFor(t, wrap)
  501. proc deps(c: var Partitions; dest, src: PNode) =
  502. if borrowChecking in c.goals:
  503. borrowingAsgn(c, dest, src)
  504. var targets, sources: seq[PSym]
  505. allRoots(dest, targets)
  506. allRoots(src, sources)
  507. let destIsComplex = containsPointer(dest.typ)
  508. for t in targets:
  509. if dest.kind != nkSym and c.inNoSideEffectSection == 0:
  510. potentialMutation(c, t, dest.info)
  511. if destIsComplex:
  512. for s in sources:
  513. connect(c, t, s, dest.info)
  514. if cursorInference in c.goals and src.kind != nkEmpty:
  515. if dest.kind == nkSym:
  516. let vid = variableId(c, dest.sym)
  517. if vid >= 0:
  518. destMightOwn(c, c.s[vid], src)
  519. for s in sources:
  520. if s == dest.sym:
  521. discard "assignments like: it = it.next are fine"
  522. elif {sfGlobal, sfThread} * s.flags != {} or hasDisabledAsgn(s.typ):
  523. # do not borrow from a global variable or from something with a
  524. # disabled assignment operator.
  525. c.s[vid].flags.incl preventCursor
  526. when explainCursors: echo "A not a cursor: ", dest.sym, " ", s
  527. else:
  528. let srcid = variableId(c, s)
  529. if srcid >= 0:
  530. if s.kind notin {skResult, skParam} and (
  531. c.s[srcid].aliveEnd < c.s[vid].aliveEnd):
  532. # you cannot borrow from a local that lives shorter than 'vid':
  533. when explainCursors: echo "B not a cursor ", dest.sym, " ", c.s[srcid].aliveEnd, " ", c.s[vid].aliveEnd
  534. c.s[vid].flags.incl preventCursor
  535. elif {isReassigned, preventCursor} * c.s[srcid].flags != {}:
  536. # you cannot borrow from something that is re-assigned:
  537. when explainCursors: echo "C not a cursor ", dest.sym, " ", c.s[srcid].flags, " reassignedTo ", c.s[srcid].reassignedTo
  538. c.s[vid].flags.incl preventCursor
  539. elif c.s[srcid].reassignedTo != 0 and c.s[srcid].reassignedTo != dest.sym.id:
  540. when explainCursors: echo "D not a cursor ", dest.sym, " reassignedTo ", c.s[srcid].reassignedTo
  541. c.s[vid].flags.incl preventCursor
  542. const
  543. nodesToIgnoreSet = {nkNone..pred(nkSym), succ(nkSym)..nkNilLit,
  544. nkTypeSection, nkProcDef, nkConverterDef,
  545. nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo,
  546. nkFuncDef, nkConstSection, nkConstDef, nkIncludeStmt, nkImportStmt,
  547. nkExportStmt, nkPragma, nkCommentStmt, nkBreakState, nkTypeOfExpr}
  548. proc potentialMutationViaArg(c: var Partitions; n: PNode; callee: PType) =
  549. if constParameters in c.goals and tfNoSideEffect in callee.flags:
  550. discard "we know there are no hidden mutations through an immutable parameter"
  551. elif c.inNoSideEffectSection == 0 and containsPointer(n.typ):
  552. var roots: seq[PSym]
  553. allRoots(n, roots)
  554. for r in roots: potentialMutation(c, r, n.info)
  555. proc traverse(c: var Partitions; n: PNode) =
  556. inc c.abstractTime
  557. case n.kind
  558. of nkLetSection, nkVarSection:
  559. for child in n:
  560. let last = lastSon(child)
  561. traverse(c, last)
  562. if child.kind == nkVarTuple and last.kind in {nkPar, nkTupleConstr}:
  563. if child.len-2 != last.len: return
  564. for i in 0..<child.len-2:
  565. #registerVariable(c, child[i])
  566. deps(c, child[i], last[i])
  567. else:
  568. for i in 0..<child.len-2:
  569. #registerVariable(c, child[i])
  570. deps(c, child[i], last)
  571. of nkAsgn, nkFastAsgn:
  572. traverse(c, n[0])
  573. inc c.inAsgnSource
  574. traverse(c, n[1])
  575. dec c.inAsgnSource
  576. deps(c, n[0], n[1])
  577. of nkSym:
  578. dec c.abstractTime
  579. of nodesToIgnoreSet:
  580. dec c.abstractTime
  581. discard "do not follow the construct"
  582. of nkCallKinds:
  583. for child in n: traverse(c, child)
  584. let parameters = n[0].typ
  585. let L = if parameters != nil: parameters.len else: 0
  586. let m = getMagic(n)
  587. for i in 1..<n.len:
  588. let it = n[i]
  589. if i < L:
  590. let paramType = parameters[i].skipTypes({tyGenericInst, tyAlias})
  591. if not paramType.isCompileTimeOnly and paramType.kind in {tyVar, tySink, tyOwned}:
  592. var roots: seq[PSym]
  593. allRoots(it, roots)
  594. if paramType.kind == tyVar:
  595. if c.inNoSideEffectSection == 0:
  596. for r in roots: potentialMutation(c, r, it.info)
  597. for r in roots: noCursor(c, r)
  598. if borrowChecking in c.goals:
  599. # a call like 'result.add toOpenArray()' can also be a borrow
  600. # operation. We know 'paramType' is a tyVar and we really care if
  601. # 'paramType[0]' is still a view type, this is not a typo!
  602. if directViewType(paramType[0]) == noView and classifyViewType(paramType[0]) != noView:
  603. borrowingCall(c, paramType[0], n, i)
  604. elif borrowChecking in c.goals and m == mNone:
  605. potentialMutationViaArg(c, n[i], parameters)
  606. of nkAddr, nkHiddenAddr:
  607. traverse(c, n[0])
  608. when false:
  609. # XXX investigate if this is required, it doesn't look
  610. # like it is!
  611. var roots: seq[PSym]
  612. allRoots(n[0], roots)
  613. for r in roots:
  614. potentialMutation(c, r, it.info)
  615. of nkTupleConstr, nkBracket:
  616. for child in n: traverse(c, child)
  617. if c.inAsgnSource > 0:
  618. for i in 0..<n.len:
  619. if n[i].kind == nkSym:
  620. # we assume constructions with cursors are better without
  621. # the cursors because it's likely we can move then, see
  622. # test arc/topt_no_cursor.nim
  623. pretendOwnsData(c, n[i].sym)
  624. of nkObjConstr:
  625. for child in n: traverse(c, child)
  626. if c.inAsgnSource > 0:
  627. for i in 1..<n.len:
  628. let it = n[i].skipColon
  629. if it.kind == nkSym:
  630. # we assume constructions with cursors are better without
  631. # the cursors because it's likely we can move then, see
  632. # test arc/topt_no_cursor.nim
  633. pretendOwnsData(c, it.sym)
  634. of nkPragmaBlock:
  635. let pragmaList = n[0]
  636. var enforceNoSideEffects = 0
  637. for i in 0..<pragmaList.len:
  638. if isNoSideEffectPragma(pragmaList[i]):
  639. enforceNoSideEffects = 1
  640. break
  641. inc c.inNoSideEffectSection, enforceNoSideEffects
  642. traverse(c, n.lastSon)
  643. dec c.inNoSideEffectSection, enforceNoSideEffects
  644. of nkWhileStmt, nkForStmt, nkParForStmt:
  645. for child in n: traverse(c, child)
  646. # analyse loops twice so that 'abstractTime' suffices to detect cases
  647. # like:
  648. # while cond:
  649. # mutate(graph)
  650. # connect(graph, cursorVar)
  651. for child in n: traverse(c, child)
  652. else:
  653. for child in n: traverse(c, child)
  654. proc computeLiveRanges(c: var Partitions; n: PNode) =
  655. # first pass: Compute live ranges for locals.
  656. # **Watch out!** We must traverse the tree like 'traverse' does
  657. # so that the 'c.abstractTime' is consistent.
  658. inc c.abstractTime
  659. case n.kind
  660. of nkLetSection, nkVarSection:
  661. for child in n:
  662. let last = lastSon(child)
  663. computeLiveRanges(c, last)
  664. if child.kind == nkVarTuple and last.kind in {nkPar, nkTupleConstr}:
  665. if child.len-2 != last.len: return
  666. for i in 0..<child.len-2:
  667. registerVariable(c, child[i])
  668. #deps(c, child[i], last[i])
  669. else:
  670. for i in 0..<child.len-2:
  671. registerVariable(c, child[i])
  672. #deps(c, child[i], last)
  673. of nkAsgn, nkFastAsgn:
  674. computeLiveRanges(c, n[0])
  675. computeLiveRanges(c, n[1])
  676. if n[0].kind == nkSym:
  677. let vid = variableId(c, n[0].sym)
  678. if vid >= 0:
  679. if n[1].kind == nkSym and (c.s[vid].reassignedTo == 0 or c.s[vid].reassignedTo == n[1].sym.id):
  680. c.s[vid].reassignedTo = n[1].sym.id
  681. else:
  682. c.s[vid].flags.incl isReassigned
  683. of nkSym:
  684. dec c.abstractTime
  685. if n.sym.kind in {skVar, skResult, skTemp, skLet, skForVar, skParam}:
  686. let id = variableId(c, n.sym)
  687. if id >= 0:
  688. c.s[id].aliveEnd = max(c.s[id].aliveEnd, c.abstractTime)
  689. if n.sym.kind == skResult:
  690. c.s[id].aliveStart = min(c.s[id].aliveStart, c.abstractTime)
  691. of nodesToIgnoreSet:
  692. dec c.abstractTime
  693. discard "do not follow the construct"
  694. of nkCallKinds:
  695. for child in n: computeLiveRanges(c, child)
  696. let parameters = n[0].typ
  697. let L = if parameters != nil: parameters.len else: 0
  698. for i in 1..<n.len:
  699. let it = n[i]
  700. if it.kind == nkSym and i < L:
  701. let paramType = parameters[i].skipTypes({tyGenericInst, tyAlias})
  702. if not paramType.isCompileTimeOnly and paramType.kind == tyVar:
  703. let vid = variableId(c, it.sym)
  704. if vid >= 0:
  705. c.s[vid].flags.incl isReassigned
  706. of nkAddr, nkHiddenAddr:
  707. computeLiveRanges(c, n[0])
  708. if n[0].kind == nkSym:
  709. let vid = variableId(c, n[0].sym)
  710. if vid >= 0:
  711. c.s[vid].flags.incl preventCursor
  712. of nkPragmaBlock:
  713. computeLiveRanges(c, n.lastSon)
  714. of nkWhileStmt, nkForStmt, nkParForStmt:
  715. for child in n: computeLiveRanges(c, child)
  716. # analyse loops twice so that 'abstractTime' suffices to detect cases
  717. # like:
  718. # while cond:
  719. # mutate(graph)
  720. # connect(graph, cursorVar)
  721. for child in n: computeLiveRanges(c, child)
  722. else:
  723. for child in n: computeLiveRanges(c, child)
  724. proc computeGraphPartitions*(s: PSym; n: PNode; config: ConfigRef; goals: set[Goal]): Partitions =
  725. result = Partitions(owner: s, config: config, goals: goals)
  726. if s.kind notin {skModule, skMacro}:
  727. let params = s.typ.n
  728. for i in 1..<params.len:
  729. registerParam(result, params[i])
  730. if resultPos < s.ast.safeLen:
  731. registerResult(result, s.ast[resultPos])
  732. computeLiveRanges(result, n)
  733. # restart the timer for the second pass:
  734. result.abstractTime = AbstractTime 0
  735. traverse(result, n)
  736. proc dangerousMutation(g: MutationInfo; v: VarIndex): bool =
  737. #echo "range ", v.aliveStart, " .. ", v.aliveEnd, " ", v.sym
  738. if isMutated in g.flags:
  739. for m in g.mutations:
  740. #echo "mutation ", m
  741. if m in v.aliveStart..v.aliveEnd:
  742. return true
  743. return false
  744. proc cannotBorrow(config: ConfigRef; s: PSym; g: MutationInfo) =
  745. var m = "cannot borrow " & s.name.s &
  746. "; what it borrows from is potentially mutated"
  747. if g.mutatedHere != unknownLineInfo:
  748. m.add "\n"
  749. m.add config $ g.mutatedHere
  750. m.add " the mutation is here"
  751. if g.connectedVia != unknownLineInfo:
  752. m.add "\n"
  753. m.add config $ g.connectedVia
  754. m.add " is the statement that connected the mutation to the parameter"
  755. localError(config, s.info, m)
  756. proc checkBorrowedLocations*(par: var Partitions; body: PNode; config: ConfigRef) =
  757. for i in 0 ..< par.s.len:
  758. let v = par.s[i].sym
  759. if v.kind != skParam and classifyViewType(v.typ) != noView:
  760. let rid = root(par, i)
  761. if rid >= 0:
  762. var constViolation = false
  763. for b in par.s[rid].borrowsFrom:
  764. let sid = root(par, b)
  765. if sid >= 0:
  766. if par.s[sid].con.kind == isRootOf and dangerousMutation(par.graphs[par.s[sid].con.graphIndex], par.s[i]):
  767. cannotBorrow(config, v, par.graphs[par.s[sid].con.graphIndex])
  768. if par.s[sid].sym.kind != skParam and par.s[sid].aliveEnd < par.s[rid].aliveEnd:
  769. localError(config, v.info, "'" & v.name.s & "' borrows from location '" & par.s[sid].sym.name.s &
  770. "' which does not live long enough")
  771. if viewDoesMutate in par.s[rid].flags and isConstSym(par.s[sid].sym):
  772. localError(config, v.info, "'" & v.name.s & "' borrows from the immutable location '" &
  773. par.s[sid].sym.name.s & "' and attempts to mutate it")
  774. constViolation = true
  775. if {viewDoesMutate, viewBorrowsFromConst} * par.s[rid].flags == {viewDoesMutate, viewBorrowsFromConst} and
  776. not constViolation:
  777. # we do not track the constant expressions we allow to borrow from so
  778. # we can only produce a more generic error message:
  779. localError(config, v.info, "'" & v.name.s &
  780. "' borrows from an immutable location and attempts to mutate it")
  781. #if par.s[rid].con.kind == isRootOf and dangerousMutation(par.graphs[par.s[rid].con.graphIndex], par.s[i]):
  782. # cannotBorrow(config, s, par.graphs[par.s[rid].con.graphIndex])
  783. proc computeCursors*(s: PSym; n: PNode; config: ConfigRef) =
  784. var par = computeGraphPartitions(s, n, config, {cursorInference})
  785. for i in 0 ..< par.s.len:
  786. let v = addr(par.s[i])
  787. if v.flags * {ownsData, preventCursor} == {} and v.sym.kind notin {skParam, skResult} and
  788. v.sym.flags * {sfThread, sfGlobal} == {} and hasDestructor(v.sym.typ) and
  789. v.sym.typ.skipTypes({tyGenericInst, tyAlias}).kind != tyOwned:
  790. let rid = root(par, i)
  791. if par.s[rid].con.kind == isRootOf and dangerousMutation(par.graphs[par.s[rid].con.graphIndex], par.s[i]):
  792. discard "cannot cursor into a graph that is mutated"
  793. else:
  794. v.sym.flags.incl sfCursor
  795. #echo "this is now a cursor ", v.sym, " ", par.s[rid].flags, " ", config $ v.sym.info