reorder.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import
  2. intsets, ast, idents, algorithm, renderer, strutils,
  3. msgs, modulegraphs, syntaxes, options, modulepaths,
  4. lineinfos
  5. when defined(nimPreviewSlimSystem):
  6. import std/assertions
  7. type
  8. DepN = ref object
  9. pnode: PNode
  10. id, idx, lowLink: int
  11. onStack: bool
  12. kids: seq[DepN]
  13. hAQ, hIS, hB, hCmd: int
  14. when defined(debugReorder):
  15. expls: seq[string]
  16. DepG = seq[DepN]
  17. when defined(debugReorder):
  18. var idNames = newTable[int, string]()
  19. proc newDepN(id: int, pnode: PNode): DepN =
  20. new(result)
  21. result.id = id
  22. result.pnode = pnode
  23. result.idx = -1
  24. result.lowLink = -1
  25. result.onStack = false
  26. result.kids = @[]
  27. result.hAQ = -1
  28. result.hIS = -1
  29. result.hB = -1
  30. result.hCmd = -1
  31. when defined(debugReorder):
  32. result.expls = @[]
  33. proc accQuoted(cache: IdentCache; n: PNode): PIdent =
  34. var id = ""
  35. for i in 0..<n.len:
  36. let ident = n[i].getPIdent
  37. if ident != nil: id.add(ident.s)
  38. result = getIdent(cache, id)
  39. proc addDecl(cache: IdentCache; n: PNode; declares: var IntSet) =
  40. case n.kind
  41. of nkPostfix: addDecl(cache, n[1], declares)
  42. of nkPragmaExpr: addDecl(cache, n[0], declares)
  43. of nkIdent:
  44. declares.incl n.ident.id
  45. when defined(debugReorder):
  46. idNames[n.ident.id] = n.ident.s
  47. of nkSym:
  48. declares.incl n.sym.name.id
  49. when defined(debugReorder):
  50. idNames[n.sym.name.id] = n.sym.name.s
  51. of nkAccQuoted:
  52. let a = accQuoted(cache, n)
  53. declares.incl a.id
  54. when defined(debugReorder):
  55. idNames[a.id] = a.s
  56. of nkEnumFieldDef:
  57. addDecl(cache, n[0], declares)
  58. else: discard
  59. proc computeDeps(cache: IdentCache; n: PNode, declares, uses: var IntSet; topLevel: bool) =
  60. template deps(n) = computeDeps(cache, n, declares, uses, false)
  61. template decl(n) =
  62. if topLevel: addDecl(cache, n, declares)
  63. case n.kind
  64. of procDefs, nkMacroDef, nkTemplateDef:
  65. decl(n[0])
  66. for i in 1..bodyPos: deps(n[i])
  67. of nkLetSection, nkVarSection, nkUsingStmt:
  68. for a in n:
  69. if a.kind in {nkIdentDefs, nkVarTuple}:
  70. for j in 0..<a.len-2: decl(a[j])
  71. for j in a.len-2..<a.len: deps(a[j])
  72. of nkConstSection, nkTypeSection:
  73. for a in n:
  74. if a.len >= 3:
  75. decl(a[0])
  76. for i in 1..<a.len:
  77. if a[i].kind == nkEnumTy:
  78. # declare enum members
  79. for b in a[i]:
  80. decl(b)
  81. else:
  82. deps(a[i])
  83. of nkIdentDefs:
  84. for i in 1..<n.len: # avoid members identifiers in object definition
  85. deps(n[i])
  86. of nkIdent: uses.incl n.ident.id
  87. of nkSym: uses.incl n.sym.name.id
  88. of nkAccQuoted: uses.incl accQuoted(cache, n).id
  89. of nkOpenSymChoice, nkClosedSymChoice:
  90. uses.incl n[0].sym.name.id
  91. of nkStmtList, nkStmtListExpr, nkWhenStmt, nkElifBranch, nkElse, nkStaticStmt:
  92. for i in 0..<n.len: computeDeps(cache, n[i], declares, uses, topLevel)
  93. of nkPragma:
  94. let a = n[0]
  95. if a.kind == nkExprColonExpr and a[0].kind == nkIdent and a[0].ident.s == "pragma":
  96. # user defined pragma
  97. decl(a[1])
  98. else:
  99. for i in 0..<n.safeLen: deps(n[i])
  100. of nkMixinStmt, nkBindStmt: discard
  101. else:
  102. # XXX: for callables, this technically adds the return type dep before args
  103. for i in 0..<n.safeLen: deps(n[i])
  104. proc hasIncludes(n:PNode): bool =
  105. for a in n:
  106. if a.kind == nkIncludeStmt:
  107. return true
  108. proc includeModule*(graph: ModuleGraph; s: PSym, fileIdx: FileIndex): PNode =
  109. result = syntaxes.parseFile(fileIdx, graph.cache, graph.config)
  110. graph.addDep(s, fileIdx)
  111. graph.addIncludeDep(FileIndex s.position, fileIdx)
  112. proc expandIncludes(graph: ModuleGraph, module: PSym, n: PNode,
  113. modulePath: string, includedFiles: var IntSet): PNode =
  114. # Parses includes and injects them in the current tree
  115. if not n.hasIncludes:
  116. return n
  117. result = newNodeI(nkStmtList, n.info)
  118. for a in n:
  119. if a.kind == nkIncludeStmt:
  120. for i in 0..<a.len:
  121. var f = checkModuleName(graph.config, a[i])
  122. if f != InvalidFileIdx:
  123. if containsOrIncl(includedFiles, f.int):
  124. localError(graph.config, a.info, "recursive dependency: '$1'" %
  125. toMsgFilename(graph.config, f))
  126. else:
  127. let nn = includeModule(graph, module, f)
  128. let nnn = expandIncludes(graph, module, nn, modulePath,
  129. includedFiles)
  130. excl(includedFiles, f.int)
  131. for b in nnn:
  132. result.add b
  133. else:
  134. result.add a
  135. proc splitSections(n: PNode): PNode =
  136. # Split typeSections and ConstSections into
  137. # sections that contain only one definition
  138. assert n.kind == nkStmtList
  139. result = newNodeI(nkStmtList, n.info)
  140. for a in n:
  141. if a.kind in {nkTypeSection, nkConstSection} and a.len > 1:
  142. for b in a:
  143. var s = newNode(a.kind)
  144. s.info = b.info
  145. s.add b
  146. result.add s
  147. else:
  148. result.add a
  149. proc haveSameKind(dns: seq[DepN]): bool =
  150. # Check if all the nodes in a strongly connected
  151. # component have the same kind
  152. result = true
  153. let kind = dns[0].pnode.kind
  154. for dn in dns:
  155. if dn.pnode.kind != kind:
  156. return false
  157. proc mergeSections(conf: ConfigRef; comps: seq[seq[DepN]], res: PNode) =
  158. # Merges typeSections and ConstSections when they form
  159. # a strong component (ex: circular type definition)
  160. for c in comps:
  161. assert c.len > 0
  162. if c.len == 1:
  163. res.add c[0].pnode
  164. else:
  165. let fstn = c[0].pnode
  166. let kind = fstn.kind
  167. # always return to the original order when we got circular dependencies
  168. let cs = c.sortedByIt(it.id)
  169. if kind in {nkTypeSection, nkConstSection} and haveSameKind(cs):
  170. # Circular dependency between type or const sections, we just
  171. # need to merge them
  172. var sn = newNode(kind)
  173. for dn in cs:
  174. sn.add dn.pnode[0]
  175. res.add sn
  176. else:
  177. # Problematic circular dependency, we arrange the nodes into
  178. # their original relative order and make sure to re-merge
  179. # consecutive type and const sections
  180. var wmsg = "Circular dependency detected. `codeReordering` pragma may not be able to" &
  181. " reorder some nodes properly"
  182. when defined(debugReorder):
  183. wmsg &= ":\n"
  184. for i in 0..<cs.len-1:
  185. for j in i..<cs.len:
  186. for ci in 0..<cs[i].kids.len:
  187. if cs[i].kids[ci].id == cs[j].id:
  188. wmsg &= "line " & $cs[i].pnode.info.line &
  189. " depends on line " & $cs[j].pnode.info.line &
  190. ": " & cs[i].expls[ci] & "\n"
  191. for j in 0..<cs.len-1:
  192. for ci in 0..<cs[^1].kids.len:
  193. if cs[^1].kids[ci].id == cs[j].id:
  194. wmsg &= "line " & $cs[^1].pnode.info.line &
  195. " depends on line " & $cs[j].pnode.info.line &
  196. ": " & cs[^1].expls[ci] & "\n"
  197. message(conf, cs[0].pnode.info, warnUser, wmsg)
  198. var i = 0
  199. while i < cs.len:
  200. if cs[i].pnode.kind in {nkTypeSection, nkConstSection}:
  201. let ckind = cs[i].pnode.kind
  202. var sn = newNode(ckind)
  203. sn.add cs[i].pnode[0]
  204. inc i
  205. while i < cs.len and cs[i].pnode.kind == ckind:
  206. sn.add cs[i].pnode[0]
  207. inc i
  208. res.add sn
  209. else:
  210. res.add cs[i].pnode
  211. inc i
  212. proc hasImportStmt(n: PNode): bool =
  213. # Checks if the node is an import statement or
  214. # i it contains one
  215. case n.kind
  216. of nkImportStmt, nkFromStmt, nkImportExceptStmt:
  217. return true
  218. of nkStmtList, nkStmtListExpr, nkWhenStmt, nkElifBranch, nkElse, nkStaticStmt:
  219. for a in n:
  220. if a.hasImportStmt:
  221. return true
  222. else:
  223. result = false
  224. proc hasImportStmt(n: DepN): bool =
  225. if n.hIS < 0:
  226. n.hIS = ord(n.pnode.hasImportStmt)
  227. result = bool(n.hIS)
  228. proc hasCommand(n: PNode): bool =
  229. # Checks if the node is a command or a call
  230. # or if it contains one
  231. case n.kind
  232. of nkCommand, nkCall:
  233. result = true
  234. of nkStmtList, nkStmtListExpr, nkWhenStmt, nkElifBranch, nkElse,
  235. nkStaticStmt, nkLetSection, nkConstSection, nkVarSection,
  236. nkIdentDefs:
  237. for a in n:
  238. if a.hasCommand:
  239. return true
  240. else:
  241. return false
  242. proc hasCommand(n: DepN): bool =
  243. if n.hCmd < 0:
  244. n.hCmd = ord(n.pnode.hasCommand)
  245. result = bool(n.hCmd)
  246. proc hasAccQuoted(n: PNode): bool =
  247. if n.kind == nkAccQuoted:
  248. return true
  249. for a in n:
  250. if hasAccQuoted(a):
  251. return true
  252. const extendedProcDefs = procDefs + {nkMacroDef, nkTemplateDef}
  253. proc hasAccQuotedDef(n: PNode): bool =
  254. # Checks if the node is a function, macro, template ...
  255. # with a quoted name or if it contains one
  256. case n.kind
  257. of extendedProcDefs:
  258. result = n[0].hasAccQuoted
  259. of nkStmtList, nkStmtListExpr, nkWhenStmt, nkElifBranch, nkElse, nkStaticStmt:
  260. for a in n:
  261. if hasAccQuotedDef(a):
  262. return true
  263. else:
  264. result = false
  265. proc hasAccQuotedDef(n: DepN): bool =
  266. if n.hAQ < 0:
  267. n.hAQ = ord(n.pnode.hasAccQuotedDef)
  268. result = bool(n.hAQ)
  269. proc hasBody(n: PNode): bool =
  270. # Checks if the node is a function, macro, template ...
  271. # with a body or if it contains one
  272. case n.kind
  273. of nkCommand, nkCall:
  274. result = true
  275. of extendedProcDefs:
  276. result = n[^1].kind == nkStmtList
  277. of nkStmtList, nkStmtListExpr, nkWhenStmt, nkElifBranch, nkElse, nkStaticStmt:
  278. for a in n:
  279. if a.hasBody:
  280. return true
  281. else:
  282. result = false
  283. proc hasBody(n: DepN): bool =
  284. if n.hB < 0:
  285. n.hB = ord(n.pnode.hasBody)
  286. result = bool(n.hB)
  287. proc intersects(s1, s2: IntSet): bool =
  288. for a in s1:
  289. if s2.contains(a):
  290. return true
  291. proc buildGraph(n: PNode, deps: seq[(IntSet, IntSet)]): DepG =
  292. # Build a dependency graph
  293. result = newSeqOfCap[DepN](deps.len)
  294. for i in 0..<deps.len:
  295. result.add newDepN(i, n[i])
  296. for i in 0..<deps.len:
  297. var ni = result[i]
  298. let uses = deps[i][1]
  299. let niHasBody = ni.hasBody
  300. let niHasCmd = ni.hasCommand
  301. for j in 0..<deps.len:
  302. if i == j: continue
  303. var nj = result[j]
  304. let declares = deps[j][0]
  305. if j < i and nj.hasCommand and niHasCmd:
  306. # Preserve order for commands and calls
  307. ni.kids.add nj
  308. when defined(debugReorder):
  309. ni.expls.add "both have commands and one comes after the other"
  310. elif j < i and nj.hasImportStmt:
  311. # Every node that comes after an import statement must
  312. # depend on that import
  313. ni.kids.add nj
  314. when defined(debugReorder):
  315. ni.expls.add "parent is, or contains, an import statement and child comes after it"
  316. elif j < i and niHasBody and nj.hasAccQuotedDef:
  317. # Every function, macro, template... with a body depends
  318. # on precedent function declarations that have quoted names.
  319. # That's because it is hard to detect the use of functions
  320. # like "[]=", "[]", "or" ... in their bodies.
  321. ni.kids.add nj
  322. when defined(debugReorder):
  323. ni.expls.add "one declares a quoted identifier and the other has a body and comes after it"
  324. elif j < i and niHasBody and not nj.hasBody and
  325. intersects(deps[i][0], declares):
  326. # Keep function declaration before function definition
  327. ni.kids.add nj
  328. when defined(debugReorder):
  329. for dep in deps[i][0]:
  330. if dep in declares:
  331. ni.expls.add "one declares \"" & idNames[dep] & "\" and the other defines it"
  332. else:
  333. for d in declares:
  334. if uses.contains(d):
  335. ni.kids.add nj
  336. when defined(debugReorder):
  337. ni.expls.add "one declares \"" & idNames[d] & "\" and the other uses it"
  338. proc strongConnect(v: var DepN, idx: var int, s: var seq[DepN],
  339. res: var seq[seq[DepN]]) =
  340. # Recursive part of trajan's algorithm
  341. v.idx = idx
  342. v.lowLink = idx
  343. inc idx
  344. s.add v
  345. v.onStack = true
  346. for w in v.kids.mitems:
  347. if w.idx < 0:
  348. strongConnect(w, idx, s, res)
  349. v.lowLink = min(v.lowLink, w.lowLink)
  350. elif w.onStack:
  351. v.lowLink = min(v.lowLink, w.idx)
  352. if v.lowLink == v.idx:
  353. var comp = newSeq[DepN]()
  354. while true:
  355. var w = s.pop
  356. w.onStack = false
  357. comp.add w
  358. if w.id == v.id: break
  359. res.add comp
  360. proc getStrongComponents(g: var DepG): seq[seq[DepN]] =
  361. ## Tarjan's algorithm. Performs a topological sort
  362. ## and detects strongly connected components.
  363. var s: seq[DepN]
  364. var idx = 0
  365. for v in g.mitems:
  366. if v.idx < 0:
  367. strongConnect(v, idx, s, result)
  368. proc hasForbiddenPragma(n: PNode): bool =
  369. # Checks if the tree node has some pragmas that do not
  370. # play well with reordering, like the push/pop pragma
  371. for a in n:
  372. if a.kind == nkPragma and a[0].kind == nkIdent and
  373. a[0].ident.s == "push":
  374. return true
  375. proc reorder*(graph: ModuleGraph, n: PNode, module: PSym): PNode =
  376. if n.hasForbiddenPragma:
  377. return n
  378. var includedFiles = initIntSet()
  379. let mpath = toFullPath(graph.config, module.fileIdx)
  380. let n = expandIncludes(graph, module, n, mpath,
  381. includedFiles).splitSections
  382. result = newNodeI(nkStmtList, n.info)
  383. var deps = newSeq[(IntSet, IntSet)](n.len)
  384. for i in 0..<n.len:
  385. deps[i][0] = initIntSet()
  386. deps[i][1] = initIntSet()
  387. computeDeps(graph.cache, n[i], deps[i][0], deps[i][1], true)
  388. var g = buildGraph(n, deps)
  389. let comps = getStrongComponents(g)
  390. mergeSections(graph.config, comps, result)