defines the path to a
in a model, similarly to XPath for XML. For example,
.spoon.test.path.testclasses.Foo.foo#body#statement[index=0] represents the first statement of the body of method foo.
CtPathis based on: names of elements (eg
foo), and roles of elements with respect to their parent (eg
A role is a relation between two AST nodes.
For instance, a "then" branch in a if/then/else is a role (and not an node). All roles can be found in
CtRole. In addition, each getter or setter in the metamodel is annotated with its role.
Evaluating AST paths
Paths are used to find code elements, from a given root elements.
path = new CtPathStringBuilder().fromString(".spoon.test.path.testclasses.Foo.foo#body#statement[index=0]");
List<CtElement> l = path.evaluateOn(root)
Creating AST paths
From an existing element
CtElement returns a path
CtPath path = anElement.getPath();
From a string
CtPathStringBuilder (javadoc), creates a path object from a string according to the following syntax:
.<name> which denotes a child element with name
.fr.inria.Spoon (the fully qualified name)
#<role> which denotes all children on
#body#statement[index=2]#else is the else branch of the second statement of a method body
name=<somename> - filter which accepts only elements with
signature=<somesignature> - filter which accepts only methods and constructors with signature
- Example of method signature:
- Example of constructor signature:
index=<idx> - fitler which accepts only idx-th element of the List. The first element has index 0. the fifth type memeber in a class
From the API
CtPathBuilder (javadoc) defines a fluent api to build your path:
name(String, String) (javadoc)
adds a name matcher to the current path.
type(Class, String) (javadoc)
matches on element of a given type.
role(CtPathRole, String) (javadoc)
matches on elements by their role (where
CtPathRole gives all constants supported).
matches only on elements child of current one.
matches on any child and sub-children.
For instance, if we want all elements named by "toto" and with a default value in
a project. Use
CtPathBuilder like the example below.
CtPath p1 = new CtPathBuilder().recursiveWildcard().name("toto").role(CtPathRole.DEFAULT_VALUE).build();
// equivalent to
CtPath p2 = new CtPathStringBuilder().fromString(".**.toto#default_value").build();
// takes all elements named "toto" in the project.
// takes the first element named "toto", a package or a class in the default package, at the root of your project.