public IType RenameClass(IProgressMonitor monitor, IType cls, string newName, RefactoryScope scope) { try { MemberReferenceCollection refs = new MemberReferenceCollection(); Refactor(monitor, cls, scope, new RefactorDelegate(new RefactorFindClassReferences(cls, refs, false).Refactor)); refs.RenameAll(newName); RefactorerContext gctx = GetGeneratorContext(cls); IRefactorer r = GetGeneratorForClass(cls); foreach (IMethod method in cls.Methods) { if (method.IsConstructor) { r.RenameMember(gctx, cls, (IMember)method, newName); } } cls = r.RenameClass(gctx, cls, newName); gctx.Save(); return(cls); } catch (Exception e) { LoggingService.LogError(GettextCatalog.GetString("Error while renaming {0} to {1}: {2}", cls, newName, e.ToString())); return(null); } }
public void AddAttribute(IType cls, CodeAttributeDeclaration attr) { RefactorerContext gctx = GetGeneratorContext(cls); IRefactorer gen = GetGeneratorForClass(cls); gen.AddAttribute(gctx, cls, attr); gctx.Save(); }
public IMember ImplementMember(IType cls, IMember member, IReturnType privateReturnType) { RefactorerContext gctx = GetGeneratorContext(cls); IRefactorer gen = GetGeneratorForClass(cls); IMember m = gen.ImplementMember(gctx, cls, member, privateReturnType); gctx.Save(); return(m); }
public IType AddMembers(IType cls, IEnumerable <CodeTypeMember> members, string foldingRegionName) { RefactorerContext gctx = GetGeneratorContext(cls); IRefactorer gen = GetGeneratorForClass(cls); gen.AddMembers(gctx, cls, members, foldingRegionName); gctx.Save(); return(GetUpdatedClass(gctx, cls)); }
public IMember AddMember(IType cls, CodeTypeMember member) { RefactorerContext gctx = GetGeneratorContext(cls); IRefactorer gen = GetGeneratorForClass(cls); IMember m = gen.AddMember(gctx, cls, member); gctx.Save(); return(m); }
public IType CreateClass(Project project, string language, string directory, string namspace, CodeTypeDeclaration type) { ProjectDom ctx = ProjectDomService.GetProjectDom(project); RefactorerContext gctx = new RefactorerContext(ctx, fileProvider, null); IRefactorer gen = LanguageBindingService.GetRefactorerForLanguage(language); IType c = gen.CreateClass(gctx, directory, namspace, type); gctx.Save(); return(c); }
public IMember EncapsulateField(IProgressMonitor monitor, IType cls, IField field, string propName, MemberAttributes attr, bool generateSetter, bool updateInternalRefs) { RefactoryScope scope = GetScope(field); MemberReferenceCollection refs = new MemberReferenceCollection(); Refactor(monitor, cls, scope, new RefactorDelegate(new RefactorFindMemberReferences(cls, field, refs, false).Refactor)); if (!updateInternalRefs) { ArrayList list = new ArrayList(); list.AddRange(refs); list.Sort(new MemberReferenceCollection.MemberComparer()); foreach (MemberReference mref in list) { bool rename = true; foreach (IType part in field.DeclaringType.Parts) { if (mref.FileName == part.CompilationUnit.FileName) { DomRegion region = part.BodyRegion; // check if the reference is internal to the class if ((mref.Line > region.Start.Line || (mref.Line == region.Start.Line && mref.Column >= region.Start.Column)) && (mref.Line < region.End.Line || (mref.Line == region.End.Line && mref.Column <= region.End.Column))) { // Internal to the class, don't rename rename = false; break; } } } if (rename) { mref.Rename(propName); } } } else { refs.RenameAll(propName); } RefactorerContext gctx = GetGeneratorContext(cls); IRefactorer r = GetGeneratorForClass(cls); IMember m = r.EncapsulateField(gctx, cls, field, propName, attr, generateSetter); gctx.Save(); return(m); }
public void RemoveMember(IType cls, IMember member) { try { RefactorerContext gctx = GetGeneratorContext(cls); IRefactorer gen = GetGeneratorForClass(cls); gen.RemoveMember(gctx, cls, member); gctx.Save(); } catch (Exception e) { LoggingService.LogError(GettextCatalog.GetString("Error while removing {0}:{1}", member, e.ToString())); } }
public IType ImplementMembers(IType cls, IEnumerable <KeyValuePair <IMember, IReturnType> > members, string foldingRegionName) { RefactorerContext gctx = GetGeneratorContext(cls); cls = GetUpdatedClass(gctx, cls); IRefactorer gen = GetGeneratorForClass(cls); gen.ImplementMembers(gctx, cls, members, foldingRegionName); gctx.Save(); return(GetUpdatedClass(gctx, cls)); }
public MemberReference (RefactorerContext rctx, FilePath fileName, int position, int line, int column, string name, string textLine) { this.position = position; this.line = line; this.column = column; this.fileName = fileName; this.name = name; this.rctx = rctx; this.textLine = textLine; if (textLine == null || textLine.Length == 0) textLine = name; }
public void Refactor(IProgressMonitor monitor, RefactorerContext rctx, IRefactorer r, string fileName) { try { IEnumerable <MemberReference> refs = r.FindClassReferences(rctx, fileName, cls, includeXmlComment); if (refs != null) { references.AddRange(refs); } } catch (Exception ex) { monitor.ReportError(GettextCatalog.GetString("Could not look for references in file '{0}': {1}", fileName, ex.Message), ex); } }
public IMember ReplaceMember(IType cls, IMember oldMember, CodeTypeMember member) { try { RefactorerContext gctx = GetGeneratorContext(cls); IRefactorer gen = GetGeneratorForClass(cls); IMember m = gen.ReplaceMember(gctx, cls, oldMember, member); gctx.Save(); return(m); } catch (Exception e) { LoggingService.LogError(GettextCatalog.GetString("Error while replacing {0}: {1}", member, e.ToString())); return(null); } }
public MemberReference(RefactorerContext rctx, FilePath fileName, int position, int line, int column, string name, string textLine) { this.position = position; this.line = line; this.column = column; this.fileName = fileName; this.name = name; this.rctx = rctx; this.textLine = textLine; if (textLine == null || textLine.Length == 0) { textLine = name; } }
void Refactor(IProgressMonitor monitor, LocalVariable var, RefactorDelegate refactorDelegate) { RefactorerContext gctx = GetGeneratorContext(var); string file = var.FileName; IRefactorer gen = LanguageBindingService.GetRefactorerForFile(file); if (gen == null) { return; } refactorDelegate(monitor, gctx, gen, file); gctx.Save(); }
// public IType ImplementInterface (ICompilationUnit pinfo, IType klass, IType iface, bool explicitly, IType declaringClass, IReturnType hintReturnType) // { // if (klass == null) // throw new ArgumentNullException ("klass"); // if (iface == null) // throw new ArgumentNullException ("iface"); // RefactorerContext gctx = GetGeneratorContext (klass); // klass = GetUpdatedClass (gctx, klass); // // bool alreadyImplemented; // IReturnType prefix = null; // // List<KeyValuePair<IMember,IReturnType>> toImplement = new List<KeyValuePair<IMember,IReturnType>> (); // // prefix = new DomReturnType (iface); // // // Stub out non-implemented events defined by @iface // foreach (IEvent ev in iface.Events) { // if (ev.IsSpecialName) // continue; // bool needsExplicitly = explicitly; // // alreadyImplemented = gctx.ParserContext.GetInheritanceTree (klass).Any (x => x.ClassType != ClassType.Interface && x.Events.Any (y => y.Name == ev.Name)); // // if (!alreadyImplemented) // toImplement.Add (new KeyValuePair<IMember,IReturnType> (ev, needsExplicitly ? prefix : null)); // } // // // Stub out non-implemented methods defined by @iface // foreach (IMethod method in iface.Methods) { // if (method.IsSpecialName) // continue; // bool needsExplicitly = explicitly; // alreadyImplemented = false; // foreach (IType t in gctx.ParserContext.GetInheritanceTree (klass)) { // if (t.ClassType == ClassType.Interface) // continue; // foreach (IMethod cmet in t.Methods) { // if (cmet.Name == method.Name && Equals (cmet.Parameters, method.Parameters)) { // if (!needsExplicitly && !cmet.ReturnType.Equals (method.ReturnType)) // needsExplicitly = true; // else // alreadyImplemented |= !needsExplicitly || (iface.FullName == GetExplicitPrefix (cmet.ExplicitInterfaces)); // } // } // } // // if (!alreadyImplemented) // toImplement.Add (new KeyValuePair<IMember,IReturnType> (method, needsExplicitly ? prefix : null)); // } // // // Stub out non-implemented properties defined by @iface // foreach (IProperty prop in iface.Properties) { // if (prop.IsSpecialName) // continue; // bool needsExplicitly = explicitly; // alreadyImplemented = false; // foreach (IType t in gctx.ParserContext.GetInheritanceTree (klass)) { // if (t.ClassType == ClassType.Interface) // continue; // foreach (IProperty cprop in t.Properties) { // if (cprop.Name == prop.Name) { // if (!needsExplicitly && !cprop.ReturnType.Equals (prop.ReturnType)) // needsExplicitly = true; // else // alreadyImplemented |= !needsExplicitly || (iface.FullName == GetExplicitPrefix (cprop.ExplicitInterfaces)); // } // } // } // if (!alreadyImplemented) // toImplement.Add (new KeyValuePair<IMember,IReturnType> (prop, needsExplicitly ? prefix : null)); } // // Ambience ambience = AmbienceService.GetAmbienceForFile (klass.CompilationUnit.FileName); // //implement members // ImplementMembers (klass, toImplement, ambience.GetString (iface, OutputFlags.ClassBrowserEntries | OutputFlags.IncludeGenerics | OutputFlags.IncludeParameters) + " implementation"); // gctx.Save (); // // klass = GetUpdatedClass (gctx, klass); // foreach (IType baseClass in iface.SourceProjectDom.GetInheritanceTree (iface)) { // if (baseClass.Equals (iface) || baseClass.FullName == "System.Object") // continue; // klass = ImplementInterface (pinfo, klass, baseClass, explicitly, declaringClass, hintReturnType); // } // // // return klass; // } IType GetUpdatedClass(RefactorerContext gctx, IType klass) { IEditableTextFile file = gctx.GetFile(klass.CompilationUnit.FileName); ParsedDocument doc = ProjectDomService.Parse(gctx.ParserContext.Project, file.Name, delegate() { return(file.Text); }); IType result = gctx.ParserContext.GetType(klass.FullName, klass.TypeParameters.Count, true); if (result is CompoundType) { IType hintType = doc.CompilationUnit.GetType(klass.FullName, klass.TypeParameters.Count); if (hintType != null) { ((CompoundType)result).SetMainPart(file.Name, hintType.Location); } } return(result); }
public bool RenameVariable(IProgressMonitor monitor, LocalVariable var, string newName) { try { MemberReferenceCollection refs = new MemberReferenceCollection(); Refactor(monitor, var, new RefactorDelegate(new RefactorFindVariableReferences(var, refs).Refactor)); refs.RenameAll(newName); RefactorerContext gctx = GetGeneratorContext(var); IRefactorer r = GetGeneratorForVariable(var); bool rv = r.RenameVariable(gctx, var, newName); gctx.Save(); return(rv); } catch (Exception e) { LoggingService.LogError(GettextCatalog.GetString("Error while renaming {0} to {1}: {2}", var, newName, e.ToString())); return(false); } }
IMember InnerRenameMember(IProgressMonitor monitor, IType cls, IMember member, string newName, RefactoryScope scope) { try { MemberReferenceCollection refs = new MemberReferenceCollection(); Refactor(monitor, cls, scope, new RefactorDelegate(new RefactorFindMemberReferences(cls, member, refs, false).Refactor)); refs.RenameAll(newName); RefactorerContext gctx = GetGeneratorContext(cls); IRefactorer gen = GetGeneratorForClass(cls); IMember m = gen.RenameMember(gctx, cls, member, newName); gctx.Save(); return(m); } catch (Exception e) { LoggingService.LogError(GettextCatalog.GetString("Error while renaming {0} to {1}: {2}", member, newName, e.ToString())); return(null); } }
public bool RenameParameter(IProgressMonitor monitor, IParameter param, string newName) { try { MemberReferenceCollection refs = new MemberReferenceCollection(); Refactor(monitor, param, new RefactorDelegate(new RefactorFindParameterReferences(param, refs, false).Refactor)); refs.RenameAll(newName); IMember member = param.DeclaringMember; RefactorerContext gctx = GetGeneratorContext(member.DeclaringType); IRefactorer r = GetGeneratorForClass(member.DeclaringType); bool rv = r.RenameParameter(gctx, param, newName); gctx.Save(); return(rv); } catch (Exception e) { LoggingService.LogError(GettextCatalog.GetString("Error while renaming {0} to {1}: {2}", param, newName, e.ToString())); return(false); } }
void RefactorProject(IProgressMonitor monitor, Project p, RefactorDelegate refactorDelegate) { RefactorerContext gctx = GetGeneratorContext(p); monitor.Log.WriteLine(GettextCatalog.GetString("Refactoring project {0}", p.Name)); foreach (ProjectFile file in p.Files) { if (file.BuildAction != BuildAction.Compile || !System.IO.File.Exists(file.FilePath)) { continue; } IRefactorer gen = LanguageBindingService.GetRefactorerForFile(file.Name); if (gen == null) { continue; } refactorDelegate(monitor, gctx, gen, file.Name); gctx.Save(); } }
public override IClass RenameClass (RefactorerContext ctx, IClass cls, string newName) { IEditableTextFile file = ctx.GetFile (cls.Region.FileName); if (file == null) return null; int pos1 = file.GetPositionFromLineColumn (cls.Region.BeginLine, cls.Region.BeginColumn); int pos2 = file.GetPositionFromLineColumn (cls.Region.EndLine, cls.Region.EndColumn); string txt = file.GetText (pos1, pos2); Regex targetExp = new Regex(@"\sclass\s*(" + cls.Name + @")\s", RegexOptions.Multiline); Match match = targetExp.Match (" " + txt + " "); if (!match.Success) return null; int pos = pos1 + match.Groups [1].Index - 1; file.DeleteText (pos, cls.Name.Length); file.InsertText (pos, newName); return GetGeneratedClass (ctx, file, cls); }
public virtual void AddAttribute (RefactorerContext ctx, IType cls, CodeAttributeDeclaration attr) { IEditableTextFile buffer = ctx.GetFile (cls.CompilationUnit.FileName); CodeTypeDeclaration type = new CodeTypeDeclaration ("temp"); type.CustomAttributes.Add (attr); CodeDomProvider provider = GetCodeDomProvider (); StringWriter sw = new StringWriter (); provider.GenerateCodeFromType (type, sw, GetOptions (false)); string code = sw.ToString (); int start = code.IndexOf ('['); int end = code.LastIndexOf (']'); code = code.Substring (start, end-start+1) + Environment.NewLine; int line = cls.Location.Line; int col = cls.Location.Column; int pos = buffer.GetPositionFromLineColumn (line, col); code = Indent (code, GetLineIndent (buffer, line), false); buffer.InsertText (pos, code); }
void Refactor(IProgressMonitor monitor, IParameter param, RefactorDelegate refactorDelegate) { IMember member = param.DeclaringMember; RefactorerContext gctx = GetGeneratorContext(member.DeclaringType); IType cls = member.DeclaringType; IRefactorer gen; string file; foreach (IType part in cls.Parts) { file = part.CompilationUnit.FileName; if ((gen = LanguageBindingService.GetRefactorerForFile(file)) == null) { continue; } refactorDelegate(monitor, gctx, gen, file); gctx.Save(); } }
public IType CreateClass (RefactorerContext ctx, string directory, string namspace, CodeTypeDeclaration type) { CodeCompileUnit unit = new CodeCompileUnit (); CodeNamespace ns = new CodeNamespace (namspace); ns.Types.Add (type); unit.Namespaces.Add (ns); string file = Path.Combine (directory, type.Name + ".cs"); StreamWriter sw = new StreamWriter (file); CodeDomProvider provider = GetCodeDomProvider (); provider.GenerateCodeFromCompileUnit (unit, sw, GetOptions (false)); sw.Close (); ICompilationUnit pi = ProjectDomService.Parse (ctx.ParserContext.Project, file).CompilationUnit; IList<IType> clss = pi.Types; if (clss.Count > 0) return clss [0]; else throw new Exception ("Class creation failed. The parser did not find the created class."); }
public void SetContext(RefactorerContext rctx) { this.rctx = rctx; }
public override IEnumerable<MemberReference> FindVariableReferences (RefactorerContext ctx, string fileName, LocalVariable var) { //System.Console.WriteLine("Find variable references !!!"); // ParsedDocument parsedDocument = ProjectDomService.ParseFile (fileName); NRefactoryResolver resolver = new NRefactoryResolver (ctx.ParserContext, var.CompilationUnit, ICSharpCode.NRefactory.SupportedLanguage.CSharp, null, fileName); resolver.CallingMember = var.DeclaringMember; FindMemberAstVisitor visitor = new FindMemberAstVisitor (resolver, ctx.GetFile (fileName), var); visitor.RunVisitor (); SetContext (visitor.FoundReferences, ctx); return visitor.FoundReferences; }
public override IEnumerable<MemberReference> FindClassReferences (RefactorerContext ctx, string fileName, IType cls, bool includeXmlComment) { IEditableTextFile file = ctx.GetFile (fileName); NRefactoryResolver resolver = new NRefactoryResolver (ctx.ParserContext, cls.CompilationUnit, ICSharpCode.NRefactory.SupportedLanguage.CSharp, null, fileName); FindMemberAstVisitor visitor = new FindMemberAstVisitor (resolver, file, cls); visitor.IncludeXmlDocumentation = includeXmlComment; visitor.RunVisitor (); SetContext (visitor.FoundReferences, ctx); return visitor.FoundReferences; }
public override IMember ImplementMember (RefactorerContext ctx, IType cls, IMember member, IReturnType privateImplementationType) { if (privateImplementationType != null) { // Workaround for bug in the code generator. Generic private implementation types are not generated correctly when they are generic. Ambience amb = new CSharpAmbience (); string tn = amb.GetString (privateImplementationType, OutputFlags.IncludeGenerics | OutputFlags.UseFullName | OutputFlags.UseIntrinsicTypeNames); privateImplementationType = new DomReturnType (tn); } return base.ImplementMember (ctx, cls, member, privateImplementationType); }
public override void AddLocalNamespaceImport (RefactorerContext ctx, string fileName, string nsName, DomLocation caretLocation) { IEditableTextFile file = ctx.GetFile (fileName); int pos = 0; ParsedDocument parsedDocument = parser.Parse (ctx.ParserContext, fileName, file.Text); StringBuilder text = new StringBuilder (); string indent = ""; if (parsedDocument.CompilationUnit != null) { IUsing containingUsing = null; foreach (IUsing u in parsedDocument.CompilationUnit.Usings) { if (u.IsFromNamespace && u.Region.Contains (caretLocation)) { containingUsing = u; } } if (containingUsing != null) { indent = GetLineIndent (file, containingUsing.Region.Start.Line); IUsing lastUsing = null; foreach (IUsing u in parsedDocument.CompilationUnit.Usings) { if (u == containingUsing) continue; if (containingUsing.Region.Contains (u.Region)) { if (u.IsFromNamespace) break; lastUsing = u; } } if (lastUsing != null) { pos = file.GetPositionFromLineColumn (lastUsing.Region.End.Line, lastUsing.Region.End.Column); } else { pos = file.GetPositionFromLineColumn (containingUsing.ValidRegion.Start.Line, containingUsing.ValidRegion.Start.Column); // search line end while (pos < file.Length) { char ch = file.GetCharAt (pos); if (ch == '\n') { if (file.GetCharAt (pos + 1) == '\r') pos++; break; } else if (ch == '\r') { break; } pos++; } } } else { AddGlobalNamespaceImport (ctx, fileName, nsName); return; } } if (pos != 0) text.AppendLine (); text.Append (indent); text.Append ("\t"); text.Append ("using "); text.Append (nsName); text.Append (";"); if (pos == 0) text.AppendLine (); if (file is Mono.TextEditor.ITextEditorDataProvider) { Mono.TextEditor.TextEditorData data = ((Mono.TextEditor.ITextEditorDataProvider)file).GetTextEditorData (); int caretOffset = data.Caret.Offset; int insertedChars = data.Insert (pos, text.ToString ()); if (pos < caretOffset) { data.Caret.Offset = caretOffset + insertedChars; } } else { file.InsertText (pos, text.ToString ()); } }
public override DomLocation CompleteStatement (RefactorerContext ctx, string fileName, DomLocation caretLocation) { IEditableTextFile file = ctx.GetFile (fileName); int pos = file.GetPositionFromLineColumn (caretLocation.Line + 1, 1); StringBuilder line = new StringBuilder (); int lineNr = caretLocation.Line + 1, column = 1, maxColumn = 1, lastPos = pos; while (lineNr == caretLocation.Line + 1) { maxColumn = column; lastPos = pos; line.Append (file.GetCharAt (pos)); pos++; file.GetLineColumnFromPosition (pos, out lineNr, out column); } string trimmedline = line.ToString ().Trim (); string indent = line.ToString ().Substring (0, line.Length - line.ToString ().TrimStart (' ', '\t').Length); if (trimmedline.EndsWith (";") || trimmedline.EndsWith ("{")) return caretLocation; if (trimmedline.StartsWith ("if") || trimmedline.StartsWith ("while") || trimmedline.StartsWith ("switch") || trimmedline.StartsWith ("for") || trimmedline.StartsWith ("foreach")) { if (!trimmedline.EndsWith (")")) { file.InsertText (lastPos, " () {" + Environment.NewLine + indent + TextEditorProperties.IndentString + Environment.NewLine + indent + "}"); caretLocation.Column = maxColumn + 1; } else { file.InsertText (lastPos, " {" + Environment.NewLine + indent + TextEditorProperties.IndentString + Environment.NewLine + indent + "}"); caretLocation.Column = indent.Length + 1; caretLocation.Line++; } } else if (trimmedline.StartsWith ("do")) { file.InsertText (lastPos, " {" + Environment.NewLine + indent + TextEditorProperties.IndentString + Environment.NewLine + indent + "} while ();"); caretLocation.Column = indent.Length + 1; caretLocation.Line++; } else { file.InsertText (lastPos, ";" + Environment.NewLine + indent); caretLocation.Column = indent.Length; caretLocation.Line++; } return caretLocation; }
public override IEnumerable<MemberReference> FindVariableReferences (RefactorerContext ctx, string fileName, LocalVariable var) { var editor = ((Mono.TextEditor.ITextEditorDataProvider)ctx.GetFile (fileName)).GetTextEditorData (); NRefactoryResolver resolver = new NRefactoryResolver (ctx.ParserContext, var.CompilationUnit, ICSharpCode.NRefactory.SupportedLanguage.CSharp, editor, fileName); resolver.CallingMember = var.DeclaringMember; FindMemberAstVisitor visitor = new FindMemberAstVisitor (editor.Document, resolver, var); visitor.RunVisitor (); SetContext (visitor.FoundReferences, ctx); return visitor.FoundReferences; }
public void Refactor (IProgressMonitor monitor, RefactorerContext rctx, IRefactorer r, string fileName) { try { IEnumerable<MemberReference> refs = r.FindParameterReferences (rctx, fileName, param, includeXmlComment); if (refs != null) references.AddRange (refs); } catch (Exception ex) { monitor.ReportError (GettextCatalog.GetString ("Could not look for references in file '{0}': {1}", fileName, ex.Message), ex); } }
// public IType ImplementInterface (ICompilationUnit pinfo, IType klass, IType iface, bool explicitly, IType declaringClass, IReturnType hintReturnType) // { // if (klass == null) // throw new ArgumentNullException ("klass"); // if (iface == null) // throw new ArgumentNullException ("iface"); // RefactorerContext gctx = GetGeneratorContext (klass); // klass = GetUpdatedClass (gctx, klass); // // bool alreadyImplemented; // IReturnType prefix = null; // // List<KeyValuePair<IMember,IReturnType>> toImplement = new List<KeyValuePair<IMember,IReturnType>> (); // // prefix = new DomReturnType (iface); // // // Stub out non-implemented events defined by @iface // foreach (IEvent ev in iface.Events) { // if (ev.IsSpecialName) // continue; // bool needsExplicitly = explicitly; // // alreadyImplemented = gctx.ParserContext.GetInheritanceTree (klass).Any (x => x.ClassType != ClassType.Interface && x.Events.Any (y => y.Name == ev.Name)); // // if (!alreadyImplemented) // toImplement.Add (new KeyValuePair<IMember,IReturnType> (ev, needsExplicitly ? prefix : null)); // } // // // Stub out non-implemented methods defined by @iface // foreach (IMethod method in iface.Methods) { // if (method.IsSpecialName) // continue; // bool needsExplicitly = explicitly; // alreadyImplemented = false; // foreach (IType t in gctx.ParserContext.GetInheritanceTree (klass)) { // if (t.ClassType == ClassType.Interface) // continue; // foreach (IMethod cmet in t.Methods) { // if (cmet.Name == method.Name && Equals (cmet.Parameters, method.Parameters)) { // if (!needsExplicitly && !cmet.ReturnType.Equals (method.ReturnType)) // needsExplicitly = true; // else // alreadyImplemented |= !needsExplicitly || (iface.FullName == GetExplicitPrefix (cmet.ExplicitInterfaces)); // } // } // } // // if (!alreadyImplemented) // toImplement.Add (new KeyValuePair<IMember,IReturnType> (method, needsExplicitly ? prefix : null)); // } // // // Stub out non-implemented properties defined by @iface // foreach (IProperty prop in iface.Properties) { // if (prop.IsSpecialName) // continue; // bool needsExplicitly = explicitly; // alreadyImplemented = false; // foreach (IType t in gctx.ParserContext.GetInheritanceTree (klass)) { // if (t.ClassType == ClassType.Interface) // continue; // foreach (IProperty cprop in t.Properties) { // if (cprop.Name == prop.Name) { // if (!needsExplicitly && !cprop.ReturnType.Equals (prop.ReturnType)) // needsExplicitly = true; // else // alreadyImplemented |= !needsExplicitly || (iface.FullName == GetExplicitPrefix (cprop.ExplicitInterfaces)); // } // } // } // if (!alreadyImplemented) // toImplement.Add (new KeyValuePair<IMember,IReturnType> (prop, needsExplicitly ? prefix : null)); } // // Ambience ambience = AmbienceService.GetAmbienceForFile (klass.CompilationUnit.FileName); // //implement members // ImplementMembers (klass, toImplement, ambience.GetString (iface, OutputFlags.ClassBrowserEntries | OutputFlags.IncludeGenerics | OutputFlags.IncludeParameters) + " implementation"); // gctx.Save (); // // klass = GetUpdatedClass (gctx, klass); // foreach (IType baseClass in iface.SourceProjectDom.GetInheritanceTree (iface)) { // if (baseClass.Equals (iface) || baseClass.FullName == "System.Object") // continue; // klass = ImplementInterface (pinfo, klass, baseClass, explicitly, declaringClass, hintReturnType); // } // // // return klass; // } IType GetUpdatedClass (RefactorerContext gctx, IType klass) { IEditableTextFile file = gctx.GetFile (klass.CompilationUnit.FileName); ParsedDocument doc = ProjectDomService.Parse (gctx.ParserContext.Project, file.Name, delegate () { return file.Text; }); IType result = gctx.ParserContext.GetType (klass.FullName, klass.TypeParameters.Count, true); if (result is CompoundType) { IType hintType = doc.CompilationUnit.GetType (klass.FullName, klass.TypeParameters.Count); if (hintType != null) ((CompoundType)result).SetMainPart (file.Name, hintType.Location); } return result; }
public override int AddFoldingRegion (RefactorerContext ctx, IType cls, string regionName) { IEditableTextFile buffer = ctx.GetFile (cls.CompilationUnit.FileName); int pos = GetNewMethodPosition (buffer, cls); string eolMarker = Environment.NewLine; if (cls.SourceProject != null) { TextStylePolicy policy = cls.SourceProject.Policies.Get<TextStylePolicy> (); if (policy != null) eolMarker = policy.GetEolMarker (); } int line, col; buffer.GetLineColumnFromPosition (pos, out line, out col); string indent = buffer.GetText (buffer.GetPositionFromLineColumn (line, 1), pos); string pre = "#region " + regionName + eolMarker; string post = indent + "#endregion" + eolMarker; buffer.InsertText (pos, pre + post); return pos + pre.Length; }
public IType ImplementInterface(ICompilationUnit pinfo, IType klass, IType iface, bool explicitly, IType declaringClass, IReturnType hintReturnType) { if (klass == null) { throw new ArgumentNullException("klass"); } if (iface == null) { throw new ArgumentNullException("iface"); } RefactorerContext gctx = GetGeneratorContext(klass); klass = GetUpdatedClass(gctx, klass); bool alreadyImplemented; IReturnType prefix = null; List <KeyValuePair <IMember, IReturnType> > toImplement = new List <KeyValuePair <IMember, IReturnType> > (); prefix = new DomReturnType(iface); // Stub out non-implemented events defined by @iface foreach (IEvent ev in iface.Events) { if (ev.IsSpecialName) { continue; } bool needsExplicitly = explicitly; alreadyImplemented = gctx.ParserContext.GetInheritanceTree(klass).Any(x => x.ClassType != ClassType.Interface && x.Events.Any(y => y.Name == ev.Name)); if (!alreadyImplemented) { toImplement.Add(new KeyValuePair <IMember, IReturnType> (ev, needsExplicitly ? prefix : null)); } } // Stub out non-implemented methods defined by @iface foreach (IMethod method in iface.Methods) { if (method.IsSpecialName) { continue; } bool needsExplicitly = explicitly; alreadyImplemented = false; foreach (IType t in gctx.ParserContext.GetInheritanceTree(klass)) { if (t.ClassType == ClassType.Interface) { continue; } foreach (IMethod cmet in t.Methods) { if (cmet.Name == method.Name && Equals(cmet.Parameters, method.Parameters)) { if (!needsExplicitly && !cmet.ReturnType.Equals(method.ReturnType)) { needsExplicitly = true; } else { alreadyImplemented |= !needsExplicitly || (iface.FullName == GetExplicitPrefix(cmet.ExplicitInterfaces)); } } } } if (!alreadyImplemented) { toImplement.Add(new KeyValuePair <IMember, IReturnType> (method, needsExplicitly ? prefix : null)); } } // Stub out non-implemented properties defined by @iface foreach (IProperty prop in iface.Properties) { if (prop.IsSpecialName) { continue; } bool needsExplicitly = explicitly; alreadyImplemented = false; foreach (IType t in gctx.ParserContext.GetInheritanceTree(klass)) { if (t.ClassType == ClassType.Interface) { continue; } foreach (IProperty cprop in t.Properties) { if (cprop.Name == prop.Name) { if (!needsExplicitly && !cprop.ReturnType.Equals(prop.ReturnType)) { needsExplicitly = true; } else { alreadyImplemented |= !needsExplicitly || (iface.FullName == GetExplicitPrefix(cprop.ExplicitInterfaces)); } } } } if (!alreadyImplemented) { toImplement.Add(new KeyValuePair <IMember, IReturnType> (prop, needsExplicitly ? prefix : null)); } } Ambience ambience = AmbienceService.GetAmbienceForFile(klass.CompilationUnit.FileName); //implement members ImplementMembers(klass, toImplement, ambience.GetString(iface, OutputFlags.ClassBrowserEntries | OutputFlags.IncludeGenerics | OutputFlags.IncludeParameters) + " implementation"); gctx.Save(); klass = GetUpdatedClass(gctx, klass); foreach (IType baseClass in iface.SourceProjectDom.GetInheritanceTree(iface)) { if (baseClass.Equals(iface) || baseClass.FullName == "System.Object") { continue; } klass = ImplementInterface(pinfo, klass, baseClass, explicitly, declaringClass, hintReturnType); } return(klass); }
public abstract void PerformChange (IProgressMonitor monitor, RefactorerContext rctx);
public override MemberReferenceCollection FindMemberReferences (RefactorerContext ctx, string fileName, IClass cls, IMember member) { return null; }
public override IEnumerable<MemberReference> FindMemberReferences (RefactorerContext ctx, string fileName, IType cls, IMember member, bool includeXmlComment) { var editor = ((Mono.TextEditor.ITextEditorDataProvider)ctx.GetFile (fileName)).GetTextEditorData (); var doc = ProjectDomService.GetParsedDocument (ctx.ParserContext, fileName); if (doc == null || doc.CompilationUnit == null) return null; NRefactoryResolver resolver = new NRefactoryResolver (ctx.ParserContext, doc.CompilationUnit, ICSharpCode.NRefactory.SupportedLanguage.CSharp, editor, fileName); resolver.CallingMember = member; FindMemberAstVisitor visitor = new FindMemberAstVisitor (editor.Document, resolver, member); visitor.IncludeXmlDocumentation = includeXmlComment; visitor.RunVisitor (); SetContext (visitor.FoundReferences, ctx); return visitor.FoundReferences; }
public void SetContext (RefactorerContext rctx) { this.rctx = rctx; }
public override IType RenameClass (RefactorerContext ctx, IType cls, string newName) { IEditableTextFile file; int pos, begin, end; Match match; Regex expr; string txt; foreach (IType pclass in cls.Parts) { if (pclass.BodyRegion.IsEmpty || (file = ctx.GetFile (pclass.CompilationUnit.FileName)) == null) continue; begin = file.GetPositionFromLineColumn (pclass.BodyRegion.Start.Line, pclass.BodyRegion.Start.Column); end = file.GetPositionFromLineColumn (pclass.BodyRegion.End.Line, pclass.BodyRegion.End.Column); if (begin == -1 || end == -1) continue; txt = file.GetText (begin, end); switch (cls.ClassType) { case ClassType.Interface: expr = new Regex (@"\sinterface\s*(" + cls.Name + @")(\s|:)", RegexOptions.Multiline); break; case ClassType.Struct: expr = new Regex (@"\sstruct\s*(" + cls.Name + @")(\s|:)", RegexOptions.Multiline); break; case ClassType.Enum: expr = new Regex (@"\senum\s*(" + cls.Name + @")(\s|:)", RegexOptions.Multiline); break; default: expr = new Regex (@"\sclass\s*(" + cls.Name + @")(\s|:)", RegexOptions.Multiline); break; } match = expr.Match (" " + txt + " "); if (!match.Success) continue; pos = begin + match.Groups [1].Index - 1; file.DeleteText (pos, cls.Name.Length); file.InsertText (pos, newName); } file = ctx.GetFile (cls.CompilationUnit.FileName); return GetGeneratedClass (ctx, file, cls); }
public override void PerformChange (IProgressMonitor monitor, RefactorerContext rctx) { if (rctx == null) throw new InvalidOperationException ("Refactory context not available."); TextEditorData textEditorData = this.TextEditorData; if (textEditorData == null) { IEditableTextFile file = rctx.GetFile (FileName); if (file != null) { if (RemovedChars > 0) file.DeleteText (Offset, RemovedChars); if (!string.IsNullOrEmpty (InsertedText)) file.InsertText (Offset, InsertedText); rctx.Save (); } } else if (textEditorData != null) { int charsInserted = textEditorData.Replace (Offset, RemovedChars, InsertedText); if (MoveCaretToReplace) textEditorData.Caret.Offset = Offset + charsInserted; } }
public override void AddGlobalNamespaceImport (RefactorerContext ctx, string fileName, string nsName) { IEditableTextFile file = ctx.GetFile (fileName); int pos = 0; ParsedDocument parsedDocument = parser.Parse (ctx.ParserContext, fileName, file.Text); StringBuilder text = new StringBuilder (); if (parsedDocument.CompilationUnit != null) { IUsing lastUsing = null; foreach (IUsing u in parsedDocument.CompilationUnit.Usings) { if (u.IsFromNamespace) break; lastUsing = u; } if (lastUsing != null) pos = file.GetPositionFromLineColumn (lastUsing.Region.End.Line, lastUsing.Region.End.Column); } if (pos != 0) text.AppendLine (); text.Append ("using "); text.Append (nsName); text.Append (";"); if (pos == 0) text.AppendLine (); if (file is Mono.TextEditor.ITextEditorDataProvider) { Mono.TextEditor.TextEditorData data = ((Mono.TextEditor.ITextEditorDataProvider)file).GetTextEditorData (); int caretOffset = data.Caret.Offset; int insertedChars = data.Insert (pos, text.ToString ()); if (pos < caretOffset) { data.Caret.Offset = caretOffset + insertedChars; } } else { file.InsertText (pos, text.ToString ()); } }
public override void PerformChange (IProgressMonitor monitor, RefactorerContext rctx) { File.WriteAllText (FileName, Content); rctx.ParserContext.Project.AddFile (FileName); IdeApp.ProjectOperations.Save (rctx.ParserContext.Project); }
//TODO //static CodeStatement ThrowNewNotImplementedException () //{ // CodeExpression expr = new CodeSnippetExpression ("new NotImplementedException ()"); // return new CodeThrowExceptionStatement (expr); //} // //public override IMember AddMember (RefactorerContext ctx, IType cls, CodeTypeMember member) //{ // if (member is CodeMemberProperty) { // CodeMemberProperty prop = (CodeMemberProperty) member; // if (prop.HasGet && prop.GetStatements.Count == 0) // prop.GetStatements.Add (ThrowNewNotImplementedException ()); // if (prop.HasSet && prop.SetStatements.Count == 0) // prop.SetStatements.Add (ThrowNewNotImplementedException ()); // } else if (member is CodeMemberMethod) { // CodeMemberMethod method = (CodeMemberMethod) member; // if (method.Statements.Count == 0) // method.Statements.Add (ThrowNewNotImplementedException ()); // } // // return base.AddMember (ctx, cls, member); //} protected override void EncapsulateFieldImpGetSet (RefactorerContext ctx, IType cls, IField field, CodeMemberProperty prop) { if (prop.HasGet && prop.GetStatements.Count == 0) prop.GetStatements.Add (new CodeSnippetExpression ("return " + field.Name)); if (prop.HasSet && prop.SetStatements.Count == 0) prop.SetStatements.Add (new CodeAssignStatement (new CodeVariableReferenceExpression (field.Name), new CodeVariableReferenceExpression ("value"))); }
public override void PerformChange (IProgressMonitor monitor, RefactorerContext rctx) { IdeApp.Workbench.OpenDocument (FileName); }
/* public override void ImplementMembers (RefactorerContext ctx, IType cls, IEnumerable<KeyValuePair<IMember,IReturnType>> members, string foldingRegionName) { base.ImplementMembers (ctx, cls, FixGenericImpl (ctx, cls, members), foldingRegionName); } static Ambience amb = new MonoDevelop.CSharpBinding.CSharpAmbience (); // Workaround for bug in the code generator. Generic private implementation types are not generated correctly when they are generic. IEnumerable<KeyValuePair<IMember,IReturnType>> FixGenericImpl (RefactorerContext ctx, IType cls, IEnumerable<KeyValuePair<IMember,IReturnType>> members) { foreach (KeyValuePair<IMember,IReturnType> kvp in members) { if (kvp.Value == null) { yield return kvp; continue; } string tn = amb.GetString (kvp.Value, OutputFlags.IncludeGenerics | OutputFlags.UseFullName | OutputFlags.UseIntrinsicTypeNames); Console.WriteLine ("tn :" + tn); yield return new KeyValuePair<IMember,IReturnType> (kvp.Key, new DomReturnType (tn)); } }*/ static void SetContext (IEnumerable<MemberReference> references, RefactorerContext ctx) { foreach (MemberReference r in references) { r.SetContext (ctx); } }
public override void PerformChange (IProgressMonitor monitor, RefactorerContext rctx) { FileService.RenameFile (OldName, NewName); if (rctx.ParserContext.Project != null) IdeApp.ProjectOperations.Save (rctx.ParserContext.Project); }
public override IEnumerable<MemberReference> FindMemberReferences (RefactorerContext ctx, string fileName, IType cls, IMember member, bool includeXmlComment) { ParsedDocument parsedDocument = parser.Parse (cls.SourceProjectDom, fileName, ctx.GetFile (fileName).Text); NRefactoryResolver resolver = new NRefactoryResolver (ctx.ParserContext, parsedDocument.CompilationUnit, ICSharpCode.NRefactory.SupportedLanguage.CSharp, null, fileName); resolver.SetupParsedCompilationUnit (parser.LastUnit); resolver.CallingMember = member; FindMemberAstVisitor visitor = new FindMemberAstVisitor (resolver, ctx.GetFile (fileName), member); visitor.IncludeXmlDocumentation = includeXmlComment; visitor.RunVisitor (); SetContext (visitor.FoundReferences, ctx); return visitor.FoundReferences; }
public override void PerformChange (IProgressMonitor monitor, RefactorerContext rctx) { Console.WriteLine ("SAVE !!!!"); IdeApp.ProjectOperations.Save (this.Project); }
public override IEnumerable<MemberReference> FindParameterReferences (RefactorerContext ctx, string fileName, IParameter param, bool includeXmlComment) { NRefactoryResolver resolver = new NRefactoryResolver (ctx.ParserContext, param.DeclaringMember.DeclaringType.CompilationUnit, ICSharpCode.NRefactory.SupportedLanguage.CSharp, null, fileName); resolver.CallingMember = param.DeclaringMember; FindMemberAstVisitor visitor = new FindMemberAstVisitor (resolver, ctx.GetFile (fileName), param); visitor.IncludeXmlDocumentation = includeXmlComment; visitor.RunVisitor (); SetContext (visitor.FoundReferences, ctx); return visitor.FoundReferences; }
void Refactor(IProgressMonitor monitor, IType cls, RefactoryScope scope, RefactorDelegate refactorDelegate) { switch (scope) { case RefactoryScope.DeclaringType: ProjectDom ctx = GetParserContext(cls); if (cls is InstantiatedType) { cls = ((InstantiatedType)cls).UninstantiatedType; } IType resolvedType = ctx.GetType(cls.FullName, cls.TypeParameters.Count, true, true); if (resolvedType == null) { goto case RefactoryScope.Solution; } foreach (IType part in resolvedType.Parts) { string file = part.CompilationUnit.FileName; RefactorerContext gctx = GetGeneratorContext(part); IRefactorer gen = LanguageBindingService.GetRefactorerForFile(file); if (gen == null) { return; } refactorDelegate(monitor, gctx, gen, file); gctx.Save(); } break; case RefactoryScope.File: { string file = cls.CompilationUnit.FileName; RefactorerContext gctx = GetGeneratorContext(cls); IRefactorer gen = LanguageBindingService.GetRefactorerForFile(file); if (gen == null) { return; } refactorDelegate(monitor, gctx, gen, file); gctx.Save(); break; } case RefactoryScope.Project: Project prj = GetProjectForFile(cls.CompilationUnit.FileName); if (prj == null) { return; } RefactorProject(monitor, prj, refactorDelegate); break; case RefactoryScope.Solution: if (solution == null) { goto case RefactoryScope.File; } foreach (Project project in solution.GetAllProjects()) { RefactorProject(monitor, project, refactorDelegate); } break; } }
public static void AcceptChanges (IProgressMonitor monitor, ProjectDom dom, List<Change> changes, MonoDevelop.Projects.Text.ITextFileProvider fileProvider) { var rctx = new RefactorerContext (dom, fileProvider, null); var handler = new RenameHandler (changes); FileService.FileRenamed += handler.FileRename; for (int i = 0; i < changes.Count; i++) { changes[i].PerformChange (monitor, rctx); var replaceChange = changes[i] as TextReplaceChange; if (replaceChange == null) continue; for (int j = i + 1; j < changes.Count; j++) { var change = changes[j] as TextReplaceChange; if (change == null) continue; if (replaceChange.Offset >= 0 && change.Offset >= 0 && replaceChange.FileName == change.FileName) { if (replaceChange.Offset < change.Offset) { change.Offset -= replaceChange.RemovedChars; if (!string.IsNullOrEmpty (replaceChange.InsertedText)) change.Offset += replaceChange.InsertedText.Length; } else if (replaceChange.Offset < change.Offset + change.RemovedChars) { change.RemovedChars = Math.Max (0, change.RemovedChars - replaceChange.RemovedChars); change.Offset = replaceChange.Offset + (!string.IsNullOrEmpty (replaceChange.InsertedText) ? replaceChange.InsertedText.Length : 0); } } } } FileService.FileRenamed -= handler.FileRename; TextReplaceChange.FinishRefactoringOperation (); }
public IType CreateClass (Project project, string language, string directory, string namspace, CodeTypeDeclaration type) { ProjectDom ctx = ProjectDomService.GetProjectDom (project); RefactorerContext gctx = new RefactorerContext (ctx, fileProvider, null); IRefactorer gen = LanguageBindingService.GetRefactorerForLanguage (language); IType c = gen.CreateClass (gctx, directory, namspace, type); gctx.Save (); return c; }