public ResolveResult Resolve (Expression expression) { ResolveResult result = expression.AcceptVisitor (this, null) as ResolveResult; if (result == null) result = CreateResult (""); return result; }
private void ProcessQuery(Expression queryExpressionSelectClause) { var objectCreateExpression = QueryParsingUtils.GetAnonymousCreateExpression(queryExpressionSelectClause) as ObjectCreateExpression; if (objectCreateExpression == null || objectCreateExpression.IsAnonymousType == false) return; foreach ( var expression in objectCreateExpression.ObjectInitializer.CreateExpressions.OfType<NamedArgumentExpression>()) { var generateExpression = GenerateExpression(expression.Expression); if (generateExpression != null) QueryParameters.Add(generateExpression); } foreach ( var expression in objectCreateExpression.ObjectInitializer.CreateExpressions.OfType<MemberReferenceExpression>()) { var generateExpression = GenerateExpression(expression); if (generateExpression != null) QueryParameters.Add(generateExpression); } }
public GridValuesProvider(Expression targetObject, DebugType itemType) { this.targetObject = targetObject; this.itemType = itemType; this.memberFromNameMap = this.GetItemTypeMembers().MakeDictionary(memberInfo => memberInfo.Name); }
public static VariableDeclaration add_Variable(this BlockStatement blockDeclaration, string name, Expression expression, TypeReference typeReference) { var variableDeclaration = new VariableDeclaration(name, expression) {TypeReference = typeReference}; var localVariableDeclaration = new LocalVariableDeclaration(variableDeclaration); blockDeclaration.append(localVariableDeclaration); return variableDeclaration; }
bool IsValidMemberAssignment(Ast.Expression left, ref string identifier) { if (left is Ast.MemberReferenceExpression) { var e = left as Ast.MemberReferenceExpression; if (identifier == null) { identifier = e.MemberName; return(e.TargetObject is Ast.ThisReferenceExpression); } else { return(e.TargetObject is Ast.ThisReferenceExpression && e.MemberName == identifier); } } if (identifier == null) { if (left is Ast.IdentifierExpression) { identifier = (left as Ast.IdentifierExpression).Identifier; return(true); } return(false); } else { return((left is Ast.IdentifierExpression) && (left as Ast.IdentifierExpression).Identifier == identifier); } }
/// <summary> /// If given symbol is Unknown ResolveResult, returns action that can generate code for this missing symbol. /// </summary> public static GenerateCodeContextAction GetContextAction(EditorContext context) { if (context.CurrentSymbol is UnknownMethodResolveResult) { UnknownMethodResolveResult unknownMethodCall = (UnknownMethodResolveResult)context.CurrentSymbol; Ast.Expression expression = context.GetContainingElement <Ast.InvocationExpression>(); if (expression == null) { return(null); } string title = "${res:AddIns.SharpRefactoring.IntroduceMethod}"; try { title = string.Format(StringParser.Parse("${res:AddIns.SharpRefactoring.IntroduceMethod}"), unknownMethodCall.CallName, unknownMethodCall.Target.FullyQualifiedName); } catch (FormatException) { } if (unknownMethodCall.Target != null && unknownMethodCall.Target.IsUserCode()) { // Don't introduce method on non-modyfiable types return(new IntroduceMethodContextAction(unknownMethodCall, expression, context.Editor) { Title = title }); } } return(null); }
public static IEnumerable<TreeNode> LazyGetChildNodesOfArray(TreeNode parent, Expression expression, ArrayDimensions dimensions) { if (dimensions.TotalElementCount == 0) return new TreeNode[] { new TreeNode(null, "(empty)", null, null, parent, null) }; return new ArrayRangeNode(parent, expression, dimensions, dimensions).ChildNodes; }
private string GenerateExpression(Expression expression) { var sb = new StringBuilder(); var memberReferenceExpression = expression as MemberReferenceExpression; while (memberReferenceExpression != null) { if (sb.Length != 0) sb.Insert(0, "."); sb.Insert(0, memberReferenceExpression.MemberName); expression = memberReferenceExpression.TargetObject; memberReferenceExpression = expression as MemberReferenceExpression; } var identifierExpression = expression as IdentifierExpression; if(identifierExpression != null && sb.Length != 0) { string path; if (aliasToName.TryGetValue(identifierExpression.Identifier, out path)) { sb.Insert(0, path); } } if (sb.Length == 0) return null; return sb.ToString(); }
/// <summary> /// Gets "a.b" from "a.b.c" /// </summary> Expression GetTarget(Expression memberReferenceExpr) { if (memberReferenceExpr is MemberReferenceExpression) { return ((MemberReferenceExpression)memberReferenceExpr).TargetObject; } return null; }
private void ProcessQuery(Expression queryExpressionSelectClause) { var objectCreateExpression = queryExpressionSelectClause as ObjectCreateExpression; if (objectCreateExpression == null || objectCreateExpression.IsAnonymousType == false) return; // we only want the outer most value if (queryProcessed) return; queryProcessed = true; foreach ( var expression in objectCreateExpression.ObjectInitializer.CreateExpressions.OfType<NamedArgumentExpression>()) { FieldNames.Add(expression.Name); } foreach ( var expression in objectCreateExpression.ObjectInitializer.CreateExpressions.OfType<MemberReferenceExpression>()) { FieldNames.Add(expression.MemberName); } foreach ( var expression in objectCreateExpression.ObjectInitializer.CreateExpressions.OfType<IdentifierExpression>()) { FieldNames.Add(expression.Identifier); } }
public IListNode(Expression targetObject) { this.targetObject = targetObject; this.Name = "IList"; this.count = Utils.GetIListCount(this.targetObject); this.ChildNodes = Utils.LazyGetItemsOfIList(this.targetObject); }
ListValuesProvider CreateListValuesProvider(ICSharpCode.NRefactory.Ast.Expression targetObject, DebugType iListType, DebugType listItemType) { var listValuesProvider = new ListValuesProvider(targetObject, iListType, listItemType); var virtCollection = new VirtualizingCollection <ObjectValue>(listValuesProvider); this.listView.ItemsSource = virtCollection; return(listValuesProvider); }
internal InferredReturnType(Expression expression, NRefactoryResolver resolver) { if (resolver == null) throw new ArgumentNullException("resolver"); _expression = expression; _resolver = resolver; }
public IReturnType ResolveType(Expression expression) { ResolveResult rr = Resolve(expression); if (rr != null) return rr.ResolvedType; else return null; }
public static void Assign(this BlockStatement block, Expression left, Expression right) { if (left == null) throw new ArgumentNullException("left"); if (right == null) throw new ArgumentNullException("right"); AddStatement(block, new AssignmentExpression(left, AssignmentOperatorType.Assign, right)); }
private bool IsMethodInvocation(Expression expression) { if (expression.Parent is InvocationExpression) { InvocationExpression invocation = (InvocationExpression) expression.Parent; return expression.GetHashCode() == invocation.TargetObject.GetHashCode(); } return false; }
public ArrayRangeNode(Expression arrayTarget, ArrayDimensions bounds, ArrayDimensions originalBounds) { this.arrayTarget = arrayTarget; this.bounds = bounds; this.originalBounds = originalBounds; this.Name = GetName(); this.ChildNodes = LazyGetChildren(); }
public static IEnumerable<TreeNode> LazyGetMembersOfObject(Expression expression, MemberInfo[] members) { List<TreeNode> nodes = new List<TreeNode>(); foreach(MemberInfo memberInfo in members) { nodes.Add(new ExpressionNode(ExpressionNode.GetImageForMember((IDebugMemberInfo)memberInfo), memberInfo.Name, expression.AppendMemberReference((IDebugMemberInfo)memberInfo))); } nodes.Sort(); return nodes; }
public IListNode(TreeNode parent, Expression targetListObject) : base(parent) { this.targetList = targetListObject; this.Name = "IList"; this.listCount = this.targetList.GetIListCount(); this.childNodes = Utils.LazyGetItemsOfIList(this, this.targetList); }
public void Refresh() { // clear ListView listView.ItemsSource = null; ScrollViewer listViewScroller = listView.GetScrollViewer(); if (listViewScroller != null) { listViewScroller.ScrollToVerticalOffset(0); } Value shownValue = null; ICSharpCode.NRefactory.Ast.Expression shownExpr = null; try { shownExpr = debuggerService.GetExpression(txtExpression.Text); shownValue = shownExpr.Evaluate(debuggerService.DebuggedProcess); } catch (GetValueException) { // display ex.Message } if (shownValue != null && !shownValue.IsNull) { GridValuesProvider gridValuesProvider; // Value is IList DebugType iListType, listItemType; if (shownValue.Type.ResolveIListImplementation(out iListType, out listItemType)) { gridValuesProvider = CreateListValuesProvider(shownExpr, iListType, listItemType); } else { // Value is IEnumerable DebugType iEnumerableType, itemType; if (shownValue.Type.ResolveIEnumerableImplementation(out iEnumerableType, out itemType)) { // original /*var lazyListViewWrapper = new LazyItemsControl<ObjectValue>(this.listView, initialIEnumerableItemsCount); * var enumerableValuesProvider = new EnumerableValuesProvider(val.ExpressionTree, iEnumerableType, itemType); * lazyListViewWrapper.ItemsSource = new VirtualizingIEnumerable<ObjectValue>(enumerableValuesProvider.ItemsSource); * gridValuesProvider = enumerableValuesProvider;*/ DebugType debugListType; var debugListExpression = DebuggerHelpers.CreateDebugListExpression(shownExpr, itemType, out debugListType); gridValuesProvider = CreateListValuesProvider(debugListExpression, debugListType, itemType); } else { // Value cannot be displayed in GridVisualizer return; } } IList <MemberInfo> itemTypeMembers = gridValuesProvider.GetItemTypeMembers(); InitializeColumns((GridView)this.listView.View, itemTypeMembers); this.columnHider = new GridViewColumnHider((GridView)this.listView.View); cmbColumns.ItemsSource = this.columnHider.HideableColumns; } }
public LocalLookupVariable(string name, TypeReference typeRef, Location startPos, Location endPos, bool isConst, bool isLoopVariable, Expression initializer) { this.Name = name; this.TypeRef = typeRef; this.StartPos = startPos; this.EndPos = endPos; this.IsConst = isConst; this.IsLoopVariable = isLoopVariable; this.Initializer = initializer; }
private Expression SimplifyLetExpression(Expression expression) { var castExpression = expression as CastExpression; if (castExpression != null) return SimplifyLetExpression(castExpression.Expression); var parenthesizedExpression = expression as ParenthesizedExpression; if (parenthesizedExpression != null) return SimplifyLetExpression(parenthesizedExpression.Expression); return expression; }
public IEnumerableNode(Expression targetObject, DebugType itemType) { this.targetObject = targetObject; this.Name = "IEnumerable"; this.Text = "Expanding will enumerate the IEnumerable"; DebugType debugListType; this.debugListExpression = DebuggerHelpers.CreateDebugListExpression(targetObject, itemType, out debugListType); this.ChildNodes = Utils.LazyGetItemsOfIList(this.debugListExpression); }
public void Refresh() { try { // clear ListView listView.ItemsSource = null; ScrollViewer listViewScroller = listView.GetScrollViewer(); if (listViewScroller != null) { listViewScroller.ScrollToVerticalOffset(0); } Value shownValue = null; ICSharpCode.NRefactory.Ast.Expression shownExpr = null; try { shownExpr = debuggerService.GetExpression(txtExpression.Text); shownValue = shownExpr.Evaluate(debuggerService.DebuggedProcess); } catch (GetValueException e) { MessageService.ShowMessage(e.Message); } if (shownValue != null && !shownValue.IsNull) { GridValuesProvider gridValuesProvider; // Value is IList DebugType iListType, listItemType; if (shownValue.Type.ResolveIListImplementation(out iListType, out listItemType)) { gridValuesProvider = CreateListValuesProvider(shownExpr.CastToIList(), listItemType); } else { // Value is IEnumerable DebugType iEnumerableType, itemType; if (shownValue.Type.ResolveIEnumerableImplementation(out iEnumerableType, out itemType)) { DebugType debugListType; var debugListExpression = DebuggerHelpers.CreateDebugListExpression(shownExpr, itemType, out debugListType); gridValuesProvider = CreateListValuesProvider(debugListExpression, itemType); } else { // Not IList or IEnumerable<T> - can't be displayed in GridVisualizer return; } } IList <MemberInfo> itemTypeMembers = gridValuesProvider.GetItemTypeMembers(); InitializeColumns((GridView)this.listView.View, itemTypeMembers); this.columnHider = new GridViewColumnHider((GridView)this.listView.View); cmbColumns.ItemsSource = this.columnHider.HideableColumns; } } catch (GetValueException e) { MessageService.ShowMessage(e.Message); } catch (DebuggerVisualizerException e) { MessageService.ShowMessage(e.Message); } }
public ResolveResult Resolve(Expression expression) { ResolveResult rr; if (!cachedResults.TryGetValue(expression, out rr)) { rr = (ResolveResult)expression.AcceptVisitor(this, null); if (rr != null) rr.Freeze(); cachedResults[expression] = rr; } return rr; }
static object ConvertAttributeArgument(AST.Expression expression) { AST.PrimitiveExpression pe = expression as AST.PrimitiveExpression; if (pe != null) { return(pe.Value); } else { return(null); } }
public static Expression Convert(NR.Expression expression, ConverterSettings settings) { if (expression == null) { throw new ArgumentNullException("expression"); } if (settings == null) { throw new ArgumentNullException("settings"); } return((Expression)expression.AcceptVisitor(new ConvertVisitor(settings), null)); }
public LocalLookupVariable(string name, TypeReference typeRef, Location startPos, Location endPos, bool isConst, bool isLoopVariable, Expression initializer, LambdaExpression parentLambdaExpression, bool isQueryContinuation) { this.Name = name; this.TypeRef = typeRef; this.StartPos = startPos; this.EndPos = endPos; this.IsConst = isConst; this.IsLoopVariable = isLoopVariable; this.Initializer = initializer; this.ParentLambdaExpression = parentLambdaExpression; this.IsQueryContinuation = isQueryContinuation; }
/// <summary> /// Tries to find a resource reference in the specified expression. /// </summary> /// <param name="expressionResult">The ExpressionResult for the expression.</param> /// <param name="expr">The AST representation of the full expression.</param> /// <param name="resolveResult">SharpDevelop's ResolveResult for the expression.</param> /// <param name="caretLine">The 0-based line where the expression is located.</param> /// <param name="caretColumn">The 0-based column where the expression is located.</param> /// <param name="fileName">The name of the source file where the expression is located.</param> /// <param name="fileContent">The content of the source file where the expression is located.</param> /// <param name="expressionFinder">The ExpressionFinder for the file.</param> /// <param name="charTyped">The character that has been typed at the caret position but is not yet in the buffer (this is used when invoked from code completion), or <c>null</c>.</param> /// <returns>A ResourceResolveResult describing the referenced resource, or <c>null</c>, if this expression does not reference a resource using the ICSharpCode.Core.ResourceService class.</returns> public ResourceResolveResult Resolve(ExpressionResult expressionResult, Expression expr, ResolveResult resolveResult, int caretLine, int caretColumn, string fileName, string fileContent, IExpressionFinder expressionFinder, char? charTyped) { IMember member = null; // "ResourceService.GetString(..." may be a MemberResolveResult or // MethodResolveResult, dependent on how much of the expression // has already been typed. MemberResolveResult mrr = resolveResult as MemberResolveResult; if (mrr != null) { // If it is a MemberResolveResult, this indicates that // the complete expression is already in the buffer. // So we only assign the member if Resolve is not invoked // from code completion to prevent the code completion window // from opening when typing something like: // ResourceService.GetString(...)[ if (charTyped == null) { member = mrr.ResolvedMember; } } else { MethodGroupResolveResult methrr = resolveResult as MethodGroupResolveResult; if (methrr != null) { // If it is a MethodResolveResult, the expression is incomplete. // Accept only if '(' has been typed. if (charTyped == '(') { member = methrr.GetMethodIfSingleOverload(); } } } if (member is IMethod && LanguageProperties.CSharp.NameComparer.Equals(member.FullyQualifiedName, "ICSharpCode.Core.ResourceService.GetString") ) { #if DEBUG LoggingService.Debug("ResourceToolkit: ICSharpCodeCoreNRefactoryResourceResolver: ResourceService resource access detected"); #endif string key = GetKeyFromExpression(expr); // TODO: Add information about return type (of the resource, if present). return new ResourceResolveResult(resolveResult.CallingClass, resolveResult.CallingMember, null, ICSharpCodeCoreResourceResolver.ResolveICSharpCodeCoreResourceSet(key, fileName), key); } return null; }
public static IEnumerable<TreeNode> LazyGetMembersOfObject(Expression expression, MemberInfo[] members) { List<TreeNode> nodes = new List<TreeNode>(); foreach(MemberInfo memberInfo in members) { string imageName; var image = ExpressionNode.GetImageForMember((IDebugMemberInfo)memberInfo, out imageName); var exp = new ExpressionNode(image, memberInfo.Name, expression.AppendMemberReference((IDebugMemberInfo)memberInfo)); exp.ImageName = imageName; nodes.Add(exp); } nodes.Sort(); return nodes; }
/// <summary> /// Turns "(a.b as T).d.e" into "(a != null) && (a.b is T) && ((a.b as T).d != null)" /// </summary> Expression BuildCondition(Expression targetExpr) { var parts = GetConditionParts(targetExpr); Expression condition = null; foreach (var part in parts) { if (condition == null) { // first condition = new ParenthesizedExpression(part); } else { condition = new BinaryOperatorExpression(new ParenthesizedExpression(part), BinaryOperatorType.LogicalAnd, condition); } } return condition; }
/// <summary> /// Returns the existing expression plus the specified integer value. /// The old <paramref name="expr"/> object is not modified, but might be a subobject on the new expression /// (and thus its parent property is modified). /// </summary> public static Expression AddInteger(Expression expr, int value) { PrimitiveExpression pe = expr as PrimitiveExpression; if (pe != null && pe.Value is int) { int newVal = (int)pe.Value + value; return new PrimitiveExpression(newVal, newVal.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); } BinaryOperatorExpression boe = expr as BinaryOperatorExpression; if (boe != null && boe.Op == BinaryOperatorType.Add) { // clone boe: boe = new BinaryOperatorExpression(boe.Left, boe.Op, boe.Right); boe.Right = AddInteger(boe.Right, value); if (boe.Right is PrimitiveExpression && ((PrimitiveExpression)boe.Right).Value is int) { int newVal = (int)((PrimitiveExpression)boe.Right).Value; if (newVal == 0) { return boe.Left; } else if (newVal < 0) { ((PrimitiveExpression)boe.Right).Value = -newVal; boe.Op = BinaryOperatorType.Subtract; } } return boe; } if (boe != null && boe.Op == BinaryOperatorType.Subtract) { pe = boe.Right as PrimitiveExpression; if (pe != null && pe.Value is int) { int newVal = (int)pe.Value - value; if (newVal == 0) return boe.Left; // clone boe: boe = new BinaryOperatorExpression(boe.Left, boe.Op, boe.Right); if (newVal < 0) { newVal = -newVal; boe.Op = BinaryOperatorType.Add; } boe.Right = new PrimitiveExpression(newVal, newVal.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); return boe; } } BinaryOperatorType opType = BinaryOperatorType.Add; if (value < 0) { value = -value; opType = BinaryOperatorType.Subtract; } return new BinaryOperatorExpression(expr, opType, new PrimitiveExpression(value, value.ToString(System.Globalization.NumberFormatInfo.InvariantInfo))); }
public void AddVariable(TypeReference typeRef, string name, Location startPos, Location endPos, bool isConst, bool isLoopVariable, Expression initializer, LambdaExpression parentLambdaExpression) { if (name == null || name.Length == 0) { return; } List<LocalLookupVariable> list; if (!variables.ContainsKey(name)) { variables[name] = list = new List<LocalLookupVariable>(); } else { list = (List<LocalLookupVariable>)variables[name]; } list.Add(new LocalLookupVariable(name, typeRef, startPos, endPos, isConst, isLoopVariable, initializer, parentLambdaExpression)); }
private bool ReachToInvocation(Expression expression) { if (expression is FieldReferenceExpression) { FieldReferenceExpression fieldReferenceExpression = (FieldReferenceExpression) expression; INode node = fieldReferenceExpression.Parent.Parent; if (node is InvocationExpression) return true; else if (node is FieldReferenceExpression) { if (IsMethodInvocation((FieldReferenceExpression) node)) return true; else return ReachToInvocation((Expression) node.Parent); } } return false; }
private void ProcessQuery(Expression queryExpressionSelectClause) { var objectCreateExpression = queryExpressionSelectClause as ObjectCreateExpression; if (objectCreateExpression == null || objectCreateExpression.IsAnonymousType == false) return; foreach (var expression in objectCreateExpression.ObjectInitializer.CreateExpressions.OfType<NamedArgumentExpression>()) { FieldNames.Add(expression.Name); } foreach (var expression in objectCreateExpression.ObjectInitializer.CreateExpressions.OfType<MemberReferenceExpression>()) { FieldNames.Add(expression.MemberName); } }
public override bool IsAvailable(EditorContext context) { this.currentExpr = context.GetContainingElement<Expression>(); if (currentExpr is InvocationExpression) { // InvocationExpression (e.g. "e.Foo()") has MemberReferenceExpression as TargetObject (e.g. "e.Foo") // "e.Foo() -> e" this.targetExpr = GetTarget(((InvocationExpression)currentExpr).TargetObject); } else { // "a.b" -> "a" this.targetExpr = GetTarget(currentExpr); } return this.targetExpr is MemberReferenceExpression || this.targetExpr is CastExpression || this.targetExpr is ParenthesizedExpression; //this.targetExpr is IdentifierExpression; // "don't offer the action for just a.b, only for a.b.c" }
public IntroduceMethodContextAction(UnknownMethodResolveResult symbol, Ast.Expression invocationExpr, ITextEditor editor) { if (symbol == null) { throw new ArgumentNullException("rr"); } if (invocationExpr == null) { throw new ArgumentNullException("ex"); } if (editor == null) { throw new ArgumentNullException("editor"); } this.UnknownMethodCall = symbol; this.InvocationExpr = invocationExpr; this.Editor = editor; }
public IReturnType GetTypeSafe (Expression expression) { ResolveResult result = Resolve (expression); if (expression is LambdaExpression) { var lambda = (LambdaExpression)expression; var bodyType = GetTypeSafe (lambda.ExpressionBody); DomReturnType constructedLambdaType = new DomReturnType (bodyType.FullName == DomReturnType.Void.FullName ? "System.Action" : "System.Func"); foreach (var param in lambda.Parameters) { var typeParam = GetTypeSafe (param); // add void place holder for types that can't be resolved. if (typeParam == null || string.IsNullOrEmpty (typeParam.FullName)) typeParam = DomReturnType.Void; constructedLambdaType.AddTypeParameter (typeParam); } if (bodyType.FullName != DomReturnType.Void.FullName) constructedLambdaType.AddTypeParameter (bodyType ?? result.ResolvedType); return constructedLambdaType; } return result.ResolvedType ?? DomReturnType.Void; }
IEnumerable <Ast.ParameterDeclarationExpression> CreateParameters(UnknownMethodResolveResult rr, ClassFinder context, Ast.InvocationExpression invocation) { List <string> usedNames = new List <string>(); for (int i = 0; i < rr.Arguments.Count; i++) { IReturnType type = rr.Arguments[i]; if (type is LambdaReturnType) { type = (type as LambdaReturnType).ToDefaultDelegate(); } Ast.TypeReference typeRef = CodeGenerator.ConvertType(type, context); typeRef = typeRef.IsNull ? new Ast.TypeReference("object", true) : typeRef; Ast.Expression ex = invocation.Arguments[i]; string paramName = IsNumericType(type) ? "num" + i : type.Name + i.ToString(); if (ex is Ast.IdentifierExpression) { paramName = (ex as Ast.IdentifierExpression).Identifier; } if (ex is Ast.MemberReferenceExpression) { paramName = (ex as Ast.MemberReferenceExpression).MemberName; } Ast.ParameterModifiers mod = Ast.ParameterModifiers.None; if (ex is Ast.DirectionExpression) { var dex = ex as Ast.DirectionExpression; if (dex.Expression is Ast.IdentifierExpression) { paramName = (dex.Expression as Ast.IdentifierExpression).Identifier; } if (dex.Expression is Ast.MemberReferenceExpression) { paramName = (dex.Expression as Ast.MemberReferenceExpression).MemberName; } mod = dex.FieldDirection == Ast.FieldDirection.Out ? Ast.ParameterModifiers.Out : (dex.FieldDirection == Ast.FieldDirection.Ref ? Ast.ParameterModifiers.Ref : Ast.ParameterModifiers.None); } paramName = rr.CallingClass.ProjectContent.Language.CodeGenerator.GetParameterName(paramName); if (usedNames.Contains(paramName)) { paramName += i.ToString(); } usedNames.Add(paramName); yield return(new Ast.ParameterDeclarationExpression(typeRef, paramName) { ParamModifier = mod }); } }
internal void ExecuteIntroduceMethod(UnknownMethodResolveResult rr, Ast.Expression invocationExpr, ITextEditor editor, bool isNew, object result) { IClass targetClass = IsEqualClass(rr.CallingClass, rr.Target.GetUnderlyingClass()) ? rr.CallingClass : rr.Target.GetUnderlyingClass(); CodeGenerator gen = targetClass.ProjectContent.Language.CodeGenerator; IAmbience ambience = targetClass.ProjectContent.Language.GetAmbience(); ClassFinder finder = new ClassFinder(rr.CallingMember); ModifierEnum modifiers = ModifierEnum.None; bool isExtension = !targetClass.IsUserCode(); if (IsEqualClass(rr.CallingClass, targetClass)) { if (rr.CallingMember != null) { modifiers |= (rr.CallingMember.Modifiers & ModifierEnum.Static); } } else { if (isExtension) { if (isNew) { targetClass = rr.CallingClass; } else { targetClass = result as IClass; } } // exclude in Unit Test mode if (WorkbenchSingleton.Workbench != null) { editor = (FileService.OpenFile(targetClass.CompilationUnit.FileName) as ITextEditorProvider).TextEditor; } if (targetClass.ClassType != ClassType.Interface) { modifiers |= ModifierEnum.Public; } if (rr.IsStaticContext) { modifiers |= ModifierEnum.Static; } } NRefactoryResolver resolver = Extensions.CreateResolverForContext(targetClass.ProjectContent.Language, editor); IReturnType type = resolver.GetExpectedTypeFromContext(invocationExpr); Ast.TypeReference typeRef = CodeGenerator.ConvertType(type, finder); if (typeRef.IsNull) { if (invocationExpr.Parent is Ast.ExpressionStatement) { typeRef = new Ast.TypeReference("void", true); } else { typeRef = new Ast.TypeReference("object", true); } } Ast.MethodDeclaration method = new Ast.MethodDeclaration { Name = rr.CallName, Modifier = CodeGenerator.ConvertModifier(modifiers, finder), TypeReference = typeRef, Parameters = CreateParameters(rr, finder, invocationExpr as Ast.InvocationExpression).ToList(), }; if (targetClass.ClassType != ClassType.Interface) { method.Body = CodeGenerator.CreateNotImplementedBlock(); } RefactoringDocumentAdapter documentWrapper = new RefactoringDocumentAdapter(editor.Document); if (isExtension) { method.Parameters.Insert(0, new Ast.ParameterDeclarationExpression(CodeGenerator.ConvertType(rr.Target, finder), "thisInstance")); method.IsExtensionMethod = true; method.Modifier |= Ast.Modifiers.Static; } if (isNew) { Ast.TypeDeclaration newType = new Ast.TypeDeclaration(isExtension ? Ast.Modifiers.Static : Ast.Modifiers.None, null); newType.Name = result as string; newType.AddChild(method); gen.InsertCodeAfter(targetClass, documentWrapper, newType); } else { if (IsEqualClass(rr.CallingClass, targetClass)) { gen.InsertCodeAfter(rr.CallingMember, documentWrapper, method); } else { gen.InsertCodeAtEnd(targetClass.BodyRegion, documentWrapper, method); } } if (targetClass.ClassType == ClassType.Interface) { return; } ParseInformation info = ParserService.ParseFile(targetClass.CompilationUnit.FileName); if (info != null) { IMember newMember; if (isNew) { targetClass = info.CompilationUnit.Classes.FirstOrDefault(c => c.DotNetName == c.Namespace + "." + (result as string)); } else { targetClass = info.CompilationUnit.Classes.Flatten(c => c.InnerClasses).FirstOrDefault(c => c.DotNetName == targetClass.DotNetName); } if (targetClass == null) { return; } if (IsEqualClass(rr.CallingClass, targetClass)) { newMember = targetClass.GetInnermostMember(editor.Caret.Line, editor.Caret.Column); newMember = targetClass.AllMembers .OrderBy(m => m.BodyRegion.BeginLine) .ThenBy(m2 => m2.BodyRegion.BeginColumn) .First(m3 => m3.BodyRegion.BeginLine > newMember.BodyRegion.BeginLine); } else { newMember = targetClass.Methods.Last(); } IDocumentLine line = editor.Document.GetLine(newMember.BodyRegion.BeginLine + 2); int indentLength = DocumentUtilitites.GetWhitespaceAfter(editor.Document, line.Offset).Length; editor.Select(line.Offset + indentLength, "throw new NotImplementedException();".Length); } }