本文整理汇总了C#中RefactoringOptions.GetASTProvider方法的典型用法代码示例。如果您正苦于以下问题:C# RefactoringOptions.GetASTProvider方法的具体用法?C# RefactoringOptions.GetASTProvider怎么用?C# RefactoringOptions.GetASTProvider使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类RefactoringOptions
的用法示例。
在下文中一共展示了RefactoringOptions.GetASTProvider方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: IsValid
public override bool IsValid (RefactoringOptions options)
{
IResolver resolver = options.GetResolver ();
INRefactoryASTProvider provider = options.GetASTProvider ();
if (resolver == null || provider == null)
return false;
TextEditorData data = options.GetTextEditorData ();
if (data == null)
return false;
ResolveResult resolveResult;
if (data.IsSomethingSelected) {
ExpressionResult expressionResult = new ExpressionResult (data.SelectedText.Trim ());
if (expressionResult.Expression.Contains (" ") || expressionResult.Expression.Contains ("\t"))
expressionResult.Expression = "(" + expressionResult.Expression + ")";
resolveResult = resolver.Resolve (expressionResult, new DomLocation (data.Caret.Line, data.Caret.Column));
if (resolveResult == null)
return false;
return true;
}
LineSegment lineSegment = data.Document.GetLine (data.Caret.Line);
string line = data.Document.GetTextAt (lineSegment);
Expression expression = provider.ParseExpression (line);
BlockStatement block = provider.ParseText (line) as BlockStatement;
if (expression == null || (block != null && block.Children[0] is LocalVariableDeclaration))
return false;
resolveResult = resolver.Resolve (new ExpressionResult (line), new DomLocation (options.Document.Editor.Caret.Line, options.Document.Editor.Caret.Column));
return resolveResult.ResolvedType != null && !string.IsNullOrEmpty (resolveResult.ResolvedType.FullName) && resolveResult.ResolvedType.FullName != DomReturnType.Void.FullName;
}
示例2: IsValid
public override bool IsValid (RefactoringOptions options)
{
INRefactoryASTProvider provider = options.GetASTProvider ();
IResolver resolver = options.GetResolver ();
if (provider == null || resolver == null)
return false;
if (invoke == null)
invoke = GetInvocationExpression (options);
if (invoke == null)
return false;
returnType = DomReturnType.Void;
modifiers = ICSharpCode.NRefactory.Ast.Modifiers.None;
resolvePosition = new DomLocation (options.Document.Editor.Caret.Line + 1, options.Document.Editor.Caret.Column + 1);
ResolveResult resolveResult = resolver.Resolve (new ExpressionResult (provider.OutputNode (options.Dom, invoke)), resolvePosition);
if (resolveResult is MethodResolveResult) {
MethodResolveResult mrr = (MethodResolveResult)resolveResult ;
if (mrr.ExactMethodMatch)
return false;
returnType = mrr.MostLikelyMethod.ReturnType;
modifiers = (ICSharpCode.NRefactory.Ast.Modifiers)mrr.MostLikelyMethod.Modifiers;
}
if (invoke.TargetObject is MemberReferenceExpression) {
string callingObject = provider.OutputNode (options.Dom, ((MemberReferenceExpression)invoke.TargetObject).TargetObject);
resolveResult = resolver.Resolve (new ExpressionResult (callingObject), resolvePosition);
if (resolveResult == null || resolveResult.ResolvedType == null || resolveResult.CallingType == null)
return false;
IType type = options.Dom.GetType (resolveResult.ResolvedType);
return type != null && type.CompilationUnit != null && File.Exists (type.CompilationUnit.FileName) && RefactoringService.GetASTProvider (DesktopService.GetMimeTypeForUri (type.CompilationUnit.FileName)) != null;
}
return invoke.TargetObject is IdentifierExpression;
}
示例3: IsValid
public override bool IsValid (RefactoringOptions options)
{
MemberResolveResult resolveResult = options.ResolveResult as MemberResolveResult;
if (resolveResult == null)
return false;
IProperty property = resolveResult.ResolvedMember as IProperty;
if (property == null || resolveResult.CallingMember == null || resolveResult.CallingMember.FullName != property.FullName || !property.HasGet || property.DeclaringType == null)
return false;
TextEditorData data = options.GetTextEditorData ();
if (property.HasGet && data.Document.GetCharAt (data.Document.LocationToOffset (property.GetRegion.End.Line, property.GetRegion.End.Column - 1)) == ';')
return false;
if (property.HasSet && data.Document.GetCharAt (data.Document.LocationToOffset (property.SetRegion.End.Line, property.SetRegion.End.Column - 1)) == ';')
return false;
INRefactoryASTProvider astProvider = options.GetASTProvider ();
string backingStoreName = RetrieveBackingStore (options, astProvider, property);
if (string.IsNullOrEmpty (backingStoreName))
return false;
// look if there is a valid backing store field that doesn't have any attributes.
int backinStoreStart;
int backinStoreEnd;
IField backingStore = GetBackingStoreField (options, backingStoreName, out backinStoreStart, out backinStoreEnd);
if (backingStore == null || backingStore.Attributes.Any ())
return false;
return true;
}
示例4: IsValid
public override bool IsValid (RefactoringOptions options)
{
TextEditorData data = options.GetTextEditorData ();
LineSegment line = data.Document.GetLine (data.Caret.Line);
if (!data.IsSomethingSelected && line != null) {
var stack = line.StartSpan.Clone ();
Mono.TextEditor.Highlighting.SyntaxModeService.ScanSpans (data.Document, data.Document.SyntaxMode, data.Document.SyntaxMode, stack, line.Offset, data.Caret.Offset);
foreach (Span span in stack) {
if (span.Color == "string.single" || span.Color == "string.double")
return options.Document.CompilationUnit.GetMemberAt (data.Caret.Line, data.Caret.Column) != null;
}
}
INRefactoryASTProvider provider = options.GetASTProvider ();
if (provider == null)
return false;
string expressionText = null;
if (options.ResolveResult != null && options.ResolveResult.ResolvedExpression != null)
expressionText = options.ResolveResult.ResolvedExpression.Expression;
if (string.IsNullOrEmpty (expressionText)) {
int start, end;
expressionText = SearchNumber (data, out start, out end);
}
Expression expression = provider.ParseExpression (expressionText);
return expression is PrimitiveExpression;
}
示例5: PerformChanges
public override List<Change> PerformChanges (RefactoringOptions options, object properties)
{
List<Change> result = new List<Change> ();
ICSharpCode.NRefactory.Ast.CompilationUnit unit = options.GetASTProvider ().ParseFile (options.Document.Editor.Text);
FindTypeReferencesVisitor visitor = new FindTypeReferencesVisitor (options.GetTextEditorData (), options.GetResolver ());
visitor.VisitCompilationUnit (unit, null);
ProjectDom dom = options.Dom;
ICompilationUnit compilationUnit = options.ParseDocument ().CompilationUnit;
HashSet<string> usedUsings = new HashSet<string> ();
foreach (TypeReference r in visitor.PossibleTypeReferences) {
if (r.IsKeyword)
continue;
IType type = dom.SearchType (compilationUnit, compilationUnit, r.ConvertToReturnType ());
if (type != null) {
usedUsings.Add (type.Namespace);
}
}
Mono.TextEditor.TextEditorData textEditorData = options.GetTextEditorData ();
HashSet<string> currentUsings = new HashSet<string> ();
foreach (IUsing u in compilationUnit.Usings) {
if (u.IsFromNamespace)
continue;
if (!u.Aliases.Any () && u.Namespaces.All (name => currentUsings.Contains (name) || !usedUsings.Contains (name)) ) {
TextReplaceChange change = new TextReplaceChange ();
change.FileName = options.Document.FileName;
change.Offset = textEditorData.Document.LocationToOffset (u.Region.Start.Line, u.Region.Start.Column);
change.RemovedChars = textEditorData.Document.LocationToOffset (u.Region.End.Line, u.Region.End.Column) - change.Offset;
Mono.TextEditor.LineSegment line = textEditorData.Document.GetLineByOffset (change.Offset);
if (line != null && line.EditableLength == change.RemovedChars)
change.RemovedChars += line.DelimiterLength;
result.Add (change);
}
foreach (string nspace in u.Namespaces)
currentUsings.Add (nspace);
}
return result;
}
示例6: GetInvocationExpression
InvocationExpression GetInvocationExpression (RefactoringOptions options)
{
TextEditorData data = options.GetTextEditorData ();
if (data == null || options.ResolveResult == null || options.ResolveResult.ResolvedExpression == null)
return null;
string expression = options.ResolveResult.ResolvedExpression.Expression;
if (!expression.Contains ("(")) {
int startPos = data.Document.LocationToOffset (options.ResolveResult.ResolvedExpression.Region.Start.Line - 1, options.ResolveResult.ResolvedExpression.Region.Start.Column - 1);
if (startPos < 0)
return null;
bool gotWs = false;
for (int pos = startPos; pos > 2; pos--) {
char ch = data.Document.GetCharAt (pos);
if (char.IsWhiteSpace (ch)) {
if (gotWs)
break;
gotWs = true;
continue;
}
if (gotWs && ch == 'w' && data.Document.GetCharAt (pos - 1) == 'e' && data.Document.GetCharAt (pos - 2) == 'n')
return null;
}
for (int pos = startPos; pos < data.Document.Length; pos++) {
char ch = data.Document.GetCharAt (pos);
if (ch == '(') {
int offset = data.Document.GetMatchingBracketOffset (pos);
if (offset < startPos)
return null;
expression = data.Document.GetTextAt (startPos, offset - startPos + 1);
break;
}
}
}
INRefactoryASTProvider provider = options.GetASTProvider ();
return provider != null ? provider.ParseText (expression) as InvocationExpression : null;
}
示例7: PerformChanges
public override List<Change> PerformChanges (RefactoringOptions options, object prop)
{
List<Change> result = new List<Change> ();
IResolver resolver = options.GetResolver ();
INRefactoryASTProvider provider = options.GetASTProvider ();
if (resolver == null || provider == null)
return result;
TextEditorData data = options.GetTextEditorData ();
TextReplaceChange insertNewMethod = new TextReplaceChange ();
insertNewMethod.FileName = fileName;
insertNewMethod.RemovedChars = insertionPoint.LineBefore == NewLineInsertion.Eol ? 0 : insertionPoint.Location.Column;
insertNewMethod.Offset = insertionOffset - insertNewMethod.RemovedChars;
MethodDeclaration methodDecl = new MethodDeclaration ();
bool isInInterface = false;
methodDecl.Modifier = modifiers;
methodDecl.TypeReference = HelperMethods.ConvertToTypeReference (returnType);
methodDecl.Name = newMethodName;
if (!isInInterface) {
methodDecl.Body = new BlockStatement ();
methodDecl.Body.AddChild (new ThrowStatement (new ObjectCreateExpression (new TypeReference ("System.NotImplementedException"), null)));
}
insertNewMethod.Description = string.Format (GettextCatalog.GetString ("Create new method {0}"), methodDecl.Name);
int i = 0;
foreach (Expression expression in invoke.Arguments) {
i++;
string output = provider.OutputNode (options.Dom, expression);
string parameterName = "par" + i;
int idx = output.LastIndexOf ('.');
string lastName = output.Substring (idx + 1); // start from 0, if '.' wasn't found
ResolveResult resolveResult2 = resolver.Resolve (new ExpressionResult (output), resolvePosition);
TypeReference typeReference = new TypeReference ((resolveResult2 != null && resolveResult2.ResolvedType != null) ? options.Document.CompilationUnit.ShortenTypeName (resolveResult2.ResolvedType, data.Caret.Line, data.Caret.Column).ToInvariantString () : "System.Object");
if (lastName == "this" || lastName == "base") {
idx = typeReference.Type.LastIndexOf ('.');
lastName = typeReference.Type.Substring (idx + 1);
}
if (!string.IsNullOrEmpty (lastName))
lastName = char.ToLower (lastName[0]) + lastName.Substring (1);
if (IsValidIdentifier (lastName))
parameterName = lastName;
typeReference.IsKeyword = true;
ParameterDeclarationExpression pde = new ParameterDeclarationExpression (typeReference, parameterName);
methodDecl.Parameters.Add (pde);
}
StringBuilder sb = new StringBuilder ();
switch (insertionPoint.LineBefore) {
case NewLineInsertion.Eol:
sb.AppendLine ();
break;
case NewLineInsertion.BlankLine:
sb.Append (indent);
sb.AppendLine ();
break;
}
sb.Append (provider.OutputNode (options.Dom, methodDecl, indent).TrimEnd ('\n', '\r'));
switch (insertionPoint.LineAfter) {
case NewLineInsertion.Eol:
sb.AppendLine ();
break;
case NewLineInsertion.BlankLine:
sb.AppendLine ();
sb.AppendLine ();
sb.Append (indent);
break;
}
insertNewMethod.InsertedText = sb.ToString ();
result.Add (insertNewMethod);
if (!isInInterface) {
int idx = insertNewMethod.InsertedText.IndexOf ("throw");
selectionStart = insertNewMethod.Offset + idx;
selectionEnd = insertNewMethod.Offset + insertNewMethod.InsertedText.IndexOf (';', idx) + 1;
} else {
selectionStart = selectionEnd = insertNewMethod.Offset;
}
return result;
}
示例8: Run
public override void Run (RefactoringOptions options)
{
IResolver resolver = options.GetResolver ();
INRefactoryASTProvider provider = options.GetASTProvider ();
TextEditorData data = options.GetTextEditorData ();
IType type = options.ResolveResult.CallingType;
if (invoke.TargetObject is IdentifierExpression) {
fileName = options.Document.FileName;
newMethodName = ((IdentifierExpression)invoke.TargetObject).Identifier;
indent = options.GetIndent (options.ResolveResult.CallingMember);
if (options.ResolveResult.CallingMember.IsStatic)
modifiers |= ICSharpCode.NRefactory.Ast.Modifiers.Static;
} else {
newMethodName = ((MemberReferenceExpression)invoke.TargetObject).MemberName;
string callingObject = provider.OutputNode (options.Dom, ((MemberReferenceExpression)invoke.TargetObject).TargetObject);
ResolveResult resolveResult = resolver.Resolve (new ExpressionResult (callingObject), resolvePosition);
type = options.Dom.GetType (resolveResult.ResolvedType);
fileName = type.CompilationUnit.FileName;
if (resolveResult.StaticResolve)
modifiers |= ICSharpCode.NRefactory.Ast.Modifiers.Static;
if (fileName == options.Document.FileName) {
indent = options.GetIndent (options.ResolveResult.CallingMember);
// insertNewMethod.Offset = options.Document.TextEditor.GetPositionFromLineColumn (options.ResolveResult.CallingMember.BodyRegion.End.Line, options.ResolveResult.CallingMember.BodyRegion.End.Column);
} else {
var openDocument = IdeApp.Workbench.OpenDocument (fileName);
data = openDocument.Editor;
if (data == null)
return;
modifiers |= ICSharpCode.NRefactory.Ast.Modifiers.Public;
bool isInInterface = type.ClassType == MonoDevelop.Projects.Dom.ClassType.Interface;
if (isInInterface)
modifiers = ICSharpCode.NRefactory.Ast.Modifiers.None;
if (data == null)
throw new InvalidOperationException ("Can't open file:" + modifiers);
try {
indent = data.Document.GetLine (type.Location.Line - 1).GetIndentation (data.Document) ?? "";
} catch (Exception) {
indent = "";
}
indent += "\t";
// insertNewMethod.Offset = otherFile.Document.LocationToOffset (type.BodyRegion.End.Line - 1, 0);
}
}
InsertionCursorEditMode mode = new InsertionCursorEditMode (data.Parent, HelperMethods.GetInsertionPoints (data.Document, type));
if (fileName == options.Document.FileName) {
for (int i = 0; i < mode.InsertionPoints.Count; i++) {
var point = mode.InsertionPoints[i];
if (point.Location < data.Caret.Location) {
mode.CurIndex = i;
} else {
break;
}
}
}
ModeHelpWindow helpWindow = new ModeHelpWindow ();
helpWindow.TransientFor = IdeApp.Workbench.RootWindow;
helpWindow.TitleText = GettextCatalog.GetString ("<b>Create Method -- Targeting</b>");
helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Key</b>"), GettextCatalog.GetString ("<b>Behavior</b>")));
helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Up</b>"), GettextCatalog.GetString ("Move to <b>previous</b> target point.")));
helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Down</b>"), GettextCatalog.GetString ("Move to <b>next</b> target point.")));
helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Enter</b>"), GettextCatalog.GetString ("<b>Declare new method</b> at target point.")));
helpWindow.Items.Add (new KeyValuePair<string, string> (GettextCatalog.GetString ("<b>Esc</b>"), GettextCatalog.GetString ("<b>Cancel</b> this refactoring.")));
mode.HelpWindow = helpWindow;
mode.StartMode ();
mode.Exited += delegate(object s, InsertionCursorEventArgs args) {
if (args.Success) {
insertionPoint = args.InsertionPoint;
insertionOffset = data.Document.LocationToOffset (args.InsertionPoint.Location);
base.Run (options);
if (string.IsNullOrEmpty (fileName))
return;
MonoDevelop.Ide.Gui.Document document = IdeApp.Workbench.OpenDocument (fileName);
TextEditorData docData = document.Editor;
if (docData != null) {
docData.ClearSelection ();
docData.Caret.Offset = selectionEnd;
docData.SetSelection (selectionStart, selectionEnd);
}
}
};
}
示例9: PerformChanges
public override List<Change> PerformChanges (RefactoringOptions options, object properties)
{
List<Change> result = new List<Change> ();
ICompilationUnit compilationUnit = options.ParseDocument ().CompilationUnit;
Mono.TextEditor.TextEditorData textEditorData = options.GetTextEditorData ();
int minOffset = int.MaxValue;
foreach (IUsing u in compilationUnit.Usings) {
if (u.IsFromNamespace)
continue;
int offset = textEditorData.Document.LocationToOffset (u.Region.Start.Line, u.Region.Start.Column);
TextReplaceChange change = new TextReplaceChange () {
FileName = options.Document.FileName,
Offset = offset,
RemovedChars = textEditorData.Document.LocationToOffset (u.Region.End.Line, u.Region.End.Column) - offset
};
Mono.TextEditor.LineSegment line = textEditorData.Document.GetLineByOffset (change.Offset);
if (line != null && line.EditableLength == change.RemovedChars)
change.RemovedChars += line.DelimiterLength;
result.Add (change);
minOffset = Math.Min (minOffset, offset);
}
StringBuilder output = new StringBuilder ();
List<IUsing> usings = new List<IUsing> (compilationUnit.Usings);
usings.Sort (UsingComparer);
INRefactoryASTProvider astProvider = options.GetASTProvider ();
foreach (IUsing u in usings) {
AstNode declaration;
if (u.IsFromNamespace)
continue;
if (u.Aliases.Any ()) {
KeyValuePair<string, IReturnType> alias = u.Aliases.First ();
declaration = new UsingAliasDeclaration (alias.Key, alias.Value.ConvertToTypeReference ());
} else {
declaration = new UsingDeclaration (u.Namespaces.First ());
}
output.Append (astProvider.OutputNode (options.Dom, declaration));
}
TextReplaceChange insertSortedUsings = new TextReplaceChange () {
FileName = options.Document.FileName,
Offset = minOffset,
InsertedText = output.ToString ()
};
result.Add (insertSortedUsings);
return result;
}
示例10: PerformChanges
public override List<Change> PerformChanges (RefactoringOptions options, object properties)
{
TextEditorData data = options.GetTextEditorData ();
int start, end;
MonoDevelop.Refactoring.IntroduceConstant.IntroduceConstantRefactoring.SearchString (data, '"', out start, out end);
LineSegment line = data.Document.GetLineByOffset (start);
int closingTagLength = 1; // length of the closing "
if (end > line.Offset + line.EditableLength) { // assume missing closing tag
end = line.Offset + line.EditableLength;
closingTagLength = 0;
}
INRefactoryASTProvider provider = options.GetASTProvider ();
List<Expression> args = new List<Expression> ();
IExpressionFinder expressionFinder = options.GetParser ().CreateExpressionFinder (options.Dom);
int expressionStart = start - 1;
while (expressionStart > 0) {
if (data.Document.GetCharAt (expressionStart) == '(') {
expressionStart--;
break;
}
expressionStart--;
}
// Add parameter to existing string.format call
ExpressionResult expressionResult = expressionFinder.FindFullExpression (options.Document.TextEditor.Text, expressionStart);
InvocationExpression formatCall = null;
if (expressionResult != null) {
InvocationExpression possibleFormatCall = provider.ParseExpression (expressionResult.Expression) as InvocationExpression;
if (possibleFormatCall != null && possibleFormatCall.TargetObject is MemberReferenceExpression && ((MemberReferenceExpression)possibleFormatCall.TargetObject).MemberName == "Format") {
PrimitiveExpression expr = possibleFormatCall.Arguments[0] as PrimitiveExpression;
if (expr != null) {
string str = data.Document.GetTextBetween (start + 1, data.SelectionRange.Offset) +
"{" + (possibleFormatCall.Arguments.Count - 1) + "}" +
data.Document.GetTextBetween (data.SelectionRange.EndOffset, end);
expr.Value = str;
expr.StringValue = '"' + str + '"';
possibleFormatCall.Arguments.Add (new PrimitiveExpression (data.Document.GetTextAt (data.SelectionRange)));
formatCall = possibleFormatCall;
start = data.Document.LocationToOffset (expressionResult.Region.Start.Line - 1, expressionResult.Region.Start.Column - 1);
end = data.Document.LocationToOffset (expressionResult.Region.End.Line - 1, expressionResult.Region.End.Column - 1) - 1;
}
}
}
// insert new format call
if (formatCall == null) {
string formattedString = UnescapeString (data.Document.GetTextBetween (start + 1, data.SelectionRange.Offset) + "{0}" + data.Document.GetTextBetween (data.SelectionRange.EndOffset, end));
args.Add (new PrimitiveExpression (formattedString));
args.Add (new PrimitiveExpression (data.Document.GetTextAt (data.SelectionRange)));
TypeReference typeRef = new TypeReference ("System.String");
typeRef.IsKeyword = true;
MemberReferenceExpression stringFormat = new MemberReferenceExpression (new TypeReferenceExpression (typeRef), "Format");
formatCall = new InvocationExpression (stringFormat, args);
}
List<Change> changes = new List<Change> ();
TextReplaceChange change = new TextReplaceChange ();
change.FileName = options.Document.FileName;
change.Offset = start;
change.RemovedChars = end - start + closingTagLength;
change.InsertedText = provider.OutputNode (options.Dom, formatCall);
change.MoveCaretToReplace = true;
changes.Add (change);
return changes;
}
示例11: PerformChanges
public override List<Change> PerformChanges (RefactoringOptions options, object prop)
{
IResolver resolver = options.GetResolver ();
List<Change> result = new List<Change> ();
INRefactoryASTProvider provider = options.GetASTProvider ();
if (resolver == null || provider == null)
return result;
TypeDeclaration newType = new TypeDeclaration (ICSharpCode.NRefactory.Ast.Modifiers.None, null);
newType.Name = createExpression.CreateType.Type;
newType.Type = GetNewTypeType ();
ConstructorDeclaration constructor = new ConstructorDeclaration (newType.Name, ICSharpCode.NRefactory.Ast.Modifiers.Public, null, null);
constructor.Body = new BlockStatement ();
int i = 0;
foreach (Expression expression in createExpression.Parameters) {
i++;
string output = provider.OutputNode (options.Dom, expression);
string parameterName;
if (Char.IsLetter (output[0]) || output[0] == '_') {
parameterName = output;
} else {
parameterName = "par" + i;
}
ResolveResult resolveResult2 = resolver.Resolve (new ExpressionResult (output), options.ResolveResult.ResolvedExpression.Region.Start);
TypeReference typeReference = new TypeReference (resolveResult2.ResolvedType.ToInvariantString ());
typeReference.IsKeyword = true;
ParameterDeclarationExpression pde = new ParameterDeclarationExpression (typeReference, parameterName);
constructor.Parameters.Add (pde);
}
ICSharpCode.NRefactory.Ast.INode node = newType;
IType curType = options.Document.CompilationUnit.GetTypeAt (options.Document.TextEditor.CursorLine, options.Document.TextEditor.CursorColumn);
if (curType != null && !string.IsNullOrEmpty (curType.Namespace)) {
NamespaceDeclaration namespaceDeclaration = new NamespaceDeclaration (curType.Namespace);
namespaceDeclaration.Children.Add (newType);
node = namespaceDeclaration;
}
newType.Children.Add (constructor);
string fileName = GetName (Path.Combine (Path.GetDirectoryName (options.Document.FileName), newType.Name + Path.GetExtension (options.Document.FileName)));
string header = options.Dom.Project is DotNetProject ? StandardHeaderService.GetHeader (options.Dom.Project, fileName, true) + Environment.NewLine : "";
CreateFileChange createFile = new CreateFileChange (fileName, header + provider.OutputNode (options.Dom, node));
result.Add (createFile);
result.Add (new OpenFileChange (fileName));
return result;
}
示例12: PerformChanges
public override List<Change> PerformChanges (RefactoringOptions options, object properties)
{
List<Change> result = new List<Change> ();
IType type = options.SelectedItem as IType;
if (type == null)
return result;
string newName = GetCorrectFileName (type);
if (type.CompilationUnit.Types.Count == 1) {
result.Add (new RenameFileChange (type.CompilationUnit.FileName, newName));
} else {
StringBuilder content = new StringBuilder ();
if (options.Dom.Project is DotNetProject)
content.Append (StandardHeaderService.GetHeader (options.Dom.Project, type.CompilationUnit.FileName, true) + Environment.NewLine);
INRefactoryASTProvider provider = options.GetASTProvider ();
Mono.TextEditor.TextEditorData data = options.GetTextEditorData ();
ICSharpCode.NRefactory.Ast.CompilationUnit unit = provider.ParseFile (options.Document.TextEditor.Text);
TypeFilterTransformer typeFilterTransformer = new TypeFilterTransformer ((type is InstantiatedType) ? ((InstantiatedType)type).UninstantiatedType.DecoratedFullName : type.DecoratedFullName);
unit.AcceptVisitor (typeFilterTransformer, null);
if (typeFilterTransformer.TypeDeclaration == null)
return result;
Mono.TextEditor.Document generatedDocument = new Mono.TextEditor.Document ();
generatedDocument.Text = provider.OutputNode (options.Dom, unit);
int startLine = -1;
int minLine = typeFilterTransformer.TypeDeclaration.StartLocation.Line;
foreach (var attr in typeFilterTransformer.TypeDeclaration.Attributes) {
minLine = Math.Min (minLine, attr.StartLocation.Line);
}
for (int i = minLine - 2; i >= 0; i--) {
string lineText = data.Document.GetTextAt (data.Document.GetLine (i)).Trim ();
if (string.IsNullOrEmpty (lineText))
continue;
if (lineText.StartsWith ("///")) {
startLine = i;
} else {
break;
}
}
int start;
if (startLine >= 0) {
start = data.Document.GetLine (startLine).Offset;
} else {
var startLocation = typeFilterTransformer.TypeDeclaration.StartLocation;
startLocation.Column = 0;
foreach (var attr in typeFilterTransformer.TypeDeclaration.Attributes) {
if (attr.StartLocation < startLocation)
startLocation = attr.StartLocation;
}
start = data.Document.LocationToOffset (startLocation.Line - 1, 0);
}
int length = data.Document.LocationToOffset (typeFilterTransformer.TypeDeclaration.EndLocation.Line - 1, typeFilterTransformer.TypeDeclaration.EndLocation.Column) - start;
ICSharpCode.NRefactory.Ast.CompilationUnit generatedCompilationUnit = provider.ParseFile (generatedDocument.Text);
TypeSearchVisitor typeSearchVisitor = new TypeSearchVisitor ();
generatedCompilationUnit.AcceptVisitor (typeSearchVisitor, null);
int genStart = generatedDocument.LocationToOffset (typeSearchVisitor.Types[0].StartLocation.Line - 1, 0);
foreach (var attr in typeSearchVisitor.Types[0].Attributes) {
genStart = Math.Min (genStart, generatedDocument.LocationToOffset (attr.StartLocation.Line - 1, 0));
}
int genEnd = generatedDocument.LocationToOffset (typeSearchVisitor.Types[0].EndLocation.Line - 1, typeSearchVisitor.Types[0].EndLocation.Column - 1);
((Mono.TextEditor.IBuffer)generatedDocument).Replace (genStart, genEnd - genStart, data.Document.GetTextAt (start, length));
content.Append (generatedDocument.Text);
result.Add (new CreateFileChange (newName, content.ToString ()));
TextReplaceChange removeDeclaration = new TextReplaceChange ();
removeDeclaration.Description = "Remove type declaration";
removeDeclaration.FileName = type.CompilationUnit.FileName;
removeDeclaration.Offset = start;
removeDeclaration.RemovedChars = length;
result.Add (removeDeclaration);
}
result.Add (new SaveProjectChange (options.Document.Project));
return result;
}
示例13: PerformChanges
public override List<Change> PerformChanges (RefactoringOptions options, object prop)
{
varCount = 0;
selectionStart = selectionEnd = -1;
List<Change> result = new List<Change> ();
IResolver resolver = options.GetResolver ();
INRefactoryASTProvider provider = options.GetASTProvider ();
if (resolver == null || provider == null)
return result;
TextEditorData data = options.GetTextEditorData ();
if (data == null)
return result;
ResolveResult resolveResult;
LineSegment lineSegment;
ICSharpCode.NRefactory.Ast.CompilationUnit unit = provider.ParseFile (data.Document.Text);
MonoDevelop.Refactoring.ExtractMethod.VariableLookupVisitor visitor = new MonoDevelop.Refactoring.ExtractMethod.VariableLookupVisitor (resolver, new DomLocation (data.Caret.Line, data.Caret.Column));
if (options.ResolveResult == null) {
LoggingService.LogError ("resolve result == null:" + options.ResolveResult);
return result;
}
IMember callingMember = options.ResolveResult.CallingMember;
if (callingMember != null)
visitor.MemberLocation = new Location (callingMember.Location.Column, callingMember.Location.Line);
unit.AcceptVisitor (visitor, null);
if (data.IsSomethingSelected) {
ExpressionResult expressionResult = new ExpressionResult (data.SelectedText.Trim ());
if (expressionResult.Expression.Contains (" ") || expressionResult.Expression.Contains ("\t"))
expressionResult.Expression = "(" + expressionResult.Expression + ")";
resolveResult = resolver.Resolve (expressionResult, new DomLocation (data.Caret.Line, data.Caret.Column));
if (resolveResult == null)
return result;
IReturnType resolvedType = resolveResult.ResolvedType;
if (resolvedType == null || string.IsNullOrEmpty (resolvedType.Name))
resolvedType = DomReturnType.Object;
varName = CreateVariableName (resolvedType, visitor);
TypeReference returnType;
if (resolveResult.ResolvedType == null || string.IsNullOrEmpty (resolveResult.ResolvedType.Name)) {
returnType = new TypeReference ("var");
returnType.IsKeyword = true;
} else {
returnType = options.ShortenTypeName (resolveResult.ResolvedType).ConvertToTypeReference ();
}
options.ParseMember (resolveResult.CallingMember);
TextReplaceChange insert = new TextReplaceChange ();
insert.FileName = options.Document.FileName;
insert.Description = GettextCatalog.GetString ("Insert variable declaration");
LocalVariableDeclaration varDecl = new LocalVariableDeclaration (returnType);
varDecl.Variables.Add (new VariableDeclaration (varName, provider.ParseExpression (data.SelectedText)));
GetContainingEmbeddedStatementVisitor blockVisitor = new GetContainingEmbeddedStatementVisitor ();
blockVisitor.LookupLocation = new Location (data.Caret.Column, data.Caret.Line );
unit.AcceptVisitor (blockVisitor, null);
StatementWithEmbeddedStatement containing = blockVisitor.ContainingStatement as StatementWithEmbeddedStatement;
if (containing != null && !(containing.EmbeddedStatement is BlockStatement)) {
insert.Offset = data.Document.LocationToOffset (containing.StartLocation.Line, containing.StartLocation.Column);
lineSegment = data.Document.GetLineByOffset (insert.Offset);
insert.RemovedChars = data.Document.LocationToOffset (containing.EndLocation.Line, containing.EndLocation.Column) - insert.Offset;
BlockStatement insertedBlock = new BlockStatement ();
insertedBlock.AddChild (varDecl);
insertedBlock.AddChild (containing.EmbeddedStatement);
containing.EmbeddedStatement = insertedBlock;
insert.InsertedText = provider.OutputNode (options.Dom, containing, options.GetWhitespaces (lineSegment.Offset)).TrimStart ();
int offset, length;
if (SearchSubExpression (insert.InsertedText, data.SelectedText, 0, out offset, out length))
if (SearchSubExpression (insert.InsertedText, data.SelectedText, offset + 1, out offset, out length)) {
insert.InsertedText = insert.InsertedText.Substring (0, offset) + varName + insert.InsertedText.Substring (offset + length);
insertOffset = insert.Offset + offset;
}
} else if (blockVisitor.ContainingStatement is IfElseStatement) {
IfElseStatement ifElse = blockVisitor.ContainingStatement as IfElseStatement;
insert.Offset = data.Document.LocationToOffset (blockVisitor.ContainingStatement.StartLocation.Line, blockVisitor.ContainingStatement.StartLocation.Column);
lineSegment = data.Document.GetLineByOffset (insert.Offset);
insert.RemovedChars = data.Document.LocationToOffset (blockVisitor.ContainingStatement.EndLocation.Line, blockVisitor.ContainingStatement.EndLocation.Column) - insert.Offset;
BlockStatement insertedBlock = new BlockStatement ();
insertedBlock.AddChild (varDecl);
if (blockVisitor.ContainsLocation (ifElse.TrueStatement[0])) {
insertedBlock.AddChild (ifElse.TrueStatement[0]);
ifElse.TrueStatement[0] = insertedBlock;
} else {
insertedBlock.AddChild (ifElse.FalseStatement[0]);
ifElse.FalseStatement[0] = insertedBlock;
}
insert.InsertedText = provider.OutputNode (options.Dom, blockVisitor.ContainingStatement, options.GetWhitespaces (lineSegment.Offset));
int offset, length;
if (SearchSubExpression (insert.InsertedText, provider.OutputNode (options.Dom, insertedBlock), 0, out offset, out length))
if (SearchSubExpression (insert.InsertedText, data.SelectedText, offset + 1, out offset, out length))
if (SearchSubExpression (insert.InsertedText, data.SelectedText, offset + 1, out offset, out length)) {
insert.InsertedText = insert.InsertedText.Substring (0, offset) + varName + insert.InsertedText.Substring (offset + length);
insertOffset = insert.Offset + offset;
//.........这里部分代码省略.........
示例14: PerformChanges
public override List<Change> PerformChanges (RefactoringOptions options, object prop)
{
List<Change> result = new List<Change> ();
MemberResolveResult resolveResult = options.ResolveResult as MemberResolveResult;
IProperty property = resolveResult.ResolvedMember as IProperty;
TextEditorData data = options.GetTextEditorData ();
INRefactoryASTProvider astProvider = options.GetASTProvider ();
backingStoreName = GetBackingStoreName (property);
FieldDeclaration backingStore = new FieldDeclaration (null);
backingStore.TypeReference = options.Document.CompilationUnit.ShortenTypeName (property.ReturnType, property.Location).ConvertToTypeReference ();
backingStore.Fields.Add (new VariableDeclaration (backingStoreName));
DocumentLocation location = property.Location.ToDocumentLocation (data.Document);
location.Column = 0;
refactoringStartOffset = data.Document.LocationToOffset (location);
result.Add (new TextReplaceChange () {
FileName = options.Document.FileName,
Offset = refactoringStartOffset,
InsertedText = astProvider.OutputNode (options.Dom, backingStore, options.GetIndent (property))
});
if (property.HasGet) {
int startOffset = data.Document.LocationToOffset (property.GetRegion.Start.ToDocumentLocation (data.Document));
int endOffset = data.Document.LocationToOffset (property.GetRegion.End.ToDocumentLocation (data.Document));
BlockStatement getBlock = new BlockStatement ();
getBlock.AddChild (new ReturnStatement (new IdentifierExpression (backingStoreName)));
string text = astProvider.OutputNode (options.Dom, new PropertyGetRegion (getBlock, null), options.GetIndent (property) + "\t").Trim ();
result.Add (new TextReplaceChange () {
FileName = options.Document.FileName,
Offset = startOffset,
RemovedChars = endOffset - startOffset,
InsertedText = text
});
}
if (property.HasSet) {
int startOffset = data.Document.LocationToOffset (property.SetRegion.Start.ToDocumentLocation (data.Document));
int endOffset = data.Document.LocationToOffset (property.SetRegion.End.ToDocumentLocation (data.Document));
BlockStatement setBlock = new BlockStatement ();
setBlock.AddChild (new ExpressionStatement (new AssignmentExpression (new IdentifierExpression (backingStoreName), AssignmentOperatorType.Assign, new IdentifierExpression ("value"))));
string text = astProvider.OutputNode (options.Dom, new PropertySetRegion (setBlock, null), options.GetIndent (property) + "\t").Trim ();
result.Add (new TextReplaceChange () {
FileName = options.Document.FileName,
Offset = startOffset,
RemovedChars = endOffset - startOffset,
InsertedText = text
});
}
return result;
}
示例15: PerformChanges
public override List<Change> PerformChanges (RefactoringOptions options, object prop)
{
List<Change> result = new List<Change> ();
TextEditorData data = options.GetTextEditorData ();
MemberResolveResult resolveResult = options.ResolveResult as MemberResolveResult;
IProperty property = resolveResult.ResolvedMember as IProperty;
INRefactoryASTProvider astProvider = options.GetASTProvider ();
string backingStoreName = RetrieveBackingStore (options, astProvider, property);
int backinStoreStart;
int backinStoreEnd;
IField backingStore = GetBackingStoreField (options, backingStoreName, out backinStoreStart, out backinStoreEnd);
if (backingStore != null) {
foreach (MemberReference memberRef in ReferenceFinder.FindReferences (backingStore)) {
result.Add (new TextReplaceChange () {
FileName = memberRef.FileName,
Offset = memberRef.Position,
RemovedChars = memberRef.Name.Length,
InsertedText = property.Name
});
}
result.RemoveAll (c => backinStoreStart <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset <= backinStoreEnd);
result.Add (new TextReplaceChange () {
FileName = options.Document.FileName,
Offset = backinStoreStart,
RemovedChars = backinStoreEnd - backinStoreStart
});
}
if (property.HasGet) {
int startOffset = data.Document.LocationToOffset (property.GetRegion.Start.ToDocumentLocation (data.Document));
int endOffset = data.Document.LocationToOffset (property.GetRegion.End.ToDocumentLocation (data.Document));
string text = astProvider.OutputNode (options.Dom, new PropertyGetRegion (null, null), options.GetIndent (property) + "\t").Trim ();
result.RemoveAll (c => startOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset <= endOffset);
result.Add (new TextReplaceChange () {
FileName = options.Document.FileName,
Offset = startOffset,
RemovedChars = endOffset - startOffset,
InsertedText = text
});
}
int setStartOffset;
int setEndOffset;
PropertySetRegion setRegion = new PropertySetRegion (null, null);
string setText;
if (property.HasSet) {
setStartOffset = data.Document.LocationToOffset (property.SetRegion.Start.ToDocumentLocation (data.Document));
setEndOffset = data.Document.LocationToOffset (property.SetRegion.End.ToDocumentLocation (data.Document));
setText = astProvider.OutputNode (options.Dom, setRegion, options.GetIndent (property) + "\t").Trim ();
} else {
setEndOffset = setStartOffset = data.Document.LocationToOffset (property.GetRegion.End.ToDocumentLocation (data.Document));
setRegion.Modifier = ICSharpCode.NRefactory.Ast.Modifiers.Private;
setText = Environment.NewLine + astProvider.OutputNode (options.Dom, setRegion, options.GetIndent (property) + "\t").TrimEnd ();
}
result.RemoveAll (c => setStartOffset <= ((TextReplaceChange)c).Offset && ((TextReplaceChange)c).Offset <= setEndOffset);
result.Add (new TextReplaceChange () {
FileName = options.Document.FileName,
Offset = setStartOffset,
RemovedChars = setEndOffset - setStartOffset,
InsertedText = setText
});
return result;
}