reorder.nim 13 KB

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