reorder.nim 13 KB

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