reorder.nim 14 KB

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