Rewriting shared nodes

7 views
Skip to first unread message

etorreborre

unread,
Jan 6, 2017, 11:27:15 AM1/6/17
to kiama
Hi Tony,

Here is a graph:

case class U(name: String) {
override def toString = s"${getClass.getSimpleName}($name: ${System.identityHashCode(this)})"
override def equals(a: Any) = System.identityHashCode(this) == System.identityHashCode(a)
}
case class V(name: String, u: U) {
override def toString = s"${getClass.getSimpleName}($name: ${System.identityHashCode(this)}, $u)"
override def equals(a: Any) = System.identityHashCode(this) == System.identityHashCode(a)
}
case class T(u: U, v1: V, v2: V){
override def toString = s"${getClass.getSimpleName}(${System.identityHashCode(this)}, $u, $v1, $v2)"
}

val v = V("v1", U("u2"))
val graph = T(U("u1"), v, v)

   T
 / |\
U1 | \
   | /
   V
   |
   U2


If I rewrite this graph with this strategy, which makes singletons in a tree:

def singletonStrategy[S](implicit tag: ClassTag[S]): Strategy = {
var s: Option[S] = None
strategy[Any] {
case tag(v) =>
s match {
case Some(singleton) =>
Some(singleton)
case None =>
s = Some(v.asInstanceOf[S])
Some(v)
}
case other => Some(other)
}
}

Then rewrite(everywhere(singletonStrategy[U]))(graph) do its job and replace every instance of `U` with the first instance found.

Unfortunately it will also duplicate the shared node `v`:

   T
 / |\
U1 | \
   |  \
   V1  V2
   |   |
   U1  U1


My question is: is there a way to rewrite a graph so that shared nodes are preserved?

I tried to look at previous messages on this mailing-list and there is supposedly a solution which I previously used for this:


but I cannot recall what it was. Do you think it is even possible to do what I want?

Thanks,

Eric.

etorreborre

unread,
Jan 6, 2017, 11:33:33 AM1/6/17
to kiama
I think I found the solution: MemoRewriter!

Tony Sloane

unread,
Jan 6, 2017, 4:56:30 PM1/6/17
to ki...@googlegroups.com
Hi Eric,

Yep, that was it. Hopefully MemoRewriter will work for your current application too.

cheers,
Tony
--
You received this message because you are subscribed to the Google Groups "kiama" group.
To unsubscribe from this group and stop receiving emails from it, send an email to kiama+un...@googlegroups.com.
To post to this group, send email to ki...@googlegroups.com.
Visit this group at https://groups.google.com/group/kiama.
For more options, visit https://groups.google.com/d/optout.

etorreborre

unread,
Jan 7, 2017, 9:50:59 AM1/7/17
to kiama
It worked great, I am using it for the DI library I told you about: https://github.com/zalando/grafter.

I feel just bad that it took me so long to re-discover something which you already fixed for me year ago :-).

Happy New Year 2017!

Eric.

Tony Sloane

unread,
Jan 8, 2017, 3:51:52 PM1/8/17
to ki...@googlegroups.com
And Happy New Year to you too Eric (and everyone else here). It's good to hear that your DI library is going strong.

cheers,
Tony
Reply all
Reply to author
Forward
0 new messages