summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/nsc/typechecker/Macros.scala
blob: 470f3e711775580902d1a3d200ca72009aaabb42 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package scala.tools.nsc
package typechecker

import symtab.Flags._
import scala.tools.nsc.util._
import scala.reflect.ReflectionUtils

trait Macros { self: Analyzer =>
  import global._
  import definitions._

  def macroMeth(mac: Symbol): Symbol = {
    var owner = mac.owner
    if (!owner.isModuleClass) owner = owner.companionModule.moduleClass
    owner.info.decl(nme.macroMethodName(mac.name))
  }

  def macroArgs(tree: Tree): (List[List[Tree]]) = tree match {
    case Apply(fn, args) =>
      macroArgs(fn) :+ args
    case TypeApply(fn, args) =>
      macroArgs(fn) :+ args
    case Select(qual, name) =>
      List(List(qual))
    case _ =>
      List(List())
  }

  /**
   *  The definition of the method implementing a macro. Example:
   *  Say we have in a class C
   *
   *    def macro foo[T](xs: List[T]): T = expr
   *
   *  Then the following macro method is generated for `foo`:
   *
   *    def defmacro$foo
   *           (_context: scala.reflect.macro.Context)
   *           (_this: _context.Tree)
   *           (T: _context.TypeTree)
   *           (xs: _context.Tree): _context.Tree = {
   *      import _context._  // this means that all methods of Context can be used unqualified in macro's body
   *      expr
   *    }
   *
   *  If macro has no type arguments, the third parameter list is omitted (it's not empty, but omitted altogether).
   *
   *  To find out the desugared representation of your particular macro, compile it with -Ymacro-debug.
   */
  def macroMethDef(mdef: DefDef): Tree = {
    def paramDef(name: Name, tpt: Tree) = ValDef(Modifiers(PARAM), name, tpt, EmptyTree)
    val contextType = TypeTree(ReflectMacroContext.tpe)
    val globParamSec = List(paramDef(nme.macroContext, contextType))
    def globSelect(name: Name) = Select(Ident(nme.macroContext), name)
    def globTree = globSelect(tpnme.Tree)
    def globTypeTree = globSelect(tpnme.TypeTree)
    val thisParamSec = List(paramDef(newTermName(nme.macroThis), globTree))
    def tparamInMacro(tdef: TypeDef) = paramDef(tdef.name.toTermName, globTypeTree)
    def vparamInMacro(vdef: ValDef): ValDef = paramDef(vdef.name, vdef.tpt match {
      case tpt @ AppliedTypeTree(hk, _) if treeInfo.isRepeatedParamType(tpt) => AppliedTypeTree(hk, List(globTree))
      case _ => globTree
    })
    def wrapImplicit(tree: Tree) = atPos(tree.pos) {
      // implicit hasn't proven useful so far, so I'm disabling it
      //val implicitDecl = ValDef(Modifiers(IMPLICIT), nme.macroContextImplicit, SingletonTypeTree(Ident(nme.macroContext)), Ident(nme.macroContext))
      val importGlob = Import(Ident(nme.macroContext), List(ImportSelector(nme.WILDCARD, -1, null, -1)))
      Block(List(importGlob), tree)
    }
    var formals = (mdef.vparamss map (_ map vparamInMacro))
    if (mdef.tparams.nonEmpty) formals = (mdef.tparams map tparamInMacro) :: formals

    atPos(mdef.pos) {
      new DefDef( // can't call DefDef here; need to find out why
        mods = mdef.mods &~ MACRO &~ OVERRIDE,
        name = nme.macroMethodName(mdef.name),
        tparams = List(),
        vparamss = globParamSec :: thisParamSec :: formals,
        tpt = globTree,
        wrapImplicit(mdef.rhs))
    }
  }

  def addMacroMethods(templ: Template, namer: Namer): Unit = {
    for (ddef @ DefDef(mods, _, _, _, _, _) <- templ.body if mods hasFlag MACRO) {
      val trace = scala.tools.nsc.util.trace when settings.Ymacrodebug.value
      val sym = namer.enterSyntheticSym(trace("macro def: ")(macroMethDef(ddef)))
      trace("added to "+namer.context.owner.enclClass+": ")(sym)
    }
  }

  lazy val mirror = new scala.reflect.runtime.Mirror {
    lazy val libraryClassLoader = {
      val classpath = global.classPath.asURLs
      ScalaClassLoader.fromURLs(classpath, self.getClass.getClassLoader)
    }

    override def defaultReflectiveClassLoader() = libraryClassLoader
  }

  /** Return optionally address of companion object and implementation method symbol
   *  of given macro; or None if implementation classfile cannot be loaded or does
   *  not contain the macro implementation.
   */
  def macroImpl(mac: Symbol): Option[(AnyRef, mirror.Symbol)] = {
    val debug = settings.Ymacrodebug.value
    val trace = scala.tools.nsc.util.trace when debug
    trace("looking for macro implementation: ")(mac.fullNameString)

    try {
      val mmeth = macroMeth(mac)
      trace("found implementation at: ")(mmeth.fullNameString)

      if (mmeth == NoSymbol) None
      else {
        val receiverClass: mirror.Symbol = mirror.symbolForName(mmeth.owner.fullName)
        if (debug) {
          println("receiverClass is: " + receiverClass.fullNameString)

          val jreceiverClass = mirror.classToJava(receiverClass)
          val jreceiverSource = jreceiverClass.getProtectionDomain.getCodeSource
          println("jreceiverClass is %s from %s".format(jreceiverClass, jreceiverSource))

          val jreceiverClasspath = jreceiverClass.getClassLoader match {
            case cl: java.net.URLClassLoader => "[" + (cl.getURLs mkString ",") + "]"
            case _ => "<unknown>"
          }
          println("jreceiverClassLoader is %s with classpath %s".format(jreceiverClass.getClassLoader, jreceiverClasspath))
        }

        val receiverObj = receiverClass.companionModule
        trace("receiverObj is: ")(receiverObj.fullNameString)

        if (receiverObj == mirror.NoSymbol) None
        else {
          val receiver = mirror.companionInstance(receiverClass)
          val rmeth = receiverObj.info.member(mirror.newTermName(mmeth.name.toString))
          if (debug) {
            println("rmeth is: " + rmeth.fullNameString)
            println("jrmeth is: " + mirror.methodToJava(rmeth))
          }

          if (rmeth == mirror.NoSymbol) None
          else {
            Some((receiver, rmeth))
          }
        }
      }
    } catch {
      case ex: ClassNotFoundException =>
        None
    }
  }

  /** Return result of macro expansion.
   *  Or, if that fails, and the macro overrides a method return
   *  tree that calls this method instead of the macro.
   */
  def macroExpand(tree: Tree, context: Context): Option[Any] = {
    val trace = scala.tools.nsc.util.trace when settings.Ymacrodebug.value
    trace("macroExpand: ")(tree)

    val macroDef = tree.symbol
    macroImpl(macroDef) match {
      case Some((receiver, rmeth)) =>
        val argss = List(global) :: macroArgs(tree)
        val paramss = macroMeth(macroDef).paramss
        trace("paramss: ")(paramss)
        val rawArgss = for ((as, ps) <- argss zip paramss) yield {
          if (isVarArgsList(ps)) as.take(ps.length - 1) :+ as.drop(ps.length - 1)
          else as
        }
        val rawArgs: Seq[Any] = rawArgss.flatten
        trace("rawArgs: ")(rawArgs)
        val savedInfolevel = nodePrinters.infolevel
        try {
          // @xeno.by: InfoLevel.Verbose examines and prints out infos of symbols
          // by the means of this'es these symbols can climb up the lexical scope
          // when these symbols will be examined by a node printer
          // they will enumerate and analyze their children (ask for infos and tpes)
          // if one of those children involves macro expansion, things might get nasty
          // that's why I'm temporarily turning this behavior off
          nodePrinters.infolevel = nodePrinters.InfoLevel.Quiet
          Some(mirror.invoke(receiver, rmeth)(rawArgs: _*))
        } catch {
          case ex =>
            val realex = ReflectionUtils.unwrapThrowable(ex)
            val msg = if (settings.Ymacrodebug.value) {
              val stacktrace = new java.io.StringWriter()
              realex.printStackTrace(new java.io.PrintWriter(stacktrace))
              System.getProperty("line.separator") + stacktrace
            } else {
              realex.getMessage
            }
            context.unit.error(tree.pos, "exception during macro expansion: " + msg)
            None
        } finally {
          nodePrinters.infolevel = savedInfolevel
        }
      case None =>
        def notFound() = {
          context.unit.error(tree.pos, "macro implementation not found: " + macroDef.name)
          None
        }
        def fallBackToOverridden(tree: Tree): Option[Tree] = {
          tree match {
            case Select(qual, name) if (macroDef.isMacro) =>
              macroDef.allOverriddenSymbols match {
                case first :: _ =>
                  Some(Select(qual, name) setPos tree.pos setSymbol first)
                case _ =>
                  trace("macro is not overridden: ")(tree)
                  notFound()
              }
            case Apply(fn, args) =>
              fallBackToOverridden(fn) match {
                case Some(fn1) => Some(Apply(fn1, args) setPos tree.pos)
                case _         => None
              }
            case TypeApply(fn, args) =>
              fallBackToOverridden(fn) match {
                case Some(fn1) => Some(TypeApply(fn1, args) setPos tree.pos)
                case _         => None
              }
            case _ =>
              trace("unexpected tree in fallback: ")(tree)
              notFound()
          }
        }
        fallBackToOverridden(tree) match {
          case Some(tree1) =>
            trace("falling back to ")(tree1)
            currentRun.macroExpansionFailed = true
            Some(tree1)
          case None =>
            None
        }
    }
  }
}