varpartitions.nim 37 KB

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