Skip to content

Instantly share code, notes, and snippets.

@kpmeen
Forked from mandubian/diff-viz.scala
Created October 16, 2017 21:19
Show Gist options
  • Save kpmeen/2abe89558867296ca953de2ba5b385fa to your computer and use it in GitHub Desktop.
Save kpmeen/2abe89558867296ca953de2ba5b385fa to your computer and use it in GitHub Desktop.
Visualizing scala code diff in scala code (result is compiling Scala code with diffs annotated in comments)
// Build Scala source code
val tree = q"""
object Test {
val a = 2 + 5
def f(b: String) = { b + a.toString }
}
"""
val src = List(TreeNode(tree))
// Build Scala target code
val tree2 = q"""
object Test {
val b = 3 + 4
def g(b: String) = { c + a.toString }
}
"""
val target = List(TreeNode(tree2))
// Compute src & target diffs
val diff = Diff(src, target)
/* gives this big structure
* diff: Cpy(ObjectType(Defn.Object),Cpy(TreeListFieldLabel(mods,0),Cpy(SimpleFieldLabel(name),Cpy(ValueLabel(TreeNode(Test)),Cpy(SimpleFieldLabel(templ),Cpy(ObjectType(Template),Cpy(TreeListFieldLabel(early,0),Cpy(TreeListFieldLabel(inits,0),Cpy(SimpleFieldLabel(self),Cpy(ValueLabel(TreeNode(_)),Cpy(TreeListFieldLabel(stats,2),Cpy(ObjectType(Defn.Val),Cpy(TreeListFieldLabel(mods,0),Cpy(TreeListFieldLabel(pats,1),Cpy(ObjectType(Pat.Var),Cpy(SimpleFieldLabel(name),Del(ValueLabel(TreeNode(a)),Ins(ValueLabel(TreeNode(b)),Cpy(TreeOptionFieldLabel(decltpe,false),Cpy(SimpleFieldLabel(rhs),Cpy(ObjectType(Term.ApplyInfix),Cpy(SimpleFieldLabel(lhs),Del(ValueLabel(TreeNode(2)),Ins(ValueLabel(TreeNode(3)),Cpy(SimpleFieldLabel(op),Cpy(ValueLabel(TreeNode(+)),Cpy(TreeListFieldLabel(targs,0),Cpy(TreeListFieldLabel(args,1),Del(ValueLabel(TreeNode(5)),Ins(ValueLabel(TreeNode(4)),Cpy(ObjectType(Defn.Def),Cpy(TreeListFieldLabel(mods,0),Cpy(SimpleFieldLabel(name),Del(ValueLabel(TreeNode(f)),Ins(ValueLabel(TreeNode(g)),Cpy(TreeListFieldLabel(tparams,0),Cpy(TreeListListFieldLabel(paramss,1),Cpy(TreeListFieldLabel(paramss,1),Cpy(ValueLabel(TreeNode(b: String)),Cpy(TreeOptionFieldLabel(decltpe,false),Cpy(SimpleFieldLabel(body),Cpy(ObjectType(Term.Block),Cpy(TreeListFieldLabel(stats,1),Cpy(ObjectType(Term.ApplyInfix),Cpy(SimpleFieldLabel(lhs),Del(ValueLabel(TreeNode(b)),Ins(ValueLabel(TreeNode(c)),Cpy(SimpleFieldLabel(op),Cpy(ValueLabel(TreeNode(+)),Cpy(TreeListFieldLabel(targs,0),Cpy(TreeListFieldLabel(args,1),Cpy(ValueLabel(TreeNode(a.toString)),End))))))))))))))))))))))))))))))))))))))))))))))))))))
*/
// Visualises Diff
DiffSyntax(dialects.Scala212)(basicDiff)
// gives
object Test {
val /*REP[Term.Name:a] BY*/ b = /*REP[Lit.Int:2] BY*/ 3 + /*REP[Lit.Int:5] BY*/ 4
def /*REP[Term.Name:f] BY*/ g(b: String) = {
/*REP[Term.Name:b] BY*/ c + a.toString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment