varpartitions.nim 33 KB

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