varpartitions.nim 36 KB

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