Skip to content

[Question] Example for spoon pattern #6580

@Louis-max-H

Description

@Louis-max-H

Hi 👋
I can't figure out how to create a pattern to match some code with parameters.
You can find here a small viable solution : https://gitlab.com/Louis-max/spoonpaternloop

The goal is to have one parameter i for the local iterator variable, and another for the init value of i.
I have something like that,

// Generate AST to match for loop pattern
String patternCode = "class PatternModel { void m() { for(int _i_ = _initValue_; _i_ < 10; _i_ += 1) {} } }";
[...]
patternLauncher.buildModel();
CtFor forLoopModel = (CtFor) patternMethod.getBody().getStatements().stream()
    .filter(s -> s instanceof CtFor)
    .findFirst();

// Configure pattern
Pattern pattern = PatternBuilder.create(forLoopModel.clone())
    .configurePatternParameters(pb -> {
        // Variable de boucle
        pb.parameter("varName")
            .byVariable("_i_");
        
        // Valeur d'initialisation (doit être un entier)
        pb.parameter("initValue")
            .byVariable("_initValue_")
            .byCondition(CtLiteral.class, literal -> {
                Object value = literal.getValue();
                System.out.println("initValue: " + value);
                return value instanceof Integer;
            });
    })
    .build();


// Print matching for loop
pattern.forEachMatch(factory.getModel().getRootPackage(), (Match match) -> {
    System.out.println("For loop detected:");
    System.out.println("  Code: " + match.toString());
});

But I get no match, do you have any advices ?
If I can make this example work, I will add it to the list of examples.

Thanks !

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