本文整理汇总了C#中RefactoringOptions.GetResolver方法的典型用法代码示例。如果您正苦于以下问题:C# RefactoringOptions.GetResolver方法的具体用法?C# RefactoringOptions.GetResolver怎么用?C# RefactoringOptions.GetResolver使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类RefactoringOptions
的用法示例。
在下文中一共展示了RefactoringOptions.GetResolver方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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;
}
示例2: 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;
}
示例3: 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;
}
示例4: 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;
}
示例5: PerformChanges
public override List<Change> PerformChanges (RefactoringOptions options, object prop)
{
List<Change> result = new List<Change> ();
ExtractMethodParameters param = (ExtractMethodParameters)prop;
TextEditorData data = options.GetTextEditorData ();
INRefactoryASTProvider provider = options.GetASTProvider ();
IResolver resolver = options.GetResolver ();
ICSharpCode.NRefactory.Ast.INode node = Analyze (options, param, false);
if (param.VariablesToGenerate.Count > 0) {
TextReplaceChange varGen = new TextReplaceChange ();
varGen.Description = GettextCatalog.GetString ("Generate some temporary variables");
varGen.FileName = options.Document.FileName;
LineSegment line = data.Document.GetLine (Math.Max (0, data.Document.OffsetToLineNumber (data.SelectionRange.Offset) - 1));
varGen.Offset = line.Offset + line.EditableLength;
varGen.InsertedText = Environment.NewLine + options.GetWhitespaces (line.Offset);
foreach (VariableDescriptor var in param.VariablesToGenerate) {
TypeReference tr = options.ShortenTypeName (var.ReturnType).ConvertToTypeReference ();
varGen.InsertedText += provider.OutputNode (options.Dom, new LocalVariableDeclaration (new VariableDeclaration (var.Name, null, tr))).Trim ();
}
result.Add (varGen);
}
InvocationExpression invocation = new InvocationExpression (new IdentifierExpression (param.Name));
foreach (VariableDescriptor var in param.Parameters) {
if (!param.OneChangedVariable && param.ChangedVariables.Contains (var.Name)) {
FieldDirection fieldDirection = FieldDirection.Ref;
VariableDescriptor outsideVar = null;
if (param.VariablesOutside.TryGetValue (var.Name, out outsideVar) && (var.GetsAssigned || param.VariablesToGenerate.Where (v => v.Name == var.Name).Any ())) {
if (!outsideVar.GetsAssigned)
fieldDirection = FieldDirection.Out;
}
invocation.Arguments.Add (new DirectionExpression (fieldDirection, new IdentifierExpression (var.Name)));
} else {
invocation.Arguments.Add (new IdentifierExpression (var.Name));
}
}
// string mimeType = DesktopService.GetMimeTypeForUri (options.Document.FileName);
TypeReference returnType = new TypeReference ("System.Void", true);
ICSharpCode.NRefactory.Ast.INode outputNode;
if (param.OneChangedVariable) {
string name = param.ChangedVariables.First ();
returnType = options.ShortenTypeName (param.Variables.Find (v => v.Name == name).ReturnType).ConvertToTypeReference ();
if (param.OutsideVariableList.Any (v => v.Name == name && !v.IsDefined)) {
LocalVariableDeclaration varDecl = new LocalVariableDeclaration (returnType);
varDecl.Variables.Add (new VariableDeclaration (name, invocation));
outputNode = varDecl;
} else {
outputNode = new ExpressionStatement (new AssignmentExpression (new IdentifierExpression (name), ICSharpCode.NRefactory.Ast.AssignmentOperatorType.Assign, invocation));
}
} else {
outputNode = node is BlockStatement ? (ICSharpCode.NRefactory.Ast.INode)new ExpressionStatement (invocation) : invocation;
}
TextReplaceChange replacement = new TextReplaceChange ();
replacement.Description = string.Format (GettextCatalog.GetString ("Substitute selected statement(s) with call to {0}"), param.Name);
replacement.FileName = options.Document.FileName;
replacement.Offset = options.Document.Editor.SelectionRange.Offset;
replacement.RemovedChars = options.Document.Editor.SelectionRange.Length;
replacement.MoveCaretToReplace = true;
LineSegment line1 = data.Document.GetLineByOffset (options.Document.Editor.SelectionRange.EndOffset);
if (options.Document.Editor.SelectionRange.EndOffset == line1.Offset) {
if (line1.Offset > 0) {
LineSegment line2 = data.Document.GetLineByOffset (line1.Offset - 1);
replacement.RemovedChars -= line2.DelimiterLength;
}
}
replacement.InsertedText = options.GetWhitespaces (options.Document.Editor.SelectionRange.Offset) + provider.OutputNode (options.Dom, outputNode).Trim ();
result.Add (replacement);
TextReplaceChange insertNewMethod = new TextReplaceChange ();
insertNewMethod.FileName = options.Document.FileName;
insertNewMethod.Description = string.Format (GettextCatalog.GetString ("Create new method {0} from selected statement(s)"), param.Name);
insertNewMethod.RemovedChars = param.InsertionPoint.LineBefore == NewLineInsertion.Eol ? 0 : param.InsertionPoint.Location.Column;
insertNewMethod.Offset = data.Document.LocationToOffset (param.InsertionPoint.Location) - insertNewMethod.RemovedChars;
ExtractMethodAstTransformer transformer = new ExtractMethodAstTransformer (param.VariablesToGenerate);
node.AcceptVisitor (transformer, null);
if (!param.OneChangedVariable && node is Expression) {
ResolveResult resolveResult = resolver.Resolve (new ExpressionResult ("(" + provider.OutputNode (options.Dom, node) + ")"), new DomLocation (options.Document.Editor.Caret.Line, options.Document.Editor.Caret.Column));
if (resolveResult.ResolvedType != null)
returnType = options.ShortenTypeName (resolveResult.ResolvedType).ConvertToTypeReference ();
}
MethodDeclaration methodDecl = new MethodDeclaration ();
methodDecl.Name = param.Name;
methodDecl.Modifier = param.Modifiers;
methodDecl.TypeReference = returnType;
if (!param.ReferencesMember)
methodDecl.Modifier |= ICSharpCode.NRefactory.Ast.Modifiers.Static;
if (node is BlockStatement) {
methodDecl.Body = new BlockStatement ();
methodDecl.Body.AddChild (new EmptyStatement ());
if (param.OneChangedVariable)
methodDecl.Body.AddChild (new ReturnStatement (new IdentifierExpression (param.ChangedVariables.First ())));
} else if (node is Expression) {
methodDecl.Body = new BlockStatement ();
methodDecl.Body.AddChild (new ReturnStatement (node as Expression));
}
//.........这里部分代码省略.........
示例6: Analyze
ICSharpCode.NRefactory.Ast.INode Analyze (RefactoringOptions options, ExtractMethodParameters param, bool fillParameter)
{
IResolver resolver = options.GetResolver ();
INRefactoryASTProvider provider = options.GetASTProvider ();
if (resolver == null || provider == null)
return null;
string text = options.Document.Editor.GetTextAt (options.Document.Editor.SelectionRange);
TextEditorData data = options.GetTextEditorData ();
var cu = provider.ParseFile (data.Document.GetTextAt (0, data.SelectionRange.Offset) + "MethodCall ();" + data.Document.GetTextAt (data.SelectionRange.EndOffset, data.Document.Length - data.SelectionRange.EndOffset));
if (cu == null || provider.LastErrors.Count > 0)
cu = provider.ParseFile (data.Document.GetTextAt (0, data.SelectionRange.Offset) + "MethodCall ()" + data.Document.GetTextAt (data.SelectionRange.EndOffset, data.Document.Length - data.SelectionRange.EndOffset));
if (cu == null || provider.LastErrors.Count > 0)
return null;
param.Text = RemoveIndent (text, GetIndent (text)).TrimEnd ('\n', '\r');
ICSharpCode.NRefactory.Ast.INode result = provider.ParseText (text);
if (cu == null || provider.LastErrors.Count > 0) {
return null;
}
VariableLookupVisitor visitor = new VariableLookupVisitor (resolver, param.Location);
visitor.MemberLocation = new Location (param.DeclaringMember.Location.Column, param.DeclaringMember.Location.Line);
if (fillParameter) {
if (result != null)
result.AcceptVisitor (visitor, null);
if (result is Expression) {
ResolveResult resolveResult = resolver.Resolve (new ExpressionResult (text), param.Location);
if (resolveResult != null)
param.ExpressionType = resolveResult.ResolvedType;
}
var startLocation = data.Document.OffsetToLocation (data.SelectionRange.Offset);
var endLocation = data.Document.OffsetToLocation (data.SelectionRange.EndOffset);
// Console.WriteLine ("startLocation={0}, endLocation={1}", startLocation, endLocation);
foreach (VariableDescriptor varDescr in visitor.VariableList.Where (v => !v.IsDefined && v.InitialValueUsed)) {
if (startLocation <= varDescr.Location && varDescr.Location < endLocation)
continue;
// Console.WriteLine (varDescr.Location);
// Console.WriteLine (startLocation <= varDescr.Location);
// Console.WriteLine (varDescr.Location < endLocation);
param.Parameters.Add (varDescr);
}
param.Variables = new List<VariableDescriptor> (visitor.Variables.Values);
foreach (VariableDescriptor varDescr in visitor.VariableList.Where (v => !v.IsDefined && param.Variables.Contains (v))) {
if (param.Parameters.Contains (varDescr))
continue;
if (startLocation <= varDescr.Location && varDescr.Location < endLocation)
continue;
param.Parameters.Add (varDescr);
}
param.ReferencesMember = visitor.ReferencesMember;
param.ChangedVariables = new HashSet<string> (visitor.Variables.Values.Where (v => v.GetsChanged).Select (v => v.Name));
// analyze the variables outside of the selected text
IMember member = param.DeclaringMember;
int startOffset = data.Document.LocationToOffset (member.BodyRegion.Start.Line, member.BodyRegion.Start.Column);
int endOffset = data.Document.LocationToOffset (member.BodyRegion.End.Line, member.BodyRegion.End.Column);
if (data.SelectionRange.Offset < startOffset || endOffset < data.SelectionRange.EndOffset)
return null;
text = data.Document.GetTextBetween (startOffset, data.SelectionRange.Offset) + data.Document.GetTextBetween (data.SelectionRange.EndOffset, endOffset);
ICSharpCode.NRefactory.Ast.INode parsedNode = provider.ParseText (text);
visitor = new VariableLookupVisitor (resolver, param.Location);
visitor.CutRegion = new DomRegion (data.MainSelection.MinLine, data.MainSelection.MaxLine);
visitor.MemberLocation = new Location (param.DeclaringMember.Location.Column, param.DeclaringMember.Location.Line);
if (parsedNode != null)
parsedNode.AcceptVisitor (visitor, null);
param.VariablesOutside = new Dictionary<string, VariableDescriptor> ();
foreach (var pair in visitor.Variables) {
if (startLocation < pair.Value.Location || endLocation >= pair.Value.Location) {
param.VariablesOutside.Add (pair.Key, pair.Value);
}
}
param.OutsideVariableList = new List<VariableDescriptor> ();
foreach (var v in visitor.VariableList) {
if (startLocation < v.Location || endLocation >= v.Location)
param.OutsideVariableList.Add (v);
}
param.ChangedVariablesUsedOutside = new List<VariableDescriptor> (param.Variables.Where (v => v.GetsChanged && param.VariablesOutside.ContainsKey (v.Name)));
param.OneChangedVariable = result is BlockStatement;
if (param.OneChangedVariable)
param.OneChangedVariable = param.ChangedVariablesUsedOutside.Count == 1;
param.VariablesToGenerate = new List<VariableDescriptor> (param.ChangedVariablesUsedOutside.Where (v => v.IsDefined));
foreach (VariableDescriptor var in param.VariablesToGenerate) {
param.Parameters.Add (var);
}
if (param.OneChangedVariable) {
//.........这里部分代码省略.........
示例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> ();
Parameters param = properties as Parameters;
if (param == null)
return result;
TextEditorData data = options.GetTextEditorData ();
IResolver resolver = options.GetResolver ();
IMember curMember = options.Document.CompilationUnit.GetMemberAt (data.Caret.Line, data.Caret.Column);
ResolveResult resolveResult = options.ResolveResult;
int start = 0;
int end = 0;
if (resolveResult == null) {
LineSegment line = data.Document.GetLine (data.Caret.Line);
if (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") {
resolveResult = resolver.Resolve (new ExpressionResult (SearchString (data, span.Color == "string.single" ? '\'' : '"', out start, out end)), DomLocation.Empty);
end++;
}
}
}
if (end == 0) {
resolveResult = resolver.Resolve (new ExpressionResult (SearchNumber (data, out start, out end)), DomLocation.Empty);
}
} else {
start = data.Document.LocationToOffset (resolveResult.ResolvedExpression.Region.Start.Line, resolveResult.ResolvedExpression.Region.Start.Column);
end = data.Document.LocationToOffset (resolveResult.ResolvedExpression.Region.End.Line, resolveResult.ResolvedExpression.Region.End.Column);
}
if (start == 0 && end == 0)
return result;
INRefactoryASTProvider provider = options.GetASTProvider ();
FieldDeclaration fieldDeclaration = new FieldDeclaration (null);
VariableDeclaration varDecl = new VariableDeclaration (param.Name);
varDecl.Initializer = provider.ParseExpression (resolveResult.ResolvedExpression.Expression);
fieldDeclaration.Fields.Add (varDecl);
fieldDeclaration.Modifier = param.Modifiers;
fieldDeclaration.Modifier |= ICSharpCode.NRefactory.Ast.Modifiers.Const;
fieldDeclaration.TypeReference = resolveResult.ResolvedType.ConvertToTypeReference ();
fieldDeclaration.TypeReference.IsKeyword = true;
TextReplaceChange insertConstant = new TextReplaceChange ();
insertConstant.FileName = options.Document.FileName;
insertConstant.Description = string.Format (GettextCatalog.GetString ("Generate constant '{0}'"), param.Name);
insertConstant.Offset = data.Document.LocationToOffset (curMember.Location.Line, 1);
insertConstant.InsertedText = provider.OutputNode (options.Dom, fieldDeclaration, options.GetIndent (curMember)) + Environment.NewLine;
result.Add (insertConstant);
TextReplaceChange replaceConstant = new TextReplaceChange ();
replaceConstant.FileName = options.Document.FileName;
replaceConstant.Description = string.Format (GettextCatalog.GetString ("Replace expression with constant '{0}'"), param.Name);
replaceConstant.Offset = start;
replaceConstant.RemovedChars = end - start;
replaceConstant.InsertedText = param.Name;
result.Add (replaceConstant);
return result;
}
示例10: 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;
//.........这里部分代码省略.........
示例11: 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.InsertedText = "";
string indent = "";
MethodDeclaration methodDecl = new MethodDeclaration ();
bool isInInterface = false;
if (invoke.TargetObject is IdentifierExpression) {
insertNewMethod.FileName = options.Document.FileName;
insertNewMethod.Offset = options.Document.TextEditor.GetPositionFromLineColumn (options.ResolveResult.CallingMember.BodyRegion.End.Line, options.ResolveResult.CallingMember.BodyRegion.End.Column);
methodDecl.Name = ((IdentifierExpression)invoke.TargetObject).Identifier;
indent = options.GetIndent (options.ResolveResult.CallingMember);
insertNewMethod.InsertedText = Environment.NewLine;
if (options.ResolveResult.CallingMember.IsStatic)
methodDecl.Modifier |= ICSharpCode.NRefactory.Ast.Modifiers.Static;
} else {
methodDecl.Name = ((MemberReferenceExpression)invoke.TargetObject).MemberName;
string callingObject = provider.OutputNode (options.Dom, ((MemberReferenceExpression)invoke.TargetObject).TargetObject);
ResolveResult resolveResult = resolver.Resolve (new ExpressionResult (callingObject), resolvePosition);
IType type = options.Dom.GetType (resolveResult.ResolvedType);
insertNewMethod.FileName = type.CompilationUnit.FileName;
if (resolveResult.StaticResolve)
methodDecl.Modifier |= ICSharpCode.NRefactory.Ast.Modifiers.Static;
if (insertNewMethod.FileName == options.Document.FileName) {
indent = options.GetIndent (options.ResolveResult.CallingMember);
insertNewMethod.InsertedText = Environment.NewLine;
insertNewMethod.Offset = options.Document.TextEditor.GetPositionFromLineColumn (options.ResolveResult.CallingMember.BodyRegion.End.Line, options.ResolveResult.CallingMember.BodyRegion.End.Column);
} else {
TextEditorData otherFile = TextReplaceChange.GetTextEditorData (insertNewMethod.FileName);
if (otherFile == null) {
IdeApp.Workbench.OpenDocument (insertNewMethod.FileName);
otherFile = TextReplaceChange.GetTextEditorData (insertNewMethod.FileName);
}
methodDecl.Modifier |= ICSharpCode.NRefactory.Ast.Modifiers.Public;
isInInterface = type.ClassType == MonoDevelop.Projects.Dom.ClassType.Interface;
if (isInInterface)
methodDecl.Modifier = ICSharpCode.NRefactory.Ast.Modifiers.None;
if (otherFile == null)
throw new InvalidOperationException ("Can't open file:" + insertNewMethod.FileName);
try {
indent = otherFile.Document.GetLine (type.Location.Line - 1).GetIndentation (otherFile.Document) ?? "";
} catch (Exception) {
indent = "";
}
indent += "\t";
insertNewMethod.Offset = otherFile.Document.LocationToOffset (type.BodyRegion.End.Line - 1, 0);
}
}
methodDecl.Modifier = modifiers;
methodDecl.TypeReference = HelperMethods.ConvertToTypeReference (returnType);
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
if (IsValidIdentifier (lastName))
parameterName = lastName;
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");
typeReference.IsKeyword = true;
ParameterDeclarationExpression pde = new ParameterDeclarationExpression (typeReference, parameterName);
methodDecl.Parameters.Add (pde);
}
insertNewMethod.InsertedText += Environment.NewLine + provider.OutputNode (options.Dom, methodDecl, indent);
result.Add (insertNewMethod);
fileName = insertNewMethod.FileName;
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;
}