Replacing placeholders in a tree

8 views
Skip to first unread message

Simon Ochsenreither

unread,
Nov 28, 2017, 6:46:33 AM11/28/17
to kiama
Hi Tony,

I have a language which looks a bit like this:

"test" match {
  if _ == "bar" then ...
  if _.size < 5 then ...
  else ...
}

Given

MatchExpr(subject: Expr, ifBranches: List[Expr], /*let's ignore the then expr for now */ elseBranch: Expr)

, the AST looks like this:

MatchExpr(
  Literal("test"),
  List(
    BinaryExpr(Placeholder, EQ, Literal("bar")),
    BinaryExpr(Call(Placeholder, Method("size")), LT, Literal(5))
  ),
  ...
)

What would be the most idiomatic way in Kiama to replace the Placeholder with the subject?
Basically I want to say something like "given a match expression, I want to traverse all nodes under it, and replace some of them (placeholders) with a value from the match expression (subject)", so that I get a tree like this:

MatchExpr(
  Literal("test"),
  List(
    BinaryExpr(Literal("test"), EQ, Literal("bar")),
    BinaryExpr(Call(Literal("test"), Method("size")), LT, Literal(5))
  ),
  ...
)

I'm a bit unsure how to capture the subject or pass the context (the subject) around with the the right macro invocation. Do you have any suggestions?

Thanks,

Simon

Tony Sloane

unread,
Nov 28, 2017, 4:11:17 PM11/28/17
to ki...@googlegroups.com
Hi Simon,

This sounds like a pretty standard application of a recursive traversal operator. E.g., if you really want to do the replacement everywhere then try the everywhere combinator which does a top-down traversal.

Here’s a version from the Kiama JSON example


rewrite(everywhere(rule[(JName, JNumber)] {
      case (n @ JName("salary"), JNumber(d)) =>
             (n, JNumber(d / 2))
}))(c)

This finds all pairs of JName and JNumber values where the JName refers to “salary” and halves the salary. c is the root of the structure that you want to rewrite in.

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.
Reply all
Reply to author
Forward
0 new messages