The type of compilation units.
The type of compilation units.
Indicates than one of the enclosure methods failed to find a tree of required type among enclosing trees.
Expr wraps an abstract syntax tree and tags it with its type.
Expr wraps an abstract syntax tree and tags it with its type.
The semantic role that macroApplication
plays in the code.
The semantic role that macroApplication
plays in the code.
The type of tree modifiers.
The type of tree modifiers.
The abstract type of names.
The abstract type of names.
A factory which can create a package def from a prototype and a list of declarations.
Defines a universe-specific notion of positions.
Defines a universe-specific notion of positions.
The type of the prefix tree from which the macro is selected.
The type of the prefix tree from which the macro is selected.
See the documentation entry for prefix
for an example.
The type of compilation runs.
The type of compilation runs.
The base type of all scopes.
The base type of all scopes.
The type of symbols representing declarations.
The type of symbols representing declarations.
The abstract type of names representing terms.
The abstract type of names representing terms.
The type of Scala abstract syntax trees.
The type of Scala abstract syntax trees.
The type of Scala types, and also Scala type signatures.
The type of Scala types, and also Scala type signatures. (No difference is internally made between the two).
The abstract type of names representing types.
The abstract type of names representing types.
The type of type tags.
The type of type tags.
The type of weak type tags.
The type of weak type tags.
The role that represents an application of a term macro, e.
The role that represents an application of a term macro,
e.g. M(2)(3)
in val x = M(2)(3)
or M(a, b)
in x match { case x @ M(a, b) => }
.
A shorthand to create an expr.
A shorthand to create an expr.
Unlike the conventional expr factory, which requires a scala.reflect.api.TreeCreator, this one accepts a regular tree, but the resulting exprs are unable of being migrated to other universes/mirrors (the functionality normally not needed for macros, since there is only one compile-time universe and only one compile-time mirror).
A shorthand to create a type tag.
A shorthand to create a type tag.
Unlike the conventional type tag factory, which requires a scala.reflect.api.TypeCreator, this one accepts a regular type, but the resulting type tags are unable of being migrated to other universes/mirrors (the functionality normally not needed for macros, since there is only one compile-time universe and only one compile-time mirror).
A shorthand to create a weak type tag.
A shorthand to create a weak type tag.
Unlike the conventional type tag factory, which requires a scala.reflect.api.TypeCreator, this one accepts a regular type, but the resulting type tags are unable of being migrated to other universes/mirrors (the functionality normally not needed for macros, since there is only one compile-time universe and only one compile-time mirror).
Abruptly terminates current macro expansion leaving a note about what happened.
Abruptly terminates current macro expansion leaving a note about what happened.
Use enclosingPosition
if you're in doubt what position to pass to pos
.
Exposes current classpath.
Exposes current classpath.
Exposes current compiler settings as a list of options.
Exposes current compiler settings as a list of options.
Use scalac -help
, scalac -X
and scalac -Y
to learn about currently supported options.
For sending a message which should not be labeled as a warning/error, but also shouldn't require -verbose to be visible.
For sending a message which should not be labeled as a warning/error,
but also shouldn't require -verbose to be visible.
Use enclosingPosition
if you're in doubt what position to pass to pos
.
Tree that corresponds to the enclosing DefDef tree.
Tree that corresponds to the enclosing DefDef tree.
Throws EnclosureException
if there's no such enclosing tree.
Tree that corresponds to the enclosing ImplDef tree (i.
Tree that corresponds to the enclosing ImplDef tree (i.e. either ClassDef or ModuleDef).
Throws EnclosureException
if there's no such enclosing tree.
Types along with corresponding trees for which implicit arguments are currently searched.
Types along with corresponding trees for which implicit arguments are currently searched. Can be useful to get information about an application with an implicit parameter that is materialized during current macro expansion.
Unlike openImplicits
, this is a val, which means that it gets initialized when the context is created
and always stays the same regardless of whatever happens during macro expansion.
Contexts that represent macros in-flight, including the current one.
Contexts that represent macros in-flight, including the current one. Very much like a stack trace, but for macros only. Can be useful for interoperating with other macros and for imposing compiler-friendly limits on macro expansion.
Is also priceless for emitting sane error messages for macros that are called by other macros on synthetic (i.e. position-less) trees.
In that dire case navigate the enclosingMacros
stack, and it will most likely contain at least one macro with a position-ful macro application.
See enclosingPosition
for a default implementation of this logic.
Unlike openMacros
, this is a val, which means that it gets initialized when the context is created
and always stays the same regardless of whatever happens during macro expansion.
Tree that corresponds to the enclosing PackageDef tree.
Tree that corresponds to the enclosing PackageDef tree.
Throws EnclosureException
if there's no such enclosing tree.
Tries to guess a position for the enclosing application.
Tries to guess a position for the enclosing application.
But that is simple, right? Just dereference pos
of macroApplication
? Not really.
If we're in a synthetic macro expansion (no positions), we must do our best to infer the position of something that triggerd this expansion.
Surprisingly, quite often we can do this by navigation the enclosingMacros
stack.
Compilation run that contains this macro application.
Compilation run that contains this macro application.
Tree that corresponds to the enclosing Template tree.
Tree that corresponds to the enclosing Template tree.
Throws EnclosureException
if there's no such enclosing tree.
Compilation unit that contains this macro application.
Compilation unit that contains this macro application.
Emits a compilation error.
Emits a compilation error.
Use enclosingPosition
if you're in doubt what position to pass to pos
.
Takes a typed wrapper for a tree of type T
and evaluates it to a value of type T
.
Takes a typed wrapper for a tree of type T
and evaluates it to a value of type T
.
Can be used to perform compile-time computations on macro arguments to the extent permitted by the shape of the arguments.
Known issues: because of https://issues.scala-lang.org/browse/SI-5748
trees being evaluated first need to undergo resetAllAttrs
. Resetting symbols and types
mutates the tree in place, therefore the conventional approach is to duplicate
the tree first.
scala> def impl(c: Context)(x: c.Expr[String]) = { | val x1 = c.Expr[String](c.resetAllAttrs(x.tree.duplicate)) | println(s"compile-time value is: ${c.eval(x1)}") | x | } impl: (c: Context)(x: c.Expr[String])c.Expr[String] scala> def test(x: String) = macro impl test: (x: String)String scala> test("x") compile-time value is: x res0: String = x scala> test("x" + "y") compile-time value is: xy res1: String = xy scala> val x = "x" x: String = x scala> test(x + "y") compile-time value is: xy res2: String = xy scala> { val x = "x"; test(x + "y") } error: exception during macro expansion: scala.tools.reflect.ToolBoxError: reflective compilation failed
Note that in the last case evaluation has failed, because the argument of a macro
refers to a runtime value x
, which is unknown at compile time.
Creates a unique name having a given name as a prefix and having the same flavor (term name or type name) as the given name.
Creates a unique name having a given name as a prefix and having the same flavor (term name or type name) as the given name.
Creates a unique string having a given prefix.
Creates a unique string having a given prefix.
Creates a unique string.
Creates a unique string.
Does the compilation session have any errors?
Does the compilation session have any errors?
Does the compilation session have any warnings?
Does the compilation session have any warnings?
Infers an implicit value of the expected type pt
in the macro callsite context.
Infers an implicit value of the expected type pt
in the macro callsite context.
Optional pos
parameter provides a position that will be associated with the implicit search.
If silent
is false, TypecheckException
will be thrown in case of an inference error.
If silent
is true, the typecheck is silent and will return EmptyTree
if an error occurs.
Such errors don't vanish and can be inspected by turning on -Xlog-implicits.
Unlike in typeCheck
, silent
is true by default.
Infers an implicit view from the provided tree tree
of the type from
to the type to
in the macro callsite context.
Infers an implicit view from the provided tree tree
of the type from
to the type to
in the macro callsite context.
Optional pos
parameter provides a position that will be associated with the implicit search.
If silent
is false, TypecheckException
will be thrown in case of an inference error.
If silent
is true, the typecheck is silent and will return EmptyTree
if an error occurs.
Such errors don't vanish and can be inspected by turning on -Xlog-implicits.
Unlike in typeCheck
, silent
is true by default.
Emits an informational message, suppressed unless -verbose
or force=true
.
Emits an informational message, suppressed unless -verbose
or force=true
.
Use enclosingPosition
if you're in doubt what position to pass to pos
.
Adds a list of top-level definitions to the compiler's symbol table.
Adds a list of top-level definitions to the compiler's symbol table. _TOP_LEVEL Allowed definitions include classes (represented by ClassDef
trees), traits (represented
by ClassDef
trees having the TRAIT
flag set in mods
) and objects (represented by ModuleDef
trees).
The definitions are put into the package with a prototype provided in packagePrototype
.
Supported prototypes are (see PackageSpec for more details):
* Strings and names representing a fully-qualified name of the package
* Trees that can work as package ids
* Package or package class symbols
Typical value for a package prototype is a fully-qualified name in a string.
For example, to generate a class available at foo.bar.Test
, call this method as follows:
introduceTopLevel("foo.bar", ClassDef(<mods>, TypeName("Test"), <tparams>, <template>))
It is possible to add definitions to the empty package by using nme.EMPTY_PACKAGE_NAME.toString
, but
that's not recommended, since such definitions cannot be seen from outside the empty package.
Only the multi-parameter overload of this method can be used to introduce companions.
If companions are introduced by two different calls, then they will be put into different virtual files, and scalac
will show an error about companions being defined in different files. By the way, this also means that there's currently no way
to define a companion for an existing class or module_TOP_LEVEL.
Returns a list of fully-qualified references to the introduced definitions.
Adds a top-level definition to the compiler's symbol table.
Adds a top-level definition to the compiler's symbol table. _TOP_LEVEL Allowed definitions include classes (represented by ClassDef
trees), traits (represented
by ClassDef
trees having the TRAIT
flag set in mods
) and objects (represented by ModuleDef
trees).
The definitions are put into the package with a prototype provided in packagePrototype
.
Supported prototypes are (see PackageSpec for more details):
* Strings and names representing a fully-qualified name of the package
* Trees that can work as package ids
* Package or package class symbols
Typical value for a package prototype is a fully-qualified name in a string.
For example, to generate a class available at foo.bar.Test
, call this method as follows:
introduceTopLevel("foo.bar", ClassDef(<mods>, TypeName("Test"), <tparams>, <template>))
It is possible to add definitions to the empty package by using nme.EMPTY_PACKAGE_NAME.toString
, but
that's not recommended, since such definitions cannot be seen from outside the empty package.
Only the multi-parameter overload of this method can be used to introduce companions.
If companions are introduced by two different calls, then they will be put into different virtual files, and scalac
will show an error about companions being defined in different files. By the way, this also means that there's currently no way
to define a companion for an existing class or module_TOP_LEVEL.
Returns a fully-qualified reference to the introduced definition.
Shorthand for Literal(Constant(x: Char))
in the underlying universe
.
Shorthand for Literal(Constant(x: Char))
in the underlying universe
.
Shorthand for Literal(Constant(x: String))
in the underlying universe
.
Shorthand for Literal(Constant(x: String))
in the underlying universe
.
Shorthand for Literal(Constant(x: Double))
in the underlying universe
.
Shorthand for Literal(Constant(x: Double))
in the underlying universe
.
Shorthand for Literal(Constant(x: Float))
in the underlying universe
.
Shorthand for Literal(Constant(x: Float))
in the underlying universe
.
Shorthand for Literal(Constant(x: Long))
in the underlying universe
.
Shorthand for Literal(Constant(x: Long))
in the underlying universe
.
Shorthand for Literal(Constant(x: Int))
in the underlying universe
.
Shorthand for Literal(Constant(x: Int))
in the underlying universe
.
Shorthand for Literal(Constant(x: Short))
in the underlying universe
.
Shorthand for Literal(Constant(x: Short))
in the underlying universe
.
Shorthand for Literal(Constant(x: Byte))
in the underlying universe
.
Shorthand for Literal(Constant(x: Byte))
in the underlying universe
.
Shorthand for Literal(Constant(x: Boolean))
in the underlying universe
.
Shorthand for Literal(Constant(x: Boolean))
in the underlying universe
.
Shorthand for Literal(Constant(false))
in the underlying universe
.
Shorthand for Literal(Constant(false))
in the underlying universe
.
Shorthand for Literal(Constant(null))
in the underlying universe
.
Shorthand for Literal(Constant(null))
in the underlying universe
.
Shorthand for Literal(Constant(true))
in the underlying universe
.
Shorthand for Literal(Constant(true))
in the underlying universe
.
Shorthand for Literal(Constant(()))
in the underlying universe
.
Shorthand for Literal(Constant(()))
in the underlying universe
.
The tree that undergoes macro expansion.
The tree that undergoes macro expansion. Can be useful to get an offset or a range position of the entire tree being processed.
The semantic role that macroApplication
plays in the code.
The semantic role that macroApplication
plays in the code.
The mirror of the compile-time universe.
Types along with corresponding trees for which implicit arguments are currently searched.
Types along with corresponding trees for which implicit arguments are currently searched. Can be useful to get information about an application with an implicit parameter that is materialized during current macro expansion.
Unlike enclosingImplicits
, this is a def, which means that it gets recalculated on every invocation,
so it might change depending on what is going on during macro expansion.
Contexts that represent macros in-flight, including the current one.
Contexts that represent macros in-flight, including the current one. Very much like a stack trace, but for macros only. Can be useful for interoperating with other macros and for imposing compiler-friendly limits on macro expansion.
Is also priceless for emitting sane error messages for macros that are called by other macros on synthetic (i.e. position-less) trees.
In that dire case navigate the openMacros
stack, and it will most likely contain at least one macro with a position-ful macro application.
See enclosingPosition
for a default implementation of this logic.
Unlike enclosingMacros
, this is a def, which means that it gets recalculated on every invocation,
so it might change depending on what is going on during macro expansion.
Parses a string with a Scala expression into an abstract syntax tree.
Parses a string with a Scala expression into an abstract syntax tree. Only works for expressions, i.e. parsing a package declaration will fail.
The prefix tree from which the macro is selected.
The prefix tree from which the macro is selected.
For example, for a macro filter
defined as an instance method on a collection Coll
,
prefix
represents an equivalent of this
for normal instance methods:
scala> class Coll[T] { | def filter(p: T => Boolean): Coll[T] = macro M.filter[T] | }; object M { | def filter[T](c: Context { type PrefixType = Coll[T] }) | (p: c.Expr[T => Boolean]): c.Expr[Coll[T]] = | { | println(c.prefix.tree) | c.prefix | } | } defined class Coll defined module Macros scala> new Coll[Int]().filter(_ % 2 == 0) new Coll[Int]() res0: Coll[Int] = ... scala> val x = new Coll[String]() x: Coll[String] = ... scala> x.filter(_ != "") $line11.$read.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.$iw.x res1 @ 35563b4b: x.type = ...
Note how the value of prefix
changes depending on the qualifier of the macro call
(i.e. the expression that is at the left-hand side of the dot).
Another noteworthy thing about the snippet above is the Context { type PrefixType = Coll[T] }
type that is used to stress that the macro implementation works with prefixes of type Coll[T]
.
Given a type, generate a tree that when compiled and executed produces the runtime class of the enclosing class or module.
Given a type, generate a tree that when compiled and executed produces the runtime class of the enclosing class or module.
Returns EmptyTree
if there does not exist an enclosing class or module.
Given a type, generate a tree that when compiled and executed produces the runtime class of the original type.
Given a type, generate a tree that when compiled and executed produces the runtime class of the original type.
If concrete
is true, then this function will bail on types, who refer to abstract types (like ClassTag
does).
Given a tree, generate a tree that when compiled and executed produces the original tree.
Given a tree, generate a tree that when compiled and executed produces the original tree.
For more information and examples see the documentation for Universe.reify
.
The produced tree will be bound to the specified universe
and mirror
.
Possible values for universe
include universe.treeBuild.mkRuntimeUniverseRef
.
Possible values for mirror
include EmptyTree
(in that case the reifier will automatically pick an appropriate mirror).
This function is deeply connected to Universe.reify
, a macro that reifies arbitrary expressions into runtime trees.
They do very similar things (Universe.reify
calls Context.reifyTree
to implement itself), but they operate on different metalevels (see below).
Let's study the differences between Context.reifyTree
and Universe.reify
on an example of using them inside a fooMacro
macro:
* Since reify itself is a macro, it will be executed when fooMacro is being compiled (metalevel -1) and will produce a tree that when evaluated during macro expansion of fooMacro (metalevel 0) will recreate the input tree.
This provides a facility analogous to quasi-quoting. Writing "reify{ expr }" will generate an AST that represents expr. Afterwards this AST (or its parts) can be used to construct the return value of fooMacro.
* reifyTree is evaluated during macro expansion (metalevel 0) and will produce a tree that when evaluated during the runtime of the program (metalevel 1) will recreate the input tree.
This provides a way to retain certain trees from macro expansion time to be inspected later, in the runtime. For example, DSL authors may find it useful to capture DSL snippets into ASTs that are then processed at runtime in a domain-specific way.
Also note the difference between universes of the runtime trees produced by two reifies:
* The result of compiling and running the result of reify will be bound to the Universe that called reify. This is possible because it's a macro, so it can generate whatever code it wishes.
* The result of compiling and running the result of reifyTree will be the prefix
that needs to be passed explicitly.
This happens because the Universe of the evaluated result is from a different metalevel than the Context the called reify.
Typical usage of this function is to retain some of the trees received/created by a macro into the form that can be inspected (via pattern matching) or compiled/run (by a reflective ToolBox) during the runtime.
Given a type, generate a tree that when compiled and executed produces the original type.
Given a type, generate a tree that when compiled and executed produces the original type.
The produced tree will be bound to the specified universe
and mirror
.
For more information and examples see the documentation for Context.reifyTree
and Universe.reify
.
Recursively resets symbols and types in a given tree.
Recursively resets symbols and types in a given tree.
Note that this does not revert the tree to its pre-typer shape. For more info, read up https://issues.scala-lang.org/browse/SI-5464.
Recursively resets locally defined symbols and types in a given tree.
Recursively resets locally defined symbols and types in a given tree.
Note that this does not revert the tree to its pre-typer shape. For more info, read up https://issues.scala-lang.org/browse/SI-5464.
Exposes macro-specific settings as a list of strings.
Exposes macro-specific settings as a list of strings. These settings are passed to the compiler via the "-Xmacro-settings:setting1,setting2...,settingN" command-line option.
Looks up a top-level definition tree with a given fully-qualified name (term name for modules, type name for classes).
Looks up a top-level definition tree with a given fully-qualified name
(term name for modules, type name for classes). _TREE Top-level tree is a tree that represents a non-inner class or object in one of the currently compiled source files.
Note that top-level isn't equivalent to scala.reflect.api.Symbols#SymbolApi.isStatic,
because static also embraces definitions nested in static objects
_TREE.
If such a tree does not exist, returns EmptyTree
.
Returns a reference to a top-level definition tree with a given fully-qualified name (term name for modules, type name for classes).
Returns a reference to a top-level definition tree with a given fully-qualified name
(term name for modules, type name for classes). _TREE Top-level tree is a tree that represents a non-inner class or object in one of the currently compiled source files.
Note that top-level isn't equivalent to scala.reflect.api.Symbols#SymbolApi.isStatic,
because static also embraces definitions nested in static objects
_TREE.
If such a tree does not exist, returns EmptyTree
.
Typechecks the provided tree against the expected type pt
in the macro callsite context.
Typechecks the provided tree against the expected type pt
in the macro callsite context.
If silent
is false, TypecheckException
will be thrown in case of a typecheck error.
If silent
is true, the typecheck is silent and will return EmptyTree
if an error occurs.
Such errors don't vanish and can be inspected by turning on -Ymacro-debug-verbose.
Unlike in inferImplicitValue
and inferImplicitView
, silent
is false by default.
Typechecking can be steered with the following optional parameters:
withImplicitViewsDisabled
recursively prohibits implicit views (though, implicit vals will still be looked up and filled in), default value is false
withMacrosDisabled
recursively prohibits macro expansions and macro-based implicits, default value is false
The compile-time universe.
Undoes reification of a tree.
Undoes reification of a tree.
This reversion doesn't simply restore the original tree (that would lose the context of reification), but does something more involved that conforms to the following laws:
1) unreifyTree(reifyTree(tree)) != tree // unreified tree is tree + saved context // in current implementation, the result of unreify is opaque // i.e. there's no possibility to inspect underlying tree/context
2) reifyTree(unreifyTree(reifyTree(tree))) == reifyTree(tree) // the result of reifying a tree in its original context equals to // the result of reifying a tree along with its saved context
3) compileAndEval(unreifyTree(reifyTree(tree))) ~ compileAndEval(tree) // at runtime original and unreified trees are behaviorally equivalent
Emits a warning.
Emits a warning.
Use enclosingPosition
if you're in doubt what position to pass to pos
.
Tree that corresponds to the enclosing class, or EmptyTree if not applicable.
Tree that corresponds to the enclosing class, or EmptyTree if not applicable.
(Since version 2.10.1) Use enclosingImpl instead, but be wary of changes in semantics
Tree that corresponds to the enclosing method, or EmptyTree if not applicable.
Tree that corresponds to the enclosing method, or EmptyTree if not applicable.
(Since version 2.10.1) Use enclosingDef instead, but be wary of changes in semantics
Creates a unique name having a given name as a prefix and having the same flavor (term name or type name) as the given name.
Creates a unique name having a given name as a prefix and having the same flavor (term name or type name) as the given name.
(Since version 2.11.0) Use freshName instead
Creates a unique string having a given prefix.
Creates a unique string having a given prefix.
(Since version 2.11.0) Use freshName instead
Creates a unique string.
Creates a unique string.
(Since version 2.11.0) Use freshName instead
Constructor/Extractor for Expr
.
Constructor/Extractor for Expr
.
Hosts supported package specs.
Constructor/Extractor for TypeTag
.
Constructor/Extractor for TypeTag
.
Constructor/Extractor for WeakTypeTag
.
Constructor/Extractor for WeakTypeTag
.
Returns string formatted according to given format
string.
Returns string formatted according to given format
string.
Format strings are as for String.format
(@see java.lang.String.format).
Shortcut for implicitly[TypeTag[T]].tpe
Shortcut for implicitly[TypeTag[T]].tpe
Shortcut for implicitly[TypeTag[T]]
Shortcut for implicitly[TypeTag[T]]
Shortcut for implicitly[WeakTypeTag[T]].tpe
Shortcut for implicitly[WeakTypeTag[T]].tpe
Shortcut for implicitly[WeakTypeTag[T]]
Shortcut for implicitly[WeakTypeTag[T]]
EXPERIMENTAL
The Scala macros context.
See the overview page for a description of how macros work. This documentation entry provides information on the API available to macro writers.
A macro context wraps a compiler universe exposed in
universe
and having type scala.reflect.macros.Universe. This type is a refinement over the generic reflection API provided in scala.reflect.api.Universe. The extended Universe provides mutability for reflection artifacts (e.g. macros can change types of compiler trees, add annotation to symbols representing definitions, etc) and exposes some internal compiler functionality such asSymbol.deSkolemize
orTree.attachments
.Another fundamental part of a macro context is
macroApplication
, which provides access to the tree undergoing macro expansion. Parts of this tree can be found in arguments of the corresponding macro implementations and inprefix
, butmacroApplication
gives the full picture.Other than that, macro contexts provide facilities for typechecking, exploring the compiler's symbol table and enclosing trees and compilation units, evaluating trees, logging warnings/errors and much more. Refer to the documentation of top-level traits in this package to learn the details.