Skip to content

How to match an assignment using TemplateMatcher #1989

@EdgarACarneiro

Description

@EdgarACarneiro

Hey there!

I have a doubt regarding the usage of the TemplateMatcher that I can not seem to get clarified.
I am trying to use the TemplateMatcher to match code with some patterns. However, in the definition of the patterns, I am not being able to write assignments ( for example a pattern were inside an if clause there's an assignment to an existing variable ).

I have tried different approaches, such as

public TemplateParameter<CtVariableAccess> _var_x_
....
if (true)
			_var_x_.S() = 1;
			//_var_x_ = 1;

but I can not get it to work.. The code calling the matching is written similarly to the code present in spoon/src/test/java/spoon/test/template/TemplateTest.java

{// testing matcher1
			CtClass<?> templateKlass = factory.Class().get(CheckBoundMatcher.class);
			CtClass<?> klass = factory.Class().get(CheckBound.class);
			CtIf templateRoot = (CtIf) ((CtMethod) templateKlass.getElements(new NamedElementFilter<>(CtMethod.class,"matcher1")).get(0)).getBody().getStatement(0);
			TemplateMatcher matcher = new TemplateMatcher(templateRoot);
			assertEquals(2, matcher.find(klass).size());
			assertThat(asList("foo","fbar"), is(klass.filterChildren(matcher).map((CtElement e)->e.getParent(CtMethod.class).getSimpleName()).list())) ;
}

Any help would be much appreciated!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions