How to generate a static member and add it to a class inside a type macro?

I would like to add a static field (called bar in this example) to a class (named Foo ) with a type macro (named Static ).

Here's how I'm trying to do it now:

Macro

 import language.experimental.macros import scala.reflect.macros.Context package object statics { type Static = macro Statics.addStaticField object Statics { def addStaticField(c: Context): c.Tree = { import c.universe._ val STATIC = 1 << 23 type CompilerSymbol = scala.tools.nsc.Global#Symbol def setFlag(symbol: Symbol, flag: Long) { val compilerSymbol = symbol.asInstanceOf[CompilerSymbol] println("Setting flag ...") compilerSymbol.setFlag(flag) } def printFlags(symbol: Symbol) { println("Flags: " + symbol.asInstanceOf[CompilerSymbol].flagString) } val staticField: ValDef = ValDef( mods = Modifiers(), name = TermName("bar"), tpt = TypeTree(), rhs = Literal(Constant(42)) ) printFlags(staticField.symbol) setFlag(staticField.symbol, STATIC) printFlags(staticField.symbol) val Template(parents, _, existingCode) = c.enclosingTemplate Template(Nil, emptyValDef, staticField :: existingCode) } } } 

At compile time, calling setFlag seems to have an effect because the flag string changes:

 Flags: Setting flag ... Flags: <static> 

But it looks like it has almost no effect on the usage site:

 package statics class Foo extends Static object Main extends App { Foo.bar // Fails to compile (new Foo).bar // Compiles } 

show and showRaw also do not display Static characters.

How can I solve this problem?

+6
source share
1 answer

As far as I know, you need to create a companion object to have a static field, and at the moment this is not possible with type macros.

+1
source

All Articles