From 8f86e0f86bdbfb124c76288a498cdabd3ef48c50 Mon Sep 17 00:00:00 2001 From: Matthew Baulch Date: Sat, 27 Aug 2016 19:01:59 +1000 Subject: [PATCH] Rewrite cyclicTree. Performance improved by approx 50%. --- compiler/trees.nim | 30 ++++++++++-------------------- 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/compiler/trees.nim b/compiler/trees.nim index fdd88c348d..dde7b5367a 100644 --- a/compiler/trees.nim +++ b/compiler/trees.nim @@ -12,29 +12,19 @@ import ast, astalgo, lexer, msgs, strutils, wordrecg -proc hasSon(father, son: PNode): bool = - for i in countup(0, sonsLen(father) - 1): - if father.sons[i] == son: - return true - result = false - -proc cyclicTreeAux(n, s: PNode): bool = - if n == nil: - return false - if hasSon(s, n): - return true - var m = sonsLen(s) - addSon(s, n) +proc cyclicTreeAux(n: PNode, visited: var seq[PNode]): bool = + if n == nil: return + for v in visited: + if v == n: return true if not (n.kind in {nkEmpty..nkNilLit}): - for i in countup(0, sonsLen(n) - 1): - if cyclicTreeAux(n.sons[i], s): - return true - result = false - delSon(s, m) + visited.add(n) + for nSon in n.sons: + if cyclicTreeAux(nSon, visited): return true + discard visited.pop() proc cyclicTree*(n: PNode): bool = - var s = newNodeI(nkEmpty, n.info) - result = cyclicTreeAux(n, s) + var visited: seq[PNode] = @[] + cyclicTreeAux(n, visited) proc exprStructuralEquivalent*(a, b: PNode; strictSymEquality=false): bool = result = false