Scala: Dynamically generating match clauses for case classes
<p>I want to use the power of Scala's pattern matching within a set of `condition-action' rules. These rules are not known in advance, but rather are generated at runtime according to some complex critera. The <a href="https://www.google.co.uk/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=4&amp;cad=rja&amp;uact=8&amp;ved=0ahUKEwj-37CngrTKAhXShhoKHZ6NCWwQFgg0MAM&amp;url=https%3A%2F%2Fwww.cs.us.es%2Fcursos%2Fia2-2012%2Ftrabajos%2FBucketBrigade.pdf&amp;usg=AFQjCNFDeKWzTM9woPd4rVoahVbGPXcMZw&amp;sig2=3bWBqemx-maZ-_o8LGFC-A" rel="nofollow">algorithmic generation mechanism</a> can be considered as a completely separate and is not part of this question, which is concerned with how to express this via Scala reflection/quasiquotes.</p>

<p>Concretely, I'm looking to generate case definitions (of the general form <code>case v0@x(v1,_,v2): X =&gt; f(v1,v2)</code>) at runtime.</p>

<p>It is presumably possible to do this via <code>toolBox.parse(str)</code> for some string that is generated at runtime. However, if possible it would seem desirable to incorporate a greater degree of type-safety than this:</p>

<p>More specifically, I want the case defs to match against a sealed case class hierarchy of Terms (<code>Term,Var(name: Char),Lit(value:Int),Group(a: Term,b: Term,c: Term)</code>).</p>

<p>For example, the generated case def would in general, return some function of none, some or all of v0,v1,v2:</p>

<pre><code>  t match {
    case v0@Group(v1@_,v2@Var('a')) =&gt; Group(v2,v0,Group(v1,Var('z'),Lit(17))) // etc
  }
</code></pre>

<p>I'm attempting to follow through on the description of quasiquotes for case defs given <a href="http://docs.scala-lang.org/overviews/quasiquotes/expression-details.html" rel="nofollow">here</a>, but the syntax is rather mind-bending (and eclipse with Scala 2.11 refuses to show me the types), so below is as far as I've got. My specific questions are embedded in the code:</p>

<pre><code>def dynamicMatch(condition: SomeType, action: SomeType, tb: ToolBox)
(t: Term): Option[Term] = {

  // Q1. What type should condition and action be for maximum
  // typesafety in the calling code? Symbols? Quasiquotes? 
  // Would they best be combined into a single actual CaseDef?

  // This is obviously a hardcoded placeholder expression, in general:
  // Q2. How to bind in t, condition and action?
  val q"$expr match { case ..$cases }" =
    q"foo match { case _ : Term =&gt; Some(expr) case _ =&gt; None }"

  val cq"$pat1 =&gt; $body1" :: cq"$pat2 =&gt; $body2" :: Nil = cases

  // Q3. how should this be invoked to return the desired result?
  ???
}
</code></pre>