varpartitions.nim 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  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. for i in 1 ..< n.len:
  362. let it = n[i]
  363. if typ != nil and i < typ.n.len:
  364. assert(typ.n[i].kind == nkSym)
  365. let paramType = typ.n[i].typ
  366. if not paramType.isCompileTimeOnly and not typ.returnType.isEmptyType and
  367. canAlias(paramType, typ.returnType):
  368. allRoots(it, result, RootEscapes)
  369. else:
  370. allRoots(it, result, RootEscapes)
  371. of mSlice:
  372. allRoots(n[1], result, level+1)
  373. else:
  374. discard "harmless operation"
  375. else:
  376. discard "nothing to do"
  377. proc destMightOwn(c: var Partitions; dest: var VarIndex; n: PNode) =
  378. ## Analyse if 'n' is an expression that owns the data, if so mark 'dest'
  379. ## with 'ownsData'.
  380. case n.kind
  381. of nkEmpty, nkCharLit..nkNilLit:
  382. # primitive literals including the empty are harmless:
  383. discard
  384. of nkExprEqExpr, nkExprColonExpr, nkHiddenStdConv, nkHiddenSubConv, nkCast, nkConv:
  385. destMightOwn(c, dest, n[1])
  386. of nkIfStmt, nkIfExpr:
  387. for i in 0..<n.len:
  388. destMightOwn(c, dest, n[i].lastSon)
  389. of nkCaseStmt:
  390. for i in 1..<n.len:
  391. destMightOwn(c, dest, n[i].lastSon)
  392. of nkStmtList, nkStmtListExpr:
  393. if n.len > 0:
  394. destMightOwn(c, dest, n[^1])
  395. of nkClosure:
  396. for i in 1..<n.len:
  397. destMightOwn(c, dest, n[i])
  398. # you must destroy a closure:
  399. dest.flags.incl ownsData
  400. of nkObjConstr:
  401. for i in 1..<n.len:
  402. destMightOwn(c, dest, n[i])
  403. if hasDestructor(n.typ):
  404. # you must destroy a ref object:
  405. dest.flags.incl ownsData
  406. of nkCurly, nkBracket, nkPar, nkTupleConstr:
  407. inc c.inConstructor
  408. for son in n:
  409. destMightOwn(c, dest, son)
  410. dec c.inConstructor
  411. if n.typ.skipTypes(abstractInst).kind == tySequence:
  412. # you must destroy a sequence:
  413. dest.flags.incl ownsData
  414. of nkSym:
  415. if n.sym.kind in {skVar, skResult, skTemp, skLet, skForVar, skParam}:
  416. if n.sym.flags * {sfThread, sfGlobal} != {}:
  417. # aliasing a global is inherently dangerous:
  418. dest.flags.incl ownsData
  419. else:
  420. # otherwise it's just a dependency, nothing to worry about:
  421. connect(c, dest.sym, n.sym, n.info)
  422. # but a construct like ``[symbol]`` is dangerous:
  423. if c.inConstructor > 0: dest.flags.incl ownsData
  424. of nkDotExpr, nkBracketExpr, nkHiddenDeref, nkDerefExpr,
  425. nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr, nkAddr, nkHiddenAddr:
  426. destMightOwn(c, dest, n[0])
  427. of nkCallKinds:
  428. if n.typ != nil:
  429. if hasDestructor(n.typ):
  430. # calls do construct, what we construct must be destroyed,
  431. # so dest cannot be a cursor:
  432. dest.flags.incl ownsData
  433. elif n.typ.kind in {tyLent, tyVar} and n.len > 1:
  434. # we know the result is derived from the first argument:
  435. var roots: seq[(PSym, int)] = @[]
  436. allRoots(n[1], roots, RootEscapes)
  437. for r in roots:
  438. connect(c, dest.sym, r[0], n[1].info)
  439. else:
  440. let magic = if n[0].kind == nkSym: n[0].sym.magic else: mNone
  441. # this list is subtle, we try to answer the question if after 'dest = f(src)'
  442. # there is a connection betwen 'src' and 'dest' so that mutations to 'src'
  443. # also reflect 'dest':
  444. if magic in {mNone, mMove, mSlice,
  445. mAppendStrCh, mAppendStrStr, mAppendSeqElem,
  446. mArrToSeq, mOpenArrayToSeq}:
  447. for i in 1..<n.len:
  448. # we always have to assume a 'select(...)' like mechanism.
  449. # But at least we do filter out simple POD types from the
  450. # list of dependencies via the 'hasDestructor' check for
  451. # the root's symbol.
  452. if hasDestructor(n[i].typ.skipTypes({tyVar, tySink, tyLent, tyGenericInst, tyAlias})):
  453. destMightOwn(c, dest, n[i])
  454. else:
  455. # something we cannot handle:
  456. dest.flags.incl preventCursor
  457. proc noCursor(c: var Partitions, s: PSym) =
  458. let vid = variableId(c, s)
  459. if vid >= 0:
  460. c.s[vid].flags.incl preventCursor
  461. proc pretendOwnsData(c: var Partitions, s: PSym) =
  462. let vid = variableId(c, s)
  463. if vid >= 0:
  464. c.s[vid].flags.incl ownsData
  465. const
  466. explainCursors = false
  467. proc isConstSym(s: PSym): bool =
  468. result = s.kind in {skConst, skLet} or isConstParam(s)
  469. proc toString(n: PNode): string =
  470. if n.kind == nkEmpty: result = "<empty>"
  471. else: result = $n
  472. proc borrowFrom(c: var Partitions; dest: PSym; src: PNode) =
  473. const
  474. url = "see https://nim-lang.github.io/Nim/manual_experimental.html#view-types-algorithm-path-expressions for details"
  475. let s = pathExpr(src, c.owner)
  476. if s == nil:
  477. localError(c.g.config, src.info, "cannot borrow from " & src.toString & ", it is not a path expression; " & url)
  478. elif s.kind == nkSym:
  479. if dest.kind == skResult:
  480. if s.sym.kind != skParam or s.sym.position != 0:
  481. localError(c.g.config, src.info, "'result' must borrow from the first parameter")
  482. let vid = variableId(c, dest)
  483. if vid >= 0:
  484. var sourceIdx = variableId(c, s.sym)
  485. if sourceIdx < 0:
  486. sourceIdx = c.s.len
  487. c.s.add VarIndex(con: Connection(kind: isEmptyRoot), sym: s.sym, reassignedTo: 0,
  488. aliveStart: MinTime, aliveEnd: MaxTime)
  489. c.s[vid].borrowsFrom.add sourceIdx
  490. if isConstSym(s.sym):
  491. c.s[vid].flags.incl viewBorrowsFromConst
  492. else:
  493. let vid = variableId(c, dest)
  494. if vid >= 0:
  495. c.s[vid].flags.incl viewBorrowsFromConst
  496. #discard "a valid borrow location that is a deeply constant expression so we have nothing to track"
  497. proc borrowingCall(c: var Partitions; destType: PType; n: PNode; i: int) =
  498. let v = pathExpr(n[i], c.owner)
  499. if v != nil and v.kind == nkSym:
  500. when false:
  501. let isView = directViewType(destType) == immutableView
  502. if n[0].kind == nkSym and n[0].sym.name.s == "[]=":
  503. localError(c.g.config, n[i].info, "attempt to mutate an immutable view")
  504. for j in i+1..<n.len:
  505. if getMagic(n[j]) == mSlice:
  506. borrowFrom(c, v.sym, n[j])
  507. else:
  508. localError(c.g.config, n[i].info, "cannot determine the target of the borrow")
  509. proc borrowingAsgn(c: var Partitions; dest, src: PNode) =
  510. proc mutableParameter(n: PNode): bool {.inline.} =
  511. result = n.kind == nkSym and n.sym.kind == skParam and n.sym.typ.kind == tyVar
  512. if dest.kind == nkSym:
  513. if directViewType(dest.typ) != noView:
  514. borrowFrom(c, dest.sym, src)
  515. else:
  516. let viewOrigin = pathExpr(dest, c.owner)
  517. if viewOrigin != nil and viewOrigin.kind == nkSym:
  518. let viewSym = viewOrigin.sym
  519. let directView = directViewType(dest[0].typ) # check something like result[first] = toOpenArray(s, first, last-1)
  520. # so we don't need to iterate the original type
  521. let originSymbolView = directViewType(viewSym.typ) # find the original symbol which preserves the view type
  522. # var foo: var Object = a
  523. # foo.id = 777 # the type of foo is no view, so we need
  524. # to check the original symbol
  525. let viewSets = {directView, originSymbolView}
  526. if viewSets * {mutableView, immutableView} != {}:
  527. # we do not borrow, but we use the view to mutate the borrowed
  528. # location:
  529. let vid = variableId(c, viewSym)
  530. if vid >= 0:
  531. c.s[vid].flags.incl viewDoesMutate
  532. #[of immutableView:
  533. if dest.kind == nkBracketExpr and dest[0].kind == nkHiddenDeref and
  534. mutableParameter(dest[0][0]):
  535. discard "remains a mutable location anyhow"
  536. else:
  537. localError(c.g.config, dest.info, "attempt to mutate a borrowed location from an immutable view")
  538. ]#
  539. else:
  540. discard "nothing to do"
  541. proc containsPointer(t: PType): bool =
  542. proc wrap(t: PType): bool {.nimcall.} = t.kind in {tyRef, tyPtr}
  543. result = types.searchTypeFor(t, wrap)
  544. proc deps(c: var Partitions; dest, src: PNode) =
  545. if borrowChecking in c.goals:
  546. borrowingAsgn(c, dest, src)
  547. var targets: seq[(PSym, int)] = @[]
  548. var sources: seq[(PSym, int)] = @[]
  549. allRoots(dest, targets, 0)
  550. allRoots(src, sources, 0)
  551. let destIsComplex = containsPointer(dest.typ)
  552. for t in targets:
  553. if dest.kind != nkSym and c.inNoSideEffectSection == 0:
  554. potentialMutation(c, t[0], t[1], dest.info)
  555. if destIsComplex:
  556. for s in sources:
  557. connect(c, t[0], s[0], dest.info)
  558. if cursorInference in c.goals and src.kind != nkEmpty:
  559. let d = pathExpr(dest, c.owner)
  560. if d != nil and d.kind == nkSym:
  561. let vid = variableId(c, d.sym)
  562. if vid >= 0:
  563. destMightOwn(c, c.s[vid], src)
  564. for source in sources:
  565. let s = source[0]
  566. if s == d.sym:
  567. discard "assignments like: it = it.next are fine"
  568. elif {sfGlobal, sfThread} * s.flags != {} or hasDisabledAsgn(c.g, s.typ):
  569. # do not borrow from a global variable or from something with a
  570. # disabled assignment operator.
  571. c.s[vid].flags.incl preventCursor
  572. when explainCursors: echo "A not a cursor: ", d.sym, " ", s
  573. else:
  574. let srcid = variableId(c, s)
  575. if srcid >= 0:
  576. if s.kind notin {skResult, skParam} and (
  577. c.s[srcid].aliveEnd < c.s[vid].aliveEnd):
  578. # you cannot borrow from a local that lives shorter than 'vid':
  579. when explainCursors: echo "B not a cursor ", d.sym, " ", c.s[srcid].aliveEnd, " ", c.s[vid].aliveEnd
  580. c.s[vid].flags.incl preventCursor
  581. elif {isReassigned, preventCursor} * c.s[srcid].flags != {}:
  582. # you cannot borrow from something that is re-assigned:
  583. when explainCursors: echo "C not a cursor ", d.sym, " ", c.s[srcid].flags, " reassignedTo ", c.s[srcid].reassignedTo
  584. c.s[vid].flags.incl preventCursor
  585. elif c.s[srcid].reassignedTo != 0 and c.s[srcid].reassignedTo != d.sym.id:
  586. when explainCursors: echo "D not a cursor ", d.sym, " reassignedTo ", c.s[srcid].reassignedTo
  587. c.s[vid].flags.incl preventCursor
  588. proc potentialMutationViaArg(c: var Partitions; n: PNode; callee: PType) =
  589. if constParameters in c.goals and tfNoSideEffect in callee.flags:
  590. discard "we know there are no hidden mutations through an immutable parameter"
  591. elif c.inNoSideEffectSection == 0 and containsPointer(n.typ):
  592. var roots: seq[(PSym, int)] = @[]
  593. allRoots(n, roots, RootEscapes)
  594. for r in roots: potentialMutation(c, r[0], r[1], n.info)
  595. proc traverse(c: var Partitions; n: PNode) =
  596. inc c.abstractTime
  597. case n.kind
  598. of nkLetSection, nkVarSection:
  599. for child in n:
  600. let last = lastSon(child)
  601. traverse(c, last)
  602. if child.kind == nkVarTuple and last.kind in {nkPar, nkTupleConstr}:
  603. if child.len-2 != last.len: return
  604. for i in 0..<child.len-2:
  605. #registerVariable(c, child[i])
  606. deps(c, child[i], last[i])
  607. else:
  608. for i in 0..<child.len-2:
  609. #registerVariable(c, child[i])
  610. deps(c, child[i], last)
  611. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  612. traverse(c, n[0])
  613. inc c.inAsgnSource
  614. traverse(c, n[1])
  615. dec c.inAsgnSource
  616. deps(c, n[0], n[1])
  617. of nkSym:
  618. dec c.abstractTime
  619. of nodesToIgnoreSet:
  620. dec c.abstractTime
  621. discard "do not follow the construct"
  622. of nkCallKinds:
  623. for child in n: traverse(c, child)
  624. let parameters = n[0].typ
  625. let L = if parameters != nil: parameters.signatureLen else: 0
  626. let m = getMagic(n)
  627. if m == mEnsureMove and n[1].kind == nkSym:
  628. # we know that it must be moved so it cannot be a cursor
  629. noCursor(c, n[1].sym)
  630. for i in 1..<n.len:
  631. let it = n[i]
  632. if i < L:
  633. let paramType = parameters[i].skipTypes({tyGenericInst, tyAlias})
  634. if not paramType.isCompileTimeOnly and paramType.kind in {tyVar, tySink, tyOwned}:
  635. var roots: seq[(PSym, int)] = @[]
  636. allRoots(it, roots, RootEscapes)
  637. if paramType.kind == tyVar:
  638. if c.inNoSideEffectSection == 0:
  639. for r in roots: potentialMutation(c, r[0], r[1], it.info)
  640. for r in roots: noCursor(c, r[0])
  641. if borrowChecking in c.goals:
  642. # a call like 'result.add toOpenArray()' can also be a borrow
  643. # operation. We know 'paramType' is a tyVar and we really care if
  644. # 'paramType[0]' is still a view type, this is not a typo!
  645. if directViewType(paramType[0]) == noView and classifyViewType(paramType[0]) != noView:
  646. borrowingCall(c, paramType[0], n, i)
  647. elif m == mNone:
  648. potentialMutationViaArg(c, n[i], parameters)
  649. of nkAddr, nkHiddenAddr:
  650. traverse(c, n[0])
  651. when false:
  652. # XXX investigate if this is required, it doesn't look
  653. # like it is!
  654. var roots: seq[(PSym, int)]
  655. allRoots(n[0], roots, RootEscapes)
  656. for r in roots:
  657. potentialMutation(c, r[0], r[1], it.info)
  658. of nkTupleConstr, nkBracket:
  659. for child in n: traverse(c, child)
  660. if c.inAsgnSource > 0:
  661. for i in 0..<n.len:
  662. if n[i].kind == nkSym:
  663. # we assume constructions with cursors are better without
  664. # the cursors because it's likely we can move then, see
  665. # test arc/topt_no_cursor.nim
  666. pretendOwnsData(c, n[i].sym)
  667. of nkObjConstr:
  668. for child in n: traverse(c, child)
  669. if c.inAsgnSource > 0:
  670. for i in 1..<n.len:
  671. let it = n[i].skipColon
  672. if it.kind == nkSym:
  673. # we assume constructions with cursors are better without
  674. # the cursors because it's likely we can move then, see
  675. # test arc/topt_no_cursor.nim
  676. pretendOwnsData(c, it.sym)
  677. of nkPragmaBlock:
  678. let pragmaList = n[0]
  679. var enforceNoSideEffects = 0
  680. for i in 0..<pragmaList.len:
  681. if isNoSideEffectPragma(pragmaList[i]):
  682. enforceNoSideEffects = 1
  683. break
  684. inc c.inNoSideEffectSection, enforceNoSideEffects
  685. traverse(c, n.lastSon)
  686. dec c.inNoSideEffectSection, enforceNoSideEffects
  687. of nkWhileStmt, nkForStmt, nkParForStmt:
  688. for child in n: traverse(c, child)
  689. # analyse loops twice so that 'abstractTime' suffices to detect cases
  690. # like:
  691. # while cond:
  692. # mutate(graph)
  693. # connect(graph, cursorVar)
  694. for child in n: traverse(c, child)
  695. if n.kind == nkWhileStmt:
  696. traverse(c, n[0])
  697. # variables in while condition has longer alive time than local variables
  698. # in the while loop body
  699. of nkDefer:
  700. if c.processDefer:
  701. for child in n: traverse(c, child)
  702. else:
  703. for child in n: traverse(c, child)
  704. proc markAsReassigned(c: var Partitions; vid: int) {.inline.} =
  705. c.s[vid].flags.incl isReassigned
  706. if c.inConditional > 0 and c.inLoop > 0:
  707. # bug #17033: live ranges with loops and conditionals are too
  708. # complex for our current analysis, so we prevent the cursorfication.
  709. c.s[vid].flags.incl isConditionallyReassigned
  710. proc computeLiveRanges(c: var Partitions; n: PNode) =
  711. # first pass: Compute live ranges for locals.
  712. # **Watch out!** We must traverse the tree like 'traverse' does
  713. # so that the 'c.abstractTime' is consistent.
  714. inc c.abstractTime
  715. case n.kind
  716. of nkLetSection, nkVarSection:
  717. for child in n:
  718. let last = lastSon(child)
  719. computeLiveRanges(c, last)
  720. if child.kind == nkVarTuple and last.kind in {nkPar, nkTupleConstr}:
  721. if child.len-2 != last.len: return
  722. for i in 0..<child.len-2:
  723. registerVariable(c, child[i])
  724. #deps(c, child[i], last[i])
  725. else:
  726. for i in 0..<child.len-2:
  727. registerVariable(c, child[i])
  728. #deps(c, child[i], last)
  729. if c.inLoop > 0 and child[0].kind == nkSym: # bug #22787
  730. let vid = variableId(c, child[0].sym)
  731. if child[^1].kind != nkEmpty:
  732. markAsReassigned(c, vid)
  733. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  734. computeLiveRanges(c, n[0])
  735. computeLiveRanges(c, n[1])
  736. if n[0].kind == nkSym:
  737. let vid = variableId(c, n[0].sym)
  738. if vid >= 0:
  739. if n[1].kind == nkSym and (c.s[vid].reassignedTo == 0 or c.s[vid].reassignedTo == n[1].sym.id):
  740. c.s[vid].reassignedTo = n[1].sym.id
  741. if c.inConditional > 0 and c.inLoop > 0:
  742. # bug #22200: live ranges with loops and conditionals are too
  743. # complex for our current analysis, so we prevent the cursorfication.
  744. c.s[vid].flags.incl isConditionallyReassigned
  745. else:
  746. markAsReassigned(c, vid)
  747. of nkSym:
  748. dec c.abstractTime
  749. if n.sym.kind in {skVar, skResult, skTemp, skLet, skForVar, skParam}:
  750. let id = variableId(c, n.sym)
  751. if id >= 0:
  752. c.s[id].aliveEnd = max(c.s[id].aliveEnd, c.abstractTime)
  753. if n.sym.kind == skResult:
  754. c.s[id].aliveStart = min(c.s[id].aliveStart, c.abstractTime)
  755. of nodesToIgnoreSet:
  756. dec c.abstractTime
  757. discard "do not follow the construct"
  758. of nkCallKinds:
  759. for child in n: computeLiveRanges(c, child)
  760. let parameters = n[0].typ
  761. let L = if parameters != nil: parameters.signatureLen else: 0
  762. for i in 1..<n.len:
  763. let it = n[i]
  764. if it.kind == nkSym and i < L:
  765. let paramType = parameters[i].skipTypes({tyGenericInst, tyAlias})
  766. if not paramType.isCompileTimeOnly and paramType.kind == tyVar:
  767. let vid = variableId(c, it.sym)
  768. if vid >= 0:
  769. markAsReassigned(c, vid)
  770. of nkAddr, nkHiddenAddr:
  771. computeLiveRanges(c, n[0])
  772. if n[0].kind == nkSym:
  773. let vid = variableId(c, n[0].sym)
  774. if vid >= 0:
  775. c.s[vid].flags.incl preventCursor
  776. of nkPragmaBlock:
  777. computeLiveRanges(c, n.lastSon)
  778. of nkWhileStmt, nkForStmt, nkParForStmt:
  779. for child in n: computeLiveRanges(c, child)
  780. # analyse loops twice so that 'abstractTime' suffices to detect cases
  781. # like:
  782. # while cond:
  783. # mutate(graph)
  784. # connect(graph, cursorVar)
  785. inc c.inLoop
  786. for child in n: computeLiveRanges(c, child)
  787. dec c.inLoop
  788. if n.kind == nkWhileStmt:
  789. computeLiveRanges(c, n[0])
  790. # variables in while condition has longer alive time than local variables
  791. # in the while loop body
  792. of nkElifBranch, nkElifExpr, nkElse, nkOfBranch:
  793. inc c.inConditional
  794. for child in n: computeLiveRanges(c, child)
  795. dec c.inConditional
  796. of nkDefer:
  797. if c.processDefer:
  798. for child in n: computeLiveRanges(c, child)
  799. else:
  800. c.defers.add n
  801. else:
  802. for child in n: computeLiveRanges(c, child)
  803. proc computeGraphPartitions*(s: PSym; n: PNode; g: ModuleGraph; goals: set[Goal]): Partitions =
  804. result = Partitions(owner: s, g: g, goals: goals)
  805. if s.kind notin {skModule, skMacro}:
  806. let params = s.typ.n
  807. for i in 1..<params.len:
  808. registerParam(result, params[i])
  809. if resultPos < s.ast.safeLen:
  810. registerResult(result, s.ast[resultPos])
  811. computeLiveRanges(result, n)
  812. result.processDefer = true
  813. for i in countdown(len(result.defers)-1, 0):
  814. computeLiveRanges(result, result.defers[i])
  815. result.processDefer = false
  816. # restart the timer for the second pass:
  817. result.abstractTime = AbstractTime 0
  818. traverse(result, n)
  819. result.processDefer = true
  820. for i in countdown(len(result.defers)-1, 0):
  821. traverse(result, result.defers[i])
  822. result.processDefer = false
  823. proc dangerousMutation(g: MutationInfo; v: VarIndex): bool =
  824. #echo "range ", v.aliveStart, " .. ", v.aliveEnd, " ", v.sym
  825. if {isMutated, isMutatedByVarParam} * g.flags != {}:
  826. for m in g.mutations:
  827. #echo "mutation ", m
  828. if m in v.aliveStart..v.aliveEnd:
  829. return true
  830. return false
  831. proc cannotBorrow(config: ConfigRef; s: PSym; g: MutationInfo) =
  832. var m = "cannot borrow " & s.name.s &
  833. "; what it borrows from is potentially mutated"
  834. if g.mutatedHere != unknownLineInfo:
  835. m.add "\n"
  836. m.add config $ g.mutatedHere
  837. m.add " the mutation is here"
  838. if g.connectedVia != unknownLineInfo:
  839. m.add "\n"
  840. m.add config $ g.connectedVia
  841. m.add " is the statement that connected the mutation to the parameter"
  842. localError(config, s.info, m)
  843. proc checkBorrowedLocations*(par: var Partitions; body: PNode; config: ConfigRef) =
  844. for i in 0 ..< par.s.len:
  845. let v = par.s[i].sym
  846. if v.kind != skParam and classifyViewType(v.typ) != noView:
  847. let rid = root(par, i)
  848. if rid >= 0:
  849. var constViolation = false
  850. for b in par.s[rid].borrowsFrom:
  851. let sid = root(par, b)
  852. if sid >= 0:
  853. if par.s[sid].con.kind == isRootOf and dangerousMutation(par.graphs[par.s[sid].con.graphIndex], par.s[i]):
  854. cannotBorrow(config, v, par.graphs[par.s[sid].con.graphIndex])
  855. if par.s[sid].sym.kind != skParam and par.s[sid].aliveEnd < par.s[rid].aliveEnd:
  856. localError(config, v.info, "'" & v.name.s & "' borrows from location '" & par.s[sid].sym.name.s &
  857. "' which does not live long enough")
  858. if viewDoesMutate in par.s[rid].flags and isConstSym(par.s[sid].sym):
  859. localError(config, v.info, "'" & v.name.s & "' borrows from the immutable location '" &
  860. par.s[sid].sym.name.s & "' and attempts to mutate it")
  861. constViolation = true
  862. if {viewDoesMutate, viewBorrowsFromConst} * par.s[rid].flags == {viewDoesMutate, viewBorrowsFromConst} and
  863. not constViolation:
  864. # we do not track the constant expressions we allow to borrow from so
  865. # we can only produce a more generic error message:
  866. localError(config, v.info, "'" & v.name.s &
  867. "' borrows from an immutable location and attempts to mutate it")
  868. #if par.s[rid].con.kind == isRootOf and dangerousMutation(par.graphs[par.s[rid].con.graphIndex], par.s[i]):
  869. # cannotBorrow(config, s, par.graphs[par.s[rid].con.graphIndex])
  870. proc computeCursors*(s: PSym; n: PNode; g: ModuleGraph) =
  871. var par = computeGraphPartitions(s, n, g, {cursorInference})
  872. for i in 0 ..< par.s.len:
  873. let v = addr(par.s[i])
  874. if v.flags * {ownsData, preventCursor, isConditionallyReassigned} == {} and
  875. v.sym.kind notin {skParam, skResult} and
  876. v.sym.flags * {sfThread, sfGlobal} == {} and hasDestructor(v.sym.typ) and
  877. v.sym.typ.skipTypes({tyGenericInst, tyAlias}).kind != tyOwned and
  878. (getAttachedOp(g, v.sym.typ, attachedAsgn) == nil or
  879. sfError notin getAttachedOp(g, v.sym.typ, attachedAsgn).flags):
  880. let rid = root(par, i)
  881. if par.s[rid].con.kind == isRootOf and dangerousMutation(par.graphs[par.s[rid].con.graphIndex], par.s[i]):
  882. discard "cannot cursor into a graph that is mutated"
  883. else:
  884. v.sym.flags.incl sfCursor
  885. when false:
  886. echo "this is now a cursor ", v.sym, " ", par.s[rid].flags, " ", g.config $ v.sym.info