reorder.nim 13 KB

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