Code Modification |
Examples of code modification.
// Renaming a named code object is trivial - just assign a new name, and all resolved references will // automatically make use of the new name (for name changes, it's obviously very important that all // symbolic references are resolved first). Code objects have various other properties which can also // be directly assigned. Some code objects have direct children code objects (such as the various parts // of a For loop) which can be directly assigned to LocalDecls or Expressions. Many (such as all // BlockStatements) have a Body which is a collection of child code objects which can be manipulated // using methods such as Add(), Remove(), and Insert(). // Here are some examples using a small code fragment: const string fragment = "/// <see cref=\"OldClass\"/>\n" + "class OldClass\n" + "{\n" + " public OldClass(int arg)\n" + " { }\n" + " \n" + " private void ToBeDeletedMethod()\n" + " { }\n" + " \n" + " /// <param name=\"oldArg\">The argument.</param>\n" + " private void Method(int oldArg = -1)\n" + " {\n" + " OldClass x = new OldClass(oldArg);\n" + " for (int i = oldArg; i < 10; ++i)\n" + " x.Method(oldArg);\n" + " }\n" + "}\n"; CodeUnit codeUnit = CodeUnit.LoadFragment(fragment, "Fragment"); if (codeUnit != null) { var classDecl = codeUnit.FindFirst<ClassDecl>("OldClass"); if (classDecl != null) { // Rename 'OldClass' to 'NewClass' and change it to 'public' classDecl.Name = "NewClass"; classDecl.IsPublic = true; var methodDecl = classDecl.FindFirst<MethodDecl>("Method"); if (methodDecl != null) { // Change 'Method' to 'public', and change its return type from 'void' to 'int' methodDecl.IsPublic = true; methodDecl.ReturnType = typeof(int); // Rename the parameter of 'Method' from 'oldArg' to 'newArg', change its type from 'int' to 'long', // and change its initialization from '-1' to '0'. var parameterDecl = methodDecl.Parameters[0]; parameterDecl.Name = "newArg"; parameterDecl.Type = typeof(long); parameterDecl.Initialization = 0; } // Insert a new method after the constructor classDecl.Insert(1, new MethodDecl("InsertedMethod", typeof(void))); // Remove a method var toBeDeleted = classDecl.FindFirst<MethodDecl>("ToBeDeletedMethod"); if (toBeDeleted != null) classDecl.Remove(toBeDeleted); } // Insert an enum into the CodeUnit before the class codeUnit.Insert(0, new EnumDecl("Enum") { MemberDecls = { new EnumMemberDecl("One"), new EnumMemberDecl("Two") } }); // Display the modified code Log.WriteLine(codeUnit.AsString()); }