reorder.nim 13 KB

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