Domanda

I'm writing a compiler plugin that translates a subset of Scala to C++ (ignore the apparent insanity of this task). I'm using a number of plugins that must run after the erasure phase. However, I require the full type information to output valid code.

For example, for the Scala;

def foo(f: Type1 => Type2): Unit = { /* Snip */ }

I'd like to output the C++;

void foo(scala::Function1<Type1, Type2> f) { /* Snip */ }

However, after the erasure phase, foo looks like this:

def foo(f: Function1): Unit = { /* Snip */ }

I.e., the generic type information for the parameter, f, has been lost. I need to get it back some how. Any suggestions?

Reply to cdshines' comment

Here is an example:

example.scala

object Example {
  def func(f: Int => Boolean) { }
}

When I compile;

# scalac -version
Scala compiler version 2.9.3 -- Copyright 2002-2011, LAMP/EPFL
# scalac -Xprint:explicitouter -Xprint:erasure example.scala
[[syntax trees at end of explicitouter]]// Scala source: example.scala
package <empty> {
  final object Example extends java.lang.Object with ScalaObject {
    def this(): object Example = {
      Example.super.this();
      ()
    };
    def func(f: Int => Boolean): Unit = ()
  }
}

[[syntax trees at end of erasure]]// Scala source: example.scala
package <empty> {
  final object Example extends java.lang.Object with ScalaObject {
    def this(): object Example = {
      Example.super.this();
      ()
    };
    def func(f: Function1): Unit = ()
  }
}

Note the change in the signature of func. explicitouter is the phase before erasure.

È stato utile?

Soluzione

This solution was suggested by the scala-language mailing list. Inside something that imports scala.tools.nsc.Global's namespace, the following will recover the type of a method (more specifically a DefDef in the AST) before the erasure phase.

atPhase(currentRun.erasurePhase) { someDefDef.symbol.tpe }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top