Search code examples
refactoringtransformationrascal

How update a transformation done on a read file?


How update the content of a file, "teste.java" as example with the result of a transformation?

loc s =  |project://java-sample/teste.java|;
content = readFile(s);
CompilationUnit cUnit = parse(#CompilationUnit, content);
visit(cUnit) {
   case (Statement) `if (<Expression cond>) { return true; } else { return false; }` =>  
        (Statement) `return <Expression cond>;`
}

Solution

  • The visit returns the new tree. You can save that tree to a file using writeFile that will unparse it and save the file:

    loc s =  |project://java-sample/teste.java|;
    content = readFile(s);
    CompilationUnit cUnit = parse(#CompilationUnit, content);
    cUnitNew = visit(cUnit) { // note the assignment!
       case (Statement) `if (<Expression cond>) { return true; } else { return false; }` =>  
            (Statement) `return <Expression cond>;`
    }
    writeFile(s, cUnitNew); // write the new string to disk