Alternatives of patterns.
Eliminated by compiler phases Eliminated by compiler phases patmat (in the new pattern matcher of 2.10) or explicitouter (in the old pre-2.10 pattern matcher), except for occurrences in encoded Switch stmt (i.e. remaining Match(CaseDef(...)))
An extractor class to create and pattern match with syntax Alternative(trees)
. This AST node corresponds to the following Scala code:
pat1 | ... | patn
A tree that has an annotation attached to it. Only used for annotated types and annotation ascriptions, annotations on definitions are stored in the Modifiers. Eliminated by typechecker (typedAnnotated), the annotations are then stored in an AnnotatedType.
An extractor class to create and pattern match with syntax Annotated(annot, arg)
. This AST node corresponds to the following Scala code:
arg @annot // for types arg: @annot // for exprs
An extractor class to create and pattern match with syntax AppliedTypeTree(tpt, args)
. This AST node corresponds to the following Scala code:
tpt[args]
Should only be used with tpt
nodes which are types, i.e. which have isType
returning true
. Otherwise TypeApply
should be used instead.
List[Int] as in val x: List[Int] = ???
// represented as AppliedTypeTree(Ident(<List>), List(TypeTree(<Int>)))
def foo[T] = ??? foo[Int] // represented as TypeApply(Ident(<foo>), List(TypeTree(<Int>)))
An extractor class to create and pattern match with syntax Apply(fun, args)
. This AST node corresponds to the following Scala code:
fun(args)
For instance:
fun[targs](args)
Is expressed as:
Apply(TypeApply(fun, targs), args)
An extractor class to create and pattern match with syntax Assign(lhs, rhs)
. This AST node corresponds to the following Scala code:
lhs = rhs
Bind a variable to a rhs pattern.
Eliminated by compiler phases patmat (in the new pattern matcher of 2.10) or explicitouter (in the old pre-2.10 pattern matcher).
An extractor class to create and pattern match with syntax Bind(name, body)
. This AST node corresponds to the following Scala code:
pat*
An extractor class to create and pattern match with syntax Block(stats, expr)
. This AST node corresponds to the following Scala code:
{ stats; expr }
If the block is empty, the expr
is set to Literal(Constant(()))
.
Case clause in a pattern match. (except for occurrences in switch statements). Eliminated by compiler phases patmat (in the new pattern matcher of 2.10) or explicitouter (in the old pre-2.10 pattern matcher)
An extractor class to create and pattern match with syntax CaseDef(pat, guard, body)
. This AST node corresponds to the following Scala code:
case
pat if
guard => body
If the guard is not present, the guard
is set to EmptyTree
. If the body is not specified, the body
is set to Literal(Constant(()))
An extractor class to create and pattern match with syntax ClassDef(mods, name, tparams, impl)
. This AST node corresponds to the following Scala code:
mods class
name [tparams] impl
Where impl stands for:
extends
parents { defs }
Intersection type <parent1> with ... with <parentN> { <decls> }, eliminated by RefCheck
An extractor class to create and pattern match with syntax CompoundTypeTree(templ)
. This AST node corresponds to the following Scala code:
parent1 with ... with parentN { refinement }
An extractor class to create and pattern match with syntax DefDef(mods, name, tparams, vparamss, tpt, rhs)
. This AST node corresponds to the following Scala code:
mods def
name[tparams](vparams_1)...(vparams_n): tpt = rhs
If the return type is not specified explicitly (i.e. is meant to be inferred), this is expressed by having tpt
set to TypeTree()
(but not to an EmptyTree
!).
An extractor class to create and pattern match with syntax ExistentialTypeTree(tpt, whereClauses)
. This AST node corresponds to the following Scala code:
tpt forSome { whereClauses }
An extractor class to create and pattern match with syntax Function(vparams, body)
. This AST node corresponds to the following Scala code:
vparams => body
The symbol of a Function is a synthetic TermSymbol. It is the owner of the function's parameters.
An extractor class to create and pattern match with syntax Ident(qual, name)
. This AST node corresponds to the following Scala code:
name
Type checker converts idents that refer to enclosing fields or methods to selects. For example, name ==> this.name
An extractor class to create and pattern match with syntax If(cond, thenp, elsep)
. This AST node corresponds to the following Scala code:
if
(cond) thenp else
elsep
If the alternative is not present, the elsep
is set to Literal(Constant(()))
.
An extractor class to create and pattern match with syntax Import(expr, selectors)
. This AST node corresponds to the following Scala code:
import expr.{selectors}
Selectors are a list of ImportSelectors, which conceptually are pairs of names (from, to). The last (and maybe only name) may be a nme.WILDCARD. For instance:
import qual.{w => _, x, y => z, _}
Would be represented as:
Import(qual, List(("w", WILDCARD), ("x", "x"), ("y", "z"), (WILDCARD, null)))
The symbol of an Import
is an import symbol @see Symbol.newImport. It's used primarily as a marker to check that the import has been typechecked.
Import selector (not a tree, but a component of the Import
tree)
Representation of an imported name its optional rename and their optional positions
Eliminated by typecheck.
An extractor class to create and pattern match with syntax ImportSelector(name, namePos, rename, renamePos)
. This is not an AST node, it is used as a part of the Import
node.
A labelled expression. Not expressible in language syntax, but generated by the compiler to simulate while/do-while loops, and also by the pattern matcher.
The label acts much like a nested function, where params
represents the incoming parameters. The symbol given to the LabelDef should have a MethodType, as if it were a nested function.
Jumps are apply nodes attributed with a label's symbol. The arguments from the apply node will be passed to the label and assigned to the Idents.
Forward jumps within a block are allowed.
An extractor class to create and pattern match with syntax LabelDef(name, params, rhs)
.
This AST node does not have direct correspondence to Scala code. It is used for tailcalls and like. For example, while/do are desugared to label defs as follows:
while (cond) body ==> LabelDef($L, List(), if (cond) { body; L$() } else ())
do body while (cond) ==> LabelDef($L, List(), body; if (cond) L$() else ())
An extractor class to create and pattern match with syntax Literal(value)
. This AST node corresponds to the following Scala code:
value
- Pattern matching expression (before compiler phase explicitouter before 2.10 / patmat from 2.10)
After compiler phase explicitouter before 2.10 / patmat from 2.10, cases will satisfy the following constraints:
EmptyTree
,all patterns will be either Literal(Constant(x:Int))
or Alternative(lit|...|lit)
except for an "otherwise" branch, which has pattern Ident(nme.WILDCARD)
An extractor class to create and pattern match with syntax Match(selector, cases)
. This AST node corresponds to the following Scala code:
selector match
{ cases }
Match
is also used in pattern matching assignments like val (foo, bar) = baz
.
An extractor class to create and pattern match with syntax Modifiers(flags, privateWithin, annotations)
. Modifiers encapsulate flags, visibility annotations and Scala annotations for member definitions.
An object definition, e.g. object Foo
. Internally, objects are quite frequently called modules to reduce ambiguity. Eliminated by compiler phase refcheck.
An extractor class to create and pattern match with syntax ModuleDef(mods, name, impl)
. This AST node corresponds to the following Scala code:
mods object
name impl
Where impl stands for:
extends
parents { defs }
A tree that carries a name, e.g. by defining it (DefTree
) or by referring to it (RefTree
).
Either an assignment or a named argument. Only appears in argument lists, eliminated by compiler phase typecheck (doTypedApply), resurrected by reifier.
An extractor class to create and pattern match with syntax NamedArg(lhs, rhs)
. This AST node corresponds to the following Scala code:
m.f(lhs = rhs)
@annotation(lhs = rhs)
An extractor class to create and pattern match with syntax New(tpt)
. This AST node corresponds to the following Scala code:
new
T
This node always occurs in the following context:
(new
tpt).<init>[targs](args)
For example, an AST representation of:
new Example[Int](2)(3)
is the following code:
Apply( Apply( TypeApply( Select(New(TypeTree(typeOf[Example])), nme.CONSTRUCTOR) TypeTree(typeOf[Int])), List(Literal(Constant(2)))), List(Literal(Constant(3))))
An extractor class to create and pattern match with syntax PackageDef(pid, stats)
. This AST node corresponds to the following Scala code:
package
pid { stats }
A tree which references a symbol-carrying entity. References one, as opposed to defining one; definitions are in DefTrees.
An extractor class to create and pattern match with syntax RefTree(qual, name)
. This AST node corresponds to either Ident, Select or SelectFromTypeTree.
An extractor class to create and pattern match with syntax Return(expr)
. This AST node corresponds to the following Scala code:
return
expr
The symbol of a Return node is the enclosing method.
A member selection <qualifier> . <name>
An extractor class to create and pattern match with syntax Select(qual, name)
. This AST node corresponds to the following Scala code:
qualifier.selector
Should only be used with qualifier
nodes which are terms, i.e. which have isTerm
returning true
. Otherwise SelectFromTypeTree
should be used instead.
foo.Bar // represented as Select(Ident(<foo>), <Bar>) Foo#Bar // represented as SelectFromTypeTree(Ident(<Foo>), <Bar>)
An extractor class to create and pattern match with syntax SelectFromTypeTree(qualifier, name)
. This AST node corresponds to the following Scala code:
qualifier # selector
Note: a path-dependent type p.T is expressed as p.type # T
Should only be used with qualifier
nodes which are types, i.e. which have isType
returning true
. Otherwise Select
should be used instead.
Foo#Bar // represented as SelectFromTypeTree(Ident(<Foo>), <Bar>) foo.Bar // represented as Select(Ident(<foo>), <Bar>)
An extractor class to create and pattern match with syntax SingletonTypeTree(ref)
. This AST node corresponds to the following Scala code:
ref.type
Repetition of pattern.
Eliminated by compiler phases patmat (in the new pattern matcher of 2.10) or explicitouter (in the old pre-2.10 pattern matcher).
An extractor class to create and pattern match with syntax Star(elem)
. This AST node corresponds to the following Scala code:
pat*
Super reference, where qual
is the corresponding this
reference. A super reference C.super[M]
is represented as Super(This(C), M)
.
An extractor class to create and pattern match with syntax Super(qual, mix)
. This AST node corresponds to the following Scala code:
C.super[M]
Which is represented as:
Super(This(C), M)
If mix
is empty, it is tpnme.EMPTY.
The symbol of a Super is the class _from_ which the super reference is made. For instance in C.super(...), it would be C.
A tree that carries a symbol, e.g. by defining it (DefTree
) or by referring to it (RefTree
). Such trees start their life naked, returning NoSymbol
, but after being typechecked without errors they hold non-empty symbols.
An extractor class to create and pattern match with syntax Template(parents, self, body)
. This AST node corresponds to the following Scala code:
extends
parents { self => body }
In case when the self-type annotation is missing, it is represented as an empty value definition with nme.WILDCARD as name and NoType as type.
The symbol of a template is a local dummy. @see Symbol.newLocalDummy The owner of the local dummy is the enclosing trait or class. The local dummy is itself the owner of any local blocks. For example:
class C { def foo { // owner is C def bar // owner is local dummy } }
A tree for a term. Not all trees representing terms are TermTrees; use isTerm to reliably identify terms.
An extractor class to create and pattern match with syntax This(qual)
. This AST node corresponds to the following Scala code:
qual.this
The symbol of a This is the class to which the this refers. For instance in C.this, it would be C.
An extractor class to create and pattern match with syntax Throw(expr)
. This AST node corresponds to the following Scala code:
throw
expr
The API that all trees support. The main source of information about trees is the scala.reflect.api.Trees page.
An extractor class to create and pattern match with syntax Try(block, catches, finalizer)
. This AST node corresponds to the following Scala code:
try
block catch
{ catches } finally
finalizer
If the finalizer is not present, the finalizer
is set to EmptyTree
.
A tree for a type. Not all trees representing types are TypTrees; use isType to reliably identify types.
An extractor class to create and pattern match with syntax TypeApply(fun, args)
. This AST node corresponds to the following Scala code:
fun[args]
Should only be used with fun
nodes which are terms, i.e. which have isTerm
returning true
. Otherwise AppliedTypeTree
should be used instead.
def foo[T] = ??? foo[Int] // represented as TypeApply(Ident(<foo>), List(TypeTree(<Int>)))
List[Int] as in val x: List[Int] = ???
// represented as AppliedTypeTree(Ident(<List>), List(TypeTree(<Int>)))
An extractor class to create and pattern match with syntax TypeBoundsTree(lo, hi)
. This AST node corresponds to the following Scala code:
>: lo <: hi
An abstract type, a type parameter, or a type alias. Eliminated by erasure.
An extractor class to create and pattern match with syntax TypeDef(mods, name, tparams, rhs)
. This AST node corresponds to the following Scala code:
mods type
name[tparams] = rhs
mods type
name[tparams] >: lo <: hi
First usage illustrates TypeDefs
representing type aliases and type parameters. Second usage illustrates TypeDefs
representing abstract types, where lo and hi are both TypeBoundsTrees
and Modifier.deferred
is set in mods.
A synthetic tree holding an arbitrary type. Not to be confused with with TypTree, the trait for trees that are only used for type trees. TypeTree's are inserted in several places, but most notably in RefCheck
, where the arbitrary type trees are all replaced by TypeTree's.
An extractor class to create and pattern match with syntax TypeTree()
. This AST node does not have direct correspondence to Scala code, and is emitted by everywhere when we want to wrap a Type
in a Tree
.
An extractor class to create and pattern match with syntax Typed(expr, tpt)
. This AST node corresponds to the following Scala code:
expr: tpt
Used to represent unapply
methods in pattern matching.
For example:
2 match { case Foo(x) => x }
Is represented as:
Match( Literal(Constant(2)), List( CaseDef( UnApply( // a dummy node that carries the type of unapplication to patmat // the <unapply-selector> here doesn't have an underlying symbol // it only has a type assigned, therefore after `untypecheck` this tree is no longer typeable Apply(Select(Ident(Foo), TermName("unapply")), List(Ident(TermName("<unapply-selector>")))), // arguments of the unapply => nothing synthetic here List(Bind(TermName("x"), Ident(nme.WILDCARD)))), EmptyTree, Ident(TermName("x")))))
Introduced by typer. Eliminated by compiler phases patmat (in the new pattern matcher of 2.10) or explicitouter (in the old pre-2.10 pattern matcher).
An extractor class to create and pattern match with syntax UnApply(fun, args)
. This AST node does not have direct correspondence to Scala code, and is introduced when typechecking pattern matches and try
blocks.
Broadly speaking, a value definition. All these are encoded as ValDefs:
An extractor class to create and pattern match with syntax ValDef(mods, name, tpt, rhs)
. This AST node corresponds to any of the following Scala code:
mods val
name: tpt = rhs
mods var
name: tpt = rhs
mods name: tpt = rhs // in signatures of function and method definitions
self: Bar => // self-types
If the type of a value is not specified explicitly (i.e. is meant to be inferred), this is expressed by having tpt
set to TypeTree()
(but not to an EmptyTree
!).
Obtains string representation of a tree
A factory method for Apply
nodes.
(Since version 2.10.1) use q"$sym(..$args)" instead
0-1 argument list new, based on a type tree.
(Since version 2.10.1) use q"new $tpt(..$args)" instead
A factory method for Bind
nodes.
(Since version 2.10.1) use the canonical Bind constructor to create a bind and then initialize its symbol manually
A factory method for Block
nodes. Flattens directly nested blocks.
(Since version 2.10.1) use q"{..$stats}" instead. Flatten directly nested blocks manually if needed
A factory method for CaseDef
nodes.
(Since version 2.10.1) use cq"$pat => $body" instead
A factory method for Ident
nodes.
(Since version 2.10.1) use Ident(TermName(name)) instead
0-1 argument list new, based on a symbol.
(Since version 2.10.1) use q"new ${sym.toType}(..$args)" instead
0-1 argument list new, based on a type.
(Since version 2.10.1) use q"new $tpe(..$args)" instead
Factory method for object creation new tpt(args_1)...(args_n)
A New(t, as)
is expanded to: (new t).<init>(as)
(Since version 2.10.1) use q"new $tpt(...$argss)" instead
A factory method for Select
nodes. The string name
argument is assumed to represent a TermName
.
(Since version 2.10.1) use Select(tree, TermName(name)) instead
A factory method for Super
nodes.
(Since version 2.10.1) use q"$sym.super[$mix].x".qualifier instead
A factory method for Throw
nodes.
(Since version 2.10.1) use q"throw new $tpe(..$args)" instead
A factory method for Try
nodes.
(Since version 2.10.1) convert cases into casedefs and use q"try $body catch { case ..$newcases }" instead
(Since version 2.11.0) use noSelfType
instead
Delegates the transformation strategy to scala.reflect.internal.Trees
, because pattern matching on abstract types we have here degrades performance.
Provides an extension hook for the transformation strategy. Future-proofs against new node types.
© 2002-2019 EPFL, with contributions from Lightbend.
Licensed under the Apache License, Version 2.0.
https://www.scala-lang.org/api/2.13.0/scala-reflect/scala/reflect/api/Trees.html
EXPERIMENTAL
This trait defines the node types used in Scala abstract syntax trees (AST) and operations on them.
Trees are the basis for Scala's abstract syntax that is used to represent programs. They are also called abstract syntax trees and commonly abbreviated as ASTs.
In Scala reflection, APIs that produce or use
Tree
s are:Trees are immutable, except for three fields pos, symbol, and tpe, which are assigned when a tree is typechecked to attribute it with the information gathered by the typechecker.
Examples
The following creates an AST representing a literal 5 in Scala source code:
The following creates an AST representing
print("Hello World")
:The following creates an AST from a literal 5, and then uses
showRaw
to print it in a readable format.For more information about
Tree
s, see the Reflection Guide: Symbols, Trees, Types.